]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
* textmodes/org.el (org-rm-props, org-activate-plain-links)
[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.44
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.44
94 ;; - Clock table can be done for a limited time interval.
95 ;; - Obsolete support for the old outline mode has been removed.
96 ;; - Bug fixes and code cleaning.
97 ;;
98 ;; Version 4.43
99 ;; - Bug fixes
100 ;; - `s' key in the agenda saves all org-mode buffers.
101 ;;
102 ;; Version 4.41
103 ;; - Shift-curser keys can modify inactive time stamps (inactive time
104 ;; stamps are the ones in [...] brackets.
105 ;; - Toggle all checkboxes in a region/below a headline.
106 ;; - Bug fixes.
107 ;;
108 ;; Version 4.40
109 ;; - Bug fixes.
110 ;;
111 ;; Version 4.39
112 ;; - Special tag ARCHIVE keeps a subtree closed and away from agenda lists.
113 ;; - LaTeX code in Org-mode files can be converted to images for HTML.
114 ;; - Bug fixes.
115 ;; - CDLaTeX-mode features can be used in Org-mode to help inserting
116 ;; LaTeX environment and math.
117 ;;
118 ;; Version 4.38
119 ;; - noutline.el is now required (important for XEmacs users only).
120 ;; - Dynamic blocks.
121 ;; - Archiving of all level 1 trees without open TODO items.
122 ;; - Clock reports can be inserted into the file in a special section.
123 ;; - FAQ removed from the manual, now only on the web.
124 ;; - Bug fixes.
125 ;;
126 ;; Version 4.37
127 ;; - Clock-feature for measuring time spent on specific items.
128 ;; - Improved emphasizing allows configuration and stacking.
129 ;;
130 ;; Version 4.36
131 ;; - Improved indentation of ASCII export, when headlines become items.
132 ;; - Handling of 12am and 12pm fixed. Times beyond 24:00 can be used
133 ;; and will not lead to conflicts.
134 ;; - Support for mutually exclusive TAGS with the fast tags interface.
135 ;; - Bug fixes.
136 ;;
137 ;; Version 4.35
138 ;; - HTML export is now valid XHTML.
139 ;; - Timeline can also show dates without entries. See new option
140 ;; `org-timeline-show-empty-dates'.
141 ;; - The bullets created by the ASCII exporter can now be configured.
142 ;; See the new option `org-export-ascii-bullets'.
143 ;; - New face `org-upcoming-deadline' (was `org-scheduled-previously').
144 ;; - New function `org-context' to allow testing for local context.
145 ;;
146 ;; Version 4.34
147 ;; - Bug fixes.
148 ;;
149 ;; Version 4.33
150 ;; - New commands to move through plain lists: S-up and S-down.
151 ;; - Bug fixes and documentation update.
152 ;;
153 ;; Version 4.32
154 ;; - Fast (single-key-per-tag) interface for setting TAGS.
155 ;; - The list of legal tags can be configured globally and locally.
156 ;; - Elisp and Info links (thanks to Todd Neal).
157 ;; - `org-export-publishing-directory' can be an alist, with different
158 ;; directories for different export types.
159 ;; - All context-sensitive commands use `call-interactively' to dispatch.
160 ;; - `org-confirm-shell-links' renamed to `org-confirm-shell-link-function'.
161 ;; - Bug fixes.
162 ;;
163 ;; Version 4.31
164 ;; - Bug fixes.
165 ;;
166 ;; Version 4.30
167 ;; - Modified installation: Autoloads have been collected in org-install.el.
168 ;; - Logging (org-log-done) is now a #+STARTUP option.
169 ;; - Checkboxes in plain list items, following up on Frank Ruell's idea.
170 ;; - File links inserted with C-c C-l will use relative paths if the linked
171 ;; file is in the current directory or a subdirectory of it.
172 ;; - New variable `org-link-file-path-type' to specify preference for
173 ;; relative and absolute paths.
174 ;; - New CSS classes for tags, timestamps, timestamp keywords.
175 ;; - Bug and typo fixes.
176 ;;
177 ;; Version 4.29
178 ;; - Inlining images in HTML export now depends on wheather the link
179 ;; contains a description or not.
180 ;; - TODO items can be scheduled from the global TODO list using C-c C-s.
181 ;; - TODO items already scheduled can be made to disappear from the global
182 ;; todo list, see `org-agenda-todo-ignore-scheduled'.
183 ;; - In Tables, formulas may also be Lisp forms.
184 ;; - Exporting the visible part of an outline with `C-c C-x v' works now
185 ;; for all available exporters.
186 ;; - Bug fixes, lots of them :-(
187 ;;
188 ;; Version 4.28
189 ;; - Bug fixes.
190 ;;
191 ;; Version 4.27
192 ;; - HTML exporter generalized to receive external options.
193 ;; As part of the process, author, email and date have been moved to the
194 ;; end of the HTML file.
195 ;; - Support for customizable file search in file links.
196 ;; - BibTeX database links as first application of the above.
197 ;; - New option `org-agenda-todo-list-sublevels' to turn off listing TODO
198 ;; entries that are sublevels of another TODO entry.
199 ;;
200 ;;
201 ;;; Code:
202
203 (eval-when-compile
204 (require 'cl)
205 (require 'calendar))
206 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
207 ;; the file noutline.el being loaded.
208 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
209 ;; We require noutline, which might be provided in outline.el
210 (require 'outline) (require 'noutline)
211 ;; Other stuff we need.
212 (require 'time-date)
213 (require 'easymenu)
214
215 ;;; Customization variables
216
217 (defvar org-version "4.44"
218 "The version number of the file org.el.")
219 (defun org-version ()
220 (interactive)
221 (message "Org-mode version %s" org-version))
222
223 ;; Compatibility constants
224 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
225 (defconst org-format-transports-properties-p
226 (let ((x "a"))
227 (add-text-properties 0 1 '(test t) x)
228 (get-text-property 0 'test (format "%s" x)))
229 "Does format transport text properties?")
230
231 (defgroup org nil
232 "Outline-based notes management and organizer."
233 :tag "Org"
234 :group 'outlines
235 :group 'hypermedia
236 :group 'calendar)
237
238 (defgroup org-startup nil
239 "Options concerning startup of Org-mode."
240 :tag "Org Startup"
241 :group 'org)
242
243 (defcustom org-startup-folded t
244 "Non-nil means, entering Org-mode will switch to OVERVIEW.
245 This can also be configured on a per-file basis by adding one of
246 the following lines anywhere in the buffer:
247
248 #+STARTUP: fold
249 #+STARTUP: nofold
250 #+STARTUP: content"
251 :group 'org-startup
252 :type '(choice
253 (const :tag "nofold: show all" nil)
254 (const :tag "fold: overview" t)
255 (const :tag "content: all headlines" content)))
256
257 (defcustom org-startup-truncated t
258 "Non-nil means, entering Org-mode will set `truncate-lines'.
259 This is useful since some lines containing links can be very long and
260 uninteresting. Also tables look terrible when wrapped."
261 :group 'org-startup
262 :type 'boolean)
263
264 (defcustom org-startup-align-all-tables nil
265 "Non-nil means, align all tables when visiting a file.
266 This is useful when the column width in tables is forced with <N> cookies
267 in table fields. Such tables will look correct only after the first re-align.
268 This can also be configured on a per-file basis by adding one of
269 the following lines anywhere in the buffer:
270 #+STARTUP: align
271 #+STARTUP: noalign"
272 :group 'org-startup
273 :type 'boolean)
274
275 (defcustom org-startup-with-deadline-check nil
276 "Non-nil means, entering Org-mode will run the deadline check.
277 This means, if you start editing an org file, you will get an
278 immediate reminder of any due deadlines.
279 This can also be configured on a per-file basis by adding one of
280 the following lines anywhere in the buffer:
281 #+STARTUP: dlcheck
282 #+STARTUP: nodlcheck"
283 :group 'org-startup
284 :type 'boolean)
285
286 (defcustom org-insert-mode-line-in-empty-file nil
287 "Non-nil means insert the first line setting Org-mode in empty files.
288 When the function `org-mode' is called interactively in an empty file, this
289 normally means that the file name does not automatically trigger Org-mode.
290 To ensure that the file will always be in Org-mode in the future, a
291 line enforcing Org-mode will be inserted into the buffer, if this option
292 has been set."
293 :group 'org-startup
294 :type 'boolean)
295
296 (defcustom org-CUA-compatible nil
297 "Non-nil means use alternative key bindings for S-<cursor movement>.
298 Org-mode used S-<cursor movement> for changing timestamps and priorities.
299 S-<cursor movement> is also used for example by `CUA-mode' to select text.
300 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
301 alternative bindings. Setting this variable to t will replace the following
302 keys both in Org-mode and in the Org-agenda buffer.
303
304 S-RET -> C-S-RET
305 S-up -> M-p
306 S-down -> M-n
307 S-left -> M--
308 S-right -> M-+
309
310 If you do not like the alternative keys, take a look at the variable
311 `org-disputed-keys'.
312
313 This option is only relevant at load-time of Org-mode. Changing it requires
314 a restart of Emacs to become effective."
315 :group 'org-startup
316 :type 'boolean)
317
318 (defvar org-disputed-keys
319 '((S-up [(shift up)] [(meta ?p)])
320 (S-down [(shift down)] [(meta ?n)])
321 (S-left [(shift left)] [(meta ?-)])
322 (S-right [(shift right)] [(meta ?+)])
323 (S-return [(shift return)] [(control shift return)]))
324 "Keys for which Org-mode and other modes compete.
325 This is an alist, cars are symbols for lookup, 1st element is the default key,
326 second element will be used when `org-CUA-compatible' is t.")
327
328 (defun org-key (key)
329 "Select a key according to `org-CUA-compatible'."
330 (nth (if org-CUA-compatible 2 1)
331 (or (assq key org-disputed-keys)
332 (error "Invalid Key %s in `org-key'" key))))
333
334 (defcustom org-ellipsis nil
335 "The ellipsis to use in the Org-mode outline.
336 When nil, just use the standard three dots. When a string, use that instead,
337 and just in Org-mode (which will then use its own display table).
338 Changing this requires executing `M-x org-mode' in a buffer to become
339 effective."
340 :group 'org-startup
341 :type '(choice (const :tag "Default" nil)
342 (string :tag "String" :value "...#")))
343
344 (defvar org-display-table nil
345 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
346
347 (defgroup org-keywords nil
348 "Keywords in Org-mode."
349 :tag "Org Keywords"
350 :group 'org)
351
352 (defcustom org-deadline-string "DEADLINE:"
353 "String to mark deadline entries.
354 A deadline is this string, followed by a time stamp. Should be a word,
355 terminated by a colon. You can insert a schedule keyword and
356 a timestamp with \\[org-deadline].
357 Changes become only effective after restarting Emacs."
358 :group 'org-keywords
359 :type 'string)
360
361 (defcustom org-scheduled-string "SCHEDULED:"
362 "String to mark scheduled TODO entries.
363 A schedule is this string, followed by a time stamp. Should be a word,
364 terminated by a colon. You can insert a schedule keyword and
365 a timestamp with \\[org-schedule].
366 Changes become only effective after restarting Emacs."
367 :group 'org-keywords
368 :type 'string)
369
370 (defcustom org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry."
372 :group 'org-keywords
373 :type 'string)
374
375 (defcustom org-clock-string "CLOCK:"
376 "String used as prefix for timestamps clocking work hours on an item."
377 :group 'org-keywords
378 :type 'string)
379
380 (defcustom org-comment-string "COMMENT"
381 "Entries starting with this keyword will never be exported.
382 An entry can be toggled between COMMENT and normal with
383 \\[org-toggle-comment].
384 Changes become only effective after restarting Emacs."
385 :group 'org-keywords
386 :type 'string)
387
388 (defcustom org-quote-string "QUOTE"
389 "Entries starting with this keyword will be exported in fixed-width font.
390 Quoting applies only to the text in the entry following the headline, and does
391 not extend beyond the next headline, even if that is lower level.
392 An entry can be toggled between QUOTE and normal with
393 \\[org-toggle-fixed-width-section]."
394 :group 'org-keywords
395 :type 'string)
396
397 (defgroup org-structure nil
398 "Options concerning the general structure of Org-mode files."
399 :tag "Org Structure"
400 :group 'org)
401
402 (defgroup org-cycle nil
403 "Options concerning visibility cycling in Org-mode."
404 :tag "Org Cycle"
405 :group 'org-structure)
406
407 (defcustom org-cycle-global-at-bob t
408 "Cycle globally if cursor is at beginning of buffer and not at a headline.
409 This makes it possible to do global cycling without having to use S-TAB or
410 C-u TAB. For this special case to work, the first line of the buffer
411 must not be a headline - it may be empty ot some other text. When used in
412 this way, `org-cycle-hook' is disables temporarily, to make sure the
413 cursor stays at the beginning of the buffer.
414 When this option is nil, don't do anything special at the beginning
415 of the buffer."
416 :group 'org-cycle
417 :type 'boolean)
418
419 (defcustom org-cycle-emulate-tab t
420 "Where should `org-cycle' emulate TAB.
421 nil Never
422 white Only in completely white lines
423 whitestart Only at the beginning of lines, before the first non-white char.
424 t Everywhere except in headlines
425 If TAB is used in a place where it does not emulate TAB, the current subtree
426 visibility is cycled."
427 :group 'org-cycle
428 :type '(choice (const :tag "Never" nil)
429 (const :tag "Only in completely white lines" white)
430 (const :tag "Before first char in a line" whitestart)
431 (const :tag "Everywhere except in headlines" t)
432 ))
433
434 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
435 org-optimize-window-after-visibility-change)
436 "Hook that is run after `org-cycle' has changed the buffer visibility.
437 The function(s) in this hook must accept a single argument which indicates
438 the new state that was set by the most recent `org-cycle' command. The
439 argument is a symbol. After a global state change, it can have the values
440 `overview', `content', or `all'. After a local state change, it can have
441 the values `folded', `children', or `subtree'."
442 :group 'org-cycle
443 :type 'hook)
444
445 (defgroup org-edit-structure nil
446 "Options concerning structure editing in Org-mode."
447 :tag "Org Edit Structure"
448 :group 'org-structure)
449
450 (defcustom org-odd-levels-only nil
451 "Non-nil means, skip even levels and only use odd levels for the outline.
452 This has the effect that two stars are being added/taken away in
453 promotion/demotion commands. It also influences how levels are
454 handled by the exporters.
455 Changing it requires restart of `font-lock-mode' to become effective
456 for fontification also in regions already fontified.
457 You may also set this on a per-file basis by adding one of the following
458 lines to the buffer:
459
460 #+STARTUP: odd
461 #+STARTUP: oddeven"
462 :group 'org-edit-structure
463 :group 'org-font-lock
464 :type 'boolean)
465
466 (defcustom org-adapt-indentation t
467 "Non-nil means, adapt indentation when promoting and demoting.
468 When this is set and the *entire* text in an entry is indented, the
469 indentation is increased by one space in a demotion command, and
470 decreased by one in a promotion command. If any line in the entry
471 body starts at column 0, indentation is not changed at all."
472 :group 'org-edit-structure
473 :type 'boolean)
474
475 (defcustom org-insert-heading-hook nil
476 "Hook being run after inserting a new heading."
477 :group 'org-edit-structure
478 :type 'boolean)
479
480 (defcustom org-enable-fixed-width-editor t
481 "Non-nil means, lines starting with \":\" are treated as fixed-width.
482 This currently only means, they are never auto-wrapped.
483 When nil, such lines will be treated like ordinary lines.
484 See also the QUOTE keyword."
485 :group 'org-edit-structure
486 :type 'boolean)
487
488 (defgroup org-sparse-trees nil
489 "Options concerning sparse trees in Org-mode."
490 :tag "Org Sparse Trees"
491 :group 'org-structure)
492
493 (defcustom org-highlight-sparse-tree-matches t
494 "Non-nil means, highlight all matches that define a sparse tree.
495 The highlights will automatically disappear the next time the buffer is
496 changed by an edit command."
497 :group 'org-sparse-trees
498 :type 'boolean)
499
500 (defcustom org-show-hierarchy-above t
501 "Non-nil means, show full hierarchy when showing a spot in the tree.
502 Turning this off makes sparse trees more compact, but also less clear."
503 :group 'org-sparse-trees
504 :type 'boolean)
505
506 (defcustom org-show-following-heading t
507 "Non-nil means, show heading following match in `org-occur'.
508 When doing an `org-occur' it is useful to show the headline which
509 follows the match, even if they do not match the regexp. This makes it
510 easier to edit directly inside the sparse tree. However, if you use
511 `org-occur' mainly as an overview, the following headlines are
512 unnecessary clutter."
513 :group 'org-sparse-trees
514 :type 'boolean)
515
516 (defcustom org-occur-hook '(org-first-headline-recenter)
517 "Hook that is run after `org-occur' has constructed a sparse tree.
518 This can be used to recenter the window to show as much of the structure
519 as possible."
520 :group 'org-sparse-trees
521 :type 'hook)
522
523 (defgroup org-plain-lists nil
524 "Options concerning plain lists in Org-mode."
525 :tag "Org Plain lists"
526 :group 'org-structure)
527
528 (defcustom org-cycle-include-plain-lists nil
529 "Non-nil means, include plain lists into visibility cycling.
530 This means that during cycling, plain list items will *temporarily* be
531 interpreted as outline headlines with a level given by 1000+i where i is the
532 indentation of the bullet. In all other operations, plain list items are
533 not seen as headlines. For example, you cannot assign a TODO keyword to
534 such an item."
535 :group 'org-plain-lists
536 :type 'boolean)
537
538
539 (defcustom org-plain-list-ordered-item-terminator t
540 "The character that makes a line with leading number an ordered list item.
541 Valid values are ?. and ?\). To get both terminators, use t. While
542 ?. may look nicer, it creates the danger that a line with leading
543 number may be incorrectly interpreted as an item. ?\) therefore is
544 the safe choice."
545 :group 'org-plain-lists
546 :type '(choice (const :tag "dot like in \"2.\"" ?.)
547 (const :tag "paren like in \"2)\"" ?\))
548 (const :tab "both" t)))
549
550 (defcustom org-auto-renumber-ordered-lists t
551 "Non-nil means, automatically renumber ordered plain lists.
552 Renumbering happens when the sequence have been changed with
553 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
554 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
555 :group 'org-plain-lists
556 :type 'boolean)
557
558 (defgroup org-archive nil
559 "Options concerning archiving in Org-mode."
560 :tag "Org Archive"
561 :group 'org-structure)
562
563 (defcustom org-archive-tag "ARCHIVE"
564 "The tag that marks a subtree as archived.
565 An archived subtree does not open during visibility cycling, and does
566 not contribute to the agenda listings."
567 :group 'org-archive
568 :group 'org-keywords
569 :type 'string)
570
571 (defcustom org-agenda-skip-archived-trees t
572 "Non-nil means, the agenda will skip any items located in archived trees.
573 An archived tree is a tree marked with the tag ARCHIVE."
574 :group 'org-archive
575 :group 'org-agenda-display
576 :type 'boolean)
577
578 (defcustom org-cycle-open-archived-trees nil
579 "Non-nil means, `org-cycle' will open archived trees.
580 An archived tree is a tree marked with the tag ARCHIVE.
581 When nil, archived trees will stay folded. You can still open them with
582 normal outline commands like `show-all', but not with the cycling commands."
583 :group 'org-archive
584 :group 'org-cycle
585 :type 'boolean)
586
587 (defcustom org-sparse-tree-open-archived-trees nil
588 "Non-nil means sparse tree construction shows matches in archived trees.
589 When nil, matches in these trees are highlighted, but the trees are kept in
590 collapsed state."
591 :group 'org-archive
592 :group 'org-sparse-trees
593 :type 'boolean)
594
595 (defcustom org-archive-location "%s_archive::"
596 "The location where subtrees should be archived.
597 This string consists of two parts, separated by a double-colon.
598
599 The first part is a file name - when omitted, archiving happens in the same
600 file. %s will be replaced by the current file name (without directory part).
601 Archiving to a different file is useful to keep archived entries from
602 contributing to the Org-mode Agenda.
603
604 The part after the double colon is a headline. The archived entries will be
605 filed under that headline. When omitted, the subtrees are simply filed away
606 at the end of the file, as top-level entries.
607
608 Here are a few examples:
609 \"%s_archive::\"
610 If the current file is Projects.org, archive in file
611 Projects.org_archive, as top-level trees. This is the default.
612
613 \"::* Archived Tasks\"
614 Archive in the current file, under the top-level headline
615 \"* Archived Tasks\".
616
617 \"~/org/archive.org::\"
618 Archive in file ~/org/archive.org (absolute path), as top-level trees.
619
620 \"basement::** Finished Tasks\"
621 Archive in file ./basement (relative path), as level 3 trees
622 below the level 2 heading \"** Finished Tasks\".
623
624 You may set this option on a per-file basis by adding to the buffer a
625 line like
626
627 #+ARCHIVE: basement::** Finished Tasks"
628 :group 'org-archive
629 :type 'string)
630
631 (defcustom org-archive-mark-done t
632 "Non-nil means, mark entries as DONE when they are moved to the archive file."
633 :group 'org-archive
634 :type 'boolean)
635
636 (defcustom org-archive-stamp-time t
637 "Non-nil means, add a time stamp to entries moved to an archive file.
638 The time stamp will be added directly after the TODO state keyword in the
639 first line, so it is probably best to use this in combinations with
640 `org-archive-mark-done'."
641 :group 'org-archive
642 :type 'boolean)
643
644 (defgroup org-table nil
645 "Options concerning tables in Org-mode."
646 :tag "Org Table"
647 :group 'org)
648
649 (defcustom org-enable-table-editor 'optimized
650 "Non-nil means, lines starting with \"|\" are handled by the table editor.
651 When nil, such lines will be treated like ordinary lines.
652
653 When equal to the symbol `optimized', the table editor will be optimized to
654 do the following:
655 - Use automatic overwrite mode in front of whitespace in table fields.
656 This make the structure of the table stay in tact as long as the edited
657 field does not exceed the column width.
658 - Minimize the number of realigns. Normally, the table is aligned each time
659 TAB or RET are pressed to move to another field. With optimization this
660 happens only if changes to a field might have changed the column width.
661 Optimization requires replacing the functions `self-insert-command',
662 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
663 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
664 very good at guessing when a re-align will be necessary, but you can always
665 force one with \\[org-ctrl-c-ctrl-c].
666
667 If you would like to use the optimized version in Org-mode, but the
668 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
669
670 This variable can be used to turn on and off the table editor during a session,
671 but in order to toggle optimization, a restart is required.
672
673 See also the variable `org-table-auto-blank-field'."
674 :group 'org-table
675 :type '(choice
676 (const :tag "off" nil)
677 (const :tag "on" t)
678 (const :tag "on, optimized" optimized)))
679
680 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
681 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
682 In the optimized version, the table editor takes over all simple keys that
683 normally just insert a character. In tables, the characters are inserted
684 in a way to minimize disturbing the table structure (i.e. in overwrite mode
685 for empty fields). Outside tables, the correct binding of the keys is
686 restored.
687
688 The default for this option is t if the optimized version is also used in
689 Org-mode. See the variable `org-enable-table-editor' for details. Changing
690 this variable requires a restart of Emacs to become effective."
691 :group 'org-table
692 :type 'boolean)
693
694 (defgroup org-table-settings nil
695 "Settings for tables in Org-mode."
696 :tag "Org Table Settings"
697 :group 'org-table)
698
699 (defcustom org-table-default-size "5x2"
700 "The default size for newly created tables, Columns x Rows."
701 :group 'org-table-settings
702 :type 'string)
703
704 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
705 "Regular expression for recognizing numbers in table columns.
706 If a table column contains mostly numbers, it will be aligned to the
707 right. If not, it will be aligned to the left.
708
709 The default value of this option is a regular expression which allows
710 anything which looks remotely like a number as used in scientific
711 context. For example, all of the following will be considered a
712 number:
713 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
714
715 Other options offered by the customize interface are more restrictive."
716 :group 'org-table-settings
717 :type '(choice
718 (const :tag "Positive Integers"
719 "^[0-9]+$")
720 (const :tag "Integers"
721 "^[-+]?[0-9]+$")
722 (const :tag "Floating Point Numbers"
723 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
724 (const :tag "Floating Point Number or Integer"
725 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
726 (const :tag "Exponential, Floating point, Integer"
727 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
728 (const :tag "Very General Number-Like"
729 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
730 (string :tag "Regexp:")))
731
732 (defcustom org-table-number-fraction 0.5
733 "Fraction of numbers in a column required to make the column align right.
734 In a column all non-white fields are considered. If at least this
735 fraction of fields is matched by `org-table-number-fraction',
736 alignment to the right border applies."
737 :group 'org-table-settings
738 :type 'number)
739
740 (defgroup org-table-editing nil
741 "Bahavior of tables during editing in Org-mode."
742 :tag "Org Table Editing"
743 :group 'org-table)
744
745 (defcustom org-table-automatic-realign t
746 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
747 When nil, aligning is only done with \\[org-table-align], or after column
748 removal/insertion."
749 :group 'org-table-editing
750 :type 'boolean)
751
752 (defcustom org-table-limit-column-width t ;kw
753 "Non-nil means, allow to limit the width of table columns with <N> fields."
754 :group 'org-table-editing
755 :type 'boolean)
756
757 (defcustom org-table-auto-blank-field t
758 "Non-nil means, automatically blank table field when starting to type into it.
759 This only happens when typing immediately after a field motion
760 command (TAB, S-TAB or RET).
761 Only relevant when `org-enable-table-editor' is equal to `optimized'."
762 :group 'org-table-editing
763 :type 'boolean)
764
765 (defcustom org-table-tab-jumps-over-hlines t
766 "Non-nil means, tab in the last column of a table with jump over a hline.
767 If a horizontal separator line is following the current line,
768 `org-table-next-field' can either create a new row before that line, or jump
769 over the line. When this option is nil, a new line will be created before
770 this line."
771 :group 'org-table-editing
772 :type 'boolean)
773
774 (defcustom org-table-tab-recognizes-table.el t
775 "Non-nil means, TAB will automatically notice a table.el table.
776 When it sees such a table, it moves point into it and - if necessary -
777 calls `table-recognize-table'."
778 :group 'org-table-editing
779 :type 'boolean)
780
781 (defgroup org-table-calculation nil
782 "Options concerning tables in Org-mode."
783 :tag "Org Table Calculation"
784 :group 'org-table)
785
786 (defcustom org-table-copy-increment t
787 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
788 :group 'org-table-calculation
789 :type 'boolean)
790
791 (defcustom org-calc-default-modes
792 '(calc-internal-prec 12
793 calc-float-format (float 5)
794 calc-angle-mode deg
795 calc-prefer-frac nil
796 calc-symbolic-mode nil
797 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
798 calc-display-working-message t
799 )
800 "List with Calc mode settings for use in calc-eval for table formulas.
801 The list must contain alternating symbols (Calc modes variables and values).
802 Don't remove any of the default settings, just change the values. Org-mode
803 relies on the variables to be present in the list."
804 :group 'org-table-calculation
805 :type 'plist)
806
807 (defcustom org-table-formula-evaluate-inline t
808 "Non-nil means, TAB and RET evaluate a formula in current table field.
809 If the current field starts with an equal sign, it is assumed to be a formula
810 which should be evaluated as described in the manual and in the documentation
811 string of the command `org-table-eval-formula'. This feature requires the
812 Emacs calc package.
813 When this variable is nil, formula calculation is only available through
814 the command \\[org-table-eval-formula]."
815 :group 'org-table-calculation
816 :type 'boolean)
817
818
819 (defcustom org-table-formula-use-constants t
820 "Non-nil means, interpret constants in formulas in tables.
821 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
822 by the value given in `org-table-formula-constants', or by a value obtained
823 from the `constants.el' package."
824 :group 'org-table-calculation
825 :type 'boolean)
826
827 (defcustom org-table-formula-constants nil
828 "Alist with constant names and values, for use in table formulas.
829 The car of each element is a name of a constant, without the `$' before it.
830 The cdr is the value as a string. For example, if you'd like to use the
831 speed of light in a formula, you would configure
832
833 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
834
835 and then use it in an equation like `$1*$c'."
836 :group 'org-table-calculation
837 :type '(repeat
838 (cons (string :tag "name")
839 (string :tag "value"))))
840
841 (defcustom org-table-formula-numbers-only nil
842 "Non-nil means, calculate only with numbers in table formulas.
843 Then all input fields will be converted to a number, and the result
844 must also be a number. When nil, calc's full potential is available
845 in table calculations, including symbolics etc."
846 :group 'org-table-calculation
847 :type 'boolean)
848
849 (defcustom org-table-allow-automatic-line-recalculation t
850 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
851 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
852 :group 'org-table-calculation
853 :type 'boolean)
854
855 (defgroup org-link nil
856 "Options concerning links in Org-mode."
857 :tag "Org Link"
858 :group 'org)
859
860 (defcustom org-descriptive-links t
861 "Non-nil means, hide link part and only show description of bracket links.
862 Bracket links are like [[link][descritpion]]. This variable sets the initial
863 state in new org-mode buffers. The setting can then be toggled on a
864 per-buffer basis from the Org->Hyperlinks menu."
865 :group 'org-link
866 :type 'boolean)
867
868 (defcustom org-link-style 'bracket
869 "The style of links to be inserted with \\[org-insert-link].
870 Possible values are:
871 bracket [[link][description]]. This is recommended
872 plain Description \\n link. The old way, no longer recommended."
873 :group 'org-link
874 :type '(choice
875 (const :tag "Bracket (recommended)" bracket)
876 (const :tag "Plain (no longer recommended)" plain)))
877
878 (defcustom org-link-format "%s"
879 "Default format for external, URL-like linkes in the buffer.
880 This is a format string for printf, %s will be replaced by the link text.
881 The recommended value is just \"%s\", since links will be protected by
882 enclosing them in double brackets. If you prefer plain links (see variable
883 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
884 additional URL: prefix, so the format would be \"<URL:%s>\"."
885 :group 'org-link
886 :type '(choice
887 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
888 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
889 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
890 (string :tag "Other" :value "<%s>")))
891
892 (defcustom org-link-file-path-type 'adaptive
893 "How the path name in file links should be stored.
894 Valid values are:
895
896 relative relative to the current directory, i.e. the directory of the file
897 into which the link is being inserted.
898 absolute absolute path, if possible with ~ for home directory.
899 noabbrev absolute path, no abbreviation of home directory.
900 adaptive Use relative path for files in the current directory and sub-
901 directories of it. For other files, use an absolute path."
902 :group 'org-link
903 :type '(choice
904 (const relative)
905 (const absolute)
906 (const noabbrev)
907 (const adaptive)))
908
909 (defcustom org-activate-links '(bracket angle plain radio tag date)
910 "Types of links that should be activated in Org-mode files.
911 This is a list of symbols, each leading to the activation of a certain link
912 type. In principle, it does not hurt to turn on most link types - there may
913 be a small gain when turning off unused link types. The types are:
914
915 bracket The recommended [[link][description]] or [[link]] links with hiding.
916 angular Links in angular brackes that may contain whitespace like
917 <bbdb:Carsten Dominik>.
918 plain Plain links in normal text, no whitespace, like http://google.com.
919 radio Text that is matched by a radio target, see manual for details.
920 tag Tag settings in a headline (link to tag search).
921 date Time stamps (link to calendar).
922 camel CamelCase words defining text searches.
923
924 Changing this variable requires a restart of Emacs to become effective."
925 :group 'org-link
926 :type '(set (const :tag "Double bracket links (new style)" bracket)
927 (const :tag "Angular bracket links (old style)" angular)
928 (const :tag "plain text links" plain)
929 (const :tag "Radio target matches" radio)
930 (const :tag "Tags" tag)
931 (const :tag "Timestamps" date)
932 (const :tag "CamelCase words" camel)))
933
934 (defgroup org-link-store nil
935 "Options concerning storing links in Org-mode"
936 :tag "Org Store Link"
937 :group 'org-link)
938
939 (defcustom org-context-in-file-links t
940 "Non-nil means, file links from `org-store-link' contain context.
941 A search string will be added to the file name with :: as separator and
942 used to find the context when the link is activated by the command
943 `org-open-at-point'.
944 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
945 negates this setting for the duration of the command."
946 :group 'org-link-store
947 :type 'boolean)
948
949 (defcustom org-file-link-context-use-camel-case nil
950 "Non-nil means, use CamelCase to store a search context in a file link.
951 When nil, the search string simply consists of the words of the string.
952 CamelCase is deprecated, and support for it may be dropped in the future."
953 :group 'org-link-store
954 :type 'boolean)
955
956 (defcustom org-keep-stored-link-after-insertion nil
957 "Non-nil means, keep link in list for entire session.
958
959 The command `org-store-link' adds a link pointing to the current
960 location to an internal list. These links accumulate during a session.
961 The command `org-insert-link' can be used to insert links into any
962 Org-mode file (offering completion for all stored links). When this
963 option is nil, every link which has been inserted once using \\[org-insert-link]
964 will be removed from the list, to make completing the unused links
965 more efficient."
966 :group 'org-link-store
967 :type 'boolean)
968
969 (defcustom org-usenet-links-prefer-google nil
970 "Non-nil means, `org-store-link' will create web links to Google groups.
971 When nil, Gnus will be used for such links.
972 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
973 negates this setting for the duration of the command."
974 :group 'org-link-store
975 :type 'boolean)
976
977 (defgroup org-link-follow nil
978 "Options concerning following links in Org-mode"
979 :tag "Org Follow Link"
980 :group 'org-link)
981
982 (defcustom org-tab-follows-link nil
983 "Non-nil means, on links TAB will follow the link.
984 Needs to be set before org.el is loaded."
985 :group 'org-link-follow
986 :type 'boolean)
987
988 (defcustom org-return-follows-link nil
989 "Non-nil means, on links RET will follow the link.
990 Needs to be set before org.el is loaded."
991 :group 'org-link-follow
992 :type 'boolean)
993
994 (defcustom org-mouse-1-follows-link t
995 "Non-nil means, mouse-1 on a link will follow the link.
996 A longer mouse click will still set point. Does not wortk on XEmacs.
997 Needs to be set before org.el is loaded."
998 :group 'org-link-follow
999 :type 'boolean)
1000
1001 (defcustom org-mark-ring-length 4
1002 "Number of different positions to be recorded in the ring
1003 Changing this requires a restart of Emacs to work correctly."
1004 :group 'org-link-follow
1005 :type 'interger)
1006
1007 (defcustom org-link-frame-setup
1008 '((vm . vm-visit-folder-other-frame)
1009 (gnus . gnus-other-frame)
1010 (file . find-file-other-window))
1011 "Setup the frame configuration for following links.
1012 When following a link with Emacs, it may often be useful to display
1013 this link in another window or frame. This variable can be used to
1014 set this up for the different types of links.
1015 For VM, use any of
1016 `vm-visit-folder'
1017 `vm-visit-folder-other-frame'
1018 For Gnus, use any of
1019 `gnus'
1020 `gnus-other-frame'
1021 For FILE, use any of
1022 `find-file'
1023 `find-file-other-window'
1024 `find-file-other-frame'
1025 For the calendar, use the variable `calendar-setup'.
1026 For BBDB, it is currently only possible to display the matches in
1027 another window."
1028 :group 'org-link-follow
1029 :type '(list
1030 (cons (const vm)
1031 (choice
1032 (const vm-visit-folder)
1033 (const vm-visit-folder-other-window)
1034 (const vm-visit-folder-other-frame)))
1035 (cons (const gnus)
1036 (choice
1037 (const gnus)
1038 (const gnus-other-frame)))
1039 (cons (const file)
1040 (choice
1041 (const find-file)
1042 (const find-file-other-window)
1043 (const find-file-other-frame)))))
1044
1045 (defcustom org-open-non-existing-files nil
1046 "Non-nil means, `org-open-file' will open non-existing file.
1047 When nil, an error will be generated."
1048 :group 'org-link-follow
1049 :type 'boolean)
1050
1051 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1052 "Non-nil means, ask for confirmation before executing shell links.
1053 Shell links can be dangerous, just thing about a link
1054
1055 [[shell:rm -rf ~/*][Google Search]]
1056
1057 This link would show up in your Org-mode document as \"Google Search\"
1058 but really it would remove your entire home directory.
1059 Therefore I *definitely* advise against setting this variable to nil.
1060 Just change it to `y-or-n-p' of you want to confirm with a single key press
1061 rather than having to type \"yes\"."
1062 :group 'org-link-follow
1063 :type '(choice
1064 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1065 (const :tag "with y-or-n (faster)" y-or-n-p)
1066 (const :tag "no confirmation (dangerous)" nil)))
1067
1068 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1069 "Non-nil means, ask for confirmation before executing elisp links.
1070 Elisp links can be dangerous, just thing about a link
1071
1072 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1073
1074 This link would show up in your Org-mode document as \"Google Search\"
1075 but really it would remove your entire home directory.
1076 Therefore I *definitely* advise against setting this variable to nil.
1077 Just change it to `y-or-n-p' of you want to confirm with a single key press
1078 rather than having to type \"yes\"."
1079 :group 'org-link-follow
1080 :type '(choice
1081 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1082 (const :tag "with y-or-n (faster)" y-or-n-p)
1083 (const :tag "no confirmation (dangerous)" nil)))
1084
1085 (defconst org-file-apps-defaults-gnu
1086 '((remote . emacs)
1087 (t . mailcap))
1088 "Default file applications on a UNIX or GNU/Linux system.
1089 See `org-file-apps'.")
1090
1091 (defconst org-file-apps-defaults-macosx
1092 '((remote . emacs)
1093 (t . "open %s")
1094 ("ps" . "gv %s")
1095 ("ps.gz" . "gv %s")
1096 ("eps" . "gv %s")
1097 ("eps.gz" . "gv %s")
1098 ("dvi" . "xdvi %s")
1099 ("fig" . "xfig %s"))
1100 "Default file applications on a MacOS X system.
1101 The system \"open\" is known as a default, but we use X11 applications
1102 for some files for which the OS does not have a good default.
1103 See `org-file-apps'.")
1104
1105 (defconst org-file-apps-defaults-windowsnt
1106 (list
1107 '(remote . emacs)
1108 (cons t
1109 (list (if (featurep 'xemacs)
1110 'mswindows-shell-execute
1111 'w32-shell-execute)
1112 "open" 'file)))
1113 "Default file applications on a Windows NT system.
1114 The system \"open\" is used for most files.
1115 See `org-file-apps'.")
1116
1117 (defcustom org-file-apps
1118 '(
1119 ("txt" . emacs)
1120 ("tex" . emacs)
1121 ("ltx" . emacs)
1122 ("org" . emacs)
1123 ("el" . emacs)
1124 ("bib" . emacs)
1125 )
1126 "External applications for opening `file:path' items in a document.
1127 Org-mode uses system defaults for different file types, but
1128 you can use this variable to set the application for a given file
1129 extension. The entries in this list are cons cells where the car identifies
1130 files and the cdr the corresponding command. Possible values for the
1131 file identifier are
1132 \"ext\" A string identifying an extension
1133 `directory' Matches a directory
1134 `remote' Matches a remote file, accessible through tramp or efs.
1135 Remote files most likely should be visited through emacs
1136 because external applications cannot handle such paths.
1137 t Default for all remaining files
1138
1139 Possible values for the command are:
1140 `emacs' The file will be visited by the current Emacs process.
1141 `default' Use the default application for this file type.
1142 string A command to be executed by a shell; %s will be replaced
1143 by the path to the file.
1144 sexp A Lisp form which will be evaluated. The file path will
1145 be available in the Lisp variable `file'.
1146 For more examples, see the system specific constants
1147 `org-file-apps-defaults-macosx'
1148 `org-file-apps-defaults-windowsnt'
1149 `org-file-apps-defaults-gnu'."
1150 :group 'org-link-follow
1151 :type '(repeat
1152 (cons (choice :value ""
1153 (string :tag "Extension")
1154 (const :tag "Default for unrecognized files" t)
1155 (const :tag "Remote file" remote)
1156 (const :tag "Links to a directory" directory))
1157 (choice :value ""
1158 (const :tag "Visit with Emacs" emacs)
1159 (const :tag "Use system default" default)
1160 (string :tag "Command")
1161 (sexp :tag "Lisp form")))))
1162
1163 (defcustom org-mhe-search-all-folders nil
1164 "Non-nil means, that the search for the mh-message will be extended to
1165 all folders if the message cannot be found in the folder given in the link.
1166 Searching all folders is very effective with one of the search engines
1167 supported by MH-E, but will be slow with pick."
1168 :group 'org-link-follow
1169 :type 'boolean)
1170
1171 (defgroup org-remember nil
1172 "Options concerning interaction with remember.el."
1173 :tag "Org Remember"
1174 :group 'org)
1175
1176 (defcustom org-directory "~/org"
1177 "Directory with org files.
1178 This directory will be used as default to prompt for org files.
1179 Used by the hooks for remember.el."
1180 :group 'org-remember
1181 :type 'directory)
1182
1183 (defcustom org-default-notes-file "~/.notes"
1184 "Default target for storing notes.
1185 Used by the hooks for remember.el. This can be a string, or nil to mean
1186 the value of `remember-data-file'."
1187 :group 'org-remember
1188 :type '(choice
1189 (const :tag "Default from remember-data-file" nil)
1190 file))
1191
1192 (defcustom org-remember-templates nil
1193 "Templates for the creation of remember buffers.
1194 When nil, just let remember make the buffer.
1195 When not nil, this is a list of 3-element lists. In each entry, the first
1196 element is a character, a unique key to select this template.
1197 The second element is the template. The third element is optional and can
1198 specify a destination file for remember items created with this template.
1199 The default file is given by `org-default-notes-file'.
1200
1201 The template specifies the structure of the remember buffer. It should have
1202 a first line starting with a star, to act as the org-mode headline.
1203 Furthermore, the following %-escapes will be replaced with content:
1204 %t time stamp, date only
1205 %T time stamp with date and time
1206 %u inactive time stamp, date only
1207 %U inactive time stamp with date and time
1208 %n user name
1209 %a annotation, normally the link created with org-store-link
1210 %i initial content, the region when remember is called with C-u.
1211 If %i is indented, the entire inserted text will be indented as well.
1212 %? This will be removed, and the cursor placed at this position."
1213 :group 'org-remember
1214 :type '(repeat :tag "enabled"
1215 (list :value (?a "\n" nil)
1216 (character :tag "Selection Key")
1217 (string :tag "Template")
1218 (file :tag "Destination file (optional)"))))
1219
1220 (defcustom org-reverse-note-order nil
1221 "Non-nil means, store new notes at the beginning of a file or entry.
1222 When nil, new notes will be filed to the end of a file or entry."
1223 :group 'org-remember
1224 :type '(choice
1225 (const :tag "Reverse always" t)
1226 (const :tag "Reverse never" nil)
1227 (repeat :tag "By file name regexp"
1228 (cons regexp boolean))))
1229
1230 (defgroup org-todo nil
1231 "Options concerning TODO items in Org-mode."
1232 :tag "Org TODO"
1233 :group 'org)
1234
1235 (defcustom org-todo-keywords '("TODO" "DONE")
1236 "List of TODO entry keywords.
1237 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1238 considered to mean that the entry is \"done\". All the other mean that
1239 action is required, and will make the entry show up in todo lists, diaries
1240 etc.
1241 The command \\[org-todo] cycles an entry through these states, and an
1242 additional state where no keyword is present. For details about this
1243 cycling, see also the variable `org-todo-interpretation'
1244 Changes become only effective after restarting Emacs."
1245 :group 'org-todo
1246 :group 'org-keywords
1247 :type '(repeat (string :tag "Keyword")))
1248
1249 (defcustom org-todo-interpretation 'sequence
1250 "Controls how TODO keywords are interpreted.
1251 This variable is only relevant if `org-todo-keywords' contains more than two
1252 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1253
1254 When `sequence', \\[org-todo] will always switch to the next state in the
1255 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1256 to state when executed several times in direct succession. Otherwise, it
1257 switches directly to DONE from any state.
1258 See the manual for more information."
1259 :group 'org-todo
1260 :group 'org-keywords
1261 :type '(choice (const sequence)
1262 (const type)))
1263
1264 (defcustom org-after-todo-state-change-hook nil
1265 "Hook which is run after the state of a TODO item was changed.
1266 The new state (a string with a TODO keyword, or nil) is available in the
1267 Lisp variable `state'."
1268 :group 'org-todo
1269 :type 'hook)
1270
1271 (defcustom org-log-done nil
1272 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1273 When the state of an entry is changed from nothing to TODO, remove a previous
1274 closing date.
1275 This can also be configured on a per-file basis by adding one of
1276 the following lines anywhere in the buffer:
1277
1278 #+STARTUP: logging
1279 #+STARTUP: nologging"
1280 :group 'org-todo
1281 :type 'boolean)
1282
1283 (defgroup org-priorities nil
1284 "Priorities in Org-mode."
1285 :tag "Org Priorities"
1286 :group 'org-todo)
1287
1288 (defcustom org-default-priority ?B
1289 "The default priority of TODO items.
1290 This is the priority an item get if no explicit priority is given."
1291 :group 'org-priorities
1292 :type 'character)
1293
1294 (defcustom org-lowest-priority ?C
1295 "The lowest priority of TODO items. A character like ?A, ?B etc."
1296 :group 'org-priorities
1297 :type 'character)
1298
1299 (defgroup org-time nil
1300 "Options concerning time stamps and deadlines in Org-mode."
1301 :tag "Org Time"
1302 :group 'org)
1303
1304 (defcustom org-insert-labeled-timestamps-at-point nil
1305 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1306 When nil, these labeled time stamps are forces into the second line of an
1307 entry, just after the headline. When scheduling from the global TODO list,
1308 the time stamp will always be forced into the second line."
1309 :group 'org-time
1310 :type 'boolean)
1311
1312 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1313 "Formats for `format-time-string' which are used for time stamps.
1314 It is not recommended to change this constant.")
1315
1316 (defcustom org-time-stamp-rounding-minutes 0
1317 "Number of minutes to round time stamps to upon insertion.
1318 When zero, insert the time unmodified. Useful rounding numbers
1319 should be factors of 60, so for example 5, 10, 15.
1320 When this is not zero, you can still force an exact time-stamp by using
1321 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1322 :group 'org-time
1323 :type 'integer)
1324
1325 (defcustom org-deadline-warning-days 30
1326 "No. of days before expiration during which a deadline becomes active.
1327 This variable governs the display in the org file."
1328 :group 'org-time
1329 :type 'number)
1330
1331 (defcustom org-popup-calendar-for-date-prompt t
1332 "Non-nil means, pop up a calendar when prompting for a date.
1333 In the calendar, the date can be selected with mouse-1. However, the
1334 minibuffer will also be active, and you can simply enter the date as well.
1335 When nil, only the minibuffer will be available."
1336 :group 'org-time
1337 :type 'boolean)
1338
1339 (defcustom org-calendar-follow-timestamp-change t
1340 "Non-nil means, make the calendar window follow timestamp changes.
1341 When a timestamp is modified and the calendar window is visible, it will be
1342 moved to the new date."
1343 :group 'org-time
1344 :type 'boolean)
1345
1346 (defgroup org-tags nil
1347 "Options concerning tags in Org-mode."
1348 :tag "Org Tags"
1349 :group 'org)
1350
1351 (defcustom org-tag-alist nil
1352 "List of tags allowed in Org-mode files.
1353 When this list is nil, Org-mode will base TAG input on what is already in the
1354 buffer.
1355 The value of this variable is an alist, the car may be (and should) be a
1356 character that is used to select that tag through the fast-tag-selection
1357 interface. See the manual for details."
1358 :group 'org-tags
1359 :type '(repeat
1360 (choice
1361 (cons (string :tag "Tag name")
1362 (character :tag "Access char"))
1363 (const :tag "Start radio group" (:startgroup))
1364 (const :tag "End radio group" (:endgroup)))))
1365
1366 (defcustom org-use-fast-tag-selection 'auto
1367 "Non-nil means, use fast tag selection scheme.
1368 This is a special interface to select and deselect tags with single keys.
1369 When nil, fast selection is never used.
1370 When the symbol `auto', fast selection is used if and only if selection
1371 characters for tags have been configured, either through the variable
1372 `org-tag-alist' or through a #+TAGS line in the buffer.
1373 When t, fast selection is always used and selection keys are assigned
1374 automatically if necessary."
1375 :group 'org-tags
1376 :type '(choice
1377 (const :tag "Always" t)
1378 (const :tag "Never" nil)
1379 (const :tag "When selection characters are configured" 'auto)))
1380
1381 (defcustom org-tags-column 48
1382 "The column to which tags should be indented in a headline.
1383 If this number is positive, it specifies the column. If it is negative,
1384 it means that the tags should be flushright to that column. For example,
1385 -79 works well for a normal 80 character screen."
1386 :group 'org-tags
1387 :type 'integer)
1388
1389 (defcustom org-auto-align-tags t
1390 "Non-nil means, realign tags after pro/demotion of TODO state change.
1391 These operations change the length of a headline and therefore shift
1392 the tags around. With this options turned on, after each such operation
1393 the tags are again aligned to `org-tags-column'."
1394 :group 'org-tags
1395 :type 'boolean)
1396
1397 (defcustom org-use-tag-inheritance t
1398 "Non-nil means, tags in levels apply also for sublevels.
1399 When nil, only the tags directly given in a specific line apply there.
1400 If you turn off this option, you very likely want to turn on the
1401 companion option `org-tags-match-list-sublevels'."
1402 :group 'org-tags
1403 :type 'boolean)
1404
1405 (defcustom org-tags-match-list-sublevels nil
1406 "Non-nil means list also sublevels of headlines matching tag search.
1407 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1408 the sublevels of a headline matching a tag search often also match
1409 the same search. Listing all of them can create very long lists.
1410 Setting this variable to nil causes subtrees of a match to be skipped.
1411 This option is off by default, because inheritance in on. If you turn
1412 inheritance off, you very likely want to turn this option on.
1413
1414 As a special case, if the tag search is restricted to TODO items, the
1415 value of this variable is ignored and sublevels are always checked, to
1416 make sure all corresponding TODO items find their way into the list."
1417 :group 'org-tags
1418 :type 'boolean)
1419
1420 (defvar org-tags-history nil
1421 "History of minibuffer reads for tags.")
1422 (defvar org-last-tags-completion-table nil
1423 "The last used completion table for tags.")
1424
1425 (defgroup org-agenda nil
1426 "Options concerning agenda display Org-mode."
1427 :tag "Org Agenda"
1428 :group 'org)
1429
1430 (defvar org-category nil
1431 "Variable used by org files to set a category for agenda display.
1432 Such files should use a file variable to set it, for example
1433
1434 -*- mode: org; org-category: \"ELisp\"
1435
1436 or contain a special line
1437
1438 #+CATEGORY: ELisp
1439
1440 If the file does not specify a category, then file's base name
1441 is used instead.")
1442 (make-variable-buffer-local 'org-category)
1443
1444 (defcustom org-agenda-files nil
1445 "The files to be used for agenda display.
1446 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1447 \\[org-remove-file]. You can also use customize to edit the list.
1448
1449 If the value of the variable is not a list but a single file name, then
1450 the list of agenda files is actually stored and maintained in that file, one
1451 agenda file per line."
1452 :group 'org-agenda
1453 :type '(choice
1454 (repeat :tag "List of files" file)
1455 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1456
1457 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1458 "Custom commands for the agenda.
1459 These commands will be offered on the splash screen displayed by the
1460 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1461
1462 key The key (a single char as a string) to be associated with the command.
1463 type The command type, any of the following symbols:
1464 todo Entries with a specific TODO keyword, in all agenda files.
1465 tags Tags match in all agenda files.
1466 tags-todo Tags match in all agenda files, TODO entries only.
1467 todo-tree Sparse tree of specific TODO keyword in *current* file.
1468 tags-tree Sparse tree with all tags matches in *current* file.
1469 occur-tree Occur sparse tree for current file.
1470 match What to search for:
1471 - a single keyword for TODO keyword searches
1472 - a tags match expression for tags searches
1473 - a regular expression for occur searches"
1474 :group 'org-agenda
1475 :type '(repeat
1476 (list (string :tag "Key")
1477 (choice :tag "Type"
1478 (const :tag "Tags search in all agenda files" tags)
1479 (const :tag "Tags search of TODO entries, all agenda files" tags-todo)
1480 (const :tag "TODO keyword search in all agenda files" todo)
1481 (const :tag "Tags sparse tree in current buffer" tags-tree)
1482 (const :tag "TODO keyword tree in current buffer" todo-tree)
1483 (const :tag "Occur tree in current buffer" occur-tree))
1484 (string :tag "Match"))))
1485
1486 (defcustom org-agenda-todo-list-sublevels t
1487 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1488 When nil, the sublevels of a TODO entry are not checked, resulting in
1489 potentially much shorter TODO lists."
1490 :group 'org-agenda
1491 :group 'org-todo
1492 :type 'boolean)
1493
1494 (defcustom org-agenda-todo-ignore-scheduled nil
1495 "Non-nil means, don't show scheduled entries in the global todo list.
1496 The idea behind this is that by scheduling it, you have already taken care
1497 of this item."
1498 :group 'org-agenda
1499 :group 'org-todo
1500 :type 'boolean)
1501
1502 (defcustom org-agenda-include-all-todo nil
1503 "Non-nil means, the agenda will always contain all TODO entries.
1504 When nil, date-less entries will only be shown if `org-agenda' is called
1505 with a prefix argument.
1506 When non-nil, the TODO entries will be listed at the top of the agenda, before
1507 the entries for specific days."
1508 :group 'org-agenda
1509 :type 'boolean)
1510
1511 (defcustom org-agenda-include-diary nil
1512 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1513 :group 'org-agenda
1514 :type 'boolean)
1515
1516 (defcustom org-calendar-to-agenda-key [?c]
1517 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1518 The command `org-calendar-goto-agenda' will be bound to this key. The
1519 default is the character `c' because then `c' can be used to switch back and
1520 forth between agenda and calendar."
1521 :group 'org-agenda
1522 :type 'sexp)
1523
1524 (defgroup org-agenda-setup nil
1525 "Options concerning setting up the Agenda window in Org Mode."
1526 :tag "Org Agenda Window Setup"
1527 :group 'org-agenda)
1528
1529 (defcustom org-agenda-mouse-1-follows-link nil
1530 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1531 A longer mouse click will still set point. Does not wortk on XEmacs.
1532 Needs to be set before org.el is loaded."
1533 :group 'org-agenda-setup
1534 :type 'boolean)
1535
1536 (defcustom org-agenda-start-with-follow-mode nil
1537 "The initial value of follwo-mode in a newly created agenda window."
1538 :group 'org-agenda-setup
1539 :type 'boolean)
1540
1541 (defcustom org-select-agenda-window t
1542 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1543 When nil, cursor will remain in the current window."
1544 :group 'org-agenda-setup
1545 :type 'boolean)
1546
1547 (defcustom org-fit-agenda-window t
1548 "Non-nil means, change window size of agenda to fit content."
1549 :group 'org-agenda-setup
1550 :type 'boolean)
1551
1552 (defgroup org-agenda-display nil
1553 "Options concerning what to display initially in Agenda."
1554 :tag "Org Agenda Display"
1555 :group 'org-agenda)
1556
1557 (defcustom org-agenda-show-all-dates t
1558 "Non-nil means, `org-agenda' shows every day in the selected range.
1559 When nil, only the days which actually have entries are shown."
1560 :group 'org-agenda-display
1561 :type 'boolean)
1562
1563 (defcustom org-agenda-start-on-weekday 1
1564 "Non-nil means, start the overview always on the specified weekday.
1565 0 denotes Sunday, 1 denotes Monday etc.
1566 When nil, always start on the current day."
1567 :group 'org-agenda-display
1568 :type '(choice (const :tag "Today" nil)
1569 (number :tag "Weekday No.")))
1570
1571 (defcustom org-agenda-ndays 7
1572 "Number of days to include in overview display.
1573 Should be 1 or 7."
1574 :group 'org-agenda-display
1575 :type 'number)
1576
1577 (defcustom org-agenda-use-time-grid t
1578 "Non-nil means, show a time grid in the agenda schedule.
1579 A time grid is a set of lines for specific times (like every two hours between
1580 8:00 and 20:00). The items scheduled for a day at specific times are
1581 sorted in between these lines.
1582 For details about when the grid will be shown, and what it will look like, see
1583 the variable `org-agenda-time-grid'."
1584 :group 'org-agenda-display
1585 :type 'boolean)
1586
1587 (defcustom org-agenda-time-grid
1588 '((daily today require-timed)
1589 "----------------"
1590 (800 1000 1200 1400 1600 1800 2000))
1591
1592 "The settings for time grid for agenda display.
1593 This is a list of three items. The first item is again a list. It contains
1594 symbols specifying conditions when the grid should be displayed:
1595
1596 daily if the agenda shows a single day
1597 weekly if the agenda shows an entire week
1598 today show grid on current date, independent of daily/weekly display
1599 require-timed show grid only if at least on item has a time specification
1600
1601 The second item is a string which will be places behing the grid time.
1602
1603 The third item is a list of integers, indicating the times that should have
1604 a grid line."
1605 :group 'org-agenda-display
1606 :type
1607 '(list
1608 (set :greedy t :tag "Grid Display Options"
1609 (const :tag "Show grid in single day agenda display" daily)
1610 (const :tag "Show grid in weekly agenda display" weekly)
1611 (const :tag "Always show grid for today" today)
1612 (const :tag "Show grid only if any timed entries are present"
1613 require-timed)
1614 (const :tag "Skip grid times already present in an entry"
1615 remove-match))
1616 (string :tag "Grid String")
1617 (repeat :tag "Grid Times" (integer :tag "Time"))))
1618
1619 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1620 "Sorting structure for the agenda items of a single day.
1621 This is a list of symbols which will be used in sequence to determine
1622 if an entry should be listed before another entry. The following
1623 symbols are recognized:
1624
1625 time-up Put entries with time-of-day indications first, early first
1626 time-down Put entries with time-of-day indications first, late first
1627 category-keep Keep the default order of categories, corresponding to the
1628 sequence in `org-agenda-files'.
1629 category-up Sort alphabetically by category, A-Z.
1630 category-down Sort alphabetically by category, Z-A.
1631 priority-up Sort numerically by priority, high priority last.
1632 priority-down Sort numerically by priority, high priority first.
1633
1634 The different possibilities will be tried in sequence, and testing stops
1635 if one comparison returns a \"not-equal\". For example, the default
1636 '(time-up category-keep priority-down)
1637 means: Pull out all entries having a specified time of day and sort them,
1638 in order to make a time schedule for the current day the first thing in the
1639 agenda listing for the day. Of the entries without a time indication, keep
1640 the grouped in categories, don't sort the categories, but keep them in
1641 the sequence given in `org-agenda-files'. Within each category sort by
1642 priority.
1643
1644 Leaving out `category-keep' would mean that items will be sorted across
1645 categories by priority."
1646 :group 'org-agenda-display
1647 :type '(repeat
1648 (choice
1649 (const time-up)
1650 (const time-down)
1651 (const category-keep)
1652 (const category-up)
1653 (const category-down)
1654 (const priority-up)
1655 (const priority-down))))
1656
1657 (defcustom org-sort-agenda-notime-is-late t
1658 "Non-nil means, items without time are considered late.
1659 This is only relevant for sorting. When t, items which have no explicit
1660 time like 15:30 will be considered as 99:01, i.e. later than any items which
1661 do have a time. When nil, the default time is before 0:00. You can use this
1662 option to decide if the schedule for today should come before or after timeless
1663 agenda entries."
1664 :group 'org-agenda-display
1665 :type 'boolean)
1666
1667
1668 (defgroup org-agenda-prefix nil
1669 "Options concerning the entry prefix in the Org-mode agenda display."
1670 :tag "Org Agenda Prefix"
1671 :group 'org-agenda)
1672
1673 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1674 "Format specification for the prefix of items in the agenda buffer.
1675 This format works similar to a printf format, with the following meaning:
1676
1677 %c the category of the item, \"Diary\" for entries from the diary, or
1678 as given by the CATEGORY keyword or derived from the file name.
1679 %T the first tag of the item.
1680 %t the time-of-day specification if one applies to the entry, in the
1681 format HH:MM
1682 %s Scheduling/Deadline information, a short string
1683
1684 All specifiers work basically like the standard `%s' of printf, but may
1685 contain two additional characters: A question mark just after the `%' and
1686 a whitespace/punctuation character just before the final letter.
1687
1688 If the first character after `%' is a question mark, the entire field
1689 will only be included if the corresponding value applies to the
1690 current entry. This is useful for fields which should have fixed
1691 width when present, but zero width when absent. For example,
1692 \"%?-12t\" will result in a 12 character time field if a time of the
1693 day is specified, but will completely disappear in entries which do
1694 not contain a time.
1695
1696 If there is punctuation or whitespace character just before the final
1697 format letter, this character will be appended to the field value if
1698 the value is not empty. For example, the format \"%-12:c\" leads to
1699 \"Diary: \" if the category is \"Diary\". If the category were be
1700 empty, no additional colon would be interted.
1701
1702 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1703 - Indent the line with two space characters
1704 - Give the category in a 12 chars wide field, padded with whitespace on
1705 the right (because of `-'). Append a colon if there is a category
1706 (because of `:').
1707 - If there is a time-of-day, put it into a 12 chars wide field. If no
1708 time, don't put in an empty field, just skip it (because of '?').
1709 - Finally, put the scheduling information and append a whitespace.
1710
1711 As another example, if you don't want the time-of-day of entries in
1712 the prefix, you could use:
1713
1714 (setq org-agenda-prefix-format \" %-11:c% s\")
1715
1716 See also the variables `org-agenda-remove-times-when-in-prefix' and
1717 `org-agenda-remove-tags-when-in-prefix'."
1718 :type 'string
1719 :group 'org-agenda-prefix)
1720
1721 (defvar org-prefix-format-compiled nil
1722 "The compiled version of the most recently used prefix format.
1723 Depending on which command was used last, this may be the compiled version
1724 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1725
1726 (defcustom org-agenda-remove-times-when-in-prefix t
1727 "Non-nil means, remove duplicate time specifications in agenda items.
1728 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1729 time-of-day specification in a headline or diary entry is extracted and
1730 placed into the prefix. If this option is non-nil, the original specification
1731 \(a timestamp or -range, or just a plain time(range) specification like
1732 11:30-4pm) will be removed for agenda display. This makes the agenda less
1733 cluttered.
1734 The option can be t or nil. It may also be the symbol `beg', indicating
1735 that the time should only be removed what it is located at the beginning of
1736 the headline/diary entry."
1737 :group 'org-agenda-prefix
1738 :type '(choice
1739 (const :tag "Always" t)
1740 (const :tag "Never" nil)
1741 (const :tag "When at beginning of entry" beg)))
1742
1743 (defcustom org-agenda-remove-tags-when-in-prefix nil
1744 "Non-nil means, remove the tags from the headline copy in the agenda.
1745 When this is the symbol `prefix', only remove tags when
1746 `org-agenda-prefix-format' contains a `%T' specifier."
1747 :group 'org-agenda-prefix
1748 :type '(choice
1749 (const :tag "Always" t)
1750 (const :tag "Never" nil)
1751 (const :tag "When prefix format contains %T" prefix)))
1752
1753 (defgroup org-agenda-timeline nil
1754 "Options concerning the timeline buffer in Org Mode."
1755 :tag "Org Agenda Timeline"
1756 :group 'org-agenda)
1757
1758 (defcustom org-timeline-prefix-format " % s"
1759 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1760 :type 'string
1761 :group 'org-agenda-timeline)
1762
1763 (defcustom org-select-timeline-window t
1764 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1765 When nil, cursor will remain in the current window."
1766 :group 'org-agenda-timeline
1767 :type 'boolean)
1768
1769 (defcustom org-timeline-show-empty-dates 3
1770 "Non-nil means, `org-timeline' also shows dates without an entry.
1771 When nil, only the days which actually have entries are shown.
1772 When t, all days between the first and the last date are shown.
1773 When an integer, show also empty dates, but if there is a gap of more than
1774 N days, just insert a special line indicating the size of the gap."
1775 :group 'org-agenda-timeline
1776 :type '(choice
1777 (const :tag "None" nil)
1778 (const :tag "All" t)
1779 (number :tag "at most")))
1780
1781 (defgroup org-latex nil
1782 "Options for embedding LaTeX code into Org-mode"
1783 :tag "Org LaTeX"
1784 :group 'org)
1785
1786 (defcustom org-format-latex-options
1787 '(:foreground "Black" :background "Transparent" :scale 1.0
1788 :matchers ("begin" "$" "$$" "\\(" "\\["))
1789 "Options for creating images from LaTeX fragments.
1790 This is a property list with the following properties:
1791 :foreground the foreground color, for example \"Black\".
1792 :background the background color, or \"Transparent\".
1793 :scale a scaling factor for the size of the images
1794 :matchers a list indicating which matchers should be used to
1795 find LaTeX fragments. Valid members of this list are:
1796 \"begin\" find environments
1797 \"$\" find math expressions surrounded by $...$
1798 \"$$\" find math expressions surrounded by $$....$$
1799 \"\\(\" find math expressions surrounded by \\(...\\)
1800 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1801 :group 'org-latex
1802 :type 'plist)
1803
1804 (defgroup org-export nil
1805 "Options for exporting org-listings."
1806 :tag "Org Export"
1807 :group 'org)
1808
1809 (defgroup org-export-general nil
1810 "General options for exporting Org-mode files."
1811 :tag "Org Export General"
1812 :group 'org-export)
1813
1814 (defcustom org-export-publishing-directory "."
1815 "Path to the location where exported files should be located.
1816 This path may be relative to the directory where the Org-mode file lives.
1817 The default is to put them into the same directory as the Org-mode file.
1818 The variable may also be an alist with export types `:html', `:ascii',
1819 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1820 is relative, it is interpreted relative to the directory where the exported
1821 Org-mode files lives."
1822 :group 'org-export-general
1823 :type '(choice
1824 (directory)
1825 (repeat
1826 (cons
1827 (choice :tag "Type"
1828 (const :html) (const :ascii) (const :ical) (const :xoxo))
1829 (directory)))))
1830
1831 (defcustom org-export-language-setup
1832 '(("en" "Author" "Date" "Table of Contents")
1833 ("cs" "Autor" "Datum" "Obsah")
1834 ("da" "Ophavsmand" "Dato" "Indhold")
1835 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1836 ("es" "Autor" "Fecha" "\xccndice")
1837 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1838 ("it" "Autore" "Data" "Indice")
1839 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1840 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1841 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1842 "Terms used in export text, translated to different languages.
1843 Use the variable `org-export-default-language' to set the language,
1844 or use the +OPTION lines for a per-file setting."
1845 :group 'org-export-general
1846 :type '(repeat
1847 (list
1848 (string :tag "HTML language tag")
1849 (string :tag "Author")
1850 (string :tag "Date")
1851 (string :tag "Table of Contents"))))
1852
1853 (defcustom org-export-default-language "en"
1854 "The default language of HTML export, as a string.
1855 This should have an association in `org-export-language-setup'."
1856 :group 'org-export-general
1857 :type 'string)
1858
1859 (defcustom org-export-headline-levels 3
1860 "The last level which is still exported as a headline.
1861 Inferior levels will produce itemize lists when exported.
1862 Note that a numeric prefix argument to an exporter function overrides
1863 this setting.
1864
1865 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1866 :group 'org-export-general
1867 :type 'number)
1868
1869 (defcustom org-export-with-section-numbers t
1870 "Non-nil means, add section numbers to headlines when exporting.
1871
1872 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1873 :group 'org-export-general
1874 :type 'boolean)
1875
1876 (defcustom org-export-with-toc t
1877 "Non-nil means, create a table of contents in exported files.
1878 The TOC contains headlines with levels up to`org-export-headline-levels'.
1879
1880 Headlines which contain any TODO items will be marked with \"(*)\" in
1881 ASCII export, and with red color in HTML output.
1882
1883 In HTML output, the TOC will be clickable.
1884
1885 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1886 :group 'org-export-general
1887 :type 'boolean)
1888
1889 (defcustom org-export-mark-todo-in-toc nil
1890 "Non-nil means, mark TOC lines that contain any open TODO items."
1891 :group 'org-export-general
1892 :type 'boolean)
1893
1894 (defcustom org-export-preserve-breaks nil
1895 "Non-nil means, preserve all line breaks when exporting.
1896 Normally, in HTML output paragraphs will be reformatted. In ASCII
1897 export, line breaks will always be preserved, regardless of this variable.
1898
1899 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1900 :group 'org-export-general
1901 :type 'boolean)
1902
1903 (defcustom org-export-with-archived-trees 'headline
1904 "Whether subtrees with the ARCHIVE tag should be exported.
1905 This can have three different values
1906 nil Do not export, pretend this tree is not present
1907 t Do export the entire tree
1908 headline Only export the headline, but skip the tree below it."
1909 :group 'org-export-general
1910 :group 'org-archive
1911 :type '(choice
1912 (const :tag "not at all" nil)
1913 (const :tag "headline only" 'headline)
1914 (const :tag "entirely" t)))
1915
1916 (defcustom org-export-with-timestamps t
1917 "Nil means, do not export time stamps and associated keywords."
1918 :group 'org-export
1919 :type 'boolean)
1920
1921 (defcustom org-export-remove-timestamps-from-toc t
1922 "Nil means, remove timestamps from the table of contents entries."
1923 :group 'org-export
1924 :type 'boolean)
1925
1926 (defcustom org-export-with-tags t
1927 "Nil means, do not export tags, just remove them from headlines."
1928 :group 'org-export-general
1929 :type 'boolean)
1930
1931 (defcustom org-export-with-timestamps t
1932 "Nil means, do not export timestamps and associated keywords."
1933 :group 'org-export-general
1934 :type 'boolean)
1935
1936 (defgroup org-export-translation nil
1937 "Options for translating special ascii sequences for the export backends."
1938 :tag "Org Export Translation"
1939 :group 'org-export)
1940
1941 (defcustom org-export-with-emphasize t
1942 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1943 If the export target supports emphasizing text, the word will be
1944 typeset in bold, italic, or underlined, respectively. Works only for
1945 single words, but you can say: I *really* *mean* *this*.
1946 Not all export backends support this.
1947
1948 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1949 :group 'org-export-translation
1950 :type 'boolean)
1951
1952 (defcustom org-export-with-sub-superscripts t
1953 "Non-nil means, interpret \"_\" and \"^\" for export.
1954 When this option is turned on, you can use TeX-like syntax for sub- and
1955 superscripts. Several characters after \"_\" or \"^\" will be
1956 considered as a single item - so grouping with {} is normally not
1957 needed. For example, the following things will be parsed as single
1958 sub- or superscripts.
1959
1960 10^24 or 10^tau several digits will be considered 1 item.
1961 10^-12 or 10^-tau a leading sign with digits or a word
1962 x^2-y^3 will be read as x^2 - y^3, because items are
1963 terminated by almost any nonword/nondigit char.
1964 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1965
1966 Still, ambiguity is possible - so when in doubt use {} to enclose the
1967 sub/superscript.
1968 Not all export backends support this, but HTML does.
1969
1970 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1971 :group 'org-export-translation
1972 :type 'boolean)
1973
1974 (defcustom org-export-with-TeX-macros t
1975 "Non-nil means, interpret simple TeX-like macros when exporting.
1976 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1977 No only real TeX macros will work here, but the standard HTML entities
1978 for math can be used as macro names as well. For a list of supported
1979 names in HTML export, see the constant `org-html-entities'.
1980 Not all export backends support this.
1981
1982 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1983 :group 'org-export-translation
1984 :group 'org-latex
1985 :type 'boolean)
1986
1987 (defcustom org-export-with-LaTeX-fragments nil
1988 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
1989 When set, the exporter will find LaTeX environments if the \\begin line is
1990 the first non-white thing on a line. It will also find the math delimiters
1991 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
1992 display math.
1993
1994 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
1995 :group 'org-export-translation
1996 :group 'org-latex
1997 :type 'boolean)
1998
1999 (defcustom org-export-with-fixed-width t
2000 "Non-nil means, lines starting with \":\" will be in fixed width font.
2001 This can be used to have pre-formatted text, fragments of code etc. For
2002 example:
2003 : ;; Some Lisp examples
2004 : (while (defc cnt)
2005 : (ding))
2006 will be looking just like this in also HTML. See also the QUOTE keyword.
2007 Not all export backends support this.
2008
2009 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2010 :group 'org-export-translation
2011 :type 'boolean)
2012
2013 (defcustom org-match-sexp-depth 3
2014 "Number of stacked braces for sub/superscript matching.
2015 This has to be set before loading org.el to be effective."
2016 :group 'org-export-translation
2017 :type 'integer)
2018
2019 (defgroup org-export-tables nil
2020 "Options for exporting tables in Org-mode."
2021 :tag "Org Export Tables"
2022 :group 'org-export)
2023
2024 (defcustom org-export-with-tables t
2025 "If non-nil, lines starting with \"|\" define a table.
2026 For example:
2027
2028 | Name | Address | Birthday |
2029 |-------------+----------+-----------|
2030 | Arthur Dent | England | 29.2.2100 |
2031
2032 Not all export backends support this.
2033
2034 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2035 :group 'org-export-tables
2036 :type 'boolean)
2037
2038 (defcustom org-export-highlight-first-table-line t
2039 "Non-nil means, highlight the first table line.
2040 In HTML export, this means use <th> instead of <td>.
2041 In tables created with table.el, this applies to the first table line.
2042 In Org-mode tables, all lines before the first horizontal separator
2043 line will be formatted with <th> tags."
2044 :group 'org-export-tables
2045 :type 'boolean)
2046
2047 (defcustom org-export-table-remove-special-lines t
2048 "Remove special lines and marking characters in calculating tables.
2049 This removes the special marking character column from tables that are set
2050 up for spreadsheet calculations. It also removes the entire lines
2051 marked with `!', `_', or `^'. The lines with `$' are kept, because
2052 the values of constants may be useful to have."
2053 :group 'org-export-tables
2054 :type 'boolean)
2055
2056 (defcustom org-export-prefer-native-exporter-for-tables nil
2057 "Non-nil means, always export tables created with table.el natively.
2058 Natively means, use the HTML code generator in table.el.
2059 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2060 the table does not use row- or column-spanning). This has the
2061 advantage, that the automatic HTML conversions for math symbols and
2062 sub/superscripts can be applied. Org-mode's HTML generator is also
2063 much faster."
2064 :group 'org-export-tables
2065 :type 'boolean)
2066
2067 (defgroup org-export-ascii nil
2068 "Options specific for ASCII export of Org-mode files."
2069 :tag "Org Export ASCII"
2070 :group 'org-export)
2071
2072 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2073 "Characters for underlining headings in ASCII export.
2074 In the given sequence, these characters will be used for level 1, 2, ..."
2075 :group 'org-export-ascii
2076 :type '(repeat character))
2077
2078 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2079 "Bullet characters for headlines converted to lists in ASCII export.
2080 The first character is is used for the first lest level generated in this
2081 way, and so on. If there are more levels than characters given here,
2082 the list will be repeated.
2083 Note that plain lists will keep the same bullets as the have in the
2084 Org-mode file."
2085 :group 'org-export-ascii
2086 :type '(repeat character))
2087
2088 (defcustom org-export-ascii-show-new-buffer t
2089 "Non-nil means, popup buffer containing the exported ASCII text.
2090 Otherwise the buffer will just be saved to a file and stay hidden."
2091 :group 'org-export-ascii
2092 :type 'boolean)
2093
2094 (defgroup org-export-xml nil
2095 "Options specific for XML export of Org-mode files."
2096 :tag "Org Export XML"
2097 :group 'org-export)
2098
2099 (defgroup org-export-html nil
2100 "Options specific for HTML export of Org-mode files."
2101 :tag "Org Export HTML"
2102 :group 'org-export)
2103
2104 (defcustom org-export-html-style
2105 "<style type=\"text/css\">
2106 html {
2107 font-family: Times, serif;
2108 font-size: 12pt;
2109 }
2110 .title { text-align: center; }
2111 .todo { color: red; }
2112 .done { color: green; }
2113 .timestamp { color: grey }
2114 .timestamp-kwd { color: CadetBlue }
2115 .tag { background-color:lightblue; font-weight:normal }
2116 .target { background-color: lavender; }
2117 pre {
2118 border: 1pt solid #AEBDCC;
2119 background-color: #F3F5F7;
2120 padding: 5pt;
2121 font-family: courier, monospace;
2122 }
2123 table { border-collapse: collapse; }
2124 td, th {
2125 vertical-align: top;
2126 border: 1pt solid #ADB9CC;
2127 }
2128 </style>"
2129 "The default style specification for exported HTML files.
2130 Since there are different ways of setting style information, this variable
2131 needs to contain the full HTML structure to provide a style, including the
2132 surrounding HTML tags. The style specifications should include definitions
2133 for new classes todo, done, title, and deadline. For example, legal values
2134 would be:
2135
2136 <style type=\"text/css\">
2137 p { font-weight: normal; color: gray; }
2138 h1 { color: black; }
2139 .title { text-align: center; }
2140 .todo, .deadline { color: red; }
2141 .done { color: green; }
2142 </style>
2143
2144 or, if you want to keep the style in a file,
2145
2146 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2147
2148 As the value of this option simply gets inserted into the HTML <head> header,
2149 you can \"misuse\" it to add arbitrary text to the header."
2150 :group 'org-export-html
2151 :type 'string)
2152
2153 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2154 "Format for typesetting the document title in HTML export."
2155 :group 'org-export-html
2156 :type 'string)
2157
2158 (defcustom org-export-html-toplevel-hlevel 2
2159 "The <H> level for level 1 headings in HTML export."
2160 :group 'org-export-html
2161 :type 'string)
2162
2163 (defcustom org-export-html-link-org-files-as-html t
2164 "Non-nil means, make file links to `file.org' point to `file.html'.
2165 When org-mode is exporting an org-mode file to HTML, links to
2166 non-html files are directly put into a href tag in HTML.
2167 However, links to other Org-mode files (recognized by the
2168 extension `.org.) should become links to the corresponding html
2169 file, assuming that the linked org-mode file will also be
2170 converted to HTML.
2171 When nil, the links still point to the plain `.org' file."
2172 :group 'org-export-html
2173 :type 'boolean)
2174
2175 (defcustom org-export-html-inline-images 'maybe
2176 "Non-nil means, inline images into exported HTML pages.
2177 This is done using an <img> tag. When nil, an anchor with href is used to
2178 link to the image. If this option is `maybe', then images in links with
2179 an empty description will be inlined, while images with a description will
2180 be linked only."
2181 :group 'org-export-html
2182 :type '(choice (const :tag "Never" nil)
2183 (const :tag "Always" t)
2184 (const :tag "When there is no description" maybe)))
2185
2186 (defcustom org-export-html-expand t
2187 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2188 When nil, these tags will be exported as plain text and therefore
2189 not be interpreted by a browser.
2190
2191 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2192 :group 'org-export-html
2193 :type 'boolean)
2194
2195 (defcustom org-export-html-table-tag
2196 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2197 "The HTML tag used to start a table.
2198 This must be a <table> tag, but you may change the options like
2199 borders and spacing."
2200 :group 'org-export-html
2201 :type 'string)
2202
2203 (defcustom org-export-html-with-timestamp nil
2204 "If non-nil, write `org-export-html-html-helper-timestamp'
2205 into the exported HTML text. Otherwise, the buffer will just be saved
2206 to a file."
2207 :group 'org-export-html
2208 :type 'boolean)
2209
2210 (defcustom org-export-html-html-helper-timestamp
2211 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2212 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2213 :group 'org-export-html
2214 :type 'string)
2215
2216 (defcustom org-export-html-show-new-buffer nil
2217 "Non-nil means, popup buffer containing the exported html text.
2218 Otherwise, the buffer will just be saved to a file and stay hidden."
2219 :group 'org-export-html
2220 :type 'boolean)
2221
2222 (defgroup org-export-icalendar nil
2223 "Options specific for iCalendar export of Org-mode files."
2224 :tag "Org Export iCalendar"
2225 :group 'org-export)
2226
2227 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2228 "The file name for the iCalendar file covering all agenda files.
2229 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2230 The file name should be absolute."
2231 :group 'org-export-icalendar
2232 :type 'file)
2233
2234 (defcustom org-icalendar-include-todo nil
2235 "Non-nil means, export to iCalendar files should also cover TODO items."
2236 :group 'org-export-icalendar
2237 :type 'boolean)
2238
2239 (defcustom org-icalendar-combined-name "OrgMode"
2240 "Calendar name for the combined iCalendar representing all agenda files."
2241 :group 'org-export-icalendar
2242 :type 'string)
2243
2244 (defgroup org-font-lock nil
2245 "Font-lock settings for highlighting in Org-mode."
2246 :tag "Org Font Lock"
2247 :group 'org)
2248
2249 (defcustom org-level-color-stars-only nil
2250 "Non-nil means fontify only the stars in each headline.
2251 When nil, the entire headline is fontified.
2252 Changing it requires restart of `font-lock-mode' to become effective
2253 also in regions already fontified."
2254 :group 'org-font-lock
2255 :type 'boolean)
2256
2257 (defcustom org-hide-leading-stars nil
2258 "Non-nil means, hide the first N-1 stars in a headline.
2259 This works by using the face `org-hide' for these stars. This
2260 face is white for a light background, and black for a dark
2261 background. You may have to customize the face `org-hide' to
2262 make this work.
2263 Changing it requires restart of `font-lock-mode' to become effective
2264 also in regions already fontified.
2265 You may also set this on a per-file basis by adding one of the following
2266 lines to the buffer:
2267
2268 #+STARTUP: hidestars
2269 #+STARTUP: showstars"
2270 :group 'org-font-lock
2271 :type 'boolean)
2272
2273 (defcustom org-fontify-done-headline nil
2274 "Non-nil means, change the face of a headline if it is marked DONE.
2275 Normally, only the TODO/DONE keyword indicates the state of a headline.
2276 When this is non-nil, the headline after the keyword is set to the
2277 `org-headline-done' as an additional indication."
2278 :group 'org-font-lock
2279 :type 'boolean)
2280
2281 (defcustom org-fontify-emphasized-text t
2282 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2283 Changing this variable requires a restart of Emacs to take effect."
2284 :group 'org-font-lock
2285 :type 'boolean)
2286
2287 (defvar org-emph-re nil
2288 "Regular expression for matching emphasis.")
2289 (defvar org-emphasis-regexp-components) ; defined just below
2290 (defvar org-emphasis-alist) ; defined just below
2291 (defun org-set-emph-re (var val)
2292 "Set variable and compute the emphasis regular expression."
2293 (set var val)
2294 (when (and (boundp 'org-emphasis-alist)
2295 (boundp 'org-emphasis-regexp-components)
2296 org-emphasis-alist org-emphasis-regexp-components)
2297 (let* ((e org-emphasis-regexp-components)
2298 (pre (car e))
2299 (post (nth 1 e))
2300 (border (nth 2 e))
2301 (body (nth 3 e))
2302 (nl (nth 4 e))
2303 (stacked (nth 5 e))
2304 (body1 (concat body "*?"))
2305 (markers (mapconcat 'car org-emphasis-alist "")))
2306 ;; make sure special characters appear at the right position in the class
2307 (if (string-match "\\^" markers)
2308 (setq markers (concat (replace-match "" t t markers) "^")))
2309 (if (string-match "-" markers)
2310 (setq markers (concat (replace-match "" t t markers) "-")))
2311 (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2312 ;; Make the regexp
2313 (setq org-emph-re
2314 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2315 "\\("
2316 "\\([" markers "]\\)"
2317 "\\("
2318 "[^" border markers "]"
2319 body1
2320 "[^" border markers "]"
2321 "\\)"
2322 "\\3\\)"
2323 "\\([" post (if stacked markers) "]\\|$\\)")))))
2324
2325 (defcustom org-emphasis-regexp-components
2326 '(" \t(" " \t.,?;:'\")" " \t\r\n,." "." 1 nil)
2327 "Components used to build the reqular expression for emphasis.
2328 This is a list with 6 entries. Terminology: In an emphasis string
2329 like \" *strong word* \", we call the initial space PREMATCH, the final
2330 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2331 and \"trong wor\" is the body. The different components in this variable
2332 specify what is allowed/forbidden in each part:
2333
2334 pre Chars allowed as prematch. Beginning of line will be allowed too.
2335 post Chars allowed as postmatch. End of line will be allowed too.
2336 border The chars *forbidden* as border characters. In addition to the
2337 characters given here, all marker characters are forbidden too.
2338 body-regexp A regexp like \".\" to match a body character. Don't use
2339 non-shy groups here, and don't allow newline here.
2340 newline The maximum number of newlines allowed in an emphasis exp.
2341 stacked Non-nil means, allow stacked styles. This works only in HTML
2342 export. When this is set, all marker characters (as given in
2343 `org-emphasis-alist') will be allowed as pre/post, aiding
2344 inside-out matching.
2345 Use customize to modify this, or restart emacs after changing it."
2346 :group 'org-font-lock
2347 :set 'org-set-emph-re
2348 :type '(list
2349 (sexp :tag "Allowed chars in pre ")
2350 (sexp :tag "Allowed chars in post ")
2351 (sexp :tag "Forbidden chars in border ")
2352 (sexp :tag "Regexp for body ")
2353 (integer :tag "number of newlines allowed")
2354 (boolean :tag "Stacking allowed ")))
2355
2356 (defcustom org-emphasis-alist
2357 '(("*" bold "<b>" "</b>")
2358 ("/" italic "<i>" "</i>")
2359 ("_" underline "<u>" "</u>")
2360 ("=" shadow "<code>" "</code>")
2361 ("+" (:strike-through t) "<del>" "</del>")
2362 )
2363 "Special syntax for emphasised text.
2364 Text starting and ending with a special character will be emphasized, for
2365 example *bold*, _underlined_ and /italic/. This variable sets the marker
2366 characters, the face to bbe used by font-lock for highlighting in Org-mode
2367 emacs buffers, and the HTML tags to be used for this.
2368 Use customize to modify this, or restart emacs after changing it."
2369 :group 'org-font-lock
2370 :set 'org-set-emph-re
2371 :type '(repeat
2372 (list
2373 (string :tag "Marker character")
2374 (choice
2375 (face :tag "Font-lock-face")
2376 (plist :tag "Face property list"))
2377 (string :tag "HTML start tag")
2378 (string :tag "HTML end tag"))))
2379
2380 (defgroup org-faces nil
2381 "Faces in Org-mode."
2382 :tag "Org Faces"
2383 :group 'org-font-lock)
2384
2385 (defun org-compatible-face (specs)
2386 "Make a compatible face specification.
2387 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2388 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2389 to the top of the list. The `min-colors' attribute will be removed from
2390 any other entries, and any resulting duplicates will be removed entirely."
2391 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2392 (let (r e a)
2393 (while (setq e (pop specs))
2394 (cond
2395 ((memq (car e) '(t default)) (push e r))
2396 ((setq a (member '(min-colors 8) (car e)))
2397 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2398 (cdr e)))))
2399 ((setq a (assq 'min-colors (car e)))
2400 (setq e (cons (delq a (car e)) (cdr e)))
2401 (or (assoc (car e) r) (push e r)))
2402 (t (or (assoc (car e) r) (push e r)))))
2403 (nreverse r))
2404 specs))
2405
2406 (defface org-hide
2407 '((((background light)) (:foreground "white"))
2408 (((background dark)) (:foreground "black")))
2409 "Face used to hide leading stars in headlines.
2410 The forground color of this face should be equal to the background
2411 color of the frame."
2412 :group 'org-faces)
2413
2414 (defface org-level-1 ;; font-lock-function-name-face
2415 (org-compatible-face
2416 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2417 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2418 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2419 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2420 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2421 (t (:bold t))))
2422 "Face used for level 1 headlines."
2423 :group 'org-faces)
2424
2425 (defface org-level-2 ;; font-lock-variable-name-face
2426 (org-compatible-face
2427 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2428 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2429 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2430 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2431 (t (:bold t))))
2432 "Face used for level 2 headlines."
2433 :group 'org-faces)
2434
2435 (defface org-level-3 ;; font-lock-keyword-face
2436 (org-compatible-face
2437 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2438 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2439 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2440 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2441 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2442 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2443 (t (:bold t))))
2444 "Face used for level 3 headlines."
2445 :group 'org-faces)
2446
2447 (defface org-level-4 ;; font-lock-comment-face
2448 (org-compatible-face
2449 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2450 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2451 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2452 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2453 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2454 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2455 (t (:bold t))))
2456 "Face used for level 4 headlines."
2457 :group 'org-faces)
2458
2459 (defface org-level-5 ;; font-lock-type-face
2460 (org-compatible-face
2461 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2462 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2463 (((class color) (min-colors 8)) (:foreground "green"))))
2464 "Face used for level 5 headlines."
2465 :group 'org-faces)
2466
2467 (defface org-level-6 ;; font-lock-constant-face
2468 (org-compatible-face
2469 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2470 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2471 (((class color) (min-colors 8)) (:foreground "magenta"))))
2472 "Face used for level 6 headlines."
2473 :group 'org-faces)
2474
2475 (defface org-level-7 ;; font-lock-builtin-face
2476 (org-compatible-face
2477 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2478 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2479 (((class color) (min-colors 8)) (:foreground "blue"))))
2480 "Face used for level 7 headlines."
2481 :group 'org-faces)
2482
2483 (defface org-level-8 ;; font-lock-string-face
2484 (org-compatible-face
2485 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2486 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2487 (((class color) (min-colors 8)) (:foreground "green"))))
2488 "Face used for level 8 headlines."
2489 :group 'org-faces)
2490
2491 (defface org-special-keyword ;; font-lock-string-face
2492 (org-compatible-face
2493 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2494 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2495 (t (:italic t))))
2496 "Face used for special keywords."
2497 :group 'org-faces)
2498
2499 (defface org-warning ;; font-lock-warning-face
2500 (org-compatible-face
2501 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2502 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2503 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2504 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2505 (t (:bold t))))
2506 "Face for deadlines and TODO keywords."
2507 :group 'org-faces)
2508
2509 (defface org-headline-done ;; font-lock-string-face
2510 (org-compatible-face
2511 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2512 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2513 (((class color) (min-colors 8) (background light)) (:bold nil))))
2514 "Face used to indicate that a headline is DONE.
2515 This face is only used if `org-fontify-done-headline' is set."
2516 :group 'org-faces)
2517
2518 (defface org-archived ; similar to shadow
2519 (org-compatible-face
2520 '((((class color grayscale) (min-colors 88) (background light))
2521 (:foreground "grey50"))
2522 (((class color grayscale) (min-colors 88) (background dark))
2523 (:foreground "grey70"))
2524 (((class color) (min-colors 8) (background light))
2525 (:foreground "green"))
2526 (((class color) (min-colors 8) (background dark))
2527 (:foreground "yellow"))))
2528 "Face for headline with the ARCHIVE tag."
2529 :group 'org-faces)
2530
2531 (defface org-link
2532 '((((class color) (background light)) (:foreground "Purple" :underline t))
2533 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2534 (t (:underline t)))
2535 "Face for links."
2536 :group 'org-faces)
2537
2538 (defface org-date
2539 '((((class color) (background light)) (:foreground "Purple" :underline t))
2540 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2541 (t (:underline t)))
2542 "Face for links."
2543 :group 'org-faces)
2544
2545 (defface org-tag
2546 '((t (:bold t)))
2547 "Face for tags."
2548 :group 'org-faces)
2549
2550 (defface org-todo ;; font-lock-warning-face
2551 (org-compatible-face
2552 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2553 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2554 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2555 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2556 (t (:inverse-video t :bold t))))
2557 "Face for TODO keywords."
2558 :group 'org-faces)
2559
2560 (defface org-done ;; font-lock-type-face
2561 (org-compatible-face
2562 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2563 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2564 (((class color) (min-colors 8)) (:foreground "green"))
2565 (t (:bold t))))
2566 "Face used for DONE."
2567 :group 'org-faces)
2568
2569 (defface org-table ;; font-lock-function-name-face
2570 (org-compatible-face
2571 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2572 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2573 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2574 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2575 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2576 (((class color) (min-colors 8) (background dark)))))
2577 "Face used for tables."
2578 :group 'org-faces)
2579
2580 (defface org-formula
2581 (org-compatible-face
2582 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2583 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2584 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2585 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2586 (t (:bold t :italic t))))
2587 "Face for formulas."
2588 :group 'org-faces)
2589
2590 (defface org-scheduled-today
2591 (org-compatible-face
2592 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2593 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2594 (((class color) (min-colors 8)) (:foreground "green"))
2595 (t (:bold t :italic t))))
2596 "Face for items scheduled for a certain day."
2597 :group 'org-faces)
2598
2599 (defface org-scheduled-previously
2600 (org-compatible-face
2601 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2602 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2603 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2604 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2605 (t (:bold t))))
2606 "Face for items scheduled previously, and not yet done."
2607 :group 'org-faces)
2608
2609 (defface org-upcoming-deadline
2610 (org-compatible-face
2611 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2612 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2613 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2614 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2615 (t (:bold t))))
2616 "Face for items scheduled previously, and not yet done."
2617 :group 'org-faces)
2618
2619 (defface org-time-grid ;; font-lock-variable-name-face
2620 (org-compatible-face
2621 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2622 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2623 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2624 "Face used for time grids."
2625 :group 'org-faces)
2626
2627 (defconst org-level-faces
2628 '(org-level-1 org-level-2 org-level-3 org-level-4
2629 org-level-5 org-level-6 org-level-7 org-level-8
2630 ))
2631 (defconst org-n-levels (length org-level-faces))
2632
2633
2634 ;; Variables for pre-computed regular expressions, all buffer local
2635 (defvar org-done-string nil
2636 "The last string in `org-todo-keywords', indicating an item is DONE.")
2637 (make-variable-buffer-local 'org-done-string)
2638 (defvar org-todo-regexp nil
2639 "Matches any of the TODO state keywords.")
2640 (make-variable-buffer-local 'org-todo-regexp)
2641 (defvar org-not-done-regexp nil
2642 "Matches any of the TODO state keywords except the last one.")
2643 (make-variable-buffer-local 'org-not-done-regexp)
2644 (defvar org-todo-line-regexp nil
2645 "Matches a headline and puts TODO state into group 2 if present.")
2646 (make-variable-buffer-local 'org-todo-line-regexp)
2647 (defvar org-todo-line-tags-regexp nil
2648 "Matches a headline and puts TODO state into group 2 if present.
2649 Also put tags into group 4 if tags are present.")
2650 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2651 (defvar org-nl-done-regexp nil
2652 "Matches newline followed by a headline with the DONE keyword.")
2653 (make-variable-buffer-local 'org-nl-done-regexp)
2654 (defvar org-looking-at-done-regexp nil
2655 "Matches the DONE keyword a point.")
2656 (make-variable-buffer-local 'org-looking-at-done-regexp)
2657 (defvar org-todo-kwd-priority-p nil
2658 "Do TODO items have priorities?")
2659 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2660 (defvar org-todo-kwd-max-priority nil
2661 "Maximum priority of TODO items.")
2662 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2663 (defvar org-ds-keyword-length 12
2664 "Maximum length of the Deadline and SCHEDULED keywords.")
2665 (make-variable-buffer-local 'org-ds-keyword-length)
2666 (defvar org-deadline-regexp nil
2667 "Matches the DEADLINE keyword.")
2668 (make-variable-buffer-local 'org-deadline-regexp)
2669 (defvar org-deadline-time-regexp nil
2670 "Matches the DEADLINE keyword together with a time stamp.")
2671 (make-variable-buffer-local 'org-deadline-time-regexp)
2672 (defvar org-deadline-line-regexp nil
2673 "Matches the DEADLINE keyword and the rest of the line.")
2674 (make-variable-buffer-local 'org-deadline-line-regexp)
2675 (defvar org-scheduled-regexp nil
2676 "Matches the SCHEDULED keyword.")
2677 (make-variable-buffer-local 'org-scheduled-regexp)
2678 (defvar org-scheduled-time-regexp nil
2679 "Matches the SCHEDULED keyword together with a time stamp.")
2680 (make-variable-buffer-local 'org-scheduled-time-regexp)
2681 (defvar org-closed-time-regexp nil
2682 "Matches the CLOSED keyword together with a time stamp.")
2683 (make-variable-buffer-local 'org-closed-time-regexp)
2684
2685 (defvar org-keyword-time-regexp nil
2686 "Matches any of the 3 keywords, together with the time stamp.")
2687 (make-variable-buffer-local 'org-keyword-time-regexp)
2688 (defvar org-maybe-keyword-time-regexp nil
2689 "Matches a timestamp, possibly preceeded by a keyword.")
2690 (make-variable-buffer-local 'org-keyword-time-regexp)
2691
2692 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2693 rear-nonsticky t mouse-map t)
2694 "Properties to remove when a string without properties is wanted.")
2695
2696 (defsubst org-match-string-no-properties (num &optional string)
2697 (if (featurep 'xemacs)
2698 (let ((s (match-string num string)))
2699 (remove-text-properties 0 (length s) org-rm-props s)
2700 s)
2701 (match-string-no-properties num string)))
2702
2703 (defsubst org-no-properties (s)
2704 (remove-text-properties 0 (length s) org-rm-props s)
2705 s)
2706
2707 (defsubst org-set-local (var value)
2708 "Make VAR local in current buffer and set it to VALUE."
2709 (set (make-variable-buffer-local var) value))
2710
2711 (defsubst org-mode-p ()
2712 "Check if the current buffer is in Org-mode."
2713 (eq major-mode 'org-mode))
2714
2715 (defun org-set-regexps-and-options ()
2716 "Precompute regular expressions for current buffer."
2717 (when (org-mode-p)
2718 (let ((re (org-make-options-regexp
2719 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2720 "STARTUP" "ARCHIVE" "TAGS" "CALC")))
2721 (splitre "[ \t]+")
2722 kwds int key value cat arch tags)
2723 (save-excursion
2724 (save-restriction
2725 (widen)
2726 (goto-char (point-min))
2727 (while (re-search-forward re nil t)
2728 (setq key (match-string 1) value (org-match-string-no-properties 2))
2729 (cond
2730 ((equal key "CATEGORY")
2731 (if (string-match "[ \t]+$" value)
2732 (setq value (replace-match "" t t value)))
2733 (setq cat (intern value)))
2734 ((equal key "SEQ_TODO")
2735 (setq int 'sequence
2736 kwds (append kwds (org-split-string value splitre))))
2737 ((equal key "PRI_TODO")
2738 (setq int 'priority
2739 kwds (append kwds (org-split-string value splitre))))
2740 ((equal key "TYP_TODO")
2741 (setq int 'type
2742 kwds (append kwds (org-split-string value splitre))))
2743 ((equal key "TAGS")
2744 (setq tags (append tags (org-split-string value splitre))))
2745 ((equal key "STARTUP")
2746 (let ((opts (org-split-string value splitre))
2747 (set '(("fold" org-startup-folded t)
2748 ("overview" org-startup-folded t)
2749 ("nofold" org-startup-folded nil)
2750 ("showall" org-startup-folded nil)
2751 ("content" org-startup-folded content)
2752 ("hidestars" org-hide-leading-stars t)
2753 ("showstars" org-hide-leading-stars nil)
2754 ("odd" org-odd-levels-only t)
2755 ("oddeven" org-odd-levels-only nil)
2756 ("align" org-startup-align-all-tables t)
2757 ("noalign" org-startup-align-all-tables nil)
2758 ("logging" org-log-done t)
2759 ("nologging" org-log-done nil)
2760 ("dlcheck" org-startup-with-deadline-check t)
2761 ("nodlcheck" org-startup-with-deadline-check nil)))
2762 l var val)
2763 (while (setq l (assoc (pop opts) set))
2764 (setq var (nth 1 l) val (nth 2 l))
2765 (set (make-local-variable var) val))))
2766 ((equal key "ARCHIVE")
2767 (string-match " *$" value)
2768 (setq arch (replace-match "" t t value))
2769 (remove-text-properties 0 (length arch)
2770 '(face t fontified t) arch)))
2771 )))
2772 (and cat (org-set-local 'org-category cat))
2773 (and kwds (org-set-local 'org-todo-keywords kwds))
2774 (and arch (org-set-local 'org-archive-location arch))
2775 (and int (org-set-local 'org-todo-interpretation int))
2776 (when tags
2777 (let (e tgs)
2778 (while (setq e (pop tags))
2779 (cond
2780 ((equal e "{") (push '(:startgroup) tgs))
2781 ((equal e "}") (push '(:endgroup) tgs))
2782 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2783 (push (cons (match-string 1 e)
2784 (string-to-char (match-string 2 e)))
2785 tgs))
2786 (t (push (list e) tgs))))
2787 (org-set-local 'org-tag-alist nil)
2788 (while (setq e (pop tgs))
2789 (or (and (stringp (car e))
2790 (assoc (car e) org-tag-alist))
2791 (push e org-tag-alist))))))
2792
2793 ;; Compute the regular expressions and other local variables
2794 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2795 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2796 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2797 (length org-scheduled-string)))
2798 org-done-string
2799 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2800 org-todo-regexp
2801 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2802 "\\|") "\\)\\>")
2803 org-not-done-regexp
2804 (concat "\\<\\("
2805 (mapconcat 'regexp-quote
2806 (nreverse (cdr (reverse org-todo-keywords)))
2807 "\\|")
2808 "\\)\\>")
2809 org-todo-line-regexp
2810 (concat "^\\(\\*+\\)[ \t]*\\("
2811 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2812 "\\)? *\\(.*\\)")
2813 org-nl-done-regexp
2814 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2815 org-todo-line-tags-regexp
2816 (concat "^\\(\\*+\\)[ \t]*\\("
2817 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2818 "\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
2819 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2820 org-deadline-regexp (concat "\\<" org-deadline-string)
2821 org-deadline-time-regexp
2822 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2823 org-deadline-line-regexp
2824 (concat "\\<\\(" org-deadline-string "\\).*")
2825 org-scheduled-regexp
2826 (concat "\\<" org-scheduled-string)
2827 org-scheduled-time-regexp
2828 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2829 org-closed-time-regexp
2830 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2831 org-keyword-time-regexp
2832 (concat "\\<\\(" org-scheduled-string
2833 "\\|" org-deadline-string
2834 "\\|" org-closed-string
2835 "\\|" org-clock-string "\\)"
2836 " *[[<]\\([^]>]+\\)[]>]")
2837 org-maybe-keyword-time-regexp
2838 (concat "\\(\\<\\(" org-scheduled-string
2839 "\\|" org-deadline-string
2840 "\\|" org-closed-string
2841 "\\|" org-clock-string "\\)\\)?"
2842 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
2843
2844 (org-set-font-lock-defaults)))
2845
2846 ;; Tell the compiler about dynamically scoped variables,
2847 ;; and variables from other packages
2848 (defvar calc-embedded-close-formula) ; defined by the calc package
2849 (defvar calc-embedded-open-formula) ; defined by the calc package
2850 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
2851 (defvar zmacs-regions) ; XEmacs regions
2852 (defvar original-date) ; dynamically scoped in calendar
2853 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2854 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2855 (defvar org-html-entities) ; defined later in this file
2856 (defvar org-goto-start-pos) ; dynamically scoped parameter
2857 (defvar org-time-was-given) ; dynamically scoped parameter
2858 (defvar org-ts-what) ; dynamically scoped parameter
2859 (defvar org-current-export-file) ; dynamically scoped parameter
2860 (defvar org-current-export-dir) ; dynamically scoped parameter
2861 (defvar mark-active) ; Emacs only, not available in XEmacs.
2862 (defvar timecnt) ; dynamically scoped parameter
2863 (defvar levels-open) ; dynamically scoped parameter
2864 (defvar entry) ; dynamically scoped parameter
2865 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
2866 (defvar date) ; dynamically scoped parameter
2867 (defvar description) ; dynamically scoped parameter
2868 (defvar ans1) ; dynamically scoped parameter
2869 (defvar ans2) ; dynamically scoped parameter
2870 (defvar starting-day) ; local variable
2871 (defvar include-all-loc) ; local variable
2872 (defvar vm-message-pointer) ; from vm
2873 (defvar vm-folder-directory) ; from vm
2874 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2875 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2876 (defvar gnus-group-name) ; from gnus
2877 (defvar gnus-article-current) ; from gnus
2878 (defvar w3m-current-url) ; from w3m
2879 (defvar w3m-current-title) ; from w3m
2880 (defvar mh-progs) ; from MH-E
2881 (defvar mh-current-folder) ; from MH-E
2882 (defvar mh-show-folder-buffer) ; from MH-E
2883 (defvar mh-index-folder) ; from MH-E
2884 (defvar mh-searcher) ; from MH-E
2885 (defvar org-selected-point) ; dynamically scoped parameter
2886 (defvar calendar-mode-map) ; from calendar.el
2887 (defvar last-arg) ; local variable
2888 (defvar remember-save-after-remembering) ; from remember.el
2889 (defvar remember-data-file) ; from remember.el
2890 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2891 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2892 (defvar orgtbl-mode) ; defined later in this file
2893 (defvar Info-current-file) ; from info.el
2894 (defvar Info-current-node) ; from info.el
2895 (defvar texmathp-why) ; from texmathp.el
2896 (defvar org-latex-regexps)
2897
2898 ;;; Define the mode
2899
2900 (defvar org-mode-map
2901 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2902 (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.")
2903 (copy-keymap outline-mode-map))
2904 "Keymap for Org-mode.")
2905
2906 (defvar org-struct-menu) ; defined later in this file
2907 (defvar org-org-menu) ; defined later in this file
2908 (defvar org-tbl-menu) ; defined later in this file
2909
2910 ;; We use a before-change function to check if a table might need
2911 ;; an update.
2912 (defvar org-table-may-need-update t
2913 "Indicates that a table might need an update.
2914 This variable is set by `org-before-change-function'.
2915 `org-table-align' sets it back to nil.")
2916 (defvar org-mode-hook nil)
2917 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2918 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2919
2920
2921 ;;;###autoload
2922 (define-derived-mode org-mode outline-mode "Org"
2923 "Outline-based notes management and organizer, alias
2924 \"Carsten's outline-mode for keeping track of everything.\"
2925
2926 Org-mode develops organizational tasks around a NOTES file which
2927 contains information about projects as plain text. Org-mode is
2928 implemented on top of outline-mode, which is ideal to keep the content
2929 of large files well structured. It supports ToDo items, deadlines and
2930 time stamps, which magically appear in the diary listing of the Emacs
2931 calendar. Tables are easily created with a built-in table editor.
2932 Plain text URL-like links connect to websites, emails (VM), Usenet
2933 messages (Gnus), BBDB entries, and any files related to the project.
2934 For printing and sharing of notes, an Org-mode file (or a part of it)
2935 can be exported as a structured ASCII or HTML file.
2936
2937 The following commands are available:
2938
2939 \\{org-mode-map}"
2940
2941 ;; Get rid of Outline menus, they are not needed
2942 ;; Need to do this here because define-derived-mode sets up
2943 ;; the keymap so late.
2944 (if (featurep 'xemacs)
2945 (progn
2946 ;; Assume this is Greg's port, it used easymenu
2947 (easy-menu-remove outline-mode-menu-heading)
2948 (easy-menu-remove outline-mode-menu-show)
2949 (easy-menu-remove outline-mode-menu-hide))
2950 (define-key org-mode-map [menu-bar headings] 'undefined)
2951 (define-key org-mode-map [menu-bar hide] 'undefined)
2952 (define-key org-mode-map [menu-bar show] 'undefined))
2953
2954 (easy-menu-add org-org-menu)
2955 (easy-menu-add org-tbl-menu)
2956 (org-install-agenda-files-menu)
2957 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2958 (org-add-to-invisibility-spec '(org-cwidth))
2959 (when (featurep 'xemacs)
2960 (org-set-local 'line-move-ignore-invisible t))
2961 (setq outline-regexp "\\*+")
2962 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2963 (setq outline-level 'org-outline-level)
2964 (when (and org-ellipsis (stringp org-ellipsis))
2965 (unless org-display-table
2966 (setq org-display-table (make-display-table)))
2967 (set-display-table-slot org-display-table
2968 4 (string-to-vector org-ellipsis))
2969 (setq buffer-display-table org-display-table))
2970 (org-set-regexps-and-options)
2971 ;; Calc embedded
2972 (org-set-local 'calc-embedded-open-mode "# ")
2973 (modify-syntax-entry ?# "<")
2974 (if org-startup-truncated (setq truncate-lines t))
2975 (org-set-local 'font-lock-unfontify-region-function
2976 'org-unfontify-region)
2977 ;; Activate before-change-function
2978 (org-set-local 'org-table-may-need-update t)
2979 (org-add-hook 'before-change-functions 'org-before-change-function nil
2980 'local)
2981 ;; Check for running clock before killing a buffer
2982 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
2983 ;; Paragraphs and auto-filling
2984 (org-set-autofill-regexps)
2985 (org-update-radio-target-regexp)
2986
2987 (if (and org-insert-mode-line-in-empty-file
2988 (interactive-p)
2989 (= (point-min) (point-max)))
2990 (insert " -*- mode: org -*-\n\n"))
2991
2992 (unless org-inhibit-startup
2993 (when org-startup-align-all-tables
2994 (let ((bmp (buffer-modified-p)))
2995 (org-table-map-tables 'org-table-align)
2996 (set-buffer-modified-p bmp)))
2997 (if org-startup-with-deadline-check
2998 (call-interactively 'org-check-deadlines)
2999 (cond
3000 ((eq org-startup-folded t)
3001 (org-cycle '(4)))
3002 ((eq org-startup-folded 'content)
3003 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3004 (org-cycle '(4)) (org-cycle '(4))))))))
3005
3006 (defsubst org-call-with-arg (command arg)
3007 "Call COMMAND interactively, but pretend prefix are was ARG."
3008 (let ((current-prefix-arg arg)) (call-interactively command)))
3009
3010 (defsubst org-current-line (&optional pos)
3011 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
3012
3013 (defun org-current-time ()
3014 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3015 (if (> org-time-stamp-rounding-minutes 0)
3016 (let ((r org-time-stamp-rounding-minutes)
3017 (time (decode-time)))
3018 (apply 'encode-time
3019 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3020 (nthcdr 2 time))))
3021 (current-time)))
3022
3023 (defun org-add-props (string plist &rest props)
3024 "Add text properties to entire string, from beginning to end.
3025 PLIST may be a list of properties, PROPS are individual properties and values
3026 that will be added to PLIST. Returns the string that was modified."
3027 (add-text-properties
3028 0 (length string) (if props (append plist props) plist) string)
3029 string)
3030 (put 'org-add-props 'lisp-indent-function 2)
3031
3032
3033 ;;; Font-Lock stuff
3034
3035 (defvar org-mouse-map (make-sparse-keymap))
3036 (define-key org-mouse-map
3037 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3038 (define-key org-mouse-map
3039 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3040 (when org-mouse-1-follows-link
3041 (define-key org-mouse-map [follow-link] 'mouse-face))
3042 (when org-tab-follows-link
3043 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3044 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3045 (when org-return-follows-link
3046 (define-key org-mouse-map [(return)] 'org-open-at-point)
3047 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3048
3049 (require 'font-lock)
3050
3051 (defconst org-non-link-chars "]\t\n\r<>")
3052 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3053 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3054 (defconst org-link-re-with-space
3055 (concat
3056 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3057 "\\([^" org-non-link-chars " ]"
3058 "[^" org-non-link-chars "]*"
3059 "[^" org-non-link-chars " ]\\)>?")
3060 "Matches a link with spaces, optional angular brackets around it.")
3061
3062 (defconst org-link-re-with-space2
3063 (concat
3064 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3065 "\\([^" org-non-link-chars " ]"
3066 "[^]\t\n\r]*"
3067 "[^" org-non-link-chars " ]\\)>?")
3068 "Matches a link with spaces, optional angular brackets around it.")
3069
3070 (defconst org-angle-link-re
3071 (concat
3072 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3073 "\\([^" org-non-link-chars " ]"
3074 "[^" org-non-link-chars "]*"
3075 "\\)>")
3076 "Matches link with angular brackets, spaces are allowed.")
3077 (defconst org-plain-link-re
3078 (concat
3079 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3080 "\\([^]\t\n\r<>,;() ]+\\)")
3081 "Matches plain link, without spaces.")
3082
3083 (defconst org-bracket-link-regexp
3084 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3085 "Matches a link in double brackets.")
3086
3087 (defconst org-bracket-link-analytic-regexp
3088 (concat
3089 "\\[\\["
3090 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3091 "\\([^]]+\\)"
3092 "\\]"
3093 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3094 "\\]"))
3095 ; 1: http:
3096 ; 2: http
3097 ; 3: path
3098 ; 4: [desc]
3099 ; 5: desc
3100
3101
3102 (defconst org-ts-lengths
3103 (cons (length (format-time-string (car org-time-stamp-formats)))
3104 (length (format-time-string (cdr org-time-stamp-formats))))
3105 "This holds the lengths of the two different time formats.")
3106 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3107 "Regular expression for fast time stamp matching.")
3108 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3109 "Regular expression for fast time stamp matching.")
3110 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3111 "Regular expression matching time strings for analysis.")
3112 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3113 "Regular expression matching time stamps, with groups.")
3114 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3115 "Regular expression matching time stamps (also [..]), with groups.")
3116 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3117 "Regular expression matching a time stamp range.")
3118 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3119 org-ts-regexp "\\)?")
3120 "Regular expression matching a time stamp or time stamp range.")
3121
3122 (defvar org-\81§emph-face nil)
3123
3124 (defun org-do-emphasis-faces (limit)
3125 "Run through the buffer and add overlays to links."
3126 (if (re-search-forward org-emph-re limit t)
3127 (progn
3128 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3129 'face
3130 (nth 1 (assoc (match-string 3)
3131 org-emphasis-alist)))
3132 (add-text-properties (match-beginning 2) (match-end 2)
3133 '(font-lock-multiline t))
3134 (backward-char 1)
3135 t)))
3136
3137 (defun org-activate-plain-links (limit)
3138 "Run through the buffer and add overlays to links."
3139 (if (re-search-forward org-plain-link-re limit t)
3140 (progn
3141 (add-text-properties (match-beginning 0) (match-end 0)
3142 (list 'mouse-face 'highlight
3143 'rear-nonsticky t
3144 'keymap org-mouse-map
3145 ))
3146 t)))
3147
3148 (defun org-activate-angle-links (limit)
3149 "Run through the buffer and add overlays to links."
3150 (if (re-search-forward org-angle-link-re limit t)
3151 (progn
3152 (add-text-properties (match-beginning 0) (match-end 0)
3153 (list 'mouse-face 'highlight
3154 'rear-nonsticky t
3155 'keymap org-mouse-map
3156 ))
3157 t)))
3158
3159 (defun org-activate-bracket-links (limit)
3160 "Run through the buffer and add overlays to bracketed links."
3161 (if (re-search-forward org-bracket-link-regexp limit t)
3162 (let* ((help (concat "LINK: "
3163 (org-match-string-no-properties 1)))
3164 ;; FIXME: above we should remove the escapes.
3165 ;; but that requires another match, protecting match data,
3166 ;; a lot of overhead for font-lock.
3167 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
3168 'keymap org-mouse-map 'mouse-face 'highlight
3169 'help-echo help))
3170 (vp (list 'rear-nonsticky t
3171 'keymap org-mouse-map 'mouse-face 'highlight
3172 'help-echo help)))
3173 ;; We need to remove the invisible property here. Table narrowing
3174 ;; may have made some of this invisible.
3175 (remove-text-properties (match-beginning 0) (match-end 0)
3176 '(invisible nil))
3177 (if (match-end 3)
3178 (progn
3179 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3180 (add-text-properties (match-beginning 3) (match-end 3) vp)
3181 (add-text-properties (match-end 3) (match-end 0) ip))
3182 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3183 (add-text-properties (match-beginning 1) (match-end 1) vp)
3184 (add-text-properties (match-end 1) (match-end 0) ip))
3185 t)))
3186
3187 (defun org-activate-dates (limit)
3188 "Run through the buffer and add overlays to dates."
3189 (if (re-search-forward org-tsr-regexp limit t)
3190 (progn
3191 (add-text-properties (match-beginning 0) (match-end 0)
3192 (list 'mouse-face 'highlight
3193 'rear-nonsticky t
3194 'keymap org-mouse-map))
3195 t)))
3196
3197 (defvar org-target-link-regexp nil
3198 "Regular expression matching radio targets in plain text.")
3199 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3200 "Regular expression matching a link target.")
3201 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3202 "Regular expression matching a link target.")
3203
3204 (defun org-activate-target-links (limit)
3205 "Run through the buffer and add overlays to target matches."
3206 (when org-target-link-regexp
3207 (let ((case-fold-search t))
3208 (if (re-search-forward org-target-link-regexp limit t)
3209 (progn
3210 (add-text-properties (match-beginning 0) (match-end 0)
3211 (list 'mouse-face 'highlight
3212 'rear-nonsticky t
3213 'keymap org-mouse-map
3214 'help-echo "Radio target link"
3215 'org-linked-text t))
3216 t)))))
3217
3218 (defun org-update-radio-target-regexp ()
3219 "Find all radio targets in this file and update the regular expression."
3220 (interactive)
3221 (when (memq 'radio org-activate-links)
3222 (setq org-target-link-regexp
3223 (org-make-target-link-regexp (org-all-targets 'radio)))
3224 (org-restart-font-lock)))
3225
3226 (defun org-hide-wide-columns (limit)
3227 (let (s e)
3228 (setq s (text-property-any (point) (or limit (point-max))
3229 'org-cwidth t))
3230 (when s
3231 (setq e (next-single-property-change s 'org-cwidth))
3232 (add-text-properties s e '(invisible org-cwidth intangible t))
3233 (goto-char e)
3234 t)))
3235
3236 (defun org-restart-font-lock ()
3237 "Restart font-lock-mode, to force refontification."
3238 (when (and (boundp 'font-lock-mode) font-lock-mode)
3239 (font-lock-mode -1)
3240 (font-lock-mode 1)))
3241
3242 (defun org-all-targets (&optional radio)
3243 "Return a list of all targets in this file.
3244 With optional argument RADIO, only find radio targets."
3245 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3246 rtn)
3247 (save-excursion
3248 (goto-char (point-min))
3249 (while (re-search-forward re nil t)
3250 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3251 rtn)))
3252
3253 (defun org-make-target-link-regexp (targets)
3254 "Make regular expression matching all strings in TARGETS.
3255 The regular expression finds the targets also if there is a line break
3256 between words."
3257 (and targets
3258 (concat
3259 "\\<\\("
3260 (mapconcat
3261 (lambda (x)
3262 (while (string-match " +" x)
3263 (setq x (replace-match "\\s-+" t t x)))
3264 x)
3265 targets
3266 "\\|")
3267 "\\)\\>")))
3268
3269 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3270 "Matches CamelCase words, possibly with a star before it.")
3271
3272 (defun org-activate-camels (limit)
3273 "Run through the buffer and add overlays to dates."
3274 (if (re-search-forward org-camel-regexp limit t)
3275 (progn
3276 (add-text-properties (match-beginning 0) (match-end 0)
3277 (list 'mouse-face 'highlight
3278 'rear-nonsticky t
3279 'keymap org-mouse-map))
3280 t)))
3281
3282 (defun org-activate-tags (limit)
3283 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3284 (progn
3285 (add-text-properties (match-beginning 1) (match-end 1)
3286 (list 'mouse-face 'highlight
3287 'rear-nonsticky t
3288 'keymap org-mouse-map))
3289 t)))
3290
3291 (defun org-font-lock-level ()
3292 (save-excursion
3293 (org-back-to-heading t)
3294 (- (match-end 0) (match-beginning 0))))
3295
3296 (defun org-outline-level ()
3297 (save-excursion
3298 (looking-at outline-regexp)
3299 (if (match-beginning 1)
3300 (+ (org-get-string-indentation (match-string 1)) 1000)
3301 (- (match-end 0) (match-beginning 0)))))
3302
3303 (defvar org-font-lock-keywords nil)
3304
3305 (defun org-set-font-lock-defaults ()
3306 (let* ((em org-fontify-emphasized-text)
3307 (lk org-activate-links)
3308 (org-font-lock-extra-keywords
3309 ;; Headlines
3310 (list
3311 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3312 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3313 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3314 (1 'org-table))
3315 ;; Links
3316 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3317 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3318 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3319 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3320 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3321 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3322 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3323 (if org-table-limit-column-width
3324 '(org-hide-wide-columns (0 nil append)))
3325 ;; TODO lines
3326 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3327 '(1 'org-todo t))
3328 ;; Priorities
3329 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3330 ;; Special keywords
3331 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3332 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3333 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3334 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3335 ;; Emphasis
3336 (if em '(org-do-emphasis-faces))
3337 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3338 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3339 2 'bold prepend)
3340 ;; COMMENT
3341 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3342 "\\|" org-quote-string "\\)\\>")
3343 '(1 'org-special-keyword t))
3344 '("^#.*" (0 'font-lock-comment-face t))
3345 ;; DONE
3346 (if org-fontify-done-headline
3347 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3348 '(1 'org-done t) '(2 'org-headline-done t))
3349 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3350 '(1 'org-done t)))
3351 ;; Table stuff
3352 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3353 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3354 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3355 (if org-format-transports-properties-p
3356 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3357 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3358 )))
3359 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3360 ;; Now set the full font-lock-keywords
3361 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3362 (org-set-local 'font-lock-defaults
3363 '(org-font-lock-keywords t nil nil backward-paragraph))
3364 (kill-local-variable 'font-lock-keywords) nil))
3365
3366 (defvar org-m nil)
3367 (defvar org-l nil)
3368 (defvar org-f nil)
3369 (defun org-get-level-face (n)
3370 "Get the right face for match N in font-lock matching of healdines."
3371 (setq org-l (- (match-end 2) (match-beginning 1)))
3372 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3373 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3374 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3375 (cond
3376 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3377 ((eq n 2) org-f)
3378 (t (if org-level-color-stars-only nil org-f))))
3379
3380 (defun org-unfontify-region (beg end &optional maybe_loudly)
3381 "Remove fontification and activation overlays from links."
3382 (font-lock-default-unfontify-region beg end)
3383 (let* ((buffer-undo-list t)
3384 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3385 (inhibit-modification-hooks t)
3386 deactivate-mark buffer-file-name buffer-file-truename)
3387 (remove-text-properties beg end
3388 '(mouse-face nil keymap nil org-linked-text nil
3389 rear-nonsticky nil
3390 invisible nil intangible nil))))
3391 ;;; Visibility cycling
3392
3393 (defvar org-cycle-global-status nil)
3394 (make-variable-buffer-local 'org-cycle-global-status)
3395 (defvar org-cycle-subtree-status nil)
3396 (make-variable-buffer-local 'org-cycle-subtree-status)
3397
3398 ;;;###autoload
3399 (defun org-cycle (&optional arg)
3400 "Visibility cycling for Org-mode.
3401
3402 - When this function is called with a prefix argument, rotate the entire
3403 buffer through 3 states (global cycling)
3404 1. OVERVIEW: Show only top-level headlines.
3405 2. CONTENTS: Show all headlines of all levels, but no body text.
3406 3. SHOW ALL: Show everything.
3407
3408 - When point is at the beginning of a headline, rotate the subtree started
3409 by this line through 3 different states (local cycling)
3410 1. FOLDED: Only the main headline is shown.
3411 2. CHILDREN: The main headline and the direct children are shown.
3412 From this state, you can move to one of the children
3413 and zoom in further.
3414 3. SUBTREE: Show the entire subtree, including body text.
3415
3416 - When there is a numeric prefix, go up to a heading with level ARG, do
3417 a `show-subtree' and return to the previous cursor position. If ARG
3418 is negative, go up that many levels.
3419
3420 - When point is not at the beginning of a headline, execute
3421 `indent-relative', like TAB normally does. See the option
3422 `org-cycle-emulate-tab' for details.
3423
3424 - Special case: if point is the the beginning of the buffer and there is
3425 no headline in line 1, this function will act as if called with prefix arg."
3426 (interactive "P")
3427
3428 (let* ((outline-regexp
3429 (if org-cycle-include-plain-lists
3430 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
3431 outline-regexp))
3432 (bob-special (and org-cycle-global-at-bob (bobp)
3433 (not (looking-at outline-regexp))))
3434 (org-cycle-hook
3435 (if bob-special
3436 (delq 'org-optimize-window-after-visibility-change
3437 (copy-sequence org-cycle-hook))
3438 org-cycle-hook))
3439 (pos (point)))
3440
3441 (if (or bob-special (equal arg '(4)))
3442 ;; special case: use global cycling
3443 (setq arg t))
3444
3445 (cond
3446
3447 ((org-at-table-p 'any)
3448 ;; Enter the table or move to the next field in the table
3449 (or (org-table-recognize-table.el)
3450 (progn
3451 (if arg (org-table-edit-field t)
3452 (org-table-justify-field-maybe)
3453 (call-interactively 'org-table-next-field)))))
3454
3455 ((eq arg t) ;; Global cycling
3456
3457 (cond
3458 ((and (eq last-command this-command)
3459 (eq org-cycle-global-status 'overview))
3460 ;; We just created the overview - now do table of contents
3461 ;; This can be slow in very large buffers, so indicate action
3462 (message "CONTENTS...")
3463 (org-content)
3464 (message "CONTENTS...done")
3465 (setq org-cycle-global-status 'contents)
3466 (run-hook-with-args 'org-cycle-hook 'contents))
3467
3468 ((and (eq last-command this-command)
3469 (eq org-cycle-global-status 'contents))
3470 ;; We just showed the table of contents - now show everything
3471 (show-all)
3472 (message "SHOW ALL")
3473 (setq org-cycle-global-status 'all)
3474 (run-hook-with-args 'org-cycle-hook 'all))
3475
3476 (t
3477 ;; Default action: go to overview
3478 (org-overview)
3479 (message "OVERVIEW")
3480 (setq org-cycle-global-status 'overview)
3481 (run-hook-with-args 'org-cycle-hook 'overview))))
3482
3483 ((integerp arg)
3484 ;; Show-subtree, ARG levels up from here.
3485 (save-excursion
3486 (org-back-to-heading)
3487 (outline-up-heading (if (< arg 0) (- arg)
3488 (- (funcall outline-level) arg)))
3489 (org-show-subtree)))
3490
3491 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3492 ;; At a heading: rotate between three different views
3493 (org-back-to-heading)
3494 (let ((goal-column 0) eoh eol eos)
3495 ;; First, some boundaries
3496 (save-excursion
3497 (org-back-to-heading)
3498 (save-excursion
3499 (beginning-of-line 2)
3500 (while (and (not (eobp)) ;; this is like `next-line'
3501 (get-char-property (1- (point)) 'invisible))
3502 (beginning-of-line 2)) (setq eol (point)))
3503 (outline-end-of-heading) (setq eoh (point))
3504 (org-end-of-subtree t) (setq eos (point))
3505 (outline-next-heading))
3506 ;; Find out what to do next and set `this-command'
3507 (cond
3508 ((and (= eos eoh)
3509 ;; Nothing is hidden behind this heading
3510 (message "EMPTY ENTRY")
3511 (setq org-cycle-subtree-status nil)))
3512 ((>= eol eos)
3513 ;; Entire subtree is hidden in one line: open it
3514 (org-show-entry)
3515 (show-children)
3516 (message "CHILDREN")
3517 (setq org-cycle-subtree-status 'children)
3518 (run-hook-with-args 'org-cycle-hook 'children))
3519 ((and (eq last-command this-command)
3520 (eq org-cycle-subtree-status 'children))
3521 ;; We just showed the children, now show everything.
3522 (org-show-subtree)
3523 (message "SUBTREE")
3524 (setq org-cycle-subtree-status 'subtree)
3525 (run-hook-with-args 'org-cycle-hook 'subtree))
3526 (t
3527 ;; Default action: hide the subtree.
3528 (hide-subtree)
3529 (message "FOLDED")
3530 (setq org-cycle-subtree-status 'folded)
3531 (run-hook-with-args 'org-cycle-hook 'folded)))))
3532
3533 ;; TAB emulation
3534 (buffer-read-only (org-back-to-heading))
3535
3536 ((org-try-cdlatex-tab))
3537
3538 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3539 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3540 (or (and (eq org-cycle-emulate-tab 'white)
3541 (= (match-end 0) (point-at-eol)))
3542 (and (eq org-cycle-emulate-tab 'whitestart)
3543 (>= (match-end 0) pos))))
3544 t
3545 (eq org-cycle-emulate-tab t))
3546 (if (and (looking-at "[ \n\r\t]")
3547 (string-match "^[ \t]*$" (buffer-substring
3548 (point-at-bol) (point))))
3549 (progn
3550 (beginning-of-line 1)
3551 (and (looking-at "[ \t]+") (replace-match ""))))
3552 (indent-relative))
3553
3554 (t (save-excursion
3555 (org-back-to-heading)
3556 (org-cycle))))))
3557
3558 ;;;###autoload
3559 (defun org-global-cycle (&optional arg)
3560 "Cycle the global visibility. For details see `org-cycle'."
3561 (interactive "P")
3562 (if (integerp arg)
3563 (progn
3564 (show-all)
3565 (hide-sublevels arg)
3566 (setq org-cycle-global-status 'contents))
3567 (org-cycle '(4))))
3568
3569 (defun org-overview ()
3570 "Switch to overview mode, shoing only top-level headlines.
3571 Really, this shows all headlines with level equal or greater than the level
3572 of the first headline in the buffer. This is important, because if the
3573 first headline is not level one, then (hide-sublevels 1) gives confusing
3574 results."
3575 (interactive)
3576 (hide-sublevels (save-excursion
3577 (goto-char (point-min))
3578 (if (re-search-forward (concat "^" outline-regexp) nil t)
3579 (progn
3580 (goto-char (match-beginning 0))
3581 (funcall outline-level))
3582 1))))
3583
3584 ;; FIXME: allow an argument to give a limiting level for this.
3585 (defun org-content ()
3586 "Show all headlines in the buffer, like a table of contents"
3587 (interactive)
3588 (save-excursion
3589 ;; Visit all headings and show their offspring
3590 (goto-char (point-max))
3591 (catch 'exit
3592 (while (and (progn (condition-case nil
3593 (outline-previous-visible-heading 1)
3594 (error (goto-char (point-min))))
3595 t)
3596 (looking-at outline-regexp))
3597 (show-branches)
3598 (if (bobp) (throw 'exit nil))))))
3599
3600
3601 (defun org-optimize-window-after-visibility-change (state)
3602 "Adjust the window after a change in outline visibility.
3603 This function is the default value of the hook `org-cycle-hook'."
3604 (when (get-buffer-window (current-buffer))
3605 (cond
3606 ((eq state 'overview) (org-first-headline-recenter 1))
3607 ((eq state 'content) nil)
3608 ((eq state 'all) nil)
3609 ((eq state 'folded) nil)
3610 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3611 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3612
3613 (defun org-subtree-end-visible-p ()
3614 "Is the end of the current subtree visible?"
3615 (pos-visible-in-window-p
3616 (save-excursion (org-end-of-subtree t) (point))))
3617
3618 (defun org-first-headline-recenter (&optional N)
3619 "Move cursor to the first headline and recenter the headline.
3620 Optional argument N means, put the headline into the Nth line of the window."
3621 (goto-char (point-min))
3622 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3623 (beginning-of-line)
3624 (recenter (prefix-numeric-value N))))
3625
3626 (defvar org-goto-window-configuration nil)
3627 (defvar org-goto-marker nil)
3628 (defvar org-goto-map (make-sparse-keymap))
3629 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3630 (while (setq cmd (pop cmds))
3631 (substitute-key-definition cmd cmd org-goto-map global-map)))
3632 (define-key org-goto-map "\C-m" 'org-goto-ret)
3633 (define-key org-goto-map [(left)] 'org-goto-left)
3634 (define-key org-goto-map [(right)] 'org-goto-right)
3635 (define-key org-goto-map [(?q)] 'org-goto-quit)
3636 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3637 (define-key org-goto-map "\C-i" 'org-cycle)
3638 (define-key org-goto-map [(tab)] 'org-cycle)
3639 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3640 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3641 (define-key org-goto-map "n" 'outline-next-visible-heading)
3642 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3643 (define-key org-goto-map "f" 'outline-forward-same-level)
3644 (define-key org-goto-map "b" 'outline-backward-same-level)
3645 (define-key org-goto-map "u" 'outline-up-heading)
3646 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3647 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3648 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3649 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3650 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3651 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3652 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3653
3654 (defconst org-goto-help
3655 "Select a location to jump to, press RET
3656 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3657
3658 (defun org-goto ()
3659 "Go to a different location of the document, keeping current visibility.
3660
3661 When you want to go to a different location in a document, the fastest way
3662 is often to fold the entire buffer and then dive into the tree. This
3663 method has the disadvantage, that the previous location will be folded,
3664 which may not be what you want.
3665
3666 This command works around this by showing a copy of the current buffer in
3667 overview mode. You can dive into the tree in that copy, to find the
3668 location you want to reach. When pressing RET, the command returns to the
3669 original buffer in which the visibility is still unchanged. It then jumps
3670 to the new location, making it and the headline hierarchy above it visible."
3671 (interactive)
3672 (let* ((org-goto-start-pos (point))
3673 (selected-point
3674 (org-get-location (current-buffer) org-goto-help)))
3675 (if selected-point
3676 (progn
3677 (org-mark-ring-push org-goto-start-pos)
3678 (goto-char selected-point)
3679 (if (or (org-invisible-p) (org-invisible-p2))
3680 (org-show-hierarchy-above)))
3681 (error "Quit"))))
3682
3683 (defun org-get-location (buf help)
3684 "Let the user select a location in the Org-mode buffer BUF.
3685 This function uses a recursive edit. It returns the selected position
3686 or nil."
3687 (let (org-selected-point)
3688 (save-excursion
3689 (save-window-excursion
3690 (delete-other-windows)
3691 (switch-to-buffer (get-buffer-create "*org-goto*"))
3692 (with-output-to-temp-buffer "*Help*"
3693 (princ help))
3694 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3695 (setq buffer-read-only nil)
3696 (erase-buffer)
3697 (insert-buffer-substring buf)
3698 (let ((org-startup-truncated t)
3699 (org-startup-folded t)
3700 (org-startup-align-all-tables nil)
3701 (org-startup-with-deadline-check nil))
3702 (org-mode))
3703 (setq buffer-read-only t)
3704 (if (boundp 'org-goto-start-pos)
3705 (goto-char org-goto-start-pos)
3706 (goto-char (point-min)))
3707 (org-beginning-of-line)
3708 (message "Select location and press RET")
3709 ;; now we make sure that during selection, ony very few keys work
3710 ;; and that it is impossible to switch to another window.
3711 (let ((gm (current-global-map))
3712 (overriding-local-map org-goto-map))
3713 (unwind-protect
3714 (progn
3715 (use-global-map org-goto-map)
3716 (recursive-edit))
3717 (use-global-map gm)))))
3718 (kill-buffer "*org-goto*")
3719 org-selected-point))
3720
3721 (defun org-goto-ret (&optional arg)
3722 "Finish `org-goto' by going to the new location."
3723 (interactive "P")
3724 (setq org-selected-point (point)
3725 current-prefix-arg arg)
3726 (throw 'exit nil))
3727
3728 (defun org-goto-left ()
3729 "Finish `org-goto' by going to the new location."
3730 (interactive)
3731 (if (org-on-heading-p)
3732 (progn
3733 (beginning-of-line 1)
3734 (setq org-selected-point (point)
3735 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3736 (throw 'exit nil))
3737 (error "Not on a heading")))
3738
3739 (defun org-goto-right ()
3740 "Finish `org-goto' by going to the new location."
3741 (interactive)
3742 (if (org-on-heading-p)
3743 (progn
3744 (outline-end-of-subtree)
3745 (or (eobp) (forward-char 1))
3746 (setq org-selected-point (point)
3747 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3748 (throw 'exit nil))
3749 (error "Not on a heading")))
3750
3751 (defun org-goto-quit ()
3752 "Finish `org-goto' without cursor motion."
3753 (interactive)
3754 (setq org-selected-point nil)
3755 (throw 'exit nil))
3756
3757 ;;; Promotion, Demotion, Inserting new headlines
3758
3759 (defvar org-ignore-region nil
3760 "To temporarily disable the active region.")
3761
3762 (defun org-insert-heading (&optional force-heading)
3763 "Insert a new heading or item with same depth at point.
3764 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3765 If point is at the beginning of a headline, insert a sibling before the
3766 current headline. If point is in the middle of a headline, split the headline
3767 at that position and make the rest of the headline part of the sibling below
3768 the current headline."
3769 (interactive "P")
3770 (if (= (buffer-size) 0)
3771 (insert "\n* ")
3772 (when (or force-heading (not (org-insert-item)))
3773 (let* ((head (save-excursion
3774 (condition-case nil
3775 (progn
3776 (org-back-to-heading)
3777 (match-string 0))
3778 (error "*"))))
3779 pos)
3780 (cond
3781 ((and (org-on-heading-p) (bolp)
3782 (save-excursion (backward-char 1) (not (org-invisible-p))))
3783 (open-line 1))
3784 ((and (bolp) (save-excursion
3785 (backward-char 1) (not (org-invisible-p))))
3786 nil)
3787 (t (newline)))
3788 (insert head) (just-one-space)
3789 (setq pos (point))
3790 (end-of-line 1)
3791 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3792 (run-hooks 'org-insert-heading-hook)))))
3793
3794 (defun org-insert-item (&optional checkbox)
3795 "Insert a new item at the current level.
3796 Return t when things worked, nil when we are not in an item."
3797 (when (save-excursion
3798 (condition-case nil
3799 (progn
3800 (org-beginning-of-item)
3801 (org-at-item-p)
3802 t)
3803 (error nil)))
3804 (let* ((bul (match-string 0))
3805 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3806 (match-end 0)))
3807 pos)
3808 (cond
3809 ((and (org-at-item-p) (<= (point) eow))
3810 ;; before the bullet
3811 (beginning-of-line 1)
3812 (open-line 1))
3813 ((<= (point) eow)
3814 (beginning-of-line 1))
3815 (t (newline)))
3816 (insert bul (if checkbox "[ ]" ""))
3817 (just-one-space)
3818 (setq pos (point))
3819 (end-of-line 1)
3820 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3821 (org-maybe-renumber-ordered-list)
3822 t))
3823
3824 (defun org-insert-todo-heading (arg)
3825 "Insert a new heading with the same level and TODO state as current heading.
3826 If the heading has no TODO state, or if the state is DONE, use the first
3827 state (TODO by default). Also with prefix arg, force first state."
3828 (interactive "P")
3829 (when (not (org-insert-item 'checkbox))
3830 (org-insert-heading)
3831 (save-excursion
3832 (org-back-to-heading)
3833 (outline-previous-heading)
3834 (looking-at org-todo-line-regexp))
3835 (if (or arg
3836 (not (match-beginning 2))
3837 (equal (match-string 2) org-done-string))
3838 (insert (car org-todo-keywords) " ")
3839 (insert (match-string 2) " "))))
3840
3841 (defun org-promote-subtree ()
3842 "Promote the entire subtree.
3843 See also `org-promote'."
3844 (interactive)
3845 (save-excursion
3846 (org-map-tree 'org-promote)))
3847
3848 (defun org-demote-subtree ()
3849 "Demote the entire subtree. See `org-demote'.
3850 See also `org-promote'."
3851 (interactive)
3852 (save-excursion
3853 (org-map-tree 'org-demote)))
3854
3855 (defun org-do-promote ()
3856 "Promote the current heading higher up the tree.
3857 If the region is active in `transient-mark-mode', promote all headings
3858 in the region."
3859 (interactive)
3860 (save-excursion
3861 (if (org-region-active-p)
3862 (org-map-region 'org-promote (region-beginning) (region-end))
3863 (org-promote)))
3864 (org-fix-position-after-promote))
3865
3866 (defun org-do-demote ()
3867 "Demote the current heading lower down the tree.
3868 If the region is active in `transient-mark-mode', demote all headings
3869 in the region."
3870 (interactive)
3871 (save-excursion
3872 (if (org-region-active-p)
3873 (org-map-region 'org-demote (region-beginning) (region-end))
3874 (org-demote)))
3875 (org-fix-position-after-promote))
3876
3877 (defun org-fix-position-after-promote ()
3878 "Make sure that after pro/demotion cursor position is right."
3879 (and (equal (char-after) ?\ )
3880 (equal (char-before) ?*)
3881 (forward-char 1)))
3882
3883 (defun org-get-legal-level (level change)
3884 "Rectify a level change under the influence of `org-odd-levels-only'
3885 LEVEL is a current level, CHANGE is by how much the level should be
3886 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3887 even level numbers will become the next higher odd number."
3888 (if org-odd-levels-only
3889 (cond ((not change) (1+ (* 2 (/ level 2))))
3890 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3891 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3892 (max 1 (+ level change))))
3893
3894 (defun org-promote ()
3895 "Promote the current heading higher up the tree.
3896 If the region is active in `transient-mark-mode', promote all headings
3897 in the region."
3898 (org-back-to-heading t)
3899 (let* ((level (save-match-data (funcall outline-level)))
3900 (up-head (make-string (org-get-legal-level level -1) ?*))
3901 (diff (abs (- level (length up-head)))))
3902 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3903 (replace-match up-head nil t)
3904 ;; Fixup tag positioning
3905 (and org-auto-align-tags (org-set-tags nil t))
3906 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
3907
3908 (defun org-demote ()
3909 "Demote the current heading lower down the tree.
3910 If the region is active in `transient-mark-mode', demote all headings
3911 in the region."
3912 (org-back-to-heading t)
3913 (let* ((level (save-match-data (funcall outline-level)))
3914 (down-head (make-string (org-get-legal-level level 1) ?*))
3915 (diff (abs (- level (length down-head)))))
3916 (replace-match down-head nil t)
3917 ;; Fixup tag positioning
3918 (and org-auto-align-tags (org-set-tags nil t))
3919 (if org-adapt-indentation (org-fixup-indentation diff))))
3920
3921 (defun org-map-tree (fun)
3922 "Call FUN for every heading underneath the current one."
3923 (org-back-to-heading)
3924 (let ((level (funcall outline-level)))
3925 (save-excursion
3926 (funcall fun)
3927 (while (and (progn
3928 (outline-next-heading)
3929 (> (funcall outline-level) level))
3930 (not (eobp)))
3931 (funcall fun)))))
3932
3933 (defun org-map-region (fun beg end)
3934 "Call FUN for every heading between BEG and END."
3935 (let ((org-ignore-region t))
3936 (save-excursion
3937 (setq end (copy-marker end))
3938 (goto-char beg)
3939 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3940 (< (point) end))
3941 (funcall fun))
3942 (while (and (progn
3943 (outline-next-heading)
3944 (< (point) end))
3945 (not (eobp)))
3946 (funcall fun)))))
3947
3948 (defun org-fixup-indentation (diff)
3949 "Change the indentation in the current entry by DIFF
3950 However, if any line in the current entry has no indentation, or if it
3951 would end up with no indentation after the change, nothing at all is done."
3952 (save-excursion
3953 (let ((end (save-excursion (outline-next-heading)
3954 (point-marker)))
3955 (prohibit (if (> diff 0)
3956 "^\\S-"
3957 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
3958 col)
3959 (unless (save-excursion (re-search-forward prohibit end t))
3960 (while (re-search-forward "^[ \t]+" end t)
3961 (goto-char (match-end 0))
3962 (setq col (current-column))
3963 (if (< diff 0) (replace-match ""))
3964 (indent-to (+ diff col))))
3965 (move-marker end nil))))
3966
3967 ;;; Vertical tree motion, cutting and pasting of subtrees
3968
3969 (defun org-move-subtree-up (&optional arg)
3970 "Move the current subtree up past ARG headlines of the same level."
3971 (interactive "p")
3972 (org-move-subtree-down (- (prefix-numeric-value arg))))
3973
3974 (defun org-move-subtree-down (&optional arg)
3975 "Move the current subtree down past ARG headlines of the same level."
3976 (interactive "p")
3977 (setq arg (prefix-numeric-value arg))
3978 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3979 'outline-get-last-sibling))
3980 (ins-point (make-marker))
3981 (cnt (abs arg))
3982 beg end txt folded)
3983 ;; Select the tree
3984 (org-back-to-heading)
3985 (setq beg (point))
3986 (save-match-data
3987 (save-excursion (outline-end-of-heading)
3988 (setq folded (org-invisible-p)))
3989 (outline-end-of-subtree))
3990 (outline-next-heading)
3991 (setq end (point))
3992 ;; Find insertion point, with error handling
3993 (goto-char beg)
3994 (while (> cnt 0)
3995 (or (and (funcall movfunc) (looking-at outline-regexp))
3996 (progn (goto-char beg)
3997 (error "Cannot move past superior level or buffer limit")))
3998 (setq cnt (1- cnt)))
3999 (if (> arg 0)
4000 ;; Moving forward - still need to move over subtree
4001 (progn (outline-end-of-subtree)
4002 (outline-next-heading)
4003 (if (not (or (looking-at (concat "^" outline-regexp))
4004 (bolp)))
4005 (newline))))
4006 (move-marker ins-point (point))
4007 (setq txt (buffer-substring beg end))
4008 (delete-region beg end)
4009 (insert txt)
4010 (goto-char ins-point)
4011 (if folded (hide-subtree))
4012 (move-marker ins-point nil)))
4013
4014 (defvar org-subtree-clip ""
4015 "Clipboard for cut and paste of subtrees.
4016 This is actually only a copy of the kill, because we use the normal kill
4017 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4018
4019 (defvar org-subtree-clip-folded nil
4020 "Was the last copied subtree folded?
4021 This is used to fold the tree back after pasting.")
4022
4023 (defun org-cut-subtree ()
4024 "Cut the current subtree into the clipboard.
4025 This is a short-hand for marking the subtree and then cutting it."
4026 (interactive)
4027 (org-copy-subtree 'cut))
4028
4029 (defun org-copy-subtree (&optional cut)
4030 "Cut the current subtree into the clipboard.
4031 This is a short-hand for marking the subtree and then copying it.
4032 If CUT is non nil, actually cut the subtree."
4033 (interactive)
4034 (let (beg end folded)
4035 (org-back-to-heading)
4036 (setq beg (point))
4037 (save-match-data
4038 (save-excursion (outline-end-of-heading)
4039 (setq folded (org-invisible-p)))
4040 (outline-end-of-subtree))
4041 (if (equal (char-after) ?\n) (forward-char 1))
4042 (setq end (point))
4043 (goto-char beg)
4044 (when (> end beg)
4045 (setq org-subtree-clip-folded folded)
4046 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4047 (setq org-subtree-clip (current-kill 0))
4048 (message "%s: Subtree with %d characters"
4049 (if cut "Cut" "Copied")
4050 (length org-subtree-clip)))))
4051
4052 (defun org-paste-subtree (&optional level tree)
4053 "Paste the clipboard as a subtree, with modification of headline level.
4054 The entire subtree is promoted or demoted in order to match a new headline
4055 level. By default, the new level is derived from the visible headings
4056 before and after the insertion point, and taken to be the inferior headline
4057 level of the two. So if the previous visible heading is level 3 and the
4058 next is level 4 (or vice versa), level 4 will be used for insertion.
4059 This makes sure that the subtree remains an independent subtree and does
4060 not swallow low level entries.
4061
4062 You can also force a different level, either by using a numeric prefix
4063 argument, or by inserting the heading marker by hand. For example, if the
4064 cursor is after \"*****\", then the tree will be shifted to level 5.
4065
4066 If you want to insert the tree as is, just use \\[yank].
4067
4068 If optional TREE is given, use this text instead of the kill ring."
4069 (interactive "P")
4070 (unless (org-kill-is-subtree-p tree)
4071 (error
4072 (substitute-command-keys
4073 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4074 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4075 (^re (concat "^\\(" outline-regexp "\\)"))
4076 (re (concat "\\(" outline-regexp "\\)"))
4077 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4078
4079 (old-level (if (string-match ^re txt)
4080 (- (match-end 0) (match-beginning 0))
4081 -1))
4082 (force-level (cond (level (prefix-numeric-value level))
4083 ((string-match
4084 ^re_ (buffer-substring (point-at-bol) (point)))
4085 (- (match-end 0) (match-beginning 0)))
4086 (t nil)))
4087 (previous-level (save-excursion
4088 (condition-case nil
4089 (progn
4090 (outline-previous-visible-heading 1)
4091 (if (looking-at re)
4092 (- (match-end 0) (match-beginning 0))
4093 1))
4094 (error 1))))
4095 (next-level (save-excursion
4096 (condition-case nil
4097 (progn
4098 (outline-next-visible-heading 1)
4099 (if (looking-at re)
4100 (- (match-end 0) (match-beginning 0))
4101 1))
4102 (error 1))))
4103 (new-level (or force-level (max previous-level next-level)))
4104 (shift (if (or (= old-level -1)
4105 (= new-level -1)
4106 (= old-level new-level))
4107 0
4108 (- new-level old-level)))
4109 (shift1 shift)
4110 (delta (if (> shift 0) -1 1))
4111 (func (if (> shift 0) 'org-demote 'org-promote))
4112 (org-odd-levels-only nil)
4113 beg end)
4114 ;; Remove the forces level indicator
4115 (if force-level
4116 (delete-region (point-at-bol) (point)))
4117 ;; Make sure we start at the beginning of an empty line
4118 (if (not (bolp)) (insert "\n"))
4119 (if (not (looking-at "[ \t]*$"))
4120 (progn (insert "\n") (backward-char 1)))
4121 ;; Paste
4122 (setq beg (point))
4123 (if (string-match "[ \t\r\n]+\\'" txt)
4124 (setq txt (replace-match "\n" t t txt)))
4125 (insert txt)
4126 (setq end (point))
4127 (if (looking-at "[ \t\r\n]+")
4128 (replace-match "\n"))
4129 (goto-char beg)
4130 ;; Shift if necessary
4131 (if (= shift 0)
4132 (message "Pasted at level %d, without shift" new-level)
4133 (save-restriction
4134 (narrow-to-region beg end)
4135 (while (not (= shift 0))
4136 (org-map-region func (point-min) (point-max))
4137 (setq shift (+ delta shift)))
4138 (goto-char (point-min))
4139 (message "Pasted at level %d, with shift by %d levels"
4140 new-level shift1)))
4141 (if (and kill-ring
4142 (eq org-subtree-clip (current-kill 0))
4143 org-subtree-clip-folded)
4144 ;; The tree was folded before it was killed/copied
4145 (hide-subtree))))
4146
4147 (defun org-kill-is-subtree-p (&optional txt)
4148 "Check if the current kill is an outline subtree, or a set of trees.
4149 Returns nil if kill does not start with a headline, or if the first
4150 headline level is not the largest headline level in the tree.
4151 So this will actually accept several entries of equal levels as well,
4152 which is OK for `org-paste-subtree'.
4153 If optional TXT is given, check this string instead of the current kill."
4154 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4155 (start-level (and kill
4156 (string-match (concat "\\`" outline-regexp) kill)
4157 (- (match-end 0) (match-beginning 0))))
4158 (re (concat "^" outline-regexp))
4159 (start 1))
4160 (if (not start-level)
4161 nil ;; does not even start with a heading
4162 (catch 'exit
4163 (while (setq start (string-match re kill (1+ start)))
4164 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4165 (throw 'exit nil)))
4166 t))))
4167
4168 (defun org-narrow-to-subtree ()
4169 "Narrow buffer to the current subtree."
4170 (interactive)
4171 (save-excursion
4172 (narrow-to-region
4173 (progn (org-back-to-heading) (point))
4174 (progn (org-end-of-subtree t) (point)))))
4175
4176 ;;; Plain list items
4177
4178 (defun org-at-item-p ()
4179 "Is point in a line starting a hand-formatted item?"
4180 (let ((llt org-plain-list-ordered-item-terminator))
4181 (save-excursion
4182 (goto-char (point-at-bol))
4183 (looking-at
4184 (cond
4185 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4186 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4187 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4188 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4189
4190 (defun org-at-item-checkbox-p ()
4191 "Is point at a line starting a plain-list item with a checklet?"
4192 (and (org-at-item-p)
4193 (save-excursion
4194 (goto-char (match-end 0))
4195 (skip-chars-forward " \t")
4196 (looking-at "\\[[ X]\\]"))))
4197
4198 (defun org-toggle-checkbox (&optional arg)
4199 "Toggle the checkbox in the current line."
4200 (interactive "P")
4201 (catch 'exit
4202 (let (beg end status (firstnew 'unknown))
4203 (cond
4204 ((org-region-active-p)
4205 (setq beg (region-beginning) end (region-end)))
4206 ((org-on-heading-p)
4207 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4208 ((org-at-item-checkbox-p)
4209 (save-excursion
4210 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4211 (throw 'exit t))
4212 (t (error "Not at a checkbox or heading, and no active region")))
4213 (save-excursion
4214 (goto-char beg)
4215 (while (< (point) end)
4216 (when (org-at-item-checkbox-p)
4217 (setq status (equal (match-string 0) "[X]"))
4218 (when (eq firstnew 'unknown)
4219 (setq firstnew (not status)))
4220 (replace-match
4221 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4222 (beginning-of-line 2))))))
4223
4224 (defun org-get-indentation (&optional line)
4225 "Get the indentation of the current line, interpreting tabs.
4226 When LINE is given, assume it represents a line and compute its indentation."
4227 (if line
4228 (if (string-match "^ *" (org-remove-tabs line))
4229 (match-end 0))
4230 (save-excursion
4231 (beginning-of-line 1)
4232 (skip-chars-forward " \t")
4233 (current-column))))
4234
4235 (defun org-remove-tabs (s &optional width)
4236 "Replace tabulators in S with spaces.
4237 Assumes that s is a single line, starting in column 0."
4238 (setq width (or width tab-width))
4239 (while (string-match "\t" s)
4240 (setq s (replace-match
4241 (make-string
4242 (- (* width (/ (+ (match-beginning 0) width) width))
4243 (match-beginning 0)) ?\ )
4244 t t s)))
4245 s)
4246
4247 ;; FIXME: document properly.
4248 (defun org-fix-indentation (line ind)
4249 "If the current indenation is smaller than ind1, leave it alone.
4250 If it is larger than ind, reduce it by ind."
4251 (let* ((l (org-remove-tabs line))
4252 (i (org-get-indentation l))
4253 (i1 (car ind)) (i2 (cdr ind)))
4254 (if (>= i i2) (setq l (substring line i2)))
4255 (if (> i1 0)
4256 (concat (make-string i1 ?\ ) l)
4257 l)))
4258
4259 (defun org-beginning-of-item ()
4260 "Go to the beginning of the current hand-formatted item.
4261 If the cursor is not in an item, throw an error."
4262 (interactive)
4263 (let ((pos (point))
4264 (limit (save-excursion (org-back-to-heading)
4265 (beginning-of-line 2) (point)))
4266 ind ind1)
4267 (if (org-at-item-p)
4268 (beginning-of-line 1)
4269 (beginning-of-line 1)
4270 (skip-chars-forward " \t")
4271 (setq ind (current-column))
4272 (if (catch 'exit
4273 (while t
4274 (beginning-of-line 0)
4275 (if (< (point) limit) (throw 'exit nil))
4276 (unless (looking-at "[ \t]*$")
4277 (skip-chars-forward " \t")
4278 (setq ind1 (current-column))
4279 (if (< ind1 ind)
4280 (throw 'exit (org-at-item-p))))))
4281 nil
4282 (goto-char pos)
4283 (error "Not in an item")))))
4284
4285 (defun org-end-of-item ()
4286 "Go to the end of the current hand-formatted item.
4287 If the cursor is not in an item, throw an error."
4288 (interactive)
4289 (let ((pos (point))
4290 (limit (save-excursion (outline-next-heading) (point)))
4291 (ind (save-excursion
4292 (org-beginning-of-item)
4293 (skip-chars-forward " \t")
4294 (current-column)))
4295 ind1)
4296 (if (catch 'exit
4297 (while t
4298 (beginning-of-line 2)
4299 (if (>= (point) limit) (throw 'exit t))
4300 (unless (looking-at "[ \t]*$")
4301 (skip-chars-forward " \t")
4302 (setq ind1 (current-column))
4303 (if (<= ind1 ind) (throw 'exit t)))))
4304 (beginning-of-line 1)
4305 (goto-char pos)
4306 (error "Not in an item"))))
4307
4308 (defun org-next-item ()
4309 "Move to the beginning of the next item in the current plain list.
4310 Error if not at a plain list, or if this is the last item in the list."
4311 (interactive)
4312 (let (ind ind1 (pos (point)))
4313 (org-beginning-of-item)
4314 (setq ind (org-get-indentation))
4315 (org-end-of-item)
4316 (setq ind1 (org-get-indentation))
4317 (unless (and (org-at-item-p) (= ind ind1))
4318 (goto-char pos)
4319 (error "On last item"))))
4320
4321 (defun org-previous-item ()
4322 "Move to the beginning of the previous item in the current plain list.
4323 Error if not at a plain list, or if this is the last item in the list."
4324 (interactive)
4325 (let (beg ind (pos (point)))
4326 (org-beginning-of-item)
4327 (setq beg (point))
4328 (setq ind (org-get-indentation))
4329 (goto-char beg)
4330 (catch 'exit
4331 (while t
4332 (beginning-of-line 0)
4333 (if (looking-at "[ \t]*$")
4334 nil
4335 (if (<= (org-get-indentation) ind)
4336 (throw 'exit t)))))
4337 (condition-case nil
4338 (org-beginning-of-item)
4339 (error (goto-char pos)
4340 (error "On first item")))))
4341
4342 (defun org-move-item-down ()
4343 "Move the plain list item at point down, i.e. swap with following item.
4344 Subitems (items with larger indentation) are considered part of the item,
4345 so this really moves item trees."
4346 (interactive)
4347 (let (beg end ind ind1 (pos (point)) txt)
4348 (org-beginning-of-item)
4349 (setq beg (point))
4350 (setq ind (org-get-indentation))
4351 (org-end-of-item)
4352 (setq end (point))
4353 (setq ind1 (org-get-indentation))
4354 (if (and (org-at-item-p) (= ind ind1))
4355 (progn
4356 (org-end-of-item)
4357 (setq txt (buffer-substring beg end))
4358 (save-excursion
4359 (delete-region beg end))
4360 (setq pos (point))
4361 (insert txt)
4362 (goto-char pos)
4363 (org-maybe-renumber-ordered-list))
4364 (goto-char pos)
4365 (error "Cannot move this item further down"))))
4366
4367 (defun org-move-item-up (arg)
4368 "Move the plain list item at point up, i.e. swap with previous item.
4369 Subitems (items with larger indentation) are considered part of the item,
4370 so this really moves item trees."
4371 (interactive "p")
4372 (let (beg end ind ind1 (pos (point)) txt)
4373 (org-beginning-of-item)
4374 (setq beg (point))
4375 (setq ind (org-get-indentation))
4376 (org-end-of-item)
4377 (setq end (point))
4378 (goto-char beg)
4379 (catch 'exit
4380 (while t
4381 (beginning-of-line 0)
4382 (if (looking-at "[ \t]*$")
4383 nil
4384 (if (<= (setq ind1 (org-get-indentation)) ind)
4385 (throw 'exit t)))))
4386 (condition-case nil
4387 (org-beginning-of-item)
4388 (error (goto-char beg)
4389 (error "Cannot move this item further up")))
4390 (setq ind1 (org-get-indentation))
4391 (if (and (org-at-item-p) (= ind ind1))
4392 (progn
4393 (setq txt (buffer-substring beg end))
4394 (save-excursion
4395 (delete-region beg end))
4396 (setq pos (point))
4397 (insert txt)
4398 (goto-char pos)
4399 (org-maybe-renumber-ordered-list))
4400 (goto-char pos)
4401 (error "Cannot move this item further up"))))
4402
4403 (defun org-maybe-renumber-ordered-list ()
4404 "Renumber the ordered list at point if setup allows it.
4405 This tests the user option `org-auto-renumber-ordered-lists' before
4406 doing the renumbering."
4407 (and org-auto-renumber-ordered-lists
4408 (org-at-item-p)
4409 (match-beginning 3)
4410 (org-renumber-ordered-list 1)))
4411
4412 (defun org-get-string-indentation (s)
4413 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4414 (let ((n -1) (i 0) (w tab-width) c)
4415 (catch 'exit
4416 (while (< (setq n (1+ n)) (length s))
4417 (setq c (aref s n))
4418 (cond ((= c ?\ ) (setq i (1+ i)))
4419 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4420 (t (throw 'exit t)))))
4421 i))
4422
4423 (defun org-renumber-ordered-list (arg)
4424 "Renumber an ordered plain list.
4425 Cursor needs to be in the first line of an item, the line that starts
4426 with something like \"1.\" or \"2)\"."
4427 (interactive "p")
4428 (unless (and (org-at-item-p)
4429 (match-beginning 3))
4430 (error "This is not an ordered list"))
4431 (let ((line (org-current-line))
4432 (col (current-column))
4433 (ind (org-get-string-indentation
4434 (buffer-substring (point-at-bol) (match-beginning 3))))
4435 ;; (term (substring (match-string 3) -1))
4436 ind1 (n (1- arg)))
4437 ;; find where this list begins
4438 (catch 'exit
4439 (while t
4440 (catch 'next
4441 (beginning-of-line 0)
4442 (if (looking-at "[ \t]*$") (throw 'next t))
4443 (skip-chars-forward " \t") (setq ind1 (current-column))
4444 (if (or (< ind1 ind)
4445 (and (= ind1 ind)
4446 (not (org-at-item-p))))
4447 (throw 'exit t)))))
4448 ;; Walk forward and replace these numbers
4449 (catch 'exit
4450 (while t
4451 (catch 'next
4452 (beginning-of-line 2)
4453 (if (eobp) (throw 'exit nil))
4454 (if (looking-at "[ \t]*$") (throw 'next nil))
4455 (skip-chars-forward " \t") (setq ind1 (current-column))
4456 (if (> ind1 ind) (throw 'next t))
4457 (if (< ind1 ind) (throw 'exit t))
4458 (if (not (org-at-item-p)) (throw 'exit nil))
4459 (if (not (match-beginning 3))
4460 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4461 (delete-region (match-beginning 3) (1- (match-end 3)))
4462 (goto-char (match-beginning 3))
4463 (insert (format "%d" (setq n (1+ n)))))))
4464 (goto-line line)
4465 (move-to-column col)))
4466
4467 (defvar org-last-indent-begin-marker (make-marker))
4468 (defvar org-last-indent-end-marker (make-marker))
4469
4470 (defun org-outdent-item (arg)
4471 "Outdent a local list item."
4472 (interactive "p")
4473 (org-indent-item (- arg)))
4474
4475 (defun org-indent-item (arg)
4476 "Indent a local list item."
4477 (interactive "p")
4478 (unless (org-at-item-p)
4479 (error "Not on an item"))
4480 (save-excursion
4481 (let (beg end ind ind1)
4482 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4483 (setq beg org-last-indent-begin-marker
4484 end org-last-indent-end-marker)
4485 (org-beginning-of-item)
4486 (setq beg (move-marker org-last-indent-begin-marker (point)))
4487 (org-end-of-item)
4488 (setq end (move-marker org-last-indent-end-marker (point))))
4489 (goto-char beg)
4490 (skip-chars-forward " \t") (setq ind (current-column))
4491 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4492 (while (< (point) end)
4493 (beginning-of-line 1)
4494 (skip-chars-forward " \t") (setq ind1 (current-column))
4495 (delete-region (point-at-bol) (point))
4496 (indent-to-column (+ ind1 arg))
4497 (beginning-of-line 2)))))
4498
4499 ;;; Archiving
4500
4501 (defun org-archive-subtree (&optional find-done)
4502 "Move the current subtree to the archive.
4503 The archive can be a certain top-level heading in the current file, or in
4504 a different file. The tree will be moved to that location, the subtree
4505 heading be marked DONE, and the current time will be added.
4506
4507 When called with prefix argument FIND-DONE, find whole trees without any
4508 open TODO items and archive them (after getting confirmation from the user).
4509 If the cursor is not at a headline when this comand is called, try all level
4510 1 trees. If the cursor is on a headline, only try the direct children of
4511 this heading. "
4512 (interactive "P")
4513 (if find-done
4514 (org-archive-all-done)
4515 ;; Save all relevant TODO keyword-relatex variables
4516
4517 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4518 (tr-org-todo-keywords org-todo-keywords)
4519 (tr-org-todo-interpretation org-todo-interpretation)
4520 (tr-org-done-string org-done-string)
4521 (tr-org-todo-regexp org-todo-regexp)
4522 (tr-org-todo-line-regexp org-todo-line-regexp)
4523 (this-buffer (current-buffer))
4524 file heading buffer level newfile-p)
4525 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4526 (progn
4527 (setq file (format (match-string 1 org-archive-location)
4528 (file-name-nondirectory buffer-file-name))
4529 heading (match-string 2 org-archive-location)))
4530 (error "Invalid `org-archive-location'"))
4531 (if (> (length file) 0)
4532 (setq newfile-p (not (file-exists-p file))
4533 buffer (find-file-noselect file))
4534 (setq buffer (current-buffer)))
4535 (unless buffer
4536 (error "Cannot access file \"%s\"" file))
4537 (if (and (> (length heading) 0)
4538 (string-match "^\\*+" heading))
4539 (setq level (match-end 0))
4540 (setq heading nil level 0))
4541 (save-excursion
4542 ;; We first only copy, in case something goes wrong
4543 ;; we need to protect this-command, to avoid kill-region sets it,
4544 ;; which would lead to duplication of subtrees
4545 (let (this-command) (org-copy-subtree))
4546 (set-buffer buffer)
4547 ;; Enforce org-mode for the archive buffer
4548 (if (not (org-mode-p))
4549 ;; Force the mode for future visits.
4550 (let ((org-insert-mode-line-in-empty-file t))
4551 (call-interactively 'org-mode)))
4552 (when newfile-p
4553 (goto-char (point-max))
4554 (insert (format "\nArchived entries from file %s\n\n"
4555 (buffer-file-name this-buffer))))
4556 ;; Force the TODO keywords of the original buffer
4557 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4558 (org-todo-keywords tr-org-todo-keywords)
4559 (org-todo-interpretation tr-org-todo-interpretation)
4560 (org-done-string tr-org-done-string)
4561 (org-todo-regexp tr-org-todo-regexp)
4562 (org-todo-line-regexp tr-org-todo-line-regexp))
4563 (goto-char (point-min))
4564 (if heading
4565 (progn
4566 (if (re-search-forward
4567 (concat "\\(^\\|\r\\)"
4568 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4569 nil t)
4570 (goto-char (match-end 0))
4571 ;; Heading not found, just insert it at the end
4572 (goto-char (point-max))
4573 (or (bolp) (insert "\n"))
4574 (insert "\n" heading "\n")
4575 (end-of-line 0))
4576 ;; Make the subtree visible
4577 (show-subtree)
4578 (org-end-of-subtree t)
4579 (skip-chars-backward " \t\r\n")
4580 (and (looking-at "[ \t\r\n]*")
4581 (replace-match "\n\n")))
4582 ;; No specific heading, just go to end of file.
4583 (goto-char (point-max)) (insert "\n"))
4584 ;; Paste
4585 (org-paste-subtree (1+ level))
4586 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4587 (if org-archive-mark-done
4588 (org-todo (length org-todo-keywords)))
4589 ;; Move cursor to right after the TODO keyword
4590 (when org-archive-stamp-time
4591 (beginning-of-line 1)
4592 (looking-at org-todo-line-regexp)
4593 (goto-char (or (match-end 2) (match-beginning 3)))
4594 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4595 (org-current-time))
4596 ")"))
4597 ;; Save the buffer, if it is not the same buffer.
4598 (if (not (eq this-buffer buffer)) (save-buffer))))
4599 ;; Here we are back in the original buffer. Everything seems to have
4600 ;; worked. So now cut the tree and finish up.
4601 (let (this-command) (org-cut-subtree))
4602 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4603 (message "Subtree archived %s"
4604 (if (eq this-buffer buffer)
4605 (concat "under heading: " heading)
4606 (concat "in file: " (abbreviate-file-name file)))))))
4607
4608 (defun org-archive-all-done (&optional tag)
4609 "Archive sublevels of the current tree without open TODO items.
4610 If the cursor is not on a headline, try all level 1 trees. If
4611 it is on a headline, try all direct children.
4612 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4613 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4614 (rea (concat ".*:" org-archive-tag ":"))
4615 (begm (make-marker))
4616 (endm (make-marker))
4617 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4618 "Move subtree to archive (no open TODO items)? "))
4619 beg end (cntarch 0))
4620 (if (org-on-heading-p)
4621 (progn
4622 (setq re1 (concat "^" (regexp-quote
4623 (make-string
4624 (1+ (- (match-end 0) (match-beginning 0)))
4625 ?*))
4626 " "))
4627 (move-marker begm (point))
4628 (move-marker endm (org-end-of-subtree)))
4629 (setq re1 "^* ")
4630 (move-marker begm (point-min))
4631 (move-marker endm (point-max)))
4632 (save-excursion
4633 (goto-char begm)
4634 (while (re-search-forward re1 endm t)
4635 (setq beg (match-beginning 0)
4636 end (save-excursion (org-end-of-subtree t) (point)))
4637 (goto-char beg)
4638 (if (re-search-forward re end t)
4639 (goto-char end)
4640 (goto-char beg)
4641 (if (and (or (not tag) (not (looking-at rea)))
4642 (y-or-n-p question))
4643 (progn
4644 (if tag
4645 (org-toggle-tag org-archive-tag 'on)
4646 (org-archive-subtree))
4647 (setq cntarch (1+ cntarch)))
4648 (goto-char end)))))
4649 (message "%d trees archived" cntarch)))
4650
4651 (defun org-cycle-hide-archived-subtrees (state)
4652 "Re-hide all archived subtrees after a visibility state change."
4653 (when (and (not org-cycle-open-archived-trees)
4654 (not (memq state '(overview folded))))
4655 (save-excursion
4656 (let* ((globalp (memq state '(contents all)))
4657 (beg (if globalp (point-min) (point)))
4658 (end (if globalp (point-max) (org-end-of-subtree))))
4659 (org-hide-archived-subtrees beg end)))))
4660
4661 (defun org-hide-archived-subtrees (beg end)
4662 "Re-hide all archived subtrees after a visibility state change."
4663 (save-excursion
4664 (let* ((re (concat ":" org-archive-tag ":")))
4665 (goto-char beg)
4666 (while (re-search-forward re end t)
4667 (and (org-on-heading-p) (hide-subtree))
4668 (org-end-of-subtree)))))
4669
4670 (defun org-toggle-tag (tag &optional onoff)
4671 "Toggle the tag TAG for the current line.
4672 If ONOFF is `on' or `off', don't toggle but set to this state."
4673 (unless (org-on-heading-p) (error "Not on headling"))
4674 (let (res current)
4675 (save-excursion
4676 (beginning-of-line)
4677 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
4678 (point-at-eol) t)
4679 (progn
4680 (setq current (match-string 1))
4681 (replace-match ""))
4682 (setq current ""))
4683 (setq current (nreverse (org-split-string current ":")))
4684 (cond
4685 ((eq onoff 'on)
4686 (setq res t)
4687 (or (member tag current) (push tag current)))
4688 ((eq onoff 'off)
4689 (or (not (member tag current)) (setq current (delete tag current))))
4690 (t (if (member tag current)
4691 (setq current (delete tag current))
4692 (setq res t)
4693 (push tag current))))
4694 (end-of-line 1)
4695 (when current
4696 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
4697 (org-set-tags nil t))
4698 res))
4699
4700 (defun org-toggle-archive-tag (&optional arg)
4701 "Toggle the archive tag for the current headline.
4702 With prefix ARG, check all children of current headline and offer tagging
4703 the children that do not contain any open TODO items."
4704 (interactive "P")
4705 (if arg
4706 (org-archive-all-done 'tag)
4707 (let (set)
4708 (save-excursion
4709 (org-back-to-heading t)
4710 (setq set (org-toggle-tag org-archive-tag))
4711 (when set (hide-subtree)))
4712 (and set (beginning-of-line 1))
4713 (message "Subtree %s" (if set "archived" "unarchived")))))
4714
4715 (defun org-prepare-agenda-buffers (files)
4716 "Create buffers for all agenda files, protect archived trees and comments."
4717 (interactive)
4718 (let ((pa '(:org-archived t))
4719 (pc '(:org-comment t))
4720 (pall '(:org-archived t :org-comment t))
4721 (rea (concat ":" org-archive-tag ":"))
4722 bmp file re)
4723 (save-excursion
4724 (while (setq file (pop files))
4725 (org-check-agenda-file file)
4726 (set-buffer (org-get-agenda-file-buffer file))
4727 (widen)
4728 (setq bmp (buffer-modified-p))
4729 (save-excursion
4730 (remove-text-properties (point-min) (point-max) pall)
4731 (when org-agenda-skip-archived-trees
4732 (goto-char (point-min))
4733 (while (re-search-forward rea nil t)
4734 (if (org-on-heading-p)
4735 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
4736 (goto-char (point-min))
4737 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
4738 (while (re-search-forward re nil t)
4739 (add-text-properties
4740 (match-beginning 0) (org-end-of-subtree t) pc)))
4741 (set-buffer-modified-p bmp)))))
4742
4743 (defun org-agenda-skip ()
4744 "Throw to `:skip' in places that should be skipped."
4745 (let ((p (point-at-bol)))
4746 (and org-agenda-skip-archived-trees
4747 (get-text-property p :org-archived)
4748 (org-end-of-subtree)
4749 (throw :skip t))
4750 (and (get-text-property p :org-comment)
4751 (org-end-of-subtree)
4752 (throw :skip t))
4753 (if (equal (char-after p) ?#) (throw :skip t))))
4754
4755 (defun org-agenda-toggle-archive-tag ()
4756 "Toggle the archive tag for the current entry."
4757 (interactive)
4758 (org-agenda-check-no-diary)
4759 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
4760 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
4761 (org-agenda-error)))
4762 (buffer (marker-buffer hdmarker))
4763 (pos (marker-position hdmarker))
4764 (buffer-read-only nil)
4765 newhead)
4766 (with-current-buffer buffer
4767 (widen)
4768 (goto-char pos)
4769 (org-show-hidden-entry)
4770 (save-excursion
4771 (and (outline-next-heading)
4772 (org-flag-heading nil))) ; show the next heading
4773 (call-interactively 'org-toggle-archive-tag)
4774 (end-of-line 1)
4775 (setq newhead (org-get-heading)))
4776 (org-agenda-change-all-lines newhead hdmarker)
4777 (beginning-of-line 1)))
4778
4779 ;;; Dynamic blocks
4780
4781 (defun org-find-dblock (name)
4782 "Find the first dynamic block with name NAME in the buffer.
4783 If not found, stay at current position and return nil."
4784 (let (pos)
4785 (save-excursion
4786 (goto-char (point-min))
4787 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
4788 nil t)
4789 (match-beginning 0))))
4790 (if pos (goto-char pos))
4791 pos))
4792
4793 (defconst org-dblock-start-re
4794 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
4795 "Matches the startline of a dynamic block, with parameters.")
4796
4797 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
4798 "Matches the end of a dyhamic block.")
4799
4800 (defun org-create-dblock (plist)
4801 "Create a dynamic block section, with parameters taken from PLIST.
4802 PLIST must containe a :name entry which is used as name of the block."
4803 (unless (bolp) (newline))
4804 (let ((name (plist-get plist :name)))
4805 (insert "#+BEGIN: " name)
4806 (while plist
4807 (if (eq (car plist) :name)
4808 (setq plist (cddr plist))
4809 (insert " " (prin1-to-string (pop plist)))))
4810 (insert "\n\n#+END:\n")
4811 (beginning-of-line -2)))
4812
4813 (defun org-prepare-dblock ()
4814 "Prepare dynamic block for refresh.
4815 This empties the block, puts the cursor at the insert position and returns
4816 the property list including an extra property :name with the block name."
4817 (unless (looking-at org-dblock-start-re)
4818 (error "Not at a dynamic block"))
4819 (let* ((begdel (1+ (match-end 0)))
4820 (name (match-string 1))
4821 (params (append (list :name name)
4822 (read (concat "(" (match-string 3) ")")))))
4823 (unless (re-search-forward org-dblock-end-re nil t)
4824 (error "Dynamic block not terminated"))
4825 (delete-region begdel (match-beginning 0))
4826 (goto-char begdel)
4827 (open-line 1)
4828 params))
4829
4830 (defun org-map-dblocks (&optional command)
4831 "Apply COMMAND to all dynamic blocks in the current buffer.
4832 If COMMAND is not given, use `org-update-dblock'."
4833 (let ((cmd (or command 'org-update-dblock))
4834 pos)
4835 (save-excursion
4836 (goto-char (point-min))
4837 (while (re-search-forward org-dblock-start-re nil t)
4838 (goto-char (setq pos (match-beginning 0)))
4839 (condition-case nil
4840 (funcall cmd)
4841 (error (message "Error during update of dynamic block")))
4842 (goto-char pos)
4843 (unless (re-search-forward org-dblock-end-re nil t)
4844 (error "Dynamic block not terminated"))))))
4845
4846 (defun org-dblock-update (&optional arg)
4847 "User command for updating dynamic blocks.
4848 Update the dynamic block at point. With prefix ARG, update all dynamic
4849 blocks in the buffer."
4850 (interactive "P")
4851 (if arg
4852 (org-update-all-dblocks)
4853 (or (looking-at org-dblock-start-re)
4854 (org-beginning-of-dblock))
4855 (org-update-dblock)))
4856
4857 (defun org-update-dblock ()
4858 "Update the dynamic block at point
4859 This means to empty the block, parse for parameters and then call
4860 the correct writing function."
4861 (let* ((pos (point))
4862 (params (org-prepare-dblock))
4863 (name (plist-get params :name))
4864 (cmd (intern (concat "org-dblock-write:" name))))
4865 (funcall cmd params)
4866 (goto-char pos)))
4867
4868 (defun org-beginning-of-dblock ()
4869 "Find the beginning of the dynamic block at point.
4870 Error if there is no scuh block at point."
4871 (let ((pos (point))
4872 beg)
4873 (end-of-line 1)
4874 (if (and (re-search-backward org-dblock-start-re nil t)
4875 (setq beg (match-beginning 0))
4876 (re-search-forward org-dblock-end-re nil t)
4877 (> (match-end 0) pos))
4878 (goto-char beg)
4879 (goto-char pos)
4880 (error "Not in a dynamic block"))))
4881
4882 (defun org-update-all-dblocks ()
4883 "Update all dynamic blocks in the buffer.
4884 This function can be used in a hook."
4885 (when (org-mode-p)
4886 (org-map-dblocks 'org-update-dblock)))
4887
4888
4889 ;;; Completion
4890
4891 (defun org-complete (&optional arg)
4892 "Perform completion on word at point.
4893 At the beginning of a headline, this completes TODO keywords as given in
4894 `org-todo-keywords'.
4895 If the current word is preceded by a backslash, completes the TeX symbols
4896 that are supported for HTML support.
4897 If the current word is preceded by \"#+\", completes special words for
4898 setting file options.
4899 At all other locations, this simply calls `ispell-complete-word'."
4900 (interactive "P")
4901 (catch 'exit
4902 (let* ((end (point))
4903 (beg1 (save-excursion
4904 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4905 (skip-chars-backward "a-zA-Z_@0-9")
4906 (point)))
4907 (beg (save-excursion
4908 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4909 (skip-chars-backward "a-zA-Z0-9_:$")
4910 (point)))
4911 (confirm (lambda (x) (stringp (car x))))
4912 (camel (equal (char-before beg) ?*))
4913 (tag (equal (char-before beg1) ?:))
4914 (texp (equal (char-before beg) ?\\))
4915 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
4916 beg)
4917 "#+"))
4918 (completion-ignore-case opt)
4919 (type nil)
4920 (tbl nil)
4921 (table (cond
4922 (opt
4923 (setq type :opt)
4924 (mapcar (lambda (x)
4925 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
4926 (cons (match-string 2 x) (match-string 1 x)))
4927 (org-split-string (org-get-current-options) "\n")))
4928 (texp
4929 (setq type :tex)
4930 org-html-entities)
4931 ((string-match "\\`\\*+[ \t]*\\'"
4932 (buffer-substring (point-at-bol) beg))
4933 (setq type :todo)
4934 (mapcar 'list org-todo-keywords))
4935 (camel
4936 (setq type :camel)
4937 (save-excursion
4938 (goto-char (point-min))
4939 (while (re-search-forward org-todo-line-regexp nil t)
4940 (push (list
4941 (if org-file-link-context-use-camel-case
4942 (org-make-org-heading-camel (match-string 3) t)
4943 (org-make-org-heading-search-string
4944 (match-string 3) t)))
4945 tbl)))
4946 tbl)
4947 (tag (setq type :tag beg beg1)
4948 (or org-tag-alist (org-get-buffer-tags)))
4949 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
4950 (pattern (buffer-substring-no-properties beg end))
4951 (completion (try-completion pattern table confirm)))
4952 (cond ((eq completion t)
4953 (if (equal type :opt)
4954 (insert (substring (cdr (assoc (upcase pattern) table))
4955 (length pattern)))))
4956 ((null completion)
4957 (message "Can't find completion for \"%s\"" pattern)
4958 (ding))
4959 ((not (string= pattern completion))
4960 (delete-region beg end)
4961 (if (string-match " +$" completion)
4962 (setq completion (replace-match "" t t completion)))
4963 (insert completion)
4964 (if (get-buffer-window "*Completions*")
4965 (delete-window (get-buffer-window "*Completions*")))
4966 (if (assoc completion table)
4967 (if (eq type :todo) (insert " ")
4968 (if (eq type :tag) (insert ":"))))
4969 (if (and (equal type :opt) (assoc completion table))
4970 (message "%s" (substitute-command-keys
4971 "Press \\[org-complete] again to insert example settings"))))
4972 (t
4973 (message "Making completion list...")
4974 (let ((list (sort (all-completions pattern table confirm)
4975 'string<)))
4976 (with-output-to-temp-buffer "*Completions*"
4977 (condition-case nil
4978 ;; Protection needed for XEmacs and emacs 21
4979 (display-completion-list list pattern)
4980 (error (display-completion-list list)))))
4981 (message "Making completion list...%s" "done"))))))
4982
4983 ;;; Comments, TODO and DEADLINE
4984
4985 (defun org-toggle-comment ()
4986 "Change the COMMENT state of an entry."
4987 (interactive)
4988 (save-excursion
4989 (org-back-to-heading)
4990 (if (looking-at (concat outline-regexp
4991 "\\( +\\<" org-comment-string "\\>\\)"))
4992 (replace-match "" t t nil 1)
4993 (if (looking-at outline-regexp)
4994 (progn
4995 (goto-char (match-end 0))
4996 (insert " " org-comment-string))))))
4997
4998 (defvar org-last-todo-state-is-todo nil
4999 "This is non-nil when the last TODO state change led to a TODO state.
5000 If the last change removed the TODO tag or switched to DONE, then
5001 this is nil.")
5002
5003 (defun org-todo (&optional arg)
5004 "Change the TODO state of an item.
5005 The state of an item is given by a keyword at the start of the heading,
5006 like
5007 *** TODO Write paper
5008 *** DONE Call mom
5009
5010 The different keywords are specified in the variable `org-todo-keywords'.
5011 By default the available states are \"TODO\" and \"DONE\".
5012 So for this example: when the item starts with TODO, it is changed to DONE.
5013 When it starts with DONE, the DONE is removed. And when neither TODO nor
5014 DONE are present, add TODO at the beginning of the heading.
5015
5016 With prefix arg, use completion to determine the new state. With numeric
5017 prefix arg, switch to that state."
5018 (interactive "P")
5019 (save-excursion
5020 (org-back-to-heading)
5021 (if (looking-at outline-regexp) (goto-char (match-end 0)))
5022 (or (looking-at (concat " +" org-todo-regexp " *"))
5023 (looking-at " *"))
5024 (let* ((this (match-string 1))
5025 (completion-ignore-case t)
5026 (member (member this org-todo-keywords))
5027 (tail (cdr member))
5028 (state (cond
5029 ((equal arg '(4))
5030 ;; Read a state with completion
5031 (completing-read "State: " (mapcar (lambda(x) (list x))
5032 org-todo-keywords)
5033 nil t))
5034 ((eq arg 'right)
5035 (if this
5036 (if tail (car tail) nil)
5037 (car org-todo-keywords)))
5038 ((eq arg 'left)
5039 (if (equal member org-todo-keywords)
5040 nil
5041 (if this
5042 (nth (- (length org-todo-keywords) (length tail) 2)
5043 org-todo-keywords)
5044 org-done-string)))
5045 (arg
5046 ;; user requests a specific state
5047 (nth (1- (prefix-numeric-value arg))
5048 org-todo-keywords))
5049 ((null member) (car org-todo-keywords))
5050 ((null tail) nil) ;; -> first entry
5051 ((eq org-todo-interpretation 'sequence)
5052 (car tail))
5053 ((memq org-todo-interpretation '(type priority))
5054 (if (eq this-command last-command)
5055 (car tail)
5056 (if (> (length tail) 0) org-done-string nil)))
5057 (t nil)))
5058 (next (if state (concat " " state " ") " ")))
5059 (replace-match next t t)
5060 (setq org-last-todo-state-is-todo
5061 (not (equal state org-done-string)))
5062 (when org-log-done
5063 (if (equal state org-done-string)
5064 (org-add-planning-info 'closed (current-time) 'scheduled)
5065 (if (not this)
5066 (org-add-planning-info nil nil 'closed))))
5067 ;; Fixup tag positioning
5068 (and org-auto-align-tags (org-set-tags nil t))
5069 (run-hooks 'org-after-todo-state-change-hook)))
5070 ;; Fixup cursor location if close to the keyword
5071 (if (and (outline-on-heading-p)
5072 (not (bolp))
5073 (save-excursion (beginning-of-line 1)
5074 (looking-at org-todo-line-regexp))
5075 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5076 (progn
5077 (goto-char (or (match-end 2) (match-end 1)))
5078 (just-one-space))))
5079
5080 (defun org-log-done (&optional undone)
5081 "Add a time stamp logging that a TODO entry has been closed.
5082 When UNDONE is non-nil, remove such a time stamp again."
5083 (interactive)
5084 (let (beg end col)
5085 (save-excursion
5086 (org-back-to-heading t)
5087 (setq beg (point))
5088 (looking-at (concat outline-regexp " *"))
5089 (goto-char (match-end 0))
5090 (setq col (current-column))
5091 (outline-next-heading)
5092 (setq end (point))
5093 (goto-char beg)
5094 (when (re-search-forward (concat
5095 "[\r\n]\\([ \t]*"
5096 (regexp-quote org-closed-string)
5097 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
5098 (delete-region (match-beginning 1) (match-end 1)))
5099 (unless undone
5100 (org-back-to-heading t)
5101 (skip-chars-forward "^\n\r")
5102 (goto-char (min (1+ (point)) (point-max)))
5103 (when (not (member (char-before) '(?\r ?\n)))
5104 (insert "\n"))
5105 (indent-to col)
5106 (insert org-closed-string " "
5107 (format-time-string
5108 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5109 (org-current-time))
5110 "\n")))))
5111
5112 (defun org-show-todo-tree (arg)
5113 "Make a compact tree which shows all headlines marked with TODO.
5114 The tree will show the lines where the regexp matches, and all higher
5115 headlines above the match.
5116 With \\[universal-argument] prefix, also show the DONE entries.
5117 With a numeric prefix N, construct a sparse tree for the Nth element
5118 of `org-todo-keywords'."
5119 (interactive "P")
5120 (let ((case-fold-search nil)
5121 (kwd-re
5122 (cond ((null arg) org-not-done-regexp)
5123 ((equal arg '(4)) org-todo-regexp)
5124 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5125 (regexp-quote (nth (1- (prefix-numeric-value arg))
5126 org-todo-keywords)))
5127 (t (error "Invalid prefix argument: %s" arg)))))
5128 (message "%d TODO entries found"
5129 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5130
5131 (defun org-deadline ()
5132 "Insert the DEADLINE: string to make a deadline.
5133 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5134 to modify it to the correct date."
5135 (interactive)
5136 (org-add-planning-info 'deadline nil 'closed))
5137
5138 (defun org-schedule ()
5139 "Insert the SCHEDULED: string to schedule a TODO item.
5140 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5141 to modify it to the correct date."
5142 (interactive)
5143 (org-add-planning-info 'scheduled nil 'closed))
5144
5145 (defun org-add-planning-info (what &optional time &rest remove)
5146 "Insert new timestamp with keyword in the line directly after the headline.
5147 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5148 If non is given, the user is prompted for a date.
5149 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5150 be removed."
5151 (interactive)
5152 (when what (setq time (or time (org-read-date nil 'to-time))))
5153 (when (and org-insert-labeled-timestamps-at-point
5154 (member what '(scheduled deadline)))
5155 (insert
5156 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
5157 " "
5158 (format-time-string (car org-time-stamp-formats) time))
5159 (setq what nil))
5160 (save-excursion
5161 (let (col list elt (buffer-invisibility-spec nil) ts)
5162 (org-back-to-heading t)
5163 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5164 (goto-char (match-end 1))
5165 (setq col (current-column))
5166 (goto-char (1+ (match-end 0)))
5167 (if (and (not (looking-at outline-regexp))
5168 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5169 "[^\r\n]*"))
5170 (not (equal (match-string 1) org-clock-string)))
5171 (narrow-to-region (match-beginning 0) (match-end 0))
5172 (insert "\n")
5173 (backward-char 1)
5174 (narrow-to-region (point) (point))
5175 (indent-to-column col))
5176 ;; Check if we have to remove something.
5177 (setq list (cons what remove))
5178 (while list
5179 (setq elt (pop list))
5180 (goto-char (point-min))
5181 (when (or (and (eq elt 'scheduled)
5182 (re-search-forward org-scheduled-time-regexp nil t))
5183 (and (eq elt 'deadline)
5184 (re-search-forward org-deadline-time-regexp nil t))
5185 (and (eq elt 'closed)
5186 (re-search-forward org-closed-time-regexp nil t)))
5187 (replace-match "")
5188 (if (looking-at " +") (replace-match ""))))
5189 (goto-char (point-max))
5190 (when what
5191 (insert
5192 (if (not (equal (char-before) ?\ )) " " "")
5193 (cond ((eq what 'scheduled) org-scheduled-string)
5194 ((eq what 'deadline) org-deadline-string)
5195 ((eq what 'closed) org-closed-string))
5196 " ")
5197 (insert
5198 (setq ts
5199 (format-time-string
5200 (if (eq what 'closed)
5201 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5202 (car org-time-stamp-formats))
5203 time))))
5204 (goto-char (point-min))
5205 (widen)
5206 (if (looking-at "[ \t]+\r?\n")
5207 (replace-match ""))
5208 ts)))
5209
5210 (defun org-occur (regexp &optional callback)
5211 "Make a compact tree which shows all matches of REGEXP.
5212 The tree will show the lines where the regexp matches, and all higher
5213 headlines above the match. It will also show the heading after the match,
5214 to make sure editing the matching entry is easy.
5215 If CALLBACK is non-nil, it is a function which is called to confirm
5216 that the match should indeed be shown."
5217 (interactive "sRegexp: ")
5218 (org-remove-occur-highlights nil nil t)
5219 (let ((cnt 0))
5220 (save-excursion
5221 (goto-char (point-min))
5222 (org-overview)
5223 (while (re-search-forward regexp nil t)
5224 (when (or (not callback)
5225 (save-match-data (funcall callback)))
5226 (setq cnt (1+ cnt))
5227 (org-highlight-new-match (match-beginning 0) (match-end 0))
5228 (org-show-hierarchy-above))))
5229 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5230 nil 'local)
5231 (unless org-sparse-tree-open-archived-trees
5232 (org-hide-archived-subtrees (point-min) (point-max)))
5233 (run-hooks 'org-occur-hook)
5234 (if (interactive-p)
5235 (message "%d match(es) for regexp %s" cnt regexp))
5236 cnt))
5237
5238 (defun org-show-hierarchy-above ()
5239 "Make sure point and the headings hierarchy above is visible."
5240 (catch 'exit
5241 (if (org-on-heading-p t)
5242 (org-flag-heading nil) ; only show the heading
5243 (and (or (org-invisible-p) (org-invisible-p2))
5244 (org-show-hidden-entry))) ; show entire entry
5245 (save-excursion
5246 (and org-show-following-heading
5247 (outline-next-heading)
5248 (org-flag-heading nil))) ; show the next heading
5249 (when org-show-hierarchy-above
5250 (save-excursion ; show all higher headings
5251 (while (and (condition-case nil
5252 (progn (org-up-heading-all 1) t)
5253 (error nil))
5254 (not (bobp)))
5255 (org-flag-heading nil))))))
5256
5257 ;; Overlay compatibility functions
5258 (defun org-make-overlay (beg end &optional buffer)
5259 (if (featurep 'xemacs)
5260 (make-extent beg end buffer)
5261 (make-overlay beg end buffer)))
5262 (defun org-delete-overlay (ovl)
5263 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5264 (defun org-detatch-overlay (ovl)
5265 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5266 (defun org-move-overlay (ovl beg end &optional buffer)
5267 (if (featurep 'xemacs)
5268 (set-extent-endpoints ovl beg end buffer)
5269 (move-overlay ovl beg end buffer)))
5270 (defun org-overlay-put (ovl prop value)
5271 (if (featurep 'xemacs)
5272 (set-extent-property ovl prop value)
5273 (overlay-put ovl prop value)))
5274 (defun org-overlays-at (pos)
5275 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5276 (defun org-overlay-start (o)
5277 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5278 (defun org-overlay-end (o)
5279 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5280
5281 (defvar org-occur-highlights nil)
5282 (make-variable-buffer-local 'org-occur-highlights)
5283 (defun org-highlight-new-match (beg end)
5284 "Highlight from BEG to END and mark the highlight is an occur headline."
5285 (let ((ov (org-make-overlay beg end)))
5286 (org-overlay-put ov 'face 'secondary-selection)
5287 (push ov org-occur-highlights)))
5288
5289 (defvar org-inhibit-highlight-removal nil)
5290 (defun org-remove-occur-highlights (&optional beg end noremove)
5291 "Remove the occur highlights from the buffer.
5292 BEG and END are ignored. If NOREMOVE is nil, remove this function
5293 from the `before-change-functions' in the current buffer."
5294 (interactive)
5295 (unless org-inhibit-highlight-removal
5296 (mapc 'org-delete-overlay org-occur-highlights)
5297 (setq org-occur-highlights nil)
5298 (unless noremove
5299 (remove-hook 'before-change-functions
5300 'org-remove-occur-highlights 'local))))
5301
5302 ;;; Priorities
5303
5304 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5305 "Regular expression matching the priority indicator.")
5306
5307 (defvar org-remove-priority-next-time nil)
5308
5309 (defun org-priority-up ()
5310 "Increase the priority of the current item."
5311 (interactive)
5312 (org-priority 'up))
5313
5314 (defun org-priority-down ()
5315 "Decrease the priority of the current item."
5316 (interactive)
5317 (org-priority 'down))
5318
5319 (defun org-priority (&optional action)
5320 "Change the priority of an item by ARG.
5321 ACTION can be set, up, or down."
5322 (interactive)
5323 (setq action (or action 'set))
5324 (let (current new news have remove)
5325 (save-excursion
5326 (org-back-to-heading)
5327 (if (looking-at org-priority-regexp)
5328 (setq current (string-to-char (match-string 2))
5329 have t)
5330 (setq current org-default-priority))
5331 (cond
5332 ((eq action 'set)
5333 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5334 (setq new (read-char-exclusive))
5335 (cond ((equal new ?\ ) (setq remove t))
5336 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5337 (error "Priority must be between `%c' and `%c'"
5338 ?A org-lowest-priority))))
5339 ((eq action 'up)
5340 (setq new (1- current)))
5341 ((eq action 'down)
5342 (setq new (1+ current)))
5343 (t (error "Invalid action")))
5344 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5345 (setq news (format "%c" new))
5346 (if have
5347 (if remove
5348 (replace-match "" t t nil 1)
5349 (replace-match news t t nil 2))
5350 (if remove
5351 (error "No priority cookie found in line")
5352 (looking-at org-todo-line-regexp)
5353 (if (match-end 2)
5354 (progn
5355 (goto-char (match-end 2))
5356 (insert " [#" news "]"))
5357 (goto-char (match-beginning 3))
5358 (insert "[#" news "] ")))))
5359 (if remove
5360 (message "Priority removed")
5361 (message "Priority of current item set to %s" news))))
5362
5363
5364 (defun org-get-priority (s)
5365 "Find priority cookie and return priority."
5366 (save-match-data
5367 (if (not (string-match org-priority-regexp s))
5368 (* 1000 (- org-lowest-priority org-default-priority))
5369 (* 1000 (- org-lowest-priority
5370 (string-to-char (match-string 2 s)))))))
5371
5372 ;;; Timestamps
5373
5374 (defvar org-last-changed-timestamp nil)
5375
5376 (defun org-time-stamp (arg)
5377 "Prompt for a date/time and insert a time stamp.
5378 If the user specifies a time like HH:MM, or if this command is called
5379 with a prefix argument, the time stamp will contain date and time.
5380 Otherwise, only the date will be included. All parts of a date not
5381 specified by the user will be filled in from the current date/time.
5382 So if you press just return without typing anything, the time stamp
5383 will represent the current date/time. If there is already a timestamp
5384 at the cursor, it will be modified."
5385 (interactive "P")
5386 (let ((fmt (if arg (cdr org-time-stamp-formats)
5387 (car org-time-stamp-formats)))
5388 (org-time-was-given nil)
5389 time)
5390 (cond
5391 ((and (org-at-timestamp-p)
5392 (eq last-command 'org-time-stamp)
5393 (eq this-command 'org-time-stamp))
5394 (insert "--")
5395 (setq time (let ((this-command this-command))
5396 (org-read-date arg 'totime)))
5397 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5398 (insert (format-time-string fmt time)))
5399 ((org-at-timestamp-p)
5400 (setq time (let ((this-command this-command))
5401 (org-read-date arg 'totime)))
5402 (and (org-at-timestamp-p) (replace-match
5403 (setq org-last-changed-timestamp
5404 (format-time-string fmt time))
5405 t t))
5406 (message "Timestamp updated"))
5407 (t
5408 (setq time (let ((this-command this-command))
5409 (org-read-date arg 'totime)))
5410 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5411 (insert (format-time-string fmt time))))))
5412
5413 (defun org-time-stamp-inactive (&optional arg)
5414 "Insert an inactive time stamp.
5415 An inactive time stamp is enclosed in square brackets instead of angle
5416 brackets. It is inactive in the sense that it does not trigger agenda entries,
5417 does not link to the calendar and cannot be changed with the S-cursor keys.
5418 So these are more for recording a certain time/date."
5419 (interactive "P")
5420 (let ((fmt (if arg (cdr org-time-stamp-formats)
5421 (car org-time-stamp-formats)))
5422 (org-time-was-given nil)
5423 time)
5424 (setq time (org-read-date arg 'totime))
5425 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5426 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
5427 (insert (format-time-string fmt time))))
5428
5429 (defvar org-date-ovl (org-make-overlay 1 1))
5430 (org-overlay-put org-date-ovl 'face 'org-warning)
5431 (org-detatch-overlay org-date-ovl)
5432
5433 (defun org-read-date (&optional with-time to-time)
5434 "Read a date and make things smooth for the user.
5435 The prompt will suggest to enter an ISO date, but you can also enter anything
5436 which will at least partially be understood by `parse-time-string'.
5437 Unrecognized parts of the date will default to the current day, month, year,
5438 hour and minute. For example,
5439 3-2-5 --> 2003-02-05
5440 feb 15 --> currentyear-02-15
5441 sep 12 9 --> 2009-09-12
5442 12:45 --> today 12:45
5443 22 sept 0:34 --> currentyear-09-22 0:34
5444 12 --> currentyear-currentmonth-12
5445 Fri --> nearest Friday (today or later)
5446 etc.
5447 The function understands only English month and weekday abbreviations,
5448 but this can be configured with the variables `parse-time-months' and
5449 `parse-time-weekdays'.
5450
5451 While prompting, a calendar is popped up - you can also select the
5452 date with the mouse (button 1). The calendar shows a period of three
5453 months. To scroll it to other months, use the keys `>' and `<'.
5454 If you don't like the calendar, turn it off with
5455 \(setq org-popup-calendar-for-date-prompt nil)
5456
5457 With optional argument TO-TIME, the date will immediately be converted
5458 to an internal time.
5459 With an optional argument WITH-TIME, the prompt will suggest to also
5460 insert a time. Note that when WITH-TIME is not set, you can still
5461 enter a time, and this function will inform the calling routine about
5462 this change. The calling routine may then choose to change the format
5463 used to insert the time stamp into the buffer to include the time."
5464 (require 'parse-time)
5465 (let* ((org-time-stamp-rounding-minutes
5466 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5467 (ct (org-current-time))
5468 (default-time
5469 ;; Default time is either today, or, when entering a range,
5470 ;; the range start.
5471 (if (save-excursion
5472 (re-search-backward
5473 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5474 (- (point) 20) t))
5475 (apply
5476 'encode-time
5477 (mapcar (lambda(x) (or x 0))
5478 (parse-time-string (match-string 1))))
5479 ct))
5480 (calendar-move-hook nil)
5481 (view-diary-entries-initially nil)
5482 (view-calendar-holidays-initially nil)
5483 (timestr (format-time-string
5484 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5485 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5486 ans ans1 ans2
5487 second minute hour day month year tl wday wday1)
5488
5489 (if org-popup-calendar-for-date-prompt
5490 (save-excursion
5491 (save-window-excursion
5492 (calendar)
5493 (calendar-forward-day (- (time-to-days default-time)
5494 (calendar-absolute-from-gregorian
5495 (calendar-current-date))))
5496 (org-eval-in-calendar nil)
5497 (let* ((old-map (current-local-map))
5498 (map (copy-keymap calendar-mode-map))
5499 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5500 (define-key map (kbd "RET") 'org-calendar-select)
5501 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5502 'org-calendar-select-mouse)
5503 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5504 'org-calendar-select-mouse)
5505 (define-key minibuffer-local-map [(meta shift left)]
5506 (lambda () (interactive)
5507 (org-eval-in-calendar '(calendar-backward-month 1))))
5508 (define-key minibuffer-local-map [(meta shift right)]
5509 (lambda () (interactive)
5510 (org-eval-in-calendar '(calendar-forward-month 1))))
5511 (define-key minibuffer-local-map [(shift up)]
5512 (lambda () (interactive)
5513 (org-eval-in-calendar '(calendar-backward-week 1))))
5514 (define-key minibuffer-local-map [(shift down)]
5515 (lambda () (interactive)
5516 (org-eval-in-calendar '(calendar-forward-week 1))))
5517 (define-key minibuffer-local-map [(shift left)]
5518 (lambda () (interactive)
5519 (org-eval-in-calendar '(calendar-backward-day 1))))
5520 (define-key minibuffer-local-map [(shift right)]
5521 (lambda () (interactive)
5522 (org-eval-in-calendar '(calendar-forward-day 1))))
5523 (define-key minibuffer-local-map ">"
5524 (lambda () (interactive)
5525 (org-eval-in-calendar '(scroll-calendar-left 1))))
5526 (define-key minibuffer-local-map "<"
5527 (lambda () (interactive)
5528 (org-eval-in-calendar '(scroll-calendar-right 1))))
5529 (unwind-protect
5530 (progn
5531 (use-local-map map)
5532 (setq ans (read-string prompt "" nil nil))
5533 (if (not (string-match "\\S-" ans)) (setq ans nil))
5534 (setq ans (or ans1 ans ans2)))
5535 (use-local-map old-map)))))
5536 ;; Naked prompt only
5537 (setq ans (read-string prompt "" nil timestr)))
5538 (org-detatch-overlay org-date-ovl)
5539
5540 (if (string-match
5541 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5542 (progn
5543 (setq year (if (match-end 2)
5544 (string-to-number (match-string 2 ans))
5545 (string-to-number (format-time-string "%Y")))
5546 month (string-to-number (match-string 3 ans))
5547 day (string-to-number (match-string 4 ans)))
5548 (if (< year 100) (setq year (+ 2000 year)))
5549 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5550 t nil ans))))
5551 (setq tl (parse-time-string ans)
5552 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5553 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5554 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5555 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5556 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5557 second (or (nth 0 tl) 0)
5558 wday (nth 6 tl))
5559 (when (and wday (not (nth 3 tl)))
5560 ;; Weekday was given, but no day, so pick that day in the week
5561 ;; on or after the derived date.
5562 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5563 (unless (equal wday wday1)
5564 (setq day (+ day (% (- wday wday1 -7) 7)))))
5565 (if (and (boundp 'org-time-was-given)
5566 (nth 2 tl))
5567 (setq org-time-was-given t))
5568 (if (< year 100) (setq year (+ 2000 year)))
5569 (if to-time
5570 (encode-time second minute hour day month year)
5571 (if (or (nth 1 tl) (nth 2 tl))
5572 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5573 (format "%04d-%02d-%02d" year month day)))))
5574
5575 (defun org-eval-in-calendar (form)
5576 "Eval FORM in the calendar window and return to current window.
5577 Also, store the cursor date in variable ans2."
5578 (let ((sw (selected-window)))
5579 (select-window (get-buffer-window "*Calendar*"))
5580 (eval form)
5581 (when (calendar-cursor-to-date)
5582 (let* ((date (calendar-cursor-to-date))
5583 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5584 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5585 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5586 (select-window sw)))
5587
5588 (defun org-calendar-select ()
5589 "Return to `org-read-date' with the date currently selected.
5590 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5591 (interactive)
5592 (when (calendar-cursor-to-date)
5593 (let* ((date (calendar-cursor-to-date))
5594 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5595 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5596 (if (active-minibuffer-window) (exit-minibuffer))))
5597
5598 (defun org-calendar-select-mouse (ev)
5599 "Return to `org-read-date' with the date currently selected.
5600 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5601 (interactive "e")
5602 (mouse-set-point ev)
5603 (when (calendar-cursor-to-date)
5604 (let* ((date (calendar-cursor-to-date))
5605 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5606 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5607 (if (active-minibuffer-window) (exit-minibuffer))))
5608
5609 (defun org-check-deadlines (ndays)
5610 "Check if there are any deadlines due or past due.
5611 A deadline is considered due if it happens within `org-deadline-warning-days'
5612 days from today's date. If the deadline appears in an entry marked DONE,
5613 it is not shown. The prefix arg NDAYS can be used to test that many
5614 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
5615 (interactive "P")
5616 (let* ((org-warn-days
5617 (cond
5618 ((equal ndays '(4)) 100000)
5619 (ndays (prefix-numeric-value ndays))
5620 (t org-deadline-warning-days)))
5621 (case-fold-search nil)
5622 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5623 (callback
5624 (lambda ()
5625 (and (let ((d1 (time-to-days (current-time)))
5626 (d2 (time-to-days
5627 (org-time-string-to-time (match-string 1)))))
5628 (< (- d2 d1) org-warn-days))
5629 (not (org-entry-is-done-p))))))
5630 (message "%d deadlines past-due or due within %d days"
5631 (org-occur regexp callback)
5632 org-warn-days)))
5633
5634 (defun org-evaluate-time-range (&optional to-buffer)
5635 "Evaluate a time range by computing the difference between start and end.
5636 Normally the result is just printed in the echo area, but with prefix arg
5637 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5638 If the time range is actually in a table, the result is inserted into the
5639 next column.
5640 For time difference computation, a year is assumed to be exactly 365
5641 days in order to avoid rounding problems."
5642 (interactive "P")
5643 (or
5644 (org-clock-update-time-maybe)
5645 (save-excursion
5646 (unless (org-at-date-range-p)
5647 (goto-char (point-at-bol))
5648 (re-search-forward org-tr-regexp (point-at-eol) t))
5649 (if (not (org-at-date-range-p))
5650 (error "Not at a time-stamp range, and none found in current line")))
5651 (let* ((ts1 (match-string 1))
5652 (ts2 (match-string 2))
5653 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5654 (match-end (match-end 0))
5655 (time1 (org-time-string-to-time ts1))
5656 (time2 (org-time-string-to-time ts2))
5657 (t1 (time-to-seconds time1))
5658 (t2 (time-to-seconds time2))
5659 (diff (abs (- t2 t1)))
5660 (negative (< (- t2 t1) 0))
5661 ;; (ys (floor (* 365 24 60 60)))
5662 (ds (* 24 60 60))
5663 (hs (* 60 60))
5664 (fy "%dy %dd %02d:%02d")
5665 (fy1 "%dy %dd")
5666 (fd "%dd %02d:%02d")
5667 (fd1 "%dd")
5668 (fh "%02d:%02d")
5669 y d h m align)
5670 (if havetime
5671 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5672 y 0
5673 d (floor (/ diff ds)) diff (mod diff ds)
5674 h (floor (/ diff hs)) diff (mod diff hs)
5675 m (floor (/ diff 60)))
5676 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5677 y 0
5678 d (floor (+ (/ diff ds) 0.5))
5679 h 0 m 0))
5680 (if (not to-buffer)
5681 (message (org-make-tdiff-string y d h m))
5682 (when (org-at-table-p)
5683 (goto-char match-end)
5684 (setq align t)
5685 (and (looking-at " *|") (goto-char (match-end 0))))
5686 (if (looking-at
5687 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5688 (replace-match ""))
5689 (if negative (insert " -"))
5690 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5691 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5692 (insert " " (format fh h m))))
5693 (if align (org-table-align))
5694 (message "Time difference inserted")))))
5695
5696 (defun org-make-tdiff-string (y d h m)
5697 (let ((fmt "")
5698 (l nil))
5699 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5700 l (push y l)))
5701 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5702 l (push d l)))
5703 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5704 l (push h l)))
5705 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5706 l (push m l)))
5707 (apply 'format fmt (nreverse l))))
5708
5709 (defun org-time-string-to-time (s)
5710 (apply 'encode-time (org-parse-time-string s)))
5711
5712 (defun org-parse-time-string (s &optional nodefault)
5713 "Parse the standard Org-mode time string.
5714 This should be a lot faster than the normal `parse-time-string'.
5715 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5716 hour and minute fields will be nil if not given."
5717 (if (string-match org-ts-regexp1 s)
5718 (list 0
5719 (if (or (match-beginning 8) (not nodefault))
5720 (string-to-number (or (match-string 8 s) "0")))
5721 (if (or (match-beginning 7) (not nodefault))
5722 (string-to-number (or (match-string 7 s) "0")))
5723 (string-to-number (match-string 4 s))
5724 (string-to-number (match-string 3 s))
5725 (string-to-number (match-string 2 s))
5726 nil nil nil)
5727 (make-list 9 0)))
5728
5729 (defun org-timestamp-up (&optional arg)
5730 "Increase the date item at the cursor by one.
5731 If the cursor is on the year, change the year. If it is on the month or
5732 the day, change that.
5733 With prefix ARG, change by that many units."
5734 (interactive "p")
5735 (org-timestamp-change (prefix-numeric-value arg)))
5736
5737 (defun org-timestamp-down (&optional arg)
5738 "Decrease the date item at the cursor by one.
5739 If the cursor is on the year, change the year. If it is on the month or
5740 the day, change that.
5741 With prefix ARG, change by that many units."
5742 (interactive "p")
5743 (org-timestamp-change (- (prefix-numeric-value arg))))
5744
5745 (defun org-timestamp-up-day (&optional arg)
5746 "Increase the date in the time stamp by one day.
5747 With prefix ARG, change that many days."
5748 (interactive "p")
5749 (if (and (not (org-at-timestamp-p t))
5750 (org-on-heading-p))
5751 (org-todo 'up)
5752 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5753
5754 (defun org-timestamp-down-day (&optional arg)
5755 "Decrease the date in the time stamp by one day.
5756 With prefix ARG, change that many days."
5757 (interactive "p")
5758 (if (and (not (org-at-timestamp-p t))
5759 (org-on-heading-p))
5760 (org-todo 'down)
5761 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5762
5763 (defsubst org-pos-in-match-range (pos n)
5764 (and (match-beginning n)
5765 (<= (match-beginning n) pos)
5766 (>= (match-end n) pos)))
5767
5768 (defun org-at-timestamp-p (&optional also-inactive)
5769 "Determine if the cursor is in or at a timestamp."
5770 (interactive)
5771 (let* ((tsr (if also-inactive org-ts-regexp3 org-ts-regexp2))
5772 (pos (point))
5773 (ans (or (looking-at tsr)
5774 (save-excursion
5775 (skip-chars-backward "^[<\n\r\t")
5776 (if (> (point) 1) (backward-char 1))
5777 (and (looking-at tsr)
5778 (> (- (match-end 0) pos) -1))))))
5779 (and (boundp 'org-ts-what)
5780 (setq org-ts-what
5781 (cond
5782 ((org-pos-in-match-range pos 2) 'year)
5783 ((org-pos-in-match-range pos 3) 'month)
5784 ((org-pos-in-match-range pos 7) 'hour)
5785 ((org-pos-in-match-range pos 8) 'minute)
5786 ((or (org-pos-in-match-range pos 4)
5787 (org-pos-in-match-range pos 5)) 'day)
5788 (t 'day))))
5789 ans))
5790
5791 (defun org-timestamp-change (n &optional what)
5792 "Change the date in the time stamp at point.
5793 The date will be changed by N times WHAT. WHAT can be `day', `month',
5794 `year', `minute', `second'. If WHAT is not given, the cursor position
5795 in the timestamp determines what will be changed."
5796 (let ((fmt (car org-time-stamp-formats))
5797 org-ts-what
5798 (pos (point))
5799 ts time time0)
5800 (if (not (org-at-timestamp-p t))
5801 (error "Not at a timestamp"))
5802 (setq org-ts-what (or what org-ts-what))
5803 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5804 (- (match-end 0) (match-beginning 0))))
5805 1)
5806 (cdr org-time-stamp-formats)
5807 (car org-time-stamp-formats)))
5808 (if (= (char-after (match-beginning 0)) ?\[)
5809 (setq fmt (concat "[" (substring fmt 1 -1) "]")))
5810 (setq ts (match-string 0))
5811 (replace-match "")
5812 (setq time0 (org-parse-time-string ts))
5813 (setq time
5814 (apply 'encode-time
5815 (append
5816 (list (or (car time0) 0))
5817 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5818 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5819 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5820 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5821 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5822 (nthcdr 6 time0))))
5823 (if (eq what 'calendar)
5824 (let ((cal-date
5825 (save-excursion
5826 (save-match-data
5827 (set-buffer "*Calendar*")
5828 (calendar-cursor-to-date)))))
5829 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5830 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5831 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5832 (setcar time0 (or (car time0) 0))
5833 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5834 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5835 (setq time (apply 'encode-time time0))))
5836 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5837 (org-clock-update-time-maybe)
5838 (goto-char pos)
5839 ;; Try to recenter the calendar window, if any
5840 (if (and org-calendar-follow-timestamp-change
5841 (get-buffer-window "*Calendar*" t)
5842 (memq org-ts-what '(day month year)))
5843 (org-recenter-calendar (time-to-days time)))))
5844
5845 (defun org-recenter-calendar (date)
5846 "If the calendar is visible, recenter it to DATE."
5847 (let* ((win (selected-window))
5848 (cwin (get-buffer-window "*Calendar*" t))
5849 (calendar-move-hook nil))
5850 (when cwin
5851 (select-window cwin)
5852 (calendar-goto-date (if (listp date) date
5853 (calendar-gregorian-from-absolute date)))
5854 (select-window win))))
5855
5856 (defun org-goto-calendar (&optional arg)
5857 "Go to the Emacs calendar at the current date.
5858 If there is a time stamp in the current line, go to that date.
5859 A prefix ARG can be used to force the current date."
5860 (interactive "P")
5861 (let ((tsr org-ts-regexp) diff
5862 (calendar-move-hook nil)
5863 (view-calendar-holidays-initially nil)
5864 (view-diary-entries-initially nil))
5865 (if (or (org-at-timestamp-p)
5866 (save-excursion
5867 (beginning-of-line 1)
5868 (looking-at (concat ".*" tsr))))
5869 (let ((d1 (time-to-days (current-time)))
5870 (d2 (time-to-days
5871 (org-time-string-to-time (match-string 1)))))
5872 (setq diff (- d2 d1))))
5873 (calendar)
5874 (calendar-goto-today)
5875 (if (and diff (not arg)) (calendar-forward-day diff))))
5876
5877 (defun org-date-from-calendar ()
5878 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5879 If there is already a time stamp at the cursor position, update it."
5880 (interactive)
5881 (org-timestamp-change 0 'calendar))
5882
5883 ;;; The clock for measuring work time.
5884
5885 (defvar org-clock-marker (make-marker)
5886 "Marker recording the last clock-in.")
5887
5888 (defun org-clock-in ()
5889 "Start the clock on the current item.
5890 If necessary, clock-out of the currently active clock."
5891 (interactive)
5892 (org-clock-out t)
5893 (let (ts)
5894 (save-excursion
5895 (org-back-to-heading t)
5896 (beginning-of-line 2)
5897 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5898 (not (equal (match-string 1) org-clock-string)))
5899 (beginning-of-line 1))
5900 (insert "\n") (backward-char 1)
5901 (indent-relative)
5902 (insert org-clock-string " "
5903 (setq ts (concat "[" (format-time-string
5904 (substring
5905 (cdr org-time-stamp-formats) 1 -1)
5906 (current-time))
5907 "]")))
5908 (move-marker org-clock-marker (point))
5909 (message "Clock started at %s" ts))))
5910
5911 (defun org-clock-out (&optional fail-quietly)
5912 "Stop the currently running clock.
5913 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
5914 (interactive)
5915 (catch 'exit
5916 (if (not (marker-buffer org-clock-marker))
5917 (if fail-quietly (throw 'exit t) (error "No active clock")))
5918 (let (ts te s h m)
5919 (save-excursion
5920 (set-buffer (marker-buffer org-clock-marker))
5921 (goto-char org-clock-marker)
5922 (beginning-of-line 1)
5923 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5924 (equal (match-string 1) org-clock-string))
5925 (setq ts (match-string 2))
5926 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
5927 (goto-char org-clock-marker)
5928 (setq te (concat "[" (format-time-string
5929 (substring
5930 (cdr org-time-stamp-formats) 1 -1)
5931 (current-time))
5932 "]"))
5933 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
5934 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
5935 h (floor (/ s 3600))
5936 s (- s (* 3600 h))
5937 m (floor (/ s 60))
5938 s (- s (* 60 s)))
5939 (insert "--" te " => " (format "%2d:%02d" h m))
5940 (move-marker org-clock-marker nil)
5941 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
5942
5943 (defun org-clock-cancel ()
5944 "Cancel the running clock be removing the start timestamp."
5945 (interactive)
5946 (if (not (marker-buffer org-clock-marker))
5947 (error "No active clock"))
5948 (save-excursion
5949 (set-buffer (marker-buffer org-clock-marker))
5950 (goto-char org-clock-marker)
5951 (delete-region (1- (point-at-bol)) (point-at-eol)))
5952 (message "Clock canceled"))
5953
5954 (defvar org-clock-file-total-minutes nil
5955 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
5956 (make-variable-buffer-local 'org-clock-file-total-minutes)
5957
5958 (defun org-clock-sum (&optional tstart tend)
5959 "Sum the times for each subtree.
5960 Puts the resulting times in minutes as a text property on each headline."
5961 (interactive)
5962 (let* ((bmp (buffer-modified-p))
5963 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
5964 org-clock-string
5965 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
5966 (lmax 30)
5967 (ltimes (make-vector lmax 0))
5968 (t1 0)
5969 (level 0)
5970 ts te dt
5971 time)
5972 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
5973 (save-excursion
5974 (goto-char (point-max))
5975 (while (re-search-backward re nil t)
5976 (if (match-end 2)
5977 ;; A time
5978 (setq ts (match-string 2)
5979 te (match-string 3)
5980 ts (time-to-seconds
5981 (apply 'encode-time (org-parse-time-string ts)))
5982 te (time-to-seconds
5983 (apply 'encode-time (org-parse-time-string te)))
5984 ts (if tstart (max ts tstart) ts)
5985 te (if tend (min te tend) te)
5986 dt (- te ts)
5987 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
5988 ;; A headline
5989 (setq level (- (match-end 1) (match-beginning 1)))
5990 (when (or (> t1 0) (> (aref ltimes level) 0))
5991 (loop for l from 0 to level do
5992 (aset ltimes l (+ (aref ltimes l) t1)))
5993 (setq t1 0 time (aref ltimes level))
5994 (loop for l from level to (1- lmax) do
5995 (aset ltimes l 0))
5996 (goto-char (match-beginning 0))
5997 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
5998 (setq org-clock-file-total-minutes (aref ltimes 0)))
5999 (set-buffer-modified-p bmp)))
6000
6001 (defun org-clock-display (&optional total-only)
6002 "Show subtree times in the entire buffer.
6003 If TOTAL-ONLY is non-nil, only show the total time for the entire file
6004 in the echo area."
6005 (interactive)
6006 (org-remove-clock-overlays)
6007 (let (time h m p)
6008 (org-clock-sum)
6009 (unless total-only
6010 (save-excursion
6011 (goto-char (point-min))
6012 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6013 (goto-char p)
6014 (when (setq time (get-text-property p :org-clock-minutes))
6015 (org-put-clock-overlay time (funcall outline-level))))
6016 (setq h (/ org-clock-file-total-minutes 60)
6017 m (- org-clock-file-total-minutes (* 60 h)))
6018 ;; Arrange to remove the overlays upon next change.
6019 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
6020 nil 'local)))
6021 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
6022
6023 (defvar org-clock-overlays nil)
6024 (make-variable-buffer-local 'org-clock-overlays)
6025
6026 (defun org-put-clock-overlay (time &optional level)
6027 "Put an overlays on the current line, displaying TIME.
6028 If LEVEL is given, prefix time with a corresponding number of stars.
6029 This creates a new overlay and stores it in `org-clock-overlays', so that it
6030 will be easy to remove."
6031 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
6032 (l (if level (org-get-legal-level level 0) 0))
6033 (off 0)
6034 ov tx)
6035 (move-to-column c)
6036 (unless (eolp) (skip-chars-backward "^ \t"))
6037 (skip-chars-backward " \t")
6038 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6039 tx (concat (buffer-substring (1- (point)) (point))
6040 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6041 (org-add-props (format "%s %2d:%02d%s"
6042 (make-string l ?*) h m
6043 (make-string (- 10 l) ?\ ))
6044 '(face secondary-selection))
6045 ""))
6046 (org-overlay-put ov 'display tx)
6047 (push ov org-clock-overlays)))
6048
6049 (defun org-remove-clock-overlays (&optional beg end noremove)
6050 "Remove the occur highlights from the buffer.
6051 BEG and END are ignored. If NOREMOVE is nil, remove this function
6052 from the `before-change-functions' in the current buffer."
6053 (interactive)
6054 (unless org-inhibit-highlight-removal
6055 (mapc 'org-delete-overlay org-clock-overlays)
6056 (setq org-clock-overlays nil)
6057 (unless noremove
6058 (remove-hook 'before-change-functions
6059 'org-remove-clock-overlays 'local))))
6060
6061 (defun org-clock-out-if-current ()
6062 "Clock out if the current entry contains the running clock.
6063 This is used to stop the clock after a TODO entry is marked DONE."
6064 (when (and (equal state org-done-string)
6065 (equal (marker-buffer org-clock-marker) (current-buffer))
6066 (< (point) org-clock-marker)
6067 (> (save-excursion (outline-next-heading) (point))
6068 org-clock-marker))
6069 (org-clock-out)))
6070
6071 (add-hook 'org-after-todo-state-change-hook
6072 'org-clock-out-if-current)
6073
6074 (defun org-check-running-clock ()
6075 "Check if the current buffer contains the running clock.
6076 If yes, offer to stop it and to save the buffer with the changes."
6077 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6078 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6079 (buffer-name))))
6080 (org-clock-out)
6081 (when (y-or-n-p "Save changed buffer?")
6082 (save-buffer))))
6083
6084 (defun org-clock-report ()
6085 "Create a table containing a report about clocked time.
6086 If the buffer contains lines
6087 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6088
6089 #+END: clocktable
6090 then the table will be inserted between these lines, replacing whatever
6091 is was there before. If these lines are not in the buffer, the table
6092 is inserted at point, surrounded by the special lines.
6093 The BEGIN line can contain parameters. Allowed are:
6094 :maxlevel The maximum level to be included in the table. Default is 3.
6095 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6096 (interactive)
6097 (org-remove-clock-overlays)
6098 (unless (org-find-dblock "clocktable")
6099 (org-create-dblock (list :name "clocktable"
6100 :maxlevel 2 :emphasize nil)))
6101 (org-update-dblock))
6102
6103 (defun org-clock-update-time-maybe ()
6104 "If this is a CLOCK line, update it and return t.
6105 Otherwise, return nil."
6106 (interactive)
6107 (save-excursion
6108 (beginning-of-line 1)
6109 (skip-chars-forward " \t")
6110 (when (looking-at org-clock-string)
6111 (let ((re (concat "[ \t]*" org-clock-string
6112 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
6113 "\\([ \t]*=>.*\\)?"))
6114 ts te h m s)
6115 (if (not (looking-at re))
6116 nil
6117 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
6118 (end-of-line 1)
6119 (setq ts (match-string 1)
6120 te (match-string 2))
6121 (setq s (- (time-to-seconds
6122 (apply 'encode-time (org-parse-time-string te)))
6123 (time-to-seconds
6124 (apply 'encode-time (org-parse-time-string ts))))
6125 h (floor (/ s 3600))
6126 s (- s (* 3600 h))
6127 m (floor (/ s 60))
6128 s (- s (* 60 s)))
6129 (insert " => " (format "%2d:%02d" h m))
6130 t)))))
6131
6132 (defun org-clock-special-range (key &optional time as-strings)
6133 "Return two times bordering a special time range.
6134 Key is a symbol specifying the range and can be one of `today', `yesterday',
6135 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
6136 A week starts Monday 0:00 and ends Sunday 24:00.
6137 The range is determined relative to TIME. TIME defaults to the current time.
6138 The return value is a cons cell with two internal times like the ones
6139 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
6140 the returned times will be formatted strings."
6141 (let* ((tm (decode-time (or time (current-time))))
6142 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
6143 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
6144 (dow (nth 6 tm))
6145 s1 m1 h1 d1 month1 y1 diff ts te fm)
6146 (cond
6147 ((eq key 'today)
6148 (setq h 0 m 0 h1 24 m1 0))
6149 ((eq key 'yesterday)
6150 (setq d (1- d) h 0 m 0 h1 24 m1 0))
6151 ((eq key 'thisweek)
6152 (setq diff (if (= dow 0) 6 (1- dow))
6153 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6154 ((eq key 'lastweek)
6155 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
6156 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6157 ((eq key 'thismonth)
6158 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
6159 ((eq key 'lastmonth)
6160 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
6161 ((eq key 'thisyear)
6162 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
6163 ((eq key 'lastyear)
6164 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
6165 (t (error "No such time block %s" key)))
6166 (setq ts (encode-time s m h d month y)
6167 te (encode-time (or s1 s) (or m1 m) (or h1 h)
6168 (or d1 d) (or month1 month) (or y1 y)))
6169 (setq fm (cdr org-time-stamp-formats))
6170 (if as-strings
6171 (cons (format-time-string fm ts) (format-time-string fm te))
6172 (cons ts te))))
6173
6174 (defun org-dblock-write:clocktable (params)
6175 "Write the standard clocktable."
6176 (let ((hlchars '((1 . "*") (2 . ?/)))
6177 (emph nil)
6178 (ins (make-marker))
6179 ipos time h m p level hlc hdl maxlevel
6180 ts te cc block)
6181 (setq maxlevel (or (plist-get params :maxlevel) 3)
6182 emph (plist-get params :emphasize)
6183 ts (plist-get params :tstart)
6184 te (plist-get params :tend)
6185 block (plist-get params :block))
6186 (when block
6187 (setq cc (org-clock-special-range block nil t)
6188 ts (car cc) te (cdr cc)))
6189 (if ts (setq ts (time-to-seconds
6190 (apply 'encode-time (org-parse-time-string ts)))))
6191 (if te (setq te (time-to-seconds
6192 (apply 'encode-time (org-parse-time-string te)))))
6193 (move-marker ins (point))
6194 (setq ipos (point))
6195 (insert-before-markers "Clock summary at ["
6196 (substring
6197 (format-time-string (cdr org-time-stamp-formats))
6198 1 -1)
6199 "]."
6200 (if block
6201 (format " Considered range is /%s/." block)
6202 "")
6203 "\n\n|L|Headline|Time|\n")
6204 (org-clock-sum ts te)
6205 (setq h (/ org-clock-file-total-minutes 60)
6206 m (- org-clock-file-total-minutes (* 60 h)))
6207 (insert-before-markers "|-\n|0|" "*Total file time*| "
6208 (format "*%d:%02d*" h m)
6209 "|\n")
6210 (goto-char (point-min))
6211 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6212 (goto-char p)
6213 (when (setq time (get-text-property p :org-clock-minutes))
6214 (save-excursion
6215 (beginning-of-line 1)
6216 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6217 (setq level (- (match-end 1) (match-beginning 1)))
6218 (<= level maxlevel))
6219 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6220 hdl (match-string 2)
6221 h (/ time 60)
6222 m (- time (* 60 h)))
6223 (goto-char ins)
6224 (if (= level 1) (insert-before-markers "|-\n"))
6225 (insert-before-markers
6226 "| " (int-to-string level) "|" hlc hdl hlc " |"
6227 (make-string (1- level) ?|)
6228 hlc
6229 (format "%d:%02d" h m)
6230 hlc
6231 " |\n")))))
6232 (goto-char ins)
6233 (backward-delete-char 1)
6234 (goto-char ipos)
6235 (skip-chars-forward "^|")
6236 (org-table-align)))
6237
6238 (defun org-collect-clock-time-entries ()
6239 "Return an internal list with clocking information.
6240 This list has one entry for each CLOCK interval.
6241 FIXME: describe the elements."
6242 (interactive)
6243 (let ((re (concat "^[ \t]*" org-clock-string
6244 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6245 rtn beg end next cont level title total closedp leafp
6246 clockpos titlepos h m donep)
6247 (save-excursion
6248 (org-clock-sum)
6249 (goto-char (point-min))
6250 (while (re-search-forward re nil t)
6251 (setq clockpos (match-beginning 0)
6252 beg (match-string 1) end (match-string 2)
6253 cont (match-end 0))
6254 (setq beg (apply 'encode-time (org-parse-time-string beg))
6255 end (apply 'encode-time (org-parse-time-string end)))
6256 (org-back-to-heading t)
6257 (setq donep (org-entry-is-done-p))
6258 (setq titlepos (point)
6259 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6260 h (/ total 60) m (- total (* 60 h))
6261 total (cons h m))
6262 (looking-at "\\(\\*+\\) +\\(.*\\)")
6263 (setq level (- (match-end 1) (match-beginning 1))
6264 title (org-match-string-no-properties 2))
6265 (save-excursion (outline-next-heading) (setq next (point)))
6266 (setq closedp (re-search-forward org-closed-time-regexp next t))
6267 (goto-char next)
6268 (setq leafp (and (looking-at "^\\*+ ")
6269 (<= (- (match-end 0) (point)) level)))
6270 (push (list beg end clockpos closedp donep
6271 total title titlepos level leafp)
6272 rtn)
6273 (goto-char cont)))
6274 (nreverse rtn)))
6275
6276 ;;; Agenda, and Diary Integration
6277
6278 ;;; Define the mode
6279
6280 (defvar org-agenda-mode-map (make-sparse-keymap)
6281 "Keymap for `org-agenda-mode'.")
6282
6283 (defvar org-agenda-menu) ; defined later in this file.
6284 (defvar org-agenda-follow-mode nil)
6285 (defvar org-agenda-show-log nil)
6286 (defvar org-agenda-buffer-name "*Org Agenda*")
6287 (defvar org-agenda-redo-command nil)
6288 (defvar org-agenda-mode-hook nil)
6289 (defvar org-agenda-type nil)
6290 (defvar org-agenda-force-single-file nil)
6291
6292 (defun org-agenda-mode ()
6293 "Mode for time-sorted view on action items in Org-mode files.
6294
6295 The following commands are available:
6296
6297 \\{org-agenda-mode-map}"
6298 (interactive)
6299 (kill-all-local-variables)
6300 (setq major-mode 'org-agenda-mode)
6301 (setq mode-name "Org-Agenda")
6302 (use-local-map org-agenda-mode-map)
6303 (easy-menu-add org-agenda-menu)
6304 (if org-startup-truncated (setq truncate-lines t))
6305 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6306 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6307 (unless org-agenda-keep-modes
6308 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6309 org-agenda-show-log nil))
6310 (easy-menu-change
6311 '("Agenda") "Agenda Files"
6312 (append
6313 (list
6314 (vector
6315 (if (get 'org-agenda-files 'org-restrict)
6316 "Restricted to single file"
6317 "Edit File List")
6318 '(org-edit-agenda-file-list)
6319 (not (get 'org-agenda-files 'org-restrict)))
6320 "--")
6321 (mapcar 'org-file-menu-entry (org-agenda-files))))
6322 (org-agenda-set-mode-name)
6323 (apply
6324 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6325 (list 'org-agenda-mode-hook)))
6326
6327 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6328 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6329 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6330 (define-key org-agenda-mode-map " " 'org-agenda-show)
6331 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6332 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6333 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6334 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6335 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6336 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6337 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6338 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6339 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6340 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6341 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6342 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6343 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6344
6345 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6346 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6347 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6348 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6349 (while l (define-key org-agenda-mode-map
6350 (int-to-string (pop l)) 'digit-argument)))
6351
6352 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6353 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6354 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6355 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6356 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6357 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6358 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6359 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
6360 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6361 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6362 (define-key org-agenda-mode-map "n" 'next-line)
6363 (define-key org-agenda-mode-map "p" 'previous-line)
6364 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6365 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6366 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6367 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6368 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6369 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6370 (eval-after-load "calendar"
6371 '(define-key calendar-mode-map org-calendar-to-agenda-key
6372 'org-calendar-goto-agenda))
6373 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6374 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6375 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6376 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6377 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6378 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6379 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6380 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6381 (define-key org-agenda-mode-map "O" 'org-clock-out)
6382 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6383 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6384 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6385 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6386 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6387 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6388 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6389 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6390 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6391 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6392 "Local keymap for agenda entries from Org-mode.")
6393
6394 (define-key org-agenda-keymap
6395 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6396 (define-key org-agenda-keymap
6397 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6398 (when org-agenda-mouse-1-follows-link
6399 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6400 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6401 '("Agenda"
6402 ("Agenda Files")
6403 "--"
6404 ["Show" org-agenda-show t]
6405 ["Go To (other window)" org-agenda-goto t]
6406 ["Go To (one window)" org-agenda-switch-to t]
6407 ["Follow Mode" org-agenda-follow-mode
6408 :style toggle :selected org-agenda-follow-mode :active t]
6409 "--"
6410 ["Cycle TODO" org-agenda-todo t]
6411 ("Tags"
6412 ["Show all Tags" org-agenda-show-tags t]
6413 ["Set Tags" org-agenda-set-tags t])
6414 ("Schedule"
6415 ["Schedule" org-agenda-schedule t]
6416 ["Set Deadline" org-agenda-deadline t]
6417 "--"
6418 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6419 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6420 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6421 ("Priority"
6422 ["Set Priority" org-agenda-priority t]
6423 ["Increase Priority" org-agenda-priority-up t]
6424 ["Decrease Priority" org-agenda-priority-down t]
6425 ["Show Priority" org-agenda-show-priority t])
6426 "--"
6427 ;; ["New agenda command" org-agenda t]
6428 ["Rebuild buffer" org-agenda-redo t]
6429 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
6430 "--"
6431 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6432 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6433 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6434 "--"
6435 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6436 :style radio :selected (equal org-agenda-ndays 1)]
6437 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6438 :style radio :selected (equal org-agenda-ndays 7)]
6439 "--"
6440 ["Show Logbook entries" org-agenda-log-mode
6441 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6442 ["Include Diary" org-agenda-toggle-diary
6443 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6444 ["Use Time Grid" org-agenda-toggle-time-grid
6445 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6446 "--"
6447 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6448 ("Calendar Commands"
6449 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6450 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6451 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6452 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6453 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6454 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6455 "--"
6456 ["Quit" org-agenda-quit t]
6457 ["Exit and Release Buffers" org-agenda-exit t]
6458 ))
6459
6460 ;;;###autoload
6461 (defun org-agenda (arg)
6462 "Dispatch agenda commands to collect entries to the agenda buffer.
6463 Prompts for a character to select a command. Any prefix arg will be passed
6464 on to the selected command. The default selections are:
6465
6466 a Call `org-agenda' to display the agenda for the current day or week.
6467 t Call `org-todo-list' to display the global todo list.
6468 T Call `org-todo-list' to display the global todo list, select only
6469 entries with a specific TODO keyword (the user gets a prompt).
6470 m Call `org-tags-view' to display headlines with tags matching
6471 a condition (the user is prompted for the condition).
6472 M Like `m', but select only TODO entries, no ordinary headlines.
6473
6474 More commands can be added by configuring the variable
6475 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
6476 searches can be pre-defined in this way.
6477
6478 If the current buffer is in Org-mode and visiting a file, you can also
6479 first press `1' to indicate that the agenda should be temporarily (until the
6480 next use of \\[org-agenda]) restricted to the current file."
6481 (interactive "P")
6482 (catch 'exit
6483 (let ((restrict-ok (and buffer-file-name (org-mode-p)))
6484 (bfn buffer-file-name)
6485 (custom org-agenda-custom-commands)
6486 c entry key type string)
6487 (put 'org-agenda-files 'org-restrict nil)
6488 (save-window-excursion
6489 (delete-other-windows)
6490 (switch-to-buffer-other-window " *Agenda Commands*")
6491 (erase-buffer)
6492 (insert
6493 "Press key for an agenda command:
6494 --------------------------------
6495 a Agenda for current week or day
6496 t List of all TODO entries T Entries with special TODO kwd
6497 m Match a TAGS query M Like m, but only TODO entries
6498 C Configure your own agenda commands")
6499 (while (setq entry (pop custom))
6500 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
6501 (insert (format "\n%-4s%-14s: %s"
6502 key
6503 (cond
6504 ((eq type 'tags) "Tags query")
6505 ((eq type 'todo) "TODO keyword")
6506 ((eq type 'tags-tree) "Tags tree")
6507 ((eq type 'todo-tree) "TODO kwd tree")
6508 ((eq type 'occur-tree) "Occur tree")
6509 (t "???"))
6510 (org-add-props string nil 'face 'org-warning))))
6511 (goto-char (point-min))
6512 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
6513 (message "Press key for agenda command%s"
6514 (if restrict-ok ", or [1] to restrict to current file" ""))
6515 (setq c (read-char-exclusive))
6516 (message "")
6517 (when (equal c ?1)
6518 (if restrict-ok
6519 (put 'org-agenda-files 'org-restrict (list bfn))
6520 (error "Cannot restrict agenda to current buffer"))
6521 (message "Press key for agenda command%s"
6522 (if restrict-ok " (restricted to current file)" ""))
6523 (setq c (read-char-exclusive))
6524 (message "")))
6525 (require 'calendar) ; FIXME: can we avoid this for some commands?
6526 ;; For example the todo list should not need it (but does...)
6527 (cond
6528 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
6529 ((equal c ?a) (call-interactively 'org-agenda-list))
6530 ((equal c ?t) (call-interactively 'org-todo-list))
6531 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
6532 ((equal c ?m) (call-interactively 'org-tags-view))
6533 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
6534 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
6535 (setq type (nth 1 entry) string (nth 2 entry))
6536 (cond
6537 ((eq type 'tags)
6538 (org-tags-view current-prefix-arg string))
6539 ((eq type 'tags-todo)
6540 (org-tags-view '(4) string))
6541 ((eq type 'todo)
6542 (org-todo-list string))
6543 ((eq type 'tags-tree)
6544 (org-check-for-org-mode)
6545 (org-tags-sparse-tree current-prefix-arg string))
6546 ((eq type 'todo-tree)
6547 (org-check-for-org-mode)
6548 (org-occur (concat "^" outline-regexp "[ \t]*"
6549 (regexp-quote string) "\\>")))
6550 ((eq type 'occur-tree)
6551 (org-check-for-org-mode)
6552 (org-occur string))
6553 (t (error "Invalid custom agenda command type %s" type))))
6554 (t (error "Invalid key"))))))
6555
6556 (defun org-check-for-org-mode ()
6557 "Make sure current buffer is in org-mode. Error if not."
6558 (or (org-mode-p)
6559 (error "Cannot execute org-mode agenda command on buffer in %s."
6560 major-mode)))
6561
6562 (defun org-fit-agenda-window ()
6563 "Fit the window to the buffer size."
6564 (and org-fit-agenda-window
6565 (fboundp 'fit-window-to-buffer)
6566 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
6567 (/ (frame-height) 2))))
6568
6569 (defun org-agenda-files (&optional unrestricted)
6570 "Get the list of agenda files.
6571 Optional UNRESTRICTED means return the full list even if a restriction
6572 is currently in place."
6573 (cond
6574 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
6575 ((stringp org-agenda-files) (org-read-agenda-file-list))
6576 ((listp org-agenda-files) org-agenda-files)
6577 (t (error "Invalid value of `org-agenda-files'"))))
6578
6579 (defvar org-window-configuration)
6580
6581 (defun org-edit-agenda-file-list ()
6582 "Edit the list of agenda files.
6583 Depending on setup, this either uses customize to edit the variable
6584 `org-agenda-files', or it visits the file that is holding the list. In the
6585 latter case, the buffer is set up in a way that saving it automatically kills
6586 the buffer and restores the previous window configuration."
6587 (interactive)
6588 (if (stringp org-agenda-files)
6589 (let ((cw (current-window-configuration)))
6590 (find-file org-agenda-files)
6591 (org-set-local 'org-window-configuration cw)
6592 (org-add-hook 'after-save-hook
6593 (lambda ()
6594 (set-window-configuration
6595 (prog1 org-window-configuration
6596 (kill-buffer (current-buffer))))
6597 (org-install-agenda-files-menu)
6598 (message "New agenda file list installed"))
6599 nil 'local)
6600 (message (substitute-command-keys
6601 "Edit list and finish with \\[save-buffer]")))
6602 (customize-variable 'org-agenda-files)))
6603
6604 (defun org-store-new-agenda-file-list (list)
6605 "Set new value for the agenda file list and save it correcly."
6606 (if (stringp org-agenda-files)
6607 (let ((f org-agenda-files) b)
6608 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
6609 (with-temp-file f
6610 (insert (mapconcat 'identity list "\n") "\n")))
6611 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
6612 (setq org-agenda-files list)
6613 (customize-save-variable 'org-agenda-files org-agenda-files))))
6614
6615 (defun org-read-agenda-file-list ()
6616 "Read the list of agenda files from a file."
6617 (when (stringp org-agenda-files)
6618 (with-temp-buffer
6619 (insert-file-contents org-agenda-files)
6620 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
6621
6622 (defvar org-agenda-markers nil
6623 "List of all currently active markers created by `org-agenda'.")
6624 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
6625 "Creation time of the last agenda marker.")
6626
6627 (defun org-agenda-new-marker (&optional pos)
6628 "Return a new agenda marker.
6629 Org-mode keeps a list of these markers and resets them when they are
6630 no longer in use."
6631 (let ((m (copy-marker (or pos (point)))))
6632 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
6633 (push m org-agenda-markers)
6634 m))
6635
6636 (defun org-agenda-maybe-reset-markers (&optional force)
6637 "Reset markers created by `org-agenda'. But only if they are old enough."
6638 (if (or force
6639 (> (- (time-to-seconds (current-time))
6640 org-agenda-last-marker-time)
6641 5))
6642 (while org-agenda-markers
6643 (move-marker (pop org-agenda-markers) nil))))
6644
6645 (defvar org-agenda-new-buffers nil
6646 "Buffers created to visit agenda files.")
6647
6648 (defun org-get-agenda-file-buffer (file)
6649 "Get a buffer visiting FILE. If the buffer needs to be created, add
6650 it to the list of buffers which might be released later."
6651 (let ((buf (find-buffer-visiting file)))
6652 (if buf
6653 buf ; just return it
6654 ;; Make a new buffer and remember it
6655 (setq buf (find-file-noselect file))
6656 (if buf (push buf org-agenda-new-buffers))
6657 buf)))
6658
6659 (defun org-release-buffers (blist)
6660 "Release all buffers in list, asking the user for confirmation when needed.
6661 When a buffer is unmodified, it is just killed. When modified, it is saved
6662 \(if the user agrees) and then killed."
6663 (let (buf file)
6664 (while (setq buf (pop blist))
6665 (setq file (buffer-file-name buf))
6666 (when (and (buffer-modified-p buf)
6667 file
6668 (y-or-n-p (format "Save file %s? " file)))
6669 (with-current-buffer buf (save-buffer)))
6670 (kill-buffer buf))))
6671
6672 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
6673
6674 (defun org-timeline (&optional include-all keep-modes)
6675 "Show a time-sorted view of the entries in the current org file.
6676 Only entries with a time stamp of today or later will be listed. With
6677 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
6678 under the current date.
6679 If the buffer contains an active region, only check the region for
6680 dates."
6681 (interactive "P")
6682 (require 'calendar)
6683 (org-agenda-maybe-reset-markers 'force)
6684 (org-compile-prefix-format org-timeline-prefix-format)
6685 (let* ((dopast t)
6686 (dotodo include-all)
6687 (doclosed org-agenda-show-log)
6688 (org-agenda-keep-modes keep-modes)
6689 (entry buffer-file-name)
6690 (org-agenda-files (list buffer-file-name))
6691 (date (calendar-current-date))
6692 (win (selected-window))
6693 (pos1 (point))
6694 (beg (if (org-region-active-p) (region-beginning) (point-min)))
6695 (end (if (org-region-active-p) (region-end) (point-max)))
6696 (day-numbers (org-get-all-dates beg end 'no-ranges
6697 t doclosed ; always include today
6698 org-timeline-show-empty-dates))
6699 (today (time-to-days (current-time)))
6700 (org-respect-restriction t)
6701 (past t)
6702 args
6703 s e rtn d emptyp)
6704 (org-prepare-agenda-buffers org-agenda-files)
6705 (setq org-agenda-redo-command
6706 (list 'progn
6707 (list 'switch-to-buffer-other-window (current-buffer))
6708 (list 'org-timeline (list 'quote include-all) t)))
6709 (if (not dopast)
6710 ;; Remove past dates from the list of dates.
6711 (setq day-numbers (delq nil (mapcar (lambda(x)
6712 (if (>= x today) x nil))
6713 day-numbers))))
6714 (switch-to-buffer-other-window
6715 (get-buffer-create org-agenda-buffer-name))
6716 (setq buffer-read-only nil)
6717 (erase-buffer)
6718 (org-agenda-mode) (setq buffer-read-only nil)
6719 (org-set-local 'org-agenda-type 'timeline)
6720 (if doclosed (push :closed args))
6721 (push :timestamp args)
6722 (if dotodo (push :todo args))
6723 (while (setq d (pop day-numbers))
6724 (if (and (listp d) (eq (car d) :omitted))
6725 (progn
6726 (setq s (point))
6727 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
6728 (put-text-property s (1- (point)) 'face 'org-level-3))
6729 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
6730 (if (and (>= d today)
6731 dopast
6732 past)
6733 (progn
6734 (setq past nil)
6735 (insert (make-string 79 ?-) "\n")))
6736 (setq date (calendar-gregorian-from-absolute d))
6737 (setq s (point))
6738 (setq rtn (and (not emptyp)
6739 (apply 'org-agenda-get-day-entries
6740 entry date args)))
6741 (if (or rtn (equal d today) org-timeline-show-empty-dates)
6742 (progn
6743 (insert (calendar-day-name date) " "
6744 (number-to-string (extract-calendar-day date)) " "
6745 (calendar-month-name (extract-calendar-month date)) " "
6746 (number-to-string (extract-calendar-year date)) "\n")
6747 (put-text-property s (1- (point)) 'face
6748 'org-level-3)
6749 (if (equal d today)
6750 (put-text-property s (1- (point)) 'org-today t))
6751 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
6752 (put-text-property s (1- (point)) 'day d)))))
6753 (goto-char (point-min))
6754 (setq buffer-read-only t)
6755 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6756 (point-min)))
6757 (when (not org-select-timeline-window)
6758 (select-window win)
6759 (goto-char pos1))))
6760
6761 ;;;###autoload
6762 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
6763 "Produce a weekly view from all files in variable `org-agenda-files'.
6764 The view will be for the current week, but from the overview buffer you
6765 will be able to go to other weeks.
6766 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
6767 also be shown, under the current date.
6768 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
6769 on the days are also shown. See the variable `org-log-done' for how
6770 to turn on logging.
6771 START-DAY defaults to TODAY, or to the most recent match for the weekday
6772 given in `org-agenda-start-on-weekday'.
6773 NDAYS defaults to `org-agenda-ndays'."
6774 (interactive "P")
6775 (org-agenda-maybe-reset-markers 'force)
6776 (org-compile-prefix-format org-agenda-prefix-format)
6777 (require 'calendar)
6778 (let* ((org-agenda-start-on-weekday
6779 (if (or (equal ndays 1)
6780 (and (null ndays) (equal 1 org-agenda-ndays)))
6781 nil org-agenda-start-on-weekday))
6782 (org-agenda-keep-modes keep-modes)
6783 (thefiles (org-agenda-files))
6784 (files thefiles)
6785 (win (selected-window))
6786 (today (time-to-days (current-time)))
6787 (sd (or start-day today))
6788 (start (if (or (null org-agenda-start-on-weekday)
6789 (< org-agenda-ndays 7))
6790 sd
6791 (let* ((nt (calendar-day-of-week
6792 (calendar-gregorian-from-absolute sd)))
6793 (n1 org-agenda-start-on-weekday)
6794 (d (- nt n1)))
6795 (- sd (+ (if (< d 0) 7 0) d)))))
6796 (day-numbers (list start))
6797 (inhibit-redisplay t)
6798 s e rtn rtnall file date d start-pos end-pos todayp nd)
6799 (org-prepare-agenda-buffers files)
6800 (setq org-agenda-redo-command
6801 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
6802 ;; Make the list of days
6803 (setq ndays (or ndays org-agenda-ndays)
6804 nd ndays)
6805 (while (> ndays 1)
6806 (push (1+ (car day-numbers)) day-numbers)
6807 (setq ndays (1- ndays)))
6808 (setq day-numbers (nreverse day-numbers))
6809 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6810 (progn
6811 (delete-other-windows)
6812 (switch-to-buffer-other-window
6813 (get-buffer-create org-agenda-buffer-name))))
6814 (setq buffer-read-only nil)
6815 (erase-buffer)
6816 (org-agenda-mode) (setq buffer-read-only nil)
6817 (org-set-local 'org-agenda-type 'agenda)
6818 (org-set-local 'starting-day (car day-numbers))
6819 (org-set-local 'include-all-loc include-all)
6820 (when (and (or include-all org-agenda-include-all-todo)
6821 (member today day-numbers))
6822 (setq files thefiles
6823 rtnall nil)
6824 (while (setq file (pop files))
6825 (catch 'nextfile
6826 (org-check-agenda-file file)
6827 (setq date (calendar-gregorian-from-absolute today)
6828 rtn (org-agenda-get-day-entries
6829 file date :todo))
6830 (setq rtnall (append rtnall rtn))))
6831 (when rtnall
6832 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
6833 (add-text-properties (point-min) (1- (point))
6834 (list 'face 'org-level-3))
6835 (insert (org-finalize-agenda-entries rtnall) "\n")))
6836 (while (setq d (pop day-numbers))
6837 (setq date (calendar-gregorian-from-absolute d)
6838 s (point))
6839 (if (or (setq todayp (= d today))
6840 (and (not start-pos) (= d sd)))
6841 (setq start-pos (point))
6842 (if (and start-pos (not end-pos))
6843 (setq end-pos (point))))
6844 (setq files thefiles
6845 rtnall nil)
6846 (while (setq file (pop files))
6847 (catch 'nextfile
6848 (org-check-agenda-file file)
6849 (if org-agenda-show-log
6850 (setq rtn (org-agenda-get-day-entries
6851 file date
6852 :deadline :scheduled :timestamp :closed))
6853 (setq rtn (org-agenda-get-day-entries
6854 file date
6855 :deadline :scheduled :timestamp)))
6856 (setq rtnall (append rtnall rtn))))
6857 (if org-agenda-include-diary
6858 (progn
6859 (require 'diary-lib)
6860 (setq rtn (org-get-entries-from-diary date))
6861 (setq rtnall (append rtnall rtn))))
6862 (if (or rtnall org-agenda-show-all-dates)
6863 (progn
6864 (insert (format "%-9s %2d %s %4d\n"
6865 (calendar-day-name date)
6866 (extract-calendar-day date)
6867 (calendar-month-name (extract-calendar-month date))
6868 (extract-calendar-year date)))
6869 (put-text-property s (1- (point)) 'face
6870 'org-level-3)
6871 (if rtnall (insert
6872 (org-finalize-agenda-entries
6873 (org-agenda-add-time-grid-maybe
6874 rtnall nd todayp))
6875 "\n"))
6876 (put-text-property s (1- (point)) 'day d))))
6877 (goto-char (point-min))
6878 (setq buffer-read-only t)
6879 (org-fit-agenda-window)
6880 (unless (and (pos-visible-in-window-p (point-min))
6881 (pos-visible-in-window-p (point-max)))
6882 (goto-char (1- (point-max)))
6883 (recenter -1)
6884 (if (not (pos-visible-in-window-p (or start-pos 1)))
6885 (progn
6886 (goto-char (or start-pos 1))
6887 (recenter 1))))
6888 (goto-char (or start-pos 1))
6889 (if (not org-select-agenda-window) (select-window win))
6890 (message "")))
6891
6892 (defvar org-select-this-todo-keyword nil)
6893
6894 ;;;###autoload
6895 (defun org-todo-list (arg &optional keep-modes)
6896 "Show all TODO entries from all agenda file in a single list.
6897 The prefix arg can be used to select a specific TODO keyword and limit
6898 the list to these. When using \\[universal-argument], you will be prompted
6899 for a keyword. A numeric prefix directly selects the Nth keyword in
6900 `org-todo-keywords'."
6901 (interactive "P")
6902 (org-agenda-maybe-reset-markers 'force)
6903 (org-compile-prefix-format org-agenda-prefix-format)
6904 (let* ((org-agenda-keep-modes keep-modes)
6905 (today (time-to-days (current-time)))
6906 (date (calendar-gregorian-from-absolute today))
6907 (win (selected-window))
6908 (kwds org-todo-keywords)
6909 (completion-ignore-case t)
6910 (org-select-this-todo-keyword
6911 (if (stringp arg) arg
6912 (and arg (integerp arg) (> arg 0)
6913 (nth (1- arg) org-todo-keywords))))
6914 rtn rtnall files file pos)
6915 (when (equal arg '(4))
6916 (setq org-select-this-todo-keyword
6917 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
6918 nil t)))
6919 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
6920 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6921 (progn
6922 (delete-other-windows)
6923 (switch-to-buffer-other-window
6924 (get-buffer-create org-agenda-buffer-name))))
6925 (setq buffer-read-only nil)
6926 (erase-buffer)
6927 (org-agenda-mode) (setq buffer-read-only nil)
6928 (org-set-local 'org-agenda-type 'todo)
6929 (org-set-local 'last-arg arg)
6930 (org-set-local 'org-todo-keywords kwds)
6931 (org-set-local 'org-agenda-redo-command
6932 '(org-todo-list (or current-prefix-arg last-arg) t))
6933 (setq files (org-agenda-files)
6934 rtnall nil)
6935 (org-prepare-agenda-buffers files)
6936 (while (setq file (pop files))
6937 (catch 'nextfile
6938 (org-check-agenda-file file)
6939 (setq rtn (org-agenda-get-day-entries file date :todo))
6940 (setq rtnall (append rtnall rtn))))
6941 (insert "Global list of TODO items of type: ")
6942 (add-text-properties (point-min) (1- (point))
6943 (list 'face 'org-level-3))
6944 (setq pos (point))
6945 (insert (or org-select-this-todo-keyword "ALL") "\n")
6946 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6947 (setq pos (point))
6948 (insert
6949 "Available with `N r': (0)ALL "
6950 (let ((n 0))
6951 (mapconcat (lambda (x)
6952 (format "(%d)%s" (setq n (1+ n)) x))
6953 org-todo-keywords " "))
6954 "\n")
6955 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
6956 (when rtnall
6957 (insert (org-finalize-agenda-entries rtnall) "\n"))
6958 (goto-char (point-min))
6959 (setq buffer-read-only t)
6960 (org-fit-agenda-window)
6961 (if (not org-select-agenda-window) (select-window win))))
6962
6963 (defun org-check-agenda-file (file)
6964 "Make sure FILE exists. If not, ask user what to do."
6965 (when (not (file-exists-p file))
6966 (message "non-existent file %s. [R]emove from list or [A]bort?"
6967 (abbreviate-file-name file))
6968 (let ((r (downcase (read-char-exclusive))))
6969 (cond
6970 ((equal r ?r)
6971 (org-remove-file file)
6972 (throw 'nextfile t))
6973 (t (error "Abort"))))))
6974
6975 (defun org-agenda-check-type (error &rest types)
6976 "Check if agenda buffer is of allowed type.
6977 If ERROR is non-nil, throw an error, otherwise just return nil."
6978 (if (memq org-agenda-type types)
6979 t
6980 (if error
6981 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
6982 nil)))
6983
6984 (defun org-agenda-quit ()
6985 "Exit agenda by removing the window or the buffer."
6986 (interactive)
6987 (let ((buf (current-buffer)))
6988 (if (not (one-window-p)) (delete-window))
6989 (kill-buffer buf)
6990 (org-agenda-maybe-reset-markers 'force)))
6991
6992 (defun org-agenda-exit ()
6993 "Exit agenda by removing the window or the buffer.
6994 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
6995 Org-mode buffers visited directly by the user will not be touched."
6996 (interactive)
6997 (org-release-buffers org-agenda-new-buffers)
6998 (setq org-agenda-new-buffers nil)
6999 (org-agenda-quit))
7000
7001 ;; FIXME: move this function.
7002 (defun org-save-all-org-buffers ()
7003 "Save all Org-mode buffers without user confirmation."
7004 (interactive)
7005 (message "Saving all Org-mode buffers...")
7006 (save-some-buffers t 'org-mode-p)
7007 (message "Saving all Org-mode buffers... done"))
7008
7009 (defun org-agenda-redo ()
7010 "Rebuild Agenda.
7011 When this is the global TODO list, a prefix argument will be interpreted."
7012 (interactive)
7013 (message "Rebuilding agenda buffer...")
7014 (eval org-agenda-redo-command)
7015 (message "Rebuilding agenda buffer...done"))
7016
7017 (defun org-agenda-goto-today ()
7018 "Go to today."
7019 (interactive)
7020 (org-agenda-check-type t 'timeline 'agenda)
7021 (if (boundp 'starting-day)
7022 (let ((cmd (car org-agenda-redo-command))
7023 (iall (nth 1 org-agenda-redo-command))
7024 (nday (nth 3 org-agenda-redo-command))
7025 (keep (nth 4 org-agenda-redo-command)))
7026 (eval (list cmd iall nil nday keep)))
7027 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
7028 (point-min)))))
7029
7030 (defun org-agenda-later (arg)
7031 "Go forward in time by `org-agenda-ndays' days.
7032 With prefix ARG, go forward that many times `org-agenda-ndays'."
7033 (interactive "p")
7034 (org-agenda-check-type t 'agenda)
7035 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
7036 (+ starting-day (* arg org-agenda-ndays)) nil t))
7037
7038 (defun org-agenda-earlier (arg)
7039 "Go back in time by `org-agenda-ndays' days.
7040 With prefix ARG, go back that many times `org-agenda-ndays'."
7041 (interactive "p")
7042 (org-agenda-check-type t 'agenda)
7043 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
7044 (- starting-day (* arg org-agenda-ndays)) nil t))
7045
7046 (defun org-agenda-week-view ()
7047 "Switch to weekly view for agenda."
7048 (interactive)
7049 (org-agenda-check-type t 'agenda)
7050 (setq org-agenda-ndays 7)
7051 (org-agenda-list include-all-loc
7052 (or (get-text-property (point) 'day)
7053 starting-day)
7054 nil t)
7055 (org-agenda-set-mode-name)
7056 (message "Switched to week view"))
7057
7058 (defun org-agenda-day-view ()
7059 "Switch to daily view for agenda."
7060 (interactive)
7061 (org-agenda-check-type t 'agenda)
7062 (setq org-agenda-ndays 1)
7063 (org-agenda-list include-all-loc
7064 (or (get-text-property (point) 'day)
7065 starting-day)
7066 nil t)
7067 (org-agenda-set-mode-name)
7068 (message "Switched to day view"))
7069
7070 (defun org-agenda-next-date-line (&optional arg)
7071 "Jump to the next line indicating a date in agenda buffer."
7072 (interactive "p")
7073 (org-agenda-check-type t 'agenda 'timeline)
7074 (beginning-of-line 1)
7075 (if (looking-at "^\\S-") (forward-char 1))
7076 (if (not (re-search-forward "^\\S-" nil t arg))
7077 (progn
7078 (backward-char 1)
7079 (error "No next date after this line in this buffer")))
7080 (goto-char (match-beginning 0)))
7081
7082 (defun org-agenda-previous-date-line (&optional arg)
7083 "Jump to the previous line indicating a date in agenda buffer."
7084 (interactive "p")
7085 (org-agenda-check-type t 'agenda 'timeline)
7086 (beginning-of-line 1)
7087 (if (not (re-search-backward "^\\S-" nil t arg))
7088 (error "No previous date before this line in this buffer")))
7089
7090 ;; Initialize the highlight
7091 (defvar org-hl (org-make-overlay 1 1))
7092 (org-overlay-put org-hl 'face 'highlight)
7093
7094 (defun org-highlight (begin end &optional buffer)
7095 "Highlight a region with overlay."
7096 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
7097 org-hl begin end (or buffer (current-buffer))))
7098
7099 (defun org-unhighlight ()
7100 "Detach overlay INDEX."
7101 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
7102
7103
7104 (defun org-agenda-follow-mode ()
7105 "Toggle follow mode in an agenda buffer."
7106 (interactive)
7107 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
7108 (org-agenda-set-mode-name)
7109 (message "Follow mode is %s"
7110 (if org-agenda-follow-mode "on" "off")))
7111
7112 (defun org-agenda-log-mode ()
7113 "Toggle log mode in an agenda buffer."
7114 (interactive)
7115 (org-agenda-check-type t 'agenda 'timeline)
7116 (setq org-agenda-show-log (not org-agenda-show-log))
7117 (org-agenda-set-mode-name)
7118 (org-agenda-redo)
7119 (message "Log mode is %s"
7120 (if org-agenda-show-log "on" "off")))
7121
7122 (defun org-agenda-toggle-diary ()
7123 "Toggle diary inclusion in an agenda buffer."
7124 (interactive)
7125 (org-agenda-check-type t 'agenda)
7126 (setq org-agenda-include-diary (not org-agenda-include-diary))
7127 (org-agenda-redo)
7128 (org-agenda-set-mode-name)
7129 (message "Diary inclusion turned %s"
7130 (if org-agenda-include-diary "on" "off")))
7131
7132 (defun org-agenda-toggle-time-grid ()
7133 "Toggle time grid in an agenda buffer."
7134 (interactive)
7135 (org-agenda-check-type t 'agenda)
7136 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
7137 (org-agenda-redo)
7138 (org-agenda-set-mode-name)
7139 (message "Time-grid turned %s"
7140 (if org-agenda-use-time-grid "on" "off")))
7141
7142 (defun org-agenda-set-mode-name ()
7143 "Set the mode name to indicate all the small mode settings."
7144 (setq mode-name
7145 (concat "Org-Agenda"
7146 (if (equal org-agenda-ndays 1) " Day" "")
7147 (if (equal org-agenda-ndays 7) " Week" "")
7148 (if org-agenda-follow-mode " Follow" "")
7149 (if org-agenda-include-diary " Diary" "")
7150 (if org-agenda-use-time-grid " Grid" "")
7151 (if org-agenda-show-log " Log" "")))
7152 (force-mode-line-update))
7153
7154 (defun org-agenda-post-command-hook ()
7155 (and (eolp) (not (bolp)) (backward-char 1))
7156 (if (and org-agenda-follow-mode
7157 (get-text-property (point) 'org-marker))
7158 (org-agenda-show)))
7159
7160 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
7161
7162 (defun org-get-entries-from-diary (date)
7163 "Get the (Emacs Calendar) diary entries for DATE."
7164 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
7165 (diary-display-hook '(fancy-diary-display))
7166 (list-diary-entries-hook
7167 (cons 'org-diary-default-entry list-diary-entries-hook))
7168 (diary-file-name-prefix-function nil) ; turn this feature off
7169 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7170 entries
7171 (org-disable-agenda-to-diary t))
7172 (save-excursion
7173 (save-window-excursion
7174 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7175 (if (not (get-buffer fancy-diary-buffer))
7176 (setq entries nil)
7177 (with-current-buffer fancy-diary-buffer
7178 (setq buffer-read-only nil)
7179 (if (= (point-max) 1)
7180 ;; No entries
7181 (setq entries nil)
7182 ;; Omit the date and other unnecessary stuff
7183 (org-agenda-cleanup-fancy-diary)
7184 ;; Add prefix to each line and extend the text properties
7185 (if (= (point-max) 1)
7186 (setq entries nil)
7187 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7188 (set-buffer-modified-p nil)
7189 (kill-buffer fancy-diary-buffer)))
7190 (when entries
7191 (setq entries (org-split-string entries "\n"))
7192 (setq entries
7193 (mapcar
7194 (lambda (x)
7195 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7196 ;; Extend the text properties to the beginning of the line
7197 (org-add-props x (text-properties-at (1- (length x)) x)))
7198 entries)))))
7199
7200 (defun org-agenda-cleanup-fancy-diary ()
7201 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7202 This gets rid of the date, the underline under the date, and
7203 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7204 date. It also removes lines that contain only whitespace."
7205 (goto-char (point-min))
7206 (if (looking-at ".*?:[ \t]*")
7207 (progn
7208 (replace-match "")
7209 (re-search-forward "\n=+$" nil t)
7210 (replace-match "")
7211 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7212 (re-search-forward "\n=+$" nil t)
7213 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7214 (goto-char (point-min))
7215 (while (re-search-forward "^ +\n" nil t)
7216 (replace-match ""))
7217 (goto-char (point-min))
7218 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7219 (replace-match "")))
7220
7221 ;; Make sure entries from the diary have the right text properties.
7222 (eval-after-load "diary-lib"
7223 '(if (boundp 'diary-modify-entry-list-string-function)
7224 ;; We can rely on the hook, nothing to do
7225 nil
7226 ;; Hook not avaiable, must use advice to make this work
7227 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7228 "Make the position visible."
7229 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7230 (stringp string)
7231 buffer-file-name)
7232 (setq string (org-modify-diary-entry-string string))))))
7233
7234 (defun org-modify-diary-entry-string (string)
7235 "Add text properties to string, allowing org-mode to act on it."
7236 (org-add-props string nil
7237 'mouse-face 'highlight
7238 'keymap org-agenda-keymap
7239 'help-echo (format "mouse-2 or RET jump to diary file %s"
7240 (abbreviate-file-name buffer-file-name))
7241 'org-agenda-diary-link t
7242 'org-marker (org-agenda-new-marker (point-at-bol))))
7243
7244 (defun org-diary-default-entry ()
7245 "Add a dummy entry to the diary.
7246 Needed to avoid empty dates which mess up holiday display."
7247 ;; Catch the error if dealing with the new add-to-diary-alist
7248 (when org-disable-agenda-to-diary
7249 (condition-case nil
7250 (add-to-diary-list original-date "Org-mode dummy" "")
7251 (error
7252 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7253
7254 (defun org-cycle-agenda-files ()
7255 "Cycle through the files in `org-agenda-files'.
7256 If the current buffer visits an agenda file, find the next one in the list.
7257 If the current buffer does not, find the first agenda file."
7258 (interactive)
7259 (let* ((fs (org-agenda-files t))
7260 (files (append fs (list (car fs))))
7261 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7262 file)
7263 (unless files (error "No agenda files"))
7264 (catch 'exit
7265 (while (setq file (pop files))
7266 (if (equal (file-truename file) tcf)
7267 (when (car files)
7268 (find-file (car files))
7269 (throw 'exit t))))
7270 (find-file (car fs)))))
7271
7272 (defun org-agenda-file-to-end ()
7273 "Move/add the current file to the end of the agenda file list.
7274 If the file is not present in the list, it is appended to the list. If it is
7275 present, it is moved there."
7276 (interactive)
7277 (org-agenda-file-to-front 'to-end))
7278
7279 (defun org-agenda-file-to-front (&optional to-end)
7280 "Move/add the current file to the top of the agenda file list.
7281 If the file is not present in the list, it is added to the front. If it is
7282 present, it is moved there. With optional argument TO-END, add/move to the
7283 end of the list."
7284 (interactive "P")
7285 (let ((file-alist (mapcar (lambda (x)
7286 (cons (file-truename x) x))
7287 (org-agenda-files t)))
7288 (ctf (file-truename buffer-file-name))
7289 x had)
7290 (setq x (assoc ctf file-alist) had x)
7291
7292 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7293 (if to-end
7294 (setq file-alist (append (delq x file-alist) (list x)))
7295 (setq file-alist (cons x (delq x file-alist))))
7296 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7297 (org-install-agenda-files-menu)
7298 (message "File %s to %s of agenda file list"
7299 (if had "moved" "added") (if to-end "end" "front"))))
7300
7301 (defun org-remove-file (&optional file)
7302 "Remove current file from the list of files in variable `org-agenda-files'.
7303 These are the files which are being checked for agenda entries.
7304 Optional argument FILE means, use this file instead of the current."
7305 (interactive)
7306 (let* ((file (or file buffer-file-name))
7307 (true-file (file-truename file))
7308 (afile (abbreviate-file-name file))
7309 (files (delq nil (mapcar
7310 (lambda (x)
7311 (if (equal true-file
7312 (file-truename x))
7313 nil x))
7314 (org-agenda-files t)))))
7315 (if (not (= (length files) (length (org-agenda-files t))))
7316 (progn
7317 (org-store-new-agenda-file-list files)
7318 (org-install-agenda-files-menu)
7319 (message "Removed file: %s" afile))
7320 (message "File was not in list: %s" afile))))
7321
7322 (defun org-file-menu-entry (file)
7323 (vector file (list 'find-file file) t))
7324
7325 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7326 "Return a list of all relevant day numbers from BEG to END buffer positions.
7327 If NO-RANGES is non-nil, include only the start and end dates of a range,
7328 not every single day in the range. If FORCE-TODAY is non-nil, make
7329 sure that TODAY is included in the list. If INACTIVE is non-nil, also
7330 inactive time stamps (those in square brackets) are included.
7331 When EMPTY is non-nil, also include days without any entries."
7332 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
7333 dates dates1 date day day1 day2 ts1 ts2)
7334 (if force-today
7335 (setq dates (list (time-to-days (current-time)))))
7336 (save-excursion
7337 (goto-char beg)
7338 (while (re-search-forward re end t)
7339 (setq day (time-to-days (org-time-string-to-time
7340 (substring (match-string 1) 0 10))))
7341 (or (memq day dates) (push day dates)))
7342 (unless no-ranges
7343 (goto-char beg)
7344 (while (re-search-forward org-tr-regexp end t)
7345 (setq ts1 (substring (match-string 1) 0 10)
7346 ts2 (substring (match-string 2) 0 10)
7347 day1 (time-to-days (org-time-string-to-time ts1))
7348 day2 (time-to-days (org-time-string-to-time ts2)))
7349 (while (< (setq day1 (1+ day1)) day2)
7350 (or (memq day1 dates) (push day1 dates)))))
7351 (setq dates (sort dates '<))
7352 (when empty
7353 (while (setq day (pop dates))
7354 (setq day2 (car dates))
7355 (push day dates1)
7356 (when (and day2 empty)
7357 (if (or (eq empty t)
7358 (and (numberp empty) (<= (- day2 day) empty)))
7359 (while (< (setq day (1+ day)) day2)
7360 (push (list day) dates1))
7361 (push (cons :omitted (- day2 day)) dates1))))
7362 (setq dates (nreverse dates1)))
7363 dates)))
7364
7365 ;;;###autoload
7366 (defun org-diary (&rest args)
7367 "Return diary information from org-files.
7368 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
7369 It accesses org files and extracts information from those files to be
7370 listed in the diary. The function accepts arguments specifying what
7371 items should be listed. The following arguments are allowed:
7372
7373 :timestamp List the headlines of items containing a date stamp or
7374 date range matching the selected date. Deadlines will
7375 also be listed, on the expiration day.
7376
7377 :deadline List any deadlines past due, or due within
7378 `org-deadline-warning-days'. The listing occurs only
7379 in the diary for *today*, not at any other date. If
7380 an entry is marked DONE, it is no longer listed.
7381
7382 :scheduled List all items which are scheduled for the given date.
7383 The diary for *today* also contains items which were
7384 scheduled earlier and are not yet marked DONE.
7385
7386 :todo List all TODO items from the org-file. This may be a
7387 long list - so this is not turned on by default.
7388 Like deadlines, these entries only show up in the
7389 diary for *today*, not at any other date.
7390
7391 The call in the diary file should look like this:
7392
7393 &%%(org-diary) ~/path/to/some/orgfile.org
7394
7395 Use a separate line for each org file to check. Or, if you omit the file name,
7396 all files listed in `org-agenda-files' will be checked automatically:
7397
7398 &%%(org-diary)
7399
7400 If you don't give any arguments (as in the example above), the default
7401 arguments (:deadline :scheduled :timestamp) are used. So the example above may
7402 also be written as
7403
7404 &%%(org-diary :deadline :timestamp :scheduled)
7405
7406 The function expects the lisp variables `entry' and `date' to be provided
7407 by the caller, because this is how the calendar works. Don't use this
7408 function from a program - use `org-agenda-get-day-entries' instead."
7409 (org-agenda-maybe-reset-markers)
7410 (org-compile-prefix-format org-agenda-prefix-format)
7411 (setq args (or args '(:deadline :scheduled :timestamp)))
7412 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
7413 (list entry)
7414 (org-agenda-files t)))
7415 file rtn results)
7416 ;; If this is called during org-agenda, don't return any entries to
7417 ;; the calendar. Org Agenda will list these entries itself.
7418 (if org-disable-agenda-to-diary (setq files nil))
7419 (while (setq file (pop files))
7420 (setq rtn (apply 'org-agenda-get-day-entries file date args))
7421 (setq results (append results rtn)))
7422 (if results
7423 (concat (org-finalize-agenda-entries results) "\n"))))
7424 (defvar org-category-table nil)
7425 (defun org-get-category-table ()
7426 "Get the table of categories and positions in current buffer."
7427 (let (tbl)
7428 (save-excursion
7429 (goto-char (point-min))
7430 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
7431 (push (cons (point) (org-trim (match-string 2))) tbl)))
7432 tbl))
7433 (defun org-get-category (&optional pos)
7434 "Get the category applying to position POS."
7435 (if (not org-category-table)
7436 (cond
7437 ((null org-category)
7438 (setq org-category
7439 (if buffer-file-name
7440 (file-name-sans-extension
7441 (file-name-nondirectory buffer-file-name))
7442 "???")))
7443 ((symbolp org-category) (symbol-name org-category))
7444 (t org-category))
7445 (let ((tbl org-category-table)
7446 (pos (or pos (point))))
7447 (while (and tbl (> (caar tbl) pos))
7448 (pop tbl))
7449 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
7450 org-category-table))))))
7451
7452 (defun org-agenda-get-day-entries (file date &rest args)
7453 "Does the work for `org-diary' and `org-agenda'.
7454 FILE is the path to a file to be checked for entries. DATE is date like
7455 the one returned by `calendar-current-date'. ARGS are symbols indicating
7456 which kind of entries should be extracted. For details about these, see
7457 the documentation of `org-diary'."
7458 (setq args (or args '(:deadline :scheduled :timestamp)))
7459 (let* ((org-startup-with-deadline-check nil)
7460 (org-startup-folded nil)
7461 (org-startup-align-all-tables nil)
7462 (buffer (if (file-exists-p file)
7463 (org-get-agenda-file-buffer file)
7464 (error "No such file %s" file)))
7465 arg results rtn)
7466 (if (not buffer)
7467 ;; If file does not exist, make sure an error message ends up in diary
7468 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7469 (with-current-buffer buffer
7470 (unless (org-mode-p)
7471 (error "Agenda file %s is not in `org-mode'" file))
7472 (setq org-category-table (org-get-category-table))
7473 (let ((case-fold-search nil))
7474 (save-excursion
7475 (save-restriction
7476 (if org-respect-restriction
7477 (if (org-region-active-p)
7478 ;; Respect a region to restrict search
7479 (narrow-to-region (region-beginning) (region-end)))
7480 ;; If we work for the calendar or many files,
7481 ;; get rid of any restriction
7482 (widen))
7483 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
7484 (while (setq arg (pop args))
7485 (cond
7486 ((and (eq arg :todo)
7487 (equal date (calendar-current-date)))
7488 (setq rtn (org-agenda-get-todos))
7489 (setq results (append results rtn)))
7490 ((eq arg :timestamp)
7491 (setq rtn (org-agenda-get-blocks))
7492 (setq results (append results rtn))
7493 (setq rtn (org-agenda-get-timestamps))
7494 (setq results (append results rtn)))
7495 ((eq arg :scheduled)
7496 (setq rtn (org-agenda-get-scheduled))
7497 (setq results (append results rtn)))
7498 ((eq arg :closed)
7499 (setq rtn (org-agenda-get-closed))
7500 (setq results (append results rtn)))
7501 ((and (eq arg :deadline)
7502 (equal date (calendar-current-date)))
7503 (setq rtn (org-agenda-get-deadlines))
7504 (setq results (append results rtn))))))))
7505 results))))
7506
7507 (defun org-entry-is-done-p ()
7508 "Is the current entry marked DONE?"
7509 (save-excursion
7510 (and (re-search-backward "[\r\n]\\*" nil t)
7511 (looking-at org-nl-done-regexp))))
7512
7513 (defun org-at-date-range-p ()
7514 "Is the cursor inside a date range?"
7515 (interactive)
7516 (save-excursion
7517 (catch 'exit
7518 (let ((pos (point)))
7519 (skip-chars-backward "^<\r\n")
7520 (skip-chars-backward "<")
7521 (and (looking-at org-tr-regexp)
7522 (>= (match-end 0) pos)
7523 (throw 'exit t))
7524 (skip-chars-backward "^<\r\n")
7525 (skip-chars-backward "<")
7526 (and (looking-at org-tr-regexp)
7527 (>= (match-end 0) pos)
7528 (throw 'exit t)))
7529 nil)))
7530
7531 (defun org-agenda-get-todos ()
7532 "Return the TODO information for agenda display."
7533 (let* ((props (list 'face nil
7534 'done-face 'org-done
7535 'org-not-done-regexp org-not-done-regexp
7536 'mouse-face 'highlight
7537 'keymap org-agenda-keymap
7538 'help-echo
7539 (format "mouse-2 or RET jump to org file %s"
7540 (abbreviate-file-name buffer-file-name))))
7541 (regexp (concat "[\n\r]\\*+ *\\("
7542 (if org-select-this-todo-keyword
7543 (concat "\\<\\(" org-select-this-todo-keyword
7544 "\\)\\>")
7545 org-not-done-regexp)
7546 "[^\n\r]*\\)"))
7547 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
7548 marker priority category tags
7549 ee txt)
7550 (goto-char (point-min))
7551 (while (re-search-forward regexp nil t)
7552 (catch :skip
7553 (when (and org-agenda-todo-ignore-scheduled
7554 (looking-at sched-re))
7555 ;; FIXME: the following test also happens below, but we need it here
7556 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
7557 (throw :skip nil))
7558 (org-agenda-skip)
7559 (goto-char (match-beginning 1))
7560 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
7561 category (org-get-category)
7562 tags (org-get-tags-at (point))
7563 txt (org-format-agenda-item "" (match-string 1) category tags)
7564 priority
7565 (+ (org-get-priority txt)
7566 (if org-todo-kwd-priority-p
7567 (- org-todo-kwd-max-priority -2
7568 (length
7569 (member (match-string 2) org-todo-keywords)))
7570 1)))
7571 (org-add-props txt props
7572 'org-marker marker 'org-hd-marker marker
7573 'priority priority 'category category)
7574 (push txt ee)
7575 (if org-agenda-todo-list-sublevels
7576 (goto-char (match-end 1))
7577 (org-end-of-subtree 'invisible))))
7578 (nreverse ee)))
7579
7580 (defconst org-agenda-no-heading-message
7581 "No heading for this item in buffer or region.")
7582
7583 (defun org-agenda-get-timestamps ()
7584 "Return the date stamp information for agenda display."
7585 (let* ((props (list 'face nil
7586 'org-not-done-regexp org-not-done-regexp
7587 'mouse-face 'highlight
7588 'keymap org-agenda-keymap
7589 'help-echo
7590 (format "mouse-2 or RET jump to org file %s"
7591 (abbreviate-file-name buffer-file-name))))
7592 (regexp (regexp-quote
7593 (substring
7594 (format-time-string
7595 (car org-time-stamp-formats)
7596 (apply 'encode-time ; DATE bound by calendar
7597 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7598 0 11)))
7599 marker hdmarker deadlinep scheduledp donep tmp priority category
7600 ee txt timestr tags)
7601 (goto-char (point-min))
7602 (while (re-search-forward regexp nil t)
7603 (catch :skip
7604 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
7605 (org-agenda-skip)
7606 (setq marker (org-agenda-new-marker (match-beginning 0))
7607 category (org-get-category (match-beginning 0))
7608 tmp (buffer-substring (max (point-min)
7609 (- (match-beginning 0)
7610 org-ds-keyword-length))
7611 (match-beginning 0))
7612 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7613 deadlinep (string-match org-deadline-regexp tmp)
7614 scheduledp (string-match org-scheduled-regexp tmp)
7615 donep (org-entry-is-done-p))
7616 (if (string-match ">" timestr)
7617 ;; substring should only run to end of time stamp
7618 (setq timestr (substring timestr 0 (match-end 0))))
7619 (save-excursion
7620 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7621 (progn
7622 (goto-char (match-end 1))
7623 (setq hdmarker (org-agenda-new-marker)
7624 tags (org-get-tags-at))
7625 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7626 (setq txt (org-format-agenda-item
7627 (format "%s%s"
7628 (if deadlinep "Deadline: " "")
7629 (if scheduledp "Scheduled: " ""))
7630 (match-string 1) category tags timestr)))
7631 (setq txt org-agenda-no-heading-message))
7632 (setq priority (org-get-priority txt))
7633 (org-add-props txt props
7634 'org-marker marker 'org-hd-marker hdmarker)
7635 (if deadlinep
7636 (org-add-props txt nil
7637 'face (if donep 'org-done 'org-warning)
7638 'undone-face 'org-warning 'done-face 'org-done
7639 'category category 'priority (+ 100 priority))
7640 (if scheduledp
7641 (org-add-props txt nil
7642 'face 'org-scheduled-today
7643 'undone-face 'org-scheduled-today 'done-face 'org-done
7644 'category category 'priority (+ 99 priority))
7645 (org-add-props txt nil 'priority priority 'category category)))
7646 (push txt ee))
7647 (outline-next-heading)))
7648 (nreverse ee)))
7649
7650 (defun org-agenda-get-closed ()
7651 "Return the logged TODO entries for agenda display."
7652 (let* ((props (list 'mouse-face 'highlight
7653 'org-not-done-regexp org-not-done-regexp
7654 'keymap org-agenda-keymap
7655 'help-echo
7656 (format "mouse-2 or RET jump to org file %s"
7657 (abbreviate-file-name buffer-file-name))))
7658 (regexp (concat
7659 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
7660 (regexp-quote
7661 (substring
7662 (format-time-string
7663 (car org-time-stamp-formats)
7664 (apply 'encode-time ; DATE bound by calendar
7665 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7666 1 11))))
7667 marker hdmarker priority category tags closedp
7668 ee txt timestr)
7669 (goto-char (point-min))
7670 (while (re-search-forward regexp nil t)
7671 (catch :skip
7672 (org-agenda-skip)
7673 (setq marker (org-agenda-new-marker (match-beginning 0))
7674 closedp (equal (match-string 1) org-closed-string)
7675 category (org-get-category (match-beginning 0))
7676 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7677 ;; donep (org-entry-is-done-p)
7678 )
7679 (if (string-match "\\]" timestr)
7680 ;; substring should only run to end of time stamp
7681 (setq timestr (substring timestr 0 (match-end 0))))
7682 (save-excursion
7683 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7684 (progn
7685 (goto-char (match-end 1))
7686 (setq hdmarker (org-agenda-new-marker)
7687 tags (org-get-tags-at))
7688 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7689 (setq txt (org-format-agenda-item
7690 (if closedp "Closed: " "Clocked: ")
7691 (match-string 1) category tags timestr)))
7692 (setq txt org-agenda-no-heading-message))
7693 (setq priority 100000)
7694 (org-add-props txt props
7695 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
7696 'priority priority 'category category
7697 'undone-face 'org-warning 'done-face 'org-done)
7698 (push txt ee))
7699 (outline-next-heading)))
7700 (nreverse ee)))
7701
7702 (defun org-agenda-get-deadlines ()
7703 "Return the deadline information for agenda display."
7704 (let* ((wdays org-deadline-warning-days)
7705 (props (list 'mouse-face 'highlight
7706 'org-not-done-regexp org-not-done-regexp
7707 'keymap org-agenda-keymap
7708 'help-echo
7709 (format "mouse-2 or RET jump to org file %s"
7710 (abbreviate-file-name buffer-file-name))))
7711 (regexp org-deadline-time-regexp)
7712 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7713 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7714 d2 diff pos pos1 category tags
7715 ee txt head face)
7716 (goto-char (point-min))
7717 (while (re-search-forward regexp nil t)
7718 (catch :skip
7719 (org-agenda-skip)
7720 (setq pos (1- (match-beginning 1))
7721 d2 (time-to-days
7722 (org-time-string-to-time (match-string 1)))
7723 diff (- d2 d1))
7724 ;; When to show a deadline in the calendar:
7725 ;; If the expiration is within wdays warning time.
7726 ;; Past-due deadlines are only shown on the current date
7727 (if (and (< diff wdays) todayp (not (= diff 0)))
7728 (save-excursion
7729 (setq category (org-get-category))
7730 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7731 (progn
7732 (goto-char (match-end 0))
7733 (setq pos1 (match-end 1))
7734 (setq tags (org-get-tags-at pos1))
7735 (setq head (buffer-substring-no-properties
7736 (point)
7737 (progn (skip-chars-forward "^\r\n")
7738 (point))))
7739 (if (string-match org-looking-at-done-regexp head)
7740 (setq txt nil)
7741 (setq txt (org-format-agenda-item
7742 (format "In %3d d.: " diff) head category tags))))
7743 (setq txt org-agenda-no-heading-message))
7744 (when txt
7745 (setq face (cond ((<= diff 0) 'org-warning)
7746 ((<= diff 5) 'org-upcoming-deadline)
7747 (t nil)))
7748 (org-add-props txt props
7749 'org-marker (org-agenda-new-marker pos)
7750 'org-hd-marker (org-agenda-new-marker pos1)
7751 'priority (+ (- 10 diff) (org-get-priority txt))
7752 'category category
7753 'face face 'undone-face face 'done-face 'org-done)
7754 (push txt ee))))))
7755 ee))
7756
7757 (defun org-agenda-get-scheduled ()
7758 "Return the scheduled information for agenda display."
7759 (let* ((props (list 'face 'org-scheduled-previously
7760 'org-not-done-regexp org-not-done-regexp
7761 'undone-face 'org-scheduled-previously
7762 'done-face 'org-done
7763 'mouse-face 'highlight
7764 'keymap org-agenda-keymap
7765 'help-echo
7766 (format "mouse-2 or RET jump to org file %s"
7767 (abbreviate-file-name buffer-file-name))))
7768 (regexp org-scheduled-time-regexp)
7769 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7770 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7771 d2 diff pos pos1 category tags
7772 ee txt head)
7773 (goto-char (point-min))
7774 (while (re-search-forward regexp nil t)
7775 (catch :skip
7776 (org-agenda-skip)
7777 (setq pos (1- (match-beginning 1))
7778 d2 (time-to-days
7779 (org-time-string-to-time (match-string 1)))
7780 diff (- d2 d1))
7781 ;; When to show a scheduled item in the calendar:
7782 ;; If it is on or past the date.
7783 (if (and (< diff 0) todayp)
7784 (save-excursion
7785 (setq category (org-get-category))
7786 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7787 (progn
7788 (goto-char (match-end 0))
7789 (setq pos1 (match-end 1))
7790 (setq tags (org-get-tags-at))
7791 (setq head (buffer-substring-no-properties
7792 (point)
7793 (progn (skip-chars-forward "^\r\n") (point))))
7794 (if (string-match org-looking-at-done-regexp head)
7795 (setq txt nil)
7796 (setq txt (org-format-agenda-item
7797 (format "Sched.%2dx: " (- 1 diff)) head
7798 category tags))))
7799 (setq txt org-agenda-no-heading-message))
7800 (when txt
7801 (org-add-props txt props
7802 'org-marker (org-agenda-new-marker pos)
7803 'org-hd-marker (org-agenda-new-marker pos1)
7804 'priority (+ (- 5 diff) (org-get-priority txt))
7805 'category category)
7806 (push txt ee))))))
7807 ee))
7808
7809 (defun org-agenda-get-blocks ()
7810 "Return the date-range information for agenda display."
7811 (let* ((props (list 'face nil
7812 'org-not-done-regexp org-not-done-regexp
7813 'mouse-face 'highlight
7814 'keymap org-agenda-keymap
7815 'help-echo
7816 (format "mouse-2 or RET jump to org file %s"
7817 (abbreviate-file-name buffer-file-name))))
7818 (regexp org-tr-regexp)
7819 (d0 (calendar-absolute-from-gregorian date))
7820 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
7821 (goto-char (point-min))
7822 (while (re-search-forward regexp nil t)
7823 (catch :skip
7824 (org-agenda-skip)
7825 (setq pos (point))
7826 (setq timestr (match-string 0)
7827 s1 (match-string 1)
7828 s2 (match-string 2)
7829 d1 (time-to-days (org-time-string-to-time s1))
7830 d2 (time-to-days (org-time-string-to-time s2)))
7831 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
7832 ;; Only allow days between the limits, because the normal
7833 ;; date stamps will catch the limits.
7834 (save-excursion
7835 (setq marker (org-agenda-new-marker (point)))
7836 (setq category (org-get-category))
7837 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7838 (progn
7839 (setq hdmarker (org-agenda-new-marker (match-end 1)))
7840 (goto-char (match-end 1))
7841 (setq tags (org-get-tags-at))
7842 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7843 (setq txt (org-format-agenda-item
7844 (format (if (= d1 d2) "" "(%d/%d): ")
7845 (1+ (- d0 d1)) (1+ (- d2 d1)))
7846 (match-string 1) category tags
7847 (if (= d0 d1) timestr))))
7848 (setq txt org-agenda-no-heading-message))
7849 (org-add-props txt props
7850 'org-marker marker 'org-hd-marker hdmarker
7851 'priority (org-get-priority txt) 'category category)
7852 (push txt ee)))
7853 (goto-char pos)))
7854 ; (outline-next-heading))) ;FIXME: correct to be removed??????
7855 ;; Sort the entries by expiration date.
7856 (nreverse ee)))
7857
7858 (defconst org-plain-time-of-day-regexp
7859 (concat
7860 "\\(\\<[012]?[0-9]"
7861 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7862 "\\(--?"
7863 "\\(\\<[012]?[0-9]"
7864 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7865 "\\)?")
7866 "Regular expression to match a plain time or time range.
7867 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
7868 groups carry important information:
7869 0 the full match
7870 1 the first time, range or not
7871 8 the second time, if it is a range.")
7872
7873 (defconst org-stamp-time-of-day-regexp
7874 (concat
7875 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
7876 "\\([012][0-9]:[0-5][0-9]\\)>"
7877 "\\(--?"
7878 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
7879 "Regular expression to match a timestamp time or time range.
7880 After a match, the following groups carry important information:
7881 0 the full match
7882 1 date plus weekday, for backreferencing to make sure both times on same day
7883 2 the first time, range or not
7884 4 the second time, if it is a range.")
7885
7886 (defvar org-prefix-has-time nil
7887 "A flag, set by `org-compile-prefix-format'.
7888 The flag is set if the currently compiled format contains a `%t'.")
7889 (defvar org-prefix-has-tag nil
7890 "A flag, set by `org-compile-prefix-format'.
7891 The flag is set if the currently compiled format contains a `%T'.")
7892
7893 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
7894 "Format TXT to be inserted into the agenda buffer.
7895 In particular, it adds the prefix and corresponding text properties. EXTRA
7896 must be a string and replaces the `%s' specifier in the prefix format.
7897 CATEGORY (string, symbol or nil) may be used to overrule the default
7898 category taken from local variable or file name. It will replace the `%c'
7899 specifier in the format. DOTIME, when non-nil, indicates that a
7900 time-of-day should be extracted from TXT for sorting of this entry, and for
7901 the `%t' specifier in the format. When DOTIME is a string, this string is
7902 searched for a time before TXT is. NOPREFIX is a flag and indicates that
7903 only the correctly processes TXT should be returned - this is used by
7904 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
7905 (save-match-data
7906 ;; Diary entries sometimes have extra whitespace at the beginning
7907 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
7908 (let* ((category (or category
7909 org-category
7910 (if buffer-file-name
7911 (file-name-sans-extension
7912 (file-name-nondirectory buffer-file-name))
7913 "")))
7914 (tag (if tags (nth (1- (length tags)) tags) ""))
7915 time ;; needed for the eval of the prefix format
7916 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
7917 (time-of-day (and dotime (org-get-time-of-day ts)))
7918 stamp plain s0 s1 s2 rtn)
7919 (when (and dotime time-of-day org-prefix-has-time)
7920 ;; Extract starting and ending time and move them to prefix
7921 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
7922 (setq plain (string-match org-plain-time-of-day-regexp ts)))
7923 (setq s0 (match-string 0 ts)
7924 s1 (match-string (if plain 1 2) ts)
7925 s2 (match-string (if plain 8 4) ts))
7926
7927 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
7928 ;; them, we might want to remove them there to avoid duplication.
7929 ;; The user can turn this off with a variable.
7930 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
7931 (string-match (concat (regexp-quote s0) " *") txt)
7932 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
7933 (= (match-beginning 0) 0)
7934 t))
7935 (setq txt (replace-match "" nil nil txt))))
7936 ;; Normalize the time(s) to 24 hour
7937 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
7938 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
7939
7940 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
7941 ;; Tags are in the string
7942 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
7943 (and org-agenda-remove-tags-when-in-prefix
7944 org-prefix-has-tag))
7945 (setq txt (replace-match "" t t txt))
7946 (setq txt (replace-match
7947 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
7948 (match-string 2 txt))
7949 t t txt))))
7950
7951 ;; Create the final string
7952 (if noprefix
7953 (setq rtn txt)
7954 ;; Prepare the variables needed in the eval of the compiled format
7955 (setq time (cond (s2 (concat s1 "-" s2))
7956 (s1 (concat s1 "......"))
7957 (t ""))
7958 extra (or extra "")
7959 category (if (symbolp category) (symbol-name category) category))
7960 ;; Evaluate the compiled format
7961 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
7962
7963 ;; And finally add the text properties
7964 (org-add-props rtn nil
7965 'category (downcase category) 'tags tags
7966 'prefix-length (- (length rtn) (length txt))
7967 'time-of-day time-of-day
7968 'dotime dotime))))
7969
7970 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
7971 (catch 'exit
7972 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
7973 ((and todayp (member 'today (car org-agenda-time-grid))))
7974 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
7975 ((member 'weekly (car org-agenda-time-grid)))
7976 (t (throw 'exit list)))
7977 (let* ((have (delq nil (mapcar
7978 (lambda (x) (get-text-property 1 'time-of-day x))
7979 list)))
7980 (string (nth 1 org-agenda-time-grid))
7981 (gridtimes (nth 2 org-agenda-time-grid))
7982 (req (car org-agenda-time-grid))
7983 (remove (member 'remove-match req))
7984 new time)
7985 (if (and (member 'require-timed req) (not have))
7986 ;; don't show empty grid
7987 (throw 'exit list))
7988 (while (setq time (pop gridtimes))
7989 (unless (and remove (member time have))
7990 (setq time (int-to-string time))
7991 (push (org-format-agenda-item
7992 nil string "" nil
7993 (concat (substring time 0 -2) ":" (substring time -2)))
7994 new)
7995 (put-text-property
7996 1 (length (car new)) 'face 'org-time-grid (car new))))
7997 (if (member 'time-up org-agenda-sorting-strategy)
7998 (append new list)
7999 (append list new)))))
8000
8001 (defun org-compile-prefix-format (format)
8002 "Compile the prefix format into a Lisp form that can be evaluated.
8003 The resulting form is returned and stored in the variable
8004 `org-prefix-format-compiled'."
8005 (setq org-prefix-has-time nil org-prefix-has-tag nil)
8006 (let ((start 0) varform vars var (s format)e c f opt)
8007 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
8008 s start)
8009 (setq var (cdr (assoc (match-string 4 s)
8010 '(("c" . category) ("t" . time) ("s" . extra)
8011 ("T" . tag))))
8012 c (or (match-string 3 s) "")
8013 opt (match-beginning 1)
8014 start (1+ (match-beginning 0)))
8015 (if (equal var 'time) (setq org-prefix-has-time t))
8016 (if (equal var 'tag) (setq org-prefix-has-tag t))
8017 (setq f (concat "%" (match-string 2 s) "s"))
8018 (if opt
8019 (setq varform
8020 `(if (equal "" ,var)
8021 ""
8022 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
8023 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
8024 (setq s (replace-match "%s" t nil s))
8025 (push varform vars))
8026 (setq vars (nreverse vars))
8027 (setq org-prefix-format-compiled `(format ,s ,@vars))))
8028
8029 (defun org-get-time-of-day (s &optional string mod24)
8030 "Check string S for a time of day.
8031 If found, return it as a military time number between 0 and 2400.
8032 If not found, return nil.
8033 The optional STRING argument forces conversion into a 5 character wide string
8034 HH:MM."
8035 (save-match-data
8036 (when
8037 (or
8038 (string-match
8039 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
8040 (string-match
8041 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
8042 (let* ((h (string-to-number (match-string 1 s)))
8043 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
8044 (ampm (if (match-end 4) (downcase (match-string 4 s))))
8045 (am-p (equal ampm "am"))
8046 (h1 (cond ((not ampm) h)
8047 ((= h 12) (if am-p 0 12))
8048 (t (+ h (if am-p 0 12)))))
8049 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
8050 (mod h1 24) h1))
8051 (t0 (+ (* 100 h2) m))
8052 (t1 (concat (if (>= h1 24) "+" " ")
8053 (if (< t0 100) "0" "")
8054 (if (< t0 10) "0" "")
8055 (int-to-string t0))))
8056 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
8057
8058 (defun org-finalize-agenda-entries (list)
8059 "Sort and concatenate the agenda items."
8060 (setq list (mapcar 'org-agenda-highlight-todo list))
8061 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
8062
8063 (defun org-agenda-highlight-todo (x)
8064 (let (re pl)
8065 (if (eq x 'line)
8066 (save-excursion
8067 (beginning-of-line 1)
8068 (setq re (get-text-property (point) 'org-not-done-regexp))
8069 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
8070 (and (looking-at (concat "[ \t]*" re))
8071 (add-text-properties (match-beginning 0) (match-end 0)
8072 '(face org-todo))))
8073 (setq re (get-text-property 0 'org-not-done-regexp x)
8074 pl (get-text-property 0 'prefix-length x))
8075 (and re (equal (string-match re x pl) pl)
8076 (add-text-properties (match-beginning 0) (match-end 0)
8077 '(face org-todo) x))
8078 x)))
8079
8080 (defsubst org-cmp-priority (a b)
8081 "Compare the priorities of string A and B."
8082 (let ((pa (or (get-text-property 1 'priority a) 0))
8083 (pb (or (get-text-property 1 'priority b) 0)))
8084 (cond ((> pa pb) +1)
8085 ((< pa pb) -1)
8086 (t nil))))
8087
8088 (defsubst org-cmp-category (a b)
8089 "Compare the string values of categories of strings A and B."
8090 (let ((ca (or (get-text-property 1 'category a) ""))
8091 (cb (or (get-text-property 1 'category b) "")))
8092 (cond ((string-lessp ca cb) -1)
8093 ((string-lessp cb ca) +1)
8094 (t nil))))
8095
8096 (defsubst org-cmp-time (a b)
8097 "Compare the time-of-day values of strings A and B."
8098 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
8099 (ta (or (get-text-property 1 'time-of-day a) def))
8100 (tb (or (get-text-property 1 'time-of-day b) def)))
8101 (cond ((< ta tb) -1)
8102 ((< tb ta) +1)
8103 (t nil))))
8104
8105 (defun org-entries-lessp (a b)
8106 "Predicate for sorting agenda entries."
8107 ;; The following variables will be used when the form is evaluated.
8108 (let* ((time-up (org-cmp-time a b))
8109 (time-down (if time-up (- time-up) nil))
8110 (priority-up (org-cmp-priority a b))
8111 (priority-down (if priority-up (- priority-up) nil))
8112 (category-up (org-cmp-category a b))
8113 (category-down (if category-up (- category-up) nil))
8114 (category-keep (if category-up +1 nil)))
8115 (cdr (assoc
8116 (eval (cons 'or org-agenda-sorting-strategy))
8117 '((-1 . t) (1 . nil) (nil . nil))))))
8118
8119 (defun org-agenda-show-priority ()
8120 "Show the priority of the current item.
8121 This priority is composed of the main priority given with the [#A] cookies,
8122 and by additional input from the age of a schedules or deadline entry."
8123 (interactive)
8124 (let* ((pri (get-text-property (point-at-bol) 'priority)))
8125 (message "Priority is %d" (if pri pri -1000))))
8126
8127 (defun org-agenda-show-tags ()
8128 "Show the tags applicable to the current item."
8129 (interactive)
8130 (let* ((tags (get-text-property (point-at-bol) 'tags)))
8131 (if tags
8132 (message "Tags are :%s:"
8133 (org-no-properties (mapconcat 'identity tags ":")))
8134 (message "No tags associated with this line"))))
8135
8136 (defun org-agenda-goto (&optional highlight)
8137 "Go to the Org-mode file which contains the item at point."
8138 (interactive)
8139 (let* ((marker (or (get-text-property (point) 'org-marker)
8140 (org-agenda-error)))
8141 (buffer (marker-buffer marker))
8142 (pos (marker-position marker)))
8143 (switch-to-buffer-other-window buffer)
8144 (widen)
8145 (goto-char pos)
8146 (when (org-mode-p)
8147 (org-show-hidden-entry)
8148 (save-excursion
8149 (and (outline-next-heading)
8150 (org-flag-heading nil)))) ; show the next heading
8151 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
8152
8153 (defun org-agenda-switch-to ()
8154 "Go to the Org-mode file which contains the item at point."
8155 (interactive)
8156 (let* ((marker (or (get-text-property (point) 'org-marker)
8157 (org-agenda-error)))
8158 (buffer (marker-buffer marker))
8159 (pos (marker-position marker)))
8160 (switch-to-buffer buffer)
8161 (delete-other-windows)
8162 (widen)
8163 (goto-char pos)
8164 (when (org-mode-p)
8165 (org-show-hidden-entry)
8166 (save-excursion
8167 (and (outline-next-heading)
8168 (org-flag-heading nil)))))) ; show the next heading
8169
8170 (defun org-agenda-goto-mouse (ev)
8171 "Go to the Org-mode file which contains the item at the mouse click."
8172 (interactive "e")
8173 (mouse-set-point ev)
8174 (org-agenda-goto))
8175
8176 (defun org-agenda-show ()
8177 "Display the Org-mode file which contains the item at point."
8178 (interactive)
8179 (let ((win (selected-window)))
8180 (org-agenda-goto t)
8181 (select-window win)))
8182
8183 (defun org-agenda-recenter (arg)
8184 "Display the Org-mode file which contains the item at point and recenter."
8185 (interactive "P")
8186 (let ((win (selected-window)))
8187 (org-agenda-goto t)
8188 (recenter arg)
8189 (select-window win)))
8190
8191 (defun org-agenda-show-mouse (ev)
8192 "Display the Org-mode file which contains the item at the mouse click."
8193 (interactive "e")
8194 (mouse-set-point ev)
8195 (org-agenda-show))
8196
8197 (defun org-agenda-check-no-diary ()
8198 "Check if the entry is a diary link and abort if yes."
8199 (if (get-text-property (point) 'org-agenda-diary-link)
8200 (org-agenda-error)))
8201
8202 (defun org-agenda-error ()
8203 (error "Command not allowed in this line"))
8204
8205 (defvar org-last-heading-marker (make-marker)
8206 "Marker pointing to the headline that last changed its TODO state
8207 by a remote command from the agenda.")
8208
8209 (defun org-agenda-todo (&optional arg)
8210 "Cycle TODO state of line at point, also in Org-mode file.
8211 This changes the line at point, all other lines in the agenda referring to
8212 the same tree node, and the headline of the tree node in the Org-mode file."
8213 (interactive "P")
8214 (org-agenda-check-no-diary)
8215 (let* ((col (current-column))
8216 (marker (or (get-text-property (point) 'org-marker)
8217 (org-agenda-error)))
8218 (buffer (marker-buffer marker))
8219 (pos (marker-position marker))
8220 (hdmarker (get-text-property (point) 'org-hd-marker))
8221 (buffer-read-only nil)
8222 newhead)
8223 (with-current-buffer buffer
8224 (widen)
8225 (goto-char pos)
8226 (org-show-hidden-entry)
8227 (save-excursion
8228 (and (outline-next-heading)
8229 (org-flag-heading nil))) ; show the next heading
8230 (org-todo arg)
8231 (and (bolp) (forward-char 1))
8232 (setq newhead (org-get-heading))
8233 (save-excursion
8234 (org-back-to-heading)
8235 (move-marker org-last-heading-marker (point))))
8236 (beginning-of-line 1)
8237 (save-excursion
8238 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8239 (move-to-column col)))
8240
8241 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8242 "Change all lines in the agenda buffer which match HDMARKER.
8243 The new content of the line will be NEWHEAD (as modified by
8244 `org-format-agenda-item'). HDMARKER is checked with
8245 `equal' against all `org-hd-marker' text properties in the file.
8246 If FIXFACE is non-nil, the face of each item is modified acording to
8247 the new TODO state."
8248 (let* (props m pl undone-face done-face finish new dotime cat tags)
8249 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
8250 (save-excursion
8251 (goto-char (point-max))
8252 (beginning-of-line 1)
8253 (while (not finish)
8254 (setq finish (bobp))
8255 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8256 (equal m hdmarker))
8257 (setq props (text-properties-at (point))
8258 dotime (get-text-property (point) 'dotime)
8259 cat (get-text-property (point) 'category)
8260 tags (get-text-property (point) 'tags)
8261 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
8262 pl (get-text-property (point) 'prefix-length)
8263 undone-face (get-text-property (point) 'undone-face)
8264 done-face (get-text-property (point) 'done-face))
8265 (move-to-column pl)
8266 (if (looking-at ".*")
8267 (progn
8268 (replace-match new t t)
8269 (beginning-of-line 1)
8270 (add-text-properties (point-at-bol) (point-at-eol) props)
8271 (when fixface
8272 (add-text-properties
8273 (point-at-bol) (point-at-eol)
8274 (list 'face
8275 (if org-last-todo-state-is-todo
8276 undone-face done-face)))
8277 (org-agenda-highlight-todo 'line))
8278 (beginning-of-line 1))
8279 (error "Line update did not work")))
8280 (beginning-of-line 0)))))
8281
8282 (defun org-agenda-priority-up ()
8283 "Increase the priority of line at point, also in Org-mode file."
8284 (interactive)
8285 (org-agenda-priority 'up))
8286
8287 (defun org-agenda-priority-down ()
8288 "Decrease the priority of line at point, also in Org-mode file."
8289 (interactive)
8290 (org-agenda-priority 'down))
8291
8292 (defun org-agenda-priority (&optional force-direction)
8293 "Set the priority of line at point, also in Org-mode file.
8294 This changes the line at point, all other lines in the agenda referring to
8295 the same tree node, and the headline of the tree node in the Org-mode file."
8296 (interactive)
8297 (org-agenda-check-no-diary)
8298 (let* ((marker (or (get-text-property (point) 'org-marker)
8299 (org-agenda-error)))
8300 (buffer (marker-buffer marker))
8301 (pos (marker-position marker))
8302 (hdmarker (get-text-property (point) 'org-hd-marker))
8303 (buffer-read-only nil)
8304 newhead)
8305 (with-current-buffer buffer
8306 (widen)
8307 (goto-char pos)
8308 (org-show-hidden-entry)
8309 (save-excursion
8310 (and (outline-next-heading)
8311 (org-flag-heading nil))) ; show the next heading
8312 (funcall 'org-priority force-direction)
8313 (end-of-line 1)
8314 (setq newhead (org-get-heading)))
8315 (org-agenda-change-all-lines newhead hdmarker)
8316 (beginning-of-line 1)))
8317
8318 (defun org-get-tags-at (&optional pos)
8319 "Get a list of all headline tags applicable at POS.
8320 POS defaults to point. If tags are inherited, the list contains
8321 the targets in the same sequence as the headlines appear, i.e.
8322 the tags of the current headline come last."
8323 (interactive)
8324 (let (tags)
8325 (save-excursion
8326 (goto-char (or pos (point)))
8327 (save-match-data
8328 (org-back-to-heading t)
8329 (condition-case nil
8330 (while t
8331 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
8332 (setq tags (append (org-split-string
8333 (org-match-string-no-properties 1) ":")
8334 tags)))
8335 (or org-use-tag-inheritance (error ""))
8336 (org-up-heading-all 1))
8337 (error nil))))
8338 (message "%s" tags)
8339 tags))
8340
8341 (defun org-agenda-set-tags ()
8342 "Set tags for the current headline."
8343 (interactive)
8344 (org-agenda-check-no-diary)
8345 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
8346 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
8347 (org-agenda-error)))
8348 (buffer (marker-buffer hdmarker))
8349 (pos (marker-position hdmarker))
8350 (buffer-read-only nil)
8351 newhead)
8352 (with-current-buffer buffer
8353 (widen)
8354 (goto-char pos)
8355 (org-show-hidden-entry)
8356 (save-excursion
8357 (and (outline-next-heading)
8358 (org-flag-heading nil))) ; show the next heading
8359 (call-interactively 'org-set-tags)
8360 (end-of-line 1)
8361 (setq newhead (org-get-heading)))
8362 (org-agenda-change-all-lines newhead hdmarker)
8363 (beginning-of-line 1)))
8364
8365 (defun org-agenda-date-later (arg &optional what)
8366 "Change the date of this item to one day later."
8367 (interactive "p")
8368 (org-agenda-check-type t 'agenda 'timeline)
8369 (org-agenda-check-no-diary)
8370 (let* ((marker (or (get-text-property (point) 'org-marker)
8371 (org-agenda-error)))
8372 (buffer (marker-buffer marker))
8373 (pos (marker-position marker)))
8374 (with-current-buffer buffer
8375 (widen)
8376 (goto-char pos)
8377 (if (not (org-at-timestamp-p))
8378 (error "Cannot find time stamp"))
8379 (org-timestamp-change arg (or what 'day))
8380 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8381
8382 (defun org-agenda-date-earlier (arg &optional what)
8383 "Change the date of this item to one day earlier."
8384 (interactive "p")
8385 (org-agenda-date-later (- arg) what))
8386
8387 (defun org-agenda-date-prompt (arg)
8388 "Change the date of this item. Date is prompted for, with default today.
8389 The prefix ARG is passed to the `org-time-stamp' command and can therefore
8390 be used to request time specification in the time stamp."
8391 (interactive "P")
8392 (org-agenda-check-type t 'agenda 'timeline)
8393 (org-agenda-check-no-diary)
8394 (let* ((marker (or (get-text-property (point) 'org-marker)
8395 (org-agenda-error)))
8396 (buffer (marker-buffer marker))
8397 (pos (marker-position marker)))
8398 (with-current-buffer buffer
8399 (widen)
8400 (goto-char pos)
8401 (if (not (org-at-timestamp-p))
8402 (error "Cannot find time stamp"))
8403 (org-time-stamp arg)
8404 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8405
8406 (defun org-agenda-schedule (arg)
8407 "Schedule the item at point."
8408 (interactive "P")
8409 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8410 (org-agenda-check-no-diary)
8411 (let* ((marker (or (get-text-property (point) 'org-marker)
8412 (org-agenda-error)))
8413 (buffer (marker-buffer marker))
8414 (pos (marker-position marker))
8415 (org-insert-labeled-timestamps-at-point nil)
8416 ts)
8417 (with-current-buffer buffer
8418 (widen)
8419 (goto-char pos)
8420 (setq ts (org-schedule))
8421 (message "Item scheduled for %s" ts))))
8422
8423 (defun org-agenda-deadline (arg)
8424 "Schedule the item at point."
8425 (interactive "P")
8426 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8427 (org-agenda-check-no-diary)
8428 (let* ((marker (or (get-text-property (point) 'org-marker)
8429 (org-agenda-error)))
8430 (buffer (marker-buffer marker))
8431 (pos (marker-position marker))
8432 (org-insert-labeled-timestamps-at-point nil)
8433 ts)
8434 (with-current-buffer buffer
8435 (widen)
8436 (goto-char pos)
8437 (setq ts (org-deadline))
8438 (message "Deadline for this item set to %s" ts))))
8439
8440 (defun org-get-heading ()
8441 "Return the heading of the current entry, without the stars."
8442 (save-excursion
8443 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
8444 (if (and (re-search-backward "[\r\n]\\*" nil t)
8445 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
8446 (match-string 1)
8447 "")))
8448
8449 (defun org-agenda-clock-in (&optional arg)
8450 "Start the clock on the currently selected item."
8451 (interactive "P")
8452 (org-agenda-check-no-diary)
8453 (let* ((marker (or (get-text-property (point) 'org-marker)
8454 (org-agenda-error)))
8455 (pos (marker-position marker)))
8456 (with-current-buffer (marker-buffer marker)
8457 (widen)
8458 (goto-char pos)
8459 (org-clock-in))))
8460
8461 (defun org-agenda-diary-entry ()
8462 "Make a diary entry, like the `i' command from the calendar.
8463 All the standard commands work: block, weekly etc."
8464 (interactive)
8465 (org-agenda-check-type t 'agenda 'timeline)
8466 (require 'diary-lib)
8467 (let* ((char (progn
8468 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
8469 (read-char-exclusive)))
8470 (cmd (cdr (assoc char
8471 '((?d . insert-diary-entry)
8472 (?w . insert-weekly-diary-entry)
8473 (?m . insert-monthly-diary-entry)
8474 (?y . insert-yearly-diary-entry)
8475 (?a . insert-anniversary-diary-entry)
8476 (?b . insert-block-diary-entry)
8477 (?c . insert-cyclic-diary-entry)))))
8478 (oldf (symbol-function 'calendar-cursor-to-date))
8479 (point (point))
8480 (mark (or (mark t) (point))))
8481 (unless cmd
8482 (error "No command associated with <%c>" char))
8483 (unless (and (get-text-property point 'day)
8484 (or (not (equal ?b char))
8485 (get-text-property mark 'day)))
8486 (error "Don't know which date to use for diary entry"))
8487 ;; We implement this by hacking the `calendar-cursor-to-date' function
8488 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
8489 (let ((calendar-mark-ring
8490 (list (calendar-gregorian-from-absolute
8491 (or (get-text-property mark 'day)
8492 (get-text-property point 'day))))))
8493 (unwind-protect
8494 (progn
8495 (fset 'calendar-cursor-to-date
8496 (lambda (&optional error)
8497 (calendar-gregorian-from-absolute
8498 (get-text-property point 'day))))
8499 (call-interactively cmd))
8500 (fset 'calendar-cursor-to-date oldf)))))
8501
8502
8503 (defun org-agenda-execute-calendar-command (cmd)
8504 "Execute a calendar command from the agenda, with the date associated to
8505 the cursor position."
8506 (org-agenda-check-type t 'agenda 'timeline)
8507 (require 'diary-lib)
8508 (unless (get-text-property (point) 'day)
8509 (error "Don't know which date to use for calendar command"))
8510 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
8511 (point (point))
8512 (date (calendar-gregorian-from-absolute
8513 (get-text-property point 'day)))
8514 (displayed-day (extract-calendar-day date))
8515 (displayed-month (extract-calendar-month date))
8516 (displayed-year (extract-calendar-year date)))
8517 (unwind-protect
8518 (progn
8519 (fset 'calendar-cursor-to-date
8520 (lambda (&optional error)
8521 (calendar-gregorian-from-absolute
8522 (get-text-property point 'day))))
8523 (call-interactively cmd))
8524 (fset 'calendar-cursor-to-date oldf))))
8525
8526 (defun org-agenda-phases-of-moon ()
8527 "Display the phases of the moon for the 3 months around the cursor date."
8528 (interactive)
8529 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
8530
8531 (defun org-agenda-holidays ()
8532 "Display the holidays for the 3 months around the cursor date."
8533 (interactive)
8534 (org-agenda-execute-calendar-command 'list-calendar-holidays))
8535
8536 (defun org-agenda-sunrise-sunset (arg)
8537 "Display sunrise and sunset for the cursor date.
8538 Latitude and longitude can be specified with the variables
8539 `calendar-latitude' and `calendar-longitude'. When called with prefix
8540 argument, latitude and longitude will be prompted for."
8541 (interactive "P")
8542 (let ((calendar-longitude (if arg nil calendar-longitude))
8543 (calendar-latitude (if arg nil calendar-latitude))
8544 (calendar-location-name
8545 (if arg "the given coordinates" calendar-location-name)))
8546 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
8547
8548 (defun org-agenda-goto-calendar ()
8549 "Open the Emacs calendar with the date at the cursor."
8550 (interactive)
8551 (org-agenda-check-type t 'agenda 'timeline)
8552 (let* ((day (or (get-text-property (point) 'day)
8553 (error "Don't know which date to open in calendar")))
8554 (date (calendar-gregorian-from-absolute day))
8555 (calendar-move-hook nil)
8556 (view-calendar-holidays-initially nil)
8557 (view-diary-entries-initially nil))
8558 (calendar)
8559 (calendar-goto-date date)))
8560
8561 (defun org-calendar-goto-agenda ()
8562 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
8563 This is a command that has to be installed in `calendar-mode-map'."
8564 (interactive)
8565 (org-agenda-list nil (calendar-absolute-from-gregorian
8566 (calendar-cursor-to-date))
8567 nil t))
8568
8569 (defun org-agenda-convert-date ()
8570 (interactive)
8571 (org-agenda-check-type t 'agenda 'timeline)
8572 (let ((day (get-text-property (point) 'day))
8573 date s)
8574 (unless day
8575 (error "Don't know which date to convert"))
8576 (setq date (calendar-gregorian-from-absolute day))
8577 (setq s (concat
8578 "Gregorian: " (calendar-date-string date) "\n"
8579 "ISO: " (calendar-iso-date-string date) "\n"
8580 "Day of Yr: " (calendar-day-of-year-string date) "\n"
8581 "Julian: " (calendar-julian-date-string date) "\n"
8582 "Astron. JD: " (calendar-astro-date-string date)
8583 " (Julian date number at noon UTC)\n"
8584 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
8585 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
8586 "French: " (calendar-french-date-string date) "\n"
8587 "Mayan: " (calendar-mayan-date-string date) "\n"
8588 "Coptic: " (calendar-coptic-date-string date) "\n"
8589 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
8590 "Persian: " (calendar-persian-date-string date) "\n"
8591 "Chinese: " (calendar-chinese-date-string date) "\n"))
8592 (with-output-to-temp-buffer "*Dates*"
8593 (princ s))
8594 (if (fboundp 'fit-window-to-buffer)
8595 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
8596
8597 ;;; Tags
8598
8599 (defun org-scan-tags (action matcher &optional todo-only)
8600 "Scan headline tags with inheritance and produce output ACTION.
8601 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8602 evaluated, testing if a given set of tags qualifies a headline for
8603 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8604 are included in the output."
8605 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8606 (mapconcat 'regexp-quote
8607 (nreverse (cdr (reverse org-todo-keywords)))
8608 "\\|")
8609 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
8610 (props (list 'face nil
8611 'done-face 'org-done
8612 'undone-face nil
8613 'mouse-face 'highlight
8614 'keymap org-agenda-keymap
8615 'help-echo
8616 (format "mouse-2 or RET jump to org file %s"
8617 (abbreviate-file-name buffer-file-name))))
8618 lspos
8619 tags tags-list tags-alist (llast 0) rtn level category i txt
8620 todo marker)
8621 (save-excursion
8622 (goto-char (point-min))
8623 (when (eq action 'sparse-tree) (org-overview))
8624 (while (re-search-forward re nil t)
8625 (catch :skip
8626 (and (eq action 'agenda) (org-agenda-skip))
8627 (setq todo (if (match-end 1) (match-string 2))
8628 tags (if (match-end 4) (match-string 4)))
8629 (goto-char (setq lspos (1+ (match-beginning 0))))
8630 (setq level (funcall outline-level)
8631 category (org-get-category))
8632 (setq i llast llast level)
8633 ;; remove tag lists from same and sublevels
8634 (while (>= i level)
8635 (when (setq entry (assoc i tags-alist))
8636 (setq tags-alist (delete entry tags-alist)))
8637 (setq i (1- i)))
8638 ;; add the nex tags
8639 (when tags
8640 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8641 tags-alist
8642 (cons (cons level tags) tags-alist)))
8643 ;; compile tags for current headline
8644 (setq tags-list
8645 (if org-use-tag-inheritance
8646 (apply 'append (mapcar 'cdr tags-alist))
8647 tags))
8648 (when (and (or (not todo-only) todo)
8649 (eval matcher)
8650 (or (not org-agenda-skip-archived-trees)
8651 (not (member org-archive-tag tags-list))))
8652 ;; list this headline
8653 (if (eq action 'sparse-tree)
8654 (progn
8655 (org-show-hierarchy-above))
8656 (setq txt (org-format-agenda-item
8657 ""
8658 (concat
8659 (if org-tags-match-list-sublevels
8660 (make-string (1- level) ?.) "")
8661 (org-get-heading))
8662 category tags-list))
8663 (goto-char lspos)
8664 (setq marker (org-agenda-new-marker))
8665 (org-add-props txt props
8666 'org-marker marker 'org-hd-marker marker 'category category)
8667 (push txt rtn))
8668 ;; if we are to skip sublevels, jump to end of subtree
8669 (point)
8670 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8671 (when (and (eq action 'sparse-tree)
8672 (not org-sparse-tree-open-archived-trees))
8673 (org-hide-archived-subtrees (point-min) (point-max)))
8674 (nreverse rtn)))
8675
8676 (defun org-tags-sparse-tree (&optional arg match)
8677 "Create a sparse tree according to tags search string MATCH.
8678 MATCH can contain positive and negative selection of tags, like
8679 \"+WORK+URGENT-WITHBOSS\"."
8680 (interactive "P")
8681 (let ((org-show-following-heading nil)
8682 (org-show-hierarchy-above nil))
8683 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
8684
8685 (defun org-make-tags-matcher (match)
8686 "Create the TAGS matcher form for the tags-selecting string MATCH."
8687 (unless match
8688 ;; Get a new match request, with completion
8689 (setq org-last-tags-completion-table
8690 (or (org-get-buffer-tags)
8691 org-last-tags-completion-table))
8692 (setq match (completing-read
8693 "Tags: " 'org-tags-completion-function nil nil nil
8694 'org-tags-history)))
8695 ;; parse the string and create a lisp form
8696 (let ((match0 match) minus tag mm matcher orterms term orlist)
8697 (setq orterms (org-split-string match "|"))
8698 (while (setq term (pop orterms))
8699 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
8700 (setq minus (and (match-end 1)
8701 (equal (match-string 1 term) "-"))
8702 tag (match-string 2 term)
8703 term (substring term (match-end 0))
8704 mm (list 'member (downcase tag) 'tags-list)
8705 mm (if minus (list 'not mm) mm))
8706 (push mm matcher))
8707 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
8708 orlist)
8709 (setq matcher nil))
8710 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8711 ;; Return the string and lisp forms of the matcher
8712 (cons match0 matcher)))
8713
8714 ;;;###autoload
8715 (defun org-tags-view (&optional todo-only match keep-modes)
8716 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
8717 The prefix arg TODO-ONLY limits the search to TODO entries."
8718 (interactive "P")
8719 (org-agenda-maybe-reset-markers 'force)
8720 (org-compile-prefix-format org-agenda-prefix-format)
8721 (let* ((org-agenda-keep-modes keep-modes)
8722 (org-tags-match-list-sublevels
8723 (if todo-only t org-tags-match-list-sublevels))
8724 (win (selected-window))
8725 (completion-ignore-case t)
8726 rtn rtnall files file pos matcher
8727 buffer)
8728 (setq matcher (org-make-tags-matcher match)
8729 match (car matcher) matcher (cdr matcher))
8730 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
8731 (progn
8732 (delete-other-windows)
8733 (switch-to-buffer-other-window
8734 (get-buffer-create org-agenda-buffer-name))))
8735 (setq buffer-read-only nil)
8736 (erase-buffer)
8737 (org-agenda-mode) (setq buffer-read-only nil)
8738 (org-set-local 'org-agenda-type 'tags)
8739 (org-set-local 'org-agenda-redo-command
8740 (list 'org-tags-view (list 'quote todo-only)
8741 (list 'if 'current-prefix-arg nil match) t))
8742 (setq files (org-agenda-files)
8743 rtnall nil)
8744 (org-prepare-agenda-buffers files)
8745 (while (setq file (pop files))
8746 (catch 'nextfile
8747 (org-check-agenda-file file)
8748 (setq buffer (if (file-exists-p file)
8749 (org-get-agenda-file-buffer file)
8750 (error "No such file %s" file)))
8751 (if (not buffer)
8752 ;; If file does not exist, merror message to agenda
8753 (setq rtn (list
8754 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8755 rtnall (append rtnall rtn))
8756 (with-current-buffer buffer
8757 (unless (org-mode-p)
8758 (error "Agenda file %s is not in `org-mode'" file))
8759 (setq org-category-table (org-get-category-table))
8760 (save-excursion
8761 (save-restriction
8762 (if org-respect-restriction
8763 (if (org-region-active-p)
8764 ;; Respect a region to restrict search
8765 (narrow-to-region (region-beginning) (region-end)))
8766 ;; If we work for the calendar or many files,
8767 ;; get rid of any restriction
8768 (widen))
8769 (setq rtn (org-scan-tags 'agenda matcher todo-only))
8770 (setq rtnall (append rtnall rtn))))))))
8771 (insert "Headlines with TAGS match: ")
8772 (add-text-properties (point-min) (1- (point))
8773 (list 'face 'org-level-3))
8774 (setq pos (point))
8775 (insert match "\n")
8776 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
8777 (setq pos (point))
8778 (insert "Press `C-u r' to search again with new search string\n")
8779 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
8780 (when rtnall
8781 (insert (mapconcat 'identity rtnall "\n")))
8782 (goto-char (point-min))
8783 (setq buffer-read-only t)
8784 (org-fit-agenda-window)
8785 (if (not org-select-agenda-window) (select-window win))))
8786
8787 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8788 (defun org-set-tags (&optional arg just-align)
8789 "Set the tags for the current headline.
8790 With prefix ARG, realign all tags in headings in the current buffer."
8791 (interactive "P")
8792 (let* ((re (concat "^" outline-regexp))
8793 (col (current-column))
8794 (current (org-get-tags))
8795 table current-tags inherited-tags ; computed below when needed
8796 tags hd empty invis)
8797 (if arg
8798 (save-excursion
8799 (goto-char (point-min))
8800 (while (re-search-forward re nil t)
8801 (org-set-tags nil t))
8802 (message "All tags realigned to column %d" org-tags-column))
8803 (if just-align
8804 (setq tags current)
8805 (setq table (or org-tag-alist (org-get-buffer-tags))
8806 org-last-tags-completion-table table
8807 current-tags (org-split-string current ":")
8808 inherited-tags (nreverse
8809 (nthcdr (length current-tags)
8810 (nreverse (org-get-tags-at))))
8811 tags
8812 (if (or (eq t org-use-fast-tag-selection)
8813 (and org-use-fast-tag-selection
8814 (delq nil (mapcar 'cdr table))))
8815 (org-fast-tag-selection current-tags inherited-tags table)
8816 (let ((org-add-colon-after-tag-completion t))
8817 (completing-read "Tags: " 'org-tags-completion-function
8818 nil nil current 'org-tags-history))))
8819 (while (string-match "[-+&]+" tags)
8820 (setq tags (replace-match ":" t t tags))))
8821
8822 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
8823 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8824 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8825 (if (equal current "")
8826 (progn
8827 (end-of-line 1)
8828 (or empty (insert-before-markers " ")))
8829 (beginning-of-line 1)
8830 (setq invis (org-invisible-p))
8831 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
8832 (setq hd (match-string 1))
8833 (delete-region (match-beginning 0) (match-end 0))
8834 (insert-before-markers (org-trim hd) (if empty "" " ")))
8835 (if (equal tags "")
8836 (save-excursion
8837 (beginning-of-line 1)
8838 (skip-chars-forward "*")
8839 (if (= (char-after) ?\ ) (forward-char 1))
8840 (and (re-search-forward "[ \t]+$" (point-at-eol) t)
8841 (replace-match "")))
8842 (move-to-column (max (current-column)
8843 (if (> org-tags-column 0)
8844 org-tags-column
8845 (- (- org-tags-column) (length tags))))
8846 t)
8847 (insert-before-markers tags)
8848 (if (and (not invis) (org-invisible-p))
8849 (outline-flag-region (point-at-bol) (point) nil)))
8850 (move-to-column col))))
8851
8852 (defun org-tags-completion-function (string predicate &optional flag)
8853 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8854 (confirm (lambda (x) (stringp (car x)))))
8855 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8856 (setq s1 (match-string 1 string)
8857 s2 (match-string 2 string))
8858 (setq s1 "" s2 string))
8859 (cond
8860 ((eq flag nil)
8861 ;; try completion
8862 (setq rtn (try-completion s2 ctable confirm))
8863 (if (stringp rtn)
8864 (concat s1 s2 (substring rtn (length s2))
8865 (if (and org-add-colon-after-tag-completion
8866 (assoc rtn ctable))
8867 ":" "")))
8868 )
8869 ((eq flag t)
8870 ;; all-completions
8871 (all-completions s2 ctable confirm)
8872 )
8873 ((eq flag 'lambda)
8874 ;; exact match?
8875 (assoc s2 ctable)))
8876 ))
8877
8878 (defun org-fast-tag-insert (kwd tags face &optional end)
8879 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
8880 (insert (format "%-12s" (concat kwd ":"))
8881 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
8882 (or end "")))
8883
8884 (defun org-fast-tag-selection (current inherited table)
8885 "Fast tag selection with single keys.
8886 CURRENT is the current list of tags in the headline, INHERITED is the
8887 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
8888 possibly with grouping information.
8889 If the keys are nil, a-z are automatically assigned.
8890 Returns the new tags string, or nil to not change the current settings."
8891 (let* ((maxlen (apply 'max (mapcar
8892 (lambda (x)
8893 (if (stringp (car x)) (string-width (car x)) 0))
8894 table)))
8895 (fwidth (+ maxlen 3 1 3))
8896 (ncol (/ (- (window-width) 4) fwidth))
8897 (i-face 'org-done)
8898 (c-face 'org-tag)
8899 tg cnt e c char c1 c2 ntable tbl rtn
8900 groups ingroup)
8901 (save-window-excursion
8902 (delete-other-windows)
8903 (split-window-vertically)
8904 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
8905 (erase-buffer)
8906 (org-fast-tag-insert "Inherited" inherited i-face "\n")
8907 (org-fast-tag-insert "Current" current c-face "\n\n")
8908 (setq tbl table char ?a cnt 0)
8909 (while (setq e (pop tbl))
8910 (cond
8911 ((equal e '(:startgroup))
8912 (push '() groups) (setq ingroup t)
8913 (when (not (= cnt 0))
8914 (setq cnt 0)
8915 (insert "\n"))
8916 (insert "{ "))
8917 ((equal e '(:endgroup))
8918 (setq ingroup nil cnt 0)
8919 (insert "}\n"))
8920 (t
8921 (setq tg (car e) c2 nil)
8922 (if (cdr e)
8923 (setq c (cdr e))
8924 ;; automatically assign a character.
8925 (setq c1 (string-to-char
8926 (downcase (substring
8927 tg (if (= (string-to-char tg) ?@) 1 0)))))
8928 (if (or (rassoc c1 ntable) (rassoc c1 table))
8929 (while (or (rassoc char ntable) (rassoc char table))
8930 (setq char (1+ char)))
8931 (setq c2 c1))
8932 (setq c (or c2 char)))
8933 (if ingroup (push tg (car groups)))
8934 (setq tg (org-add-props tg nil 'face
8935 (cond
8936 ((member tg current) c-face)
8937 ((member tg inherited) i-face)
8938 (t nil))))
8939 (if (and (= cnt 0) (not ingroup)) (insert " "))
8940 (insert "[" c "] " tg (make-string
8941 (- fwidth 4 (length tg)) ?\ ))
8942 (push (cons tg c) ntable)
8943 (when (= (setq cnt (1+ cnt)) ncol)
8944 (insert "\n")
8945 (if ingroup (insert " "))
8946 (setq cnt 0)))))
8947 (setq ntable (nreverse ntable))
8948 (insert "\n")
8949 (goto-char (point-min))
8950 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
8951 (setq rtn
8952 (catch 'exit
8953 (while t
8954 (message "[key]:Toggle SPC: clear current RET accept%s"
8955 (if groups " [!] ignore goups" ""))
8956 (setq c (read-char-exclusive))
8957 (cond
8958 ((= c ?\r) (throw 'exit t))
8959 ((= c ?!)
8960 (setq groups nil)
8961 (goto-char (point-min))
8962 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
8963 ((or (= c ?\C-g)
8964 (and (= c ?q) (not (rassoc c ntable))))
8965 (setq quit-flag t))
8966 ((= c ?\ ) (setq current nil))
8967 ((setq e (rassoc c ntable) tg (car e))
8968 (if (member tg current)
8969 (setq current (delete tg current))
8970 (loop for g in groups do
8971 (if (member tg g)
8972 (mapcar (lambda (x)
8973 (setq current (delete x current)))
8974 g)))
8975 (setq current (cons tg current)))))
8976 ;; Create a sorted list
8977 (setq current
8978 (sort current
8979 (lambda (a b)
8980 (assoc b (cdr (memq (assoc a ntable) ntable))))))
8981 (goto-char (point-min))
8982 (beginning-of-line 2)
8983 (delete-region (point) (point-at-eol))
8984 (org-fast-tag-insert "Current" current c-face)
8985 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
8986 (setq tg (match-string 1))
8987 (add-text-properties (match-beginning 1) (match-end 1)
8988 (list 'face
8989 (cond
8990 ((member tg current) c-face)
8991 ((member tg inherited) i-face)
8992 (t nil)))))
8993 (goto-char (point-min)))))
8994 (if rtn
8995 (mapconcat 'identity current ":")
8996 nil))))
8997
8998 (defun org-get-tags ()
8999 "Get the TAGS string in the current headline."
9000 (unless (org-on-heading-p)
9001 (error "Not on a heading"))
9002 (save-excursion
9003 (beginning-of-line 1)
9004 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
9005 (org-match-string-no-properties 1)
9006 "")))
9007
9008 (defun org-get-buffer-tags ()
9009 "Get a table of all tags used in the buffer, for completion."
9010 (let (tags)
9011 (save-excursion
9012 (goto-char (point-min))
9013 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
9014 (mapc (lambda (x) (add-to-list 'tags x))
9015 (org-split-string (org-match-string-no-properties 1) ":"))))
9016 (mapcar 'list tags)))
9017
9018 ;;; Link Stuff
9019
9020 (defvar org-create-file-search-functions nil
9021 "List of functions to construct the right search string for a file link.
9022 These functions are called in turn with point at the location to
9023 which the link should point.
9024
9025 A function in the hook should first test if it would like to
9026 handle this file type, for example by checking the major-mode or
9027 the file extension. If it decides not to handle this file, it
9028 should just return nil to give other functions a chance. If it
9029 does handle the file, it must return the search string to be used
9030 when following the link. The search string will be part of the
9031 file link, given after a double colon, and `org-open-at-point'
9032 will automatically search for it. If special measures must be
9033 taken to make the search successful, another function should be
9034 added to the companion hook `org-execute-file-search-functions',
9035 which see.
9036
9037 A function in this hook may also use `setq' to set the variable
9038 `description' to provide a suggestion for the descriptive text to
9039 be used for this link when it gets inserted into an Org-mode
9040 buffer with \\[org-insert-link].")
9041
9042 (defvar org-execute-file-search-functions nil
9043 "List of functions to execute a file search triggered by a link.
9044
9045 Functions added to this hook must accept a single argument, the
9046 search string that was part of the file link, the part after the
9047 double colon. The function must first check if it would like to
9048 handle this search, for example by checking the major-mode or the
9049 file extension. If it decides not to handle this search, it
9050 should just return nil to give other functions a chance. If it
9051 does handle the search, it must return a non-nil value to keep
9052 other functions from trying.
9053
9054 Each function can access the current prefix argument through the
9055 variable `current-prefix-argument'. Note that a single prefix is
9056 used to force opening a link in Emacs, so it may be good to only
9057 use a numeric or double prefix to guide the search function.
9058
9059 In case this is needed, a function in this hook can also restore
9060 the window configuration before `org-open-at-point' was called using:
9061
9062 (set-window-configuration org-window-config-before-follow-link)")
9063
9064 (defun org-find-file-at-mouse (ev)
9065 "Open file link or URL at mouse."
9066 (interactive "e")
9067 (mouse-set-point ev)
9068 (org-open-at-point 'in-emacs))
9069
9070 (defun org-open-at-mouse (ev)
9071 "Open file link or URL at mouse."
9072 (interactive "e")
9073 (mouse-set-point ev)
9074 (org-open-at-point))
9075
9076 (defvar org-window-config-before-follow-link nil
9077 "The window configuration before following a link.
9078 This is saved in case the need arises to restore it.")
9079
9080 (defun org-open-at-point (&optional in-emacs)
9081 "Open link at or after point.
9082 If there is no link at point, this function will search forward up to
9083 the end of the current subtree.
9084 Normally, files will be opened by an appropriate application. If the
9085 optional argument IN-EMACS is non-nil, Emacs will visit the file."
9086 (interactive "P")
9087 (setq org-window-config-before-follow-link (current-window-configuration))
9088 (org-remove-occur-highlights nil nil t)
9089 (if (org-at-timestamp-p)
9090 (org-agenda-list nil (time-to-days (org-time-string-to-time
9091 (substring (match-string 1) 0 10)))
9092 1)
9093 (let (type path link line search (pos (point)))
9094 (catch 'match
9095 (save-excursion
9096 (skip-chars-forward "^]\n\r")
9097 (when (and (re-search-backward "\\[\\[" nil t)
9098 (looking-at org-bracket-link-regexp)
9099 (<= (match-beginning 0) pos)
9100 (>= (match-end 0) pos))
9101 (setq link (org-link-unescape (org-match-string-no-properties 1)))
9102 (while (string-match " *\n *" link)
9103 (setq link (replace-match " " t t link)))
9104 (if (string-match org-link-re-with-space2 link)
9105 (setq type (match-string 1 link)
9106 path (match-string 2 link))
9107 (setq type "thisfile"
9108 path link))
9109 (throw 'match t)))
9110
9111 (when (get-text-property (point) 'org-linked-text)
9112 (setq type "thisfile"
9113 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9114 (1+ (point)) (point))
9115 path (buffer-substring
9116 (previous-single-property-change pos 'org-linked-text)
9117 (next-single-property-change pos 'org-linked-text)))
9118 (throw 'match t))
9119
9120 (save-excursion
9121 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
9122 (if (equal (char-before) ?<) (backward-char 1))
9123 (when (or (looking-at org-angle-link-re)
9124 (looking-at org-plain-link-re)
9125 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
9126 (re-search-forward org-plain-link-re (point-at-eol) t))
9127 (<= (match-beginning 0) pos)
9128 (>= (match-end 0) pos)))
9129 (setq type (match-string 1)
9130 path (match-string 2))
9131 (throw 'match t)))
9132 (save-excursion
9133 (skip-chars-backward "^ \t\n\r")
9134 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9135 (setq type "tags"
9136 path (match-string 1))
9137 (while (string-match ":" path)
9138 (setq path (replace-match "+" t t path)))
9139 (throw 'match t)))
9140 (save-excursion
9141 (skip-chars-backward "a-zA-Z_")
9142 (when (and (memq 'camel org-activate-links)
9143 (looking-at org-camel-regexp))
9144 (setq type "camel" path (match-string 0))
9145 (if (equal (char-before) ?*)
9146 (setq path (concat "*" path))))
9147 (throw 'match t)))
9148 (unless path
9149 (error "No link found"))
9150 ;; Remove any trailing spaces in path
9151 (if (string-match " +\\'" path)
9152 (setq path (replace-match "" t t path)))
9153
9154 (cond
9155
9156 ((member type '("http" "https" "ftp" "mailto" "news"))
9157 (browse-url (concat type ":" path)))
9158
9159 ((string= type "tags")
9160 (org-tags-view in-emacs path))
9161 ((or (string= type "camel")
9162 (string= type "thisfile"))
9163 (org-mark-ring-push)
9164 (org-link-search
9165 path
9166 (cond ((equal in-emacs '(4)) 'occur)
9167 ((equal in-emacs '(16)) 'org-occur)
9168 (t nil))))
9169
9170 ((string= type "file")
9171 (if (string-match "::\\([0-9]+\\)\\'" path)
9172 (setq line (string-to-number (match-string 1 path))
9173 path (substring path 0 (match-beginning 0)))
9174 (if (string-match "::\\(.+\\)\\'" path)
9175 (setq search (match-string 1 path)
9176 path (substring path 0 (match-beginning 0)))))
9177 (org-open-file path in-emacs line search))
9178
9179 ((string= type "news")
9180 (org-follow-gnus-link path))
9181
9182 ((string= type "bbdb")
9183 (org-follow-bbdb-link path))
9184
9185 ((string= type "info")
9186 (org-follow-info-link path))
9187
9188 ((string= type "gnus")
9189 (let (group article)
9190 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9191 (error "Error in Gnus link"))
9192 (setq group (match-string 1 path)
9193 article (match-string 3 path))
9194 (org-follow-gnus-link group article)))
9195
9196 ((string= type "vm")
9197 (let (folder article)
9198 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9199 (error "Error in VM link"))
9200 (setq folder (match-string 1 path)
9201 article (match-string 3 path))
9202 ;; in-emacs is the prefix arg, will be interpreted as read-only
9203 (org-follow-vm-link folder article in-emacs)))
9204
9205 ((string= type "wl")
9206 (let (folder article)
9207 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9208 (error "Error in Wanderlust link"))
9209 (setq folder (match-string 1 path)
9210 article (match-string 3 path))
9211 (org-follow-wl-link folder article)))
9212
9213 ((string= type "mhe")
9214 (let (folder article)
9215 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9216 (error "Error in MHE link"))
9217 (setq folder (match-string 1 path)
9218 article (match-string 3 path))
9219 (org-follow-mhe-link folder article)))
9220
9221 ((string= type "rmail")
9222 (let (folder article)
9223 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9224 (error "Error in RMAIL link"))
9225 (setq folder (match-string 1 path)
9226 article (match-string 3 path))
9227 (org-follow-rmail-link folder article)))
9228
9229 ((string= type "shell")
9230 (let ((cmd path))
9231 (while (string-match "@{" cmd)
9232 (setq cmd (replace-match "<" t t cmd)))
9233 (while (string-match "@}" cmd)
9234 (setq cmd (replace-match ">" t t cmd)))
9235 (if (or (not org-confirm-shell-link-function)
9236 (funcall org-confirm-shell-link-function
9237 (format "Execute \"%s\" in shell? "
9238 (org-add-props cmd nil
9239 'face 'org-warning))))
9240 (progn
9241 (message "Executing %s" cmd)
9242 (shell-command cmd))
9243 (error "Abort"))))
9244
9245 ((string= type "elisp")
9246 (let ((cmd path))
9247 (if (or (not org-confirm-elisp-link-function)
9248 (funcall org-confirm-elisp-link-function
9249 (format "Execute \"%s\" as elisp? "
9250 (org-add-props cmd nil
9251 'face 'org-warning))))
9252 (message "%s => %s" cmd (eval (read cmd)))
9253 (error "Abort"))))
9254
9255 (t
9256 (browse-url-at-point))))))
9257
9258 (defun org-link-search (s &optional type)
9259 "Search for a link search option.
9260 When S is a CamelCaseWord, search for a target, or for a sentence containing
9261 the words. If S is surrounded by forward slashes, it is interpreted as a
9262 regular expression. In org-mode files, this will create an `org-occur'
9263 sparse tree. In ordinary files, `occur' will be used to list matches.
9264 If the current buffer is in `dired-mode', grep will be used to search
9265 in all files."
9266 (let ((case-fold-search t)
9267 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9268 (pos (point))
9269 (pre "") (post "")
9270 words re0 re1 re2 re3 re4 re5 re2a reall camel)
9271 (cond
9272 ;; First check if there are any special
9273 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9274 ;; Now try the builtin stuff
9275 ((save-excursion
9276 (goto-char (point-min))
9277 (and
9278 (re-search-forward
9279 (concat "<<" (regexp-quote s0) ">>") nil t)
9280 (setq pos (match-beginning 0))))
9281 ;; There is an exact target for this
9282 (goto-char pos))
9283 ((string-match "^/\\(.*\\)/$" s)
9284 ;; A regular expression
9285 (cond
9286 ((org-mode-p)
9287 (org-occur (match-string 1 s)))
9288 ;;((eq major-mode 'dired-mode)
9289 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9290 (t (org-do-occur (match-string 1 s)))))
9291 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
9292 t)
9293 ;; A camel or a normal search string
9294 (when (equal (string-to-char s) ?*)
9295 ;; Anchor on headlines, post may include tags.
9296 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9297 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9298 s (substring s 1)))
9299 (remove-text-properties
9300 0 (length s)
9301 '(face nil mouse-face nil keymap nil fontified nil) s)
9302 ;; Make a series of regular expressions to find a match
9303 (setq words
9304 (if camel
9305 (org-camel-to-words s)
9306 (org-split-string s "[ \n\r\t]+"))
9307 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9308 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9309 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9310 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9311 re1 (concat pre re2 post)
9312 re3 (concat pre re4 post)
9313 re5 (concat pre ".*" re4)
9314 re2 (concat pre re2)
9315 re2a (concat pre re2a)
9316 re4 (concat pre re4)
9317 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9318 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9319 re5 "\\)"
9320 ))
9321 (cond
9322 ((eq type 'org-occur) (org-occur reall))
9323 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9324 (t (goto-char (point-min))
9325 (if (or (org-search-not-link re0 nil t)
9326 (org-search-not-link re1 nil t)
9327 (org-search-not-link re2 nil t)
9328 (org-search-not-link re2a nil t)
9329 (org-search-not-link re3 nil t)
9330 (org-search-not-link re4 nil t)
9331 (org-search-not-link re5 nil t)
9332 )
9333 (goto-char (match-beginning 1))
9334 (goto-char pos)
9335 (error "No match")))))
9336 (t
9337 ;; Normal string-search
9338 (goto-char (point-min))
9339 (if (search-forward s nil t)
9340 (goto-char (match-beginning 0))
9341 (error "No match"))))
9342 (and (org-mode-p) (org-show-hierarchy-above))))
9343
9344 (defun org-search-not-link (&rest args)
9345 "Execute `re-search-forward', but only accept matches that are not a link."
9346 (catch 'exit
9347 (let (p1)
9348 (while (apply 're-search-forward args)
9349 (setq p1 (point))
9350 (if (not (save-match-data
9351 (and (re-search-backward "\\[\\[" nil t)
9352 (looking-at org-bracket-link-regexp)
9353 (<= (match-beginning 0) p1)
9354 (>= (match-end 0) p1))))
9355 (progn (goto-char (match-end 0))
9356 (throw 'exit (point)))
9357 (goto-char (match-end 0)))))))
9358
9359 (defun org-do-occur (regexp &optional cleanup)
9360 "Call the Emacs command `occur'.
9361 If CLEANUP is non-nil, remove the printout of the regular expression
9362 in the *Occur* buffer. This is useful if the regex is long and not useful
9363 to read."
9364 (occur regexp)
9365 (when cleanup
9366 (let ((cwin (selected-window)) win beg end)
9367 (when (setq win (get-buffer-window "*Occur*"))
9368 (select-window win))
9369 (goto-char (point-min))
9370 (when (re-search-forward "match[a-z]+" nil t)
9371 (setq beg (match-end 0))
9372 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9373 (setq end (1- (match-beginning 0)))))
9374 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9375 (goto-char (point-min))
9376 (select-window cwin))))
9377
9378 (defvar org-mark-ring nil
9379 "Mark ring for positions before jumps in Org-mode.")
9380 (defvar org-mark-ring-last-goto nil
9381 "Last position in the mark ring used to go back.")
9382 ;; Fill and close the ring
9383 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9384 (loop for i from 1 to org-mark-ring-length do
9385 (push (make-marker) org-mark-ring))
9386 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9387 org-mark-ring)
9388
9389 (defun org-mark-ring-push (&optional pos buffer)
9390 "Put the current position or POS into the mark ring and rotate it."
9391 (interactive)
9392 (setq pos (or pos (point)))
9393 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9394 (move-marker (car org-mark-ring)
9395 (or pos (point))
9396 (or buffer (current-buffer)))
9397 (message
9398 (substitute-command-keys
9399 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9400
9401 (defun org-mark-ring-goto (&optional n)
9402 "Jump to the previous position in the mark ring.
9403 With prefix arg N, jump back that many stored positions. When
9404 called several times in succession, walk through the entire ring.
9405 Org-mode commands jumping to a different position in the current file,
9406 or to another Org-mode file, automatically push the old position
9407 onto the ring."
9408 (interactive "p")
9409 (let (p m)
9410 (if (eq last-command this-command)
9411 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9412 (setq p org-mark-ring))
9413 (setq org-mark-ring-last-goto p)
9414 (setq m (car p))
9415 (switch-to-buffer (marker-buffer m))
9416 (goto-char m)
9417 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
9418
9419 (defun org-camel-to-words (s)
9420 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
9421 (let ((case-fold-search nil)
9422 words)
9423 (while (string-match "[a-z][A-Z]" s)
9424 (push (substring s 0 (1+ (match-beginning 0))) words)
9425 (setq s (substring s (1+ (match-beginning 0)))))
9426 (nreverse (cons s words))))
9427
9428 (defun org-remove-angle-brackets (s)
9429 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9430 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9431 s)
9432 (defun org-add-angle-brackets (s)
9433 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9434 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9435 s)
9436
9437 (defun org-follow-bbdb-link (name)
9438 "Follow a BBDB link to NAME."
9439 (require 'bbdb)
9440 (let ((inhibit-redisplay t)
9441 (bbdb-electric-p nil))
9442 (catch 'exit
9443 ;; Exact match on name
9444 (bbdb-name (concat "\\`" name "\\'") nil)
9445 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9446 ;; Exact match on name
9447 (bbdb-company (concat "\\`" name "\\'") nil)
9448 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9449 ;; Partial match on name
9450 (bbdb-name name nil)
9451 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9452 ;; Partial match on company
9453 (bbdb-company name nil)
9454 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9455 ;; General match including network address and notes
9456 (bbdb name nil)
9457 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9458 (delete-window (get-buffer-window "*BBDB*"))
9459 (error "No matching BBDB record")))))
9460
9461
9462 (defun org-follow-info-link (name)
9463 "Follow an info file & node link to NAME."
9464 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9465 (string-match "\\(.*\\)" name))
9466 (progn
9467 (require 'info)
9468 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9469 (Info-find-node (match-string 1 name) (match-string 2 name))
9470 (Info-find-node (match-string 1 name) "Top")))
9471 (message (concat "Could not open: " name))))
9472
9473 (defun org-follow-gnus-link (&optional group article)
9474 "Follow a Gnus link to GROUP and ARTICLE."
9475 (require 'gnus)
9476 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9477 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
9478 (if group (gnus-fetch-group group))
9479 (if article
9480 (or (gnus-summary-goto-article article nil 'force)
9481 (if (fboundp 'gnus-summary-insert-cached-articles)
9482 (progn
9483 (gnus-summary-insert-cached-articles)
9484 (gnus-summary-goto-article article nil 'force))
9485 (message "Message could not be found.")))))
9486
9487 (defun org-follow-vm-link (&optional folder article readonly)
9488 "Follow a VM link to FOLDER and ARTICLE."
9489 (require 'vm)
9490 (setq article (org-add-angle-brackets article))
9491 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9492 ;; ange-ftp or efs or tramp access
9493 (let ((user (or (match-string 1 folder) (user-login-name)))
9494 (host (match-string 2 folder))
9495 (file (match-string 3 folder)))
9496 (cond
9497 ((featurep 'tramp)
9498 ;; use tramp to access the file
9499 (if (featurep 'xemacs)
9500 (setq folder (format "[%s@%s]%s" user host file))
9501 (setq folder (format "/%s@%s:%s" user host file))))
9502 (t
9503 ;; use ange-ftp or efs
9504 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9505 (setq folder (format "/%s@%s:%s" user host file))))))
9506 (when folder
9507 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9508 (sit-for 0.1)
9509 (when article
9510 (vm-select-folder-buffer)
9511 (widen)
9512 (let ((case-fold-search t))
9513 (goto-char (point-min))
9514 (if (not (re-search-forward
9515 (concat "^" "message-id: *" (regexp-quote article))))
9516 (error "Could not find the specified message in this folder"))
9517 (vm-isearch-update)
9518 (vm-isearch-narrow)
9519 (vm-beginning-of-message)
9520 (vm-summarize)))))
9521
9522 (defun org-follow-wl-link (folder article)
9523 "Follow a Wanderlust link to FOLDER and ARTICLE."
9524 (setq article (org-add-angle-brackets article))
9525 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
9526 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
9527 (wl-summary-redisplay))
9528
9529 (defun org-follow-rmail-link (folder article)
9530 "Follow an RMAIL link to FOLDER and ARTICLE."
9531 (setq article (org-add-angle-brackets article))
9532 (let (message-number)
9533 (save-excursion
9534 (save-window-excursion
9535 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9536 (setq message-number
9537 (save-restriction
9538 (widen)
9539 (goto-char (point-max))
9540 (if (re-search-backward
9541 (concat "^Message-ID:\\s-+" (regexp-quote
9542 (or article "")))
9543 nil t)
9544 (rmail-what-message))))))
9545 (if message-number
9546 (progn
9547 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9548 (rmail-show-message message-number)
9549 message-number)
9550 (error "Message not found"))))
9551
9552 ;; mh-e integration based on planner-mode
9553 (defun org-mhe-get-message-real-folder ()
9554 "Return the name of the current message real folder, so if you use
9555 sequences, it will now work."
9556 (save-excursion
9557 (let* ((folder
9558 (if (equal major-mode 'mh-folder-mode)
9559 mh-current-folder
9560 ;; Refer to the show buffer
9561 mh-show-folder-buffer))
9562 (end-index
9563 (if (boundp 'mh-index-folder)
9564 (min (length mh-index-folder) (length folder))))
9565 )
9566 ;; a simple test on mh-index-data does not work, because
9567 ;; mh-index-data is always nil in a show buffer.
9568 (if (and (boundp 'mh-index-folder)
9569 (string= mh-index-folder (substring folder 0 end-index)))
9570 (if (equal major-mode 'mh-show-mode)
9571 (save-window-excursion
9572 (when (buffer-live-p (get-buffer folder))
9573 (progn
9574 (pop-to-buffer folder)
9575 (org-mhe-get-message-folder-from-index)
9576 )
9577 ))
9578 (org-mhe-get-message-folder-from-index)
9579 )
9580 folder
9581 )
9582 )))
9583
9584 (defun org-mhe-get-message-folder-from-index ()
9585 "Returns the name of the message folder in a index folder buffer."
9586 (save-excursion
9587 (mh-index-previous-folder)
9588 (re-search-forward "^\\(+.*\\)$" nil t)
9589 (message (match-string 1))))
9590
9591 (defun org-mhe-get-message-folder ()
9592 "Return the name of the current message folder. Be careful if you
9593 use sequences."
9594 (save-excursion
9595 (if (equal major-mode 'mh-folder-mode)
9596 mh-current-folder
9597 ;; Refer to the show buffer
9598 mh-show-folder-buffer)))
9599
9600 (defun org-mhe-get-message-num ()
9601 "Return the number of the current message. Be careful if you
9602 use sequences."
9603 (save-excursion
9604 (if (equal major-mode 'mh-folder-mode)
9605 (mh-get-msg-num nil)
9606 ;; Refer to the show buffer
9607 (mh-show-buffer-message-number))))
9608
9609 (defun org-mhe-get-header (header)
9610 "Return a header of the message in folder mode. This will create a
9611 show buffer for the corresponding message. If you have a more clever
9612 idea..."
9613 (let* ((folder (org-mhe-get-message-folder))
9614 (num (org-mhe-get-message-num))
9615 (buffer (get-buffer-create (concat "show-" folder)))
9616 (header-field))
9617 (with-current-buffer buffer
9618 (mh-display-msg num folder)
9619 (if (equal major-mode 'mh-folder-mode)
9620 (mh-header-display)
9621 (mh-show-header-display))
9622 (set-buffer buffer)
9623 (setq header-field (mh-get-header-field header))
9624 (if (equal major-mode 'mh-folder-mode)
9625 (mh-show)
9626 (mh-show-show))
9627 header-field)))
9628
9629 (defun org-follow-mhe-link (folder article)
9630 "Follow an MHE link to FOLDER and ARTICLE.
9631 If ARTICLE is nil FOLDER is shown. If the configuration variable
9632 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9633 ARTICLE is searched in all folders. Indexed searches (swish++,
9634 namazu, and others supported by MH-E) will always search in all
9635 folders."
9636 (require 'mh-e)
9637 (require 'mh-search)
9638 (require 'mh-utils)
9639 (mh-find-path)
9640 (if (not article)
9641 (mh-visit-folder (mh-normalize-folder-name folder))
9642 (setq article (org-add-angle-brackets article))
9643 (mh-search-choose)
9644 (if (equal mh-searcher 'pick)
9645 (progn
9646 (mh-search folder (list "--message-id" article))
9647 (when (and org-mhe-search-all-folders
9648 (not (org-mhe-get-message-real-folder)))
9649 (kill-this-buffer)
9650 (mh-search "+" (list "--message-id" article))))
9651 (mh-search "+" article))
9652 (if (org-mhe-get-message-real-folder)
9653 (mh-show-msg 1)
9654 (kill-this-buffer)
9655 (error "Message not found"))))
9656
9657 ;; BibTeX links
9658
9659 ;; Use the custom search meachnism to construct and use search strings for
9660 ;; file links to BibTeX database entries.
9661
9662 (defun org-create-file-search-in-bibtex ()
9663 "Create the search string and description for a BibTeX database entry."
9664 (when (eq major-mode 'bibtex-mode)
9665 ;; yes, we want to construct this search string.
9666 ;; Make a good description for this entry, using names, year and the title
9667 ;; Put it into the `description' variable which is dynamically scoped.
9668 (let ((bibtex-autokey-names 1)
9669 (bibtex-autokey-names-stretch 1)
9670 (bibtex-autokey-name-case-convert-function 'identity)
9671 (bibtex-autokey-name-separator " & ")
9672 (bibtex-autokey-additional-names " et al.")
9673 (bibtex-autokey-year-length 4)
9674 (bibtex-autokey-name-year-separator " ")
9675 (bibtex-autokey-titlewords 3)
9676 (bibtex-autokey-titleword-separator " ")
9677 (bibtex-autokey-titleword-case-convert-function 'identity)
9678 (bibtex-autokey-titleword-length 'infty)
9679 (bibtex-autokey-year-title-separator ": "))
9680 (setq description (bibtex-generate-autokey)))
9681 ;; Now parse the entry, get the key and return it.
9682 (save-excursion
9683 (bibtex-beginning-of-entry)
9684 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9685
9686 (defun org-execute-file-search-in-bibtex (s)
9687 "Find the link search string S as a key for a database entry."
9688 (when (eq major-mode 'bibtex-mode)
9689 ;; Yes, we want to do the search in this file.
9690 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9691 (goto-char (point-min))
9692 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9693 (regexp-quote s) "[ \t\n]*,") nil t)
9694 (goto-char (match-beginning 0)))
9695 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9696 ;; Use double prefix to indicate that any web link should be browsed
9697 (let ((b (current-buffer)) (p (point)))
9698 ;; Restore the window configuration because we just use the web link
9699 (set-window-configuration org-window-config-before-follow-link)
9700 (save-excursion (set-buffer b) (goto-char p)
9701 (bibtex-url)))
9702 (recenter 0)) ; Move entry start to beginning of window
9703 ;; return t to indicate that the search is done.
9704 t))
9705
9706 ;; Finally add the functions to the right hooks.
9707 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9708 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9709
9710 ;; end of Bibtex link setup
9711
9712 (defun org-upgrade-old-links (&optional query-description)
9713 "Transfer old <...> style links to new [[...]] style links.
9714 With arg query-description, ask at each match for a description text to use
9715 for this link."
9716 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
9717 (save-excursion
9718 (goto-char (point-min))
9719 (let ((re (concat "\\([^[]\\)<\\("
9720 "\\(" (mapconcat 'identity org-link-types "\\|")
9721 "\\):"
9722 "[^" org-non-link-chars "]+\\)>"))
9723 l1 l2 (cnt 0))
9724 (while (re-search-forward re nil t)
9725 (setq cnt (1+ cnt)
9726 l1 (org-match-string-no-properties 2)
9727 l2 (save-match-data (org-link-escape l1)))
9728 (when query-description (setq l1 (read-string "Desc: " l1)))
9729 (if (equal l1 l2)
9730 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
9731 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
9732 (message "%d matches have beed treated" cnt))))
9733
9734 (defun org-open-file (path &optional in-emacs line search)
9735 "Open the file at PATH.
9736 First, this expands any special file name abbreviations. Then the
9737 configuration variable `org-file-apps' is checked if it contains an
9738 entry for this file type, and if yes, the corresponding command is launched.
9739 If no application is found, Emacs simply visits the file.
9740 With optional argument IN-EMACS, Emacs will visit the file.
9741 Optional LINE specifies a line to go to, optional SEARCH a string to
9742 search for. If LINE or SEARCH is given, the file will always be
9743 opened in Emacs.
9744 If the file does not exist, an error is thrown."
9745 (setq in-emacs (or in-emacs line search))
9746 (let* ((file (if (equal path "")
9747 buffer-file-name
9748 path))
9749 (apps (append org-file-apps (org-default-apps)))
9750 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9751 (dirp (if remp nil (file-directory-p file)))
9752 (dfile (downcase file))
9753 (old-buffer (current-buffer))
9754 (old-pos (point))
9755 (old-mode major-mode)
9756 ext cmd)
9757 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9758 (setq ext (match-string 1 dfile))
9759 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9760 (setq ext (match-string 1 dfile))))
9761 (if in-emacs
9762 (setq cmd 'emacs)
9763 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9764 (and dirp (cdr (assoc 'directory apps)))
9765 (cdr (assoc ext apps))
9766 (cdr (assoc t apps)))))
9767 (when (eq cmd 'mailcap)
9768 (require 'mailcap)
9769 (mailcap-parse-mailcaps)
9770 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9771 (command (mailcap-mime-info mime-type)))
9772 (if (stringp command)
9773 (setq cmd command)
9774 (setq cmd 'emacs))))
9775 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
9776 (not (file-exists-p file))
9777 (not org-open-non-existing-files))
9778 (error "No such file: %s" file))
9779 (cond
9780 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9781 ;; Normalize use of quote, this can vary.
9782 (if (string-match "['\"]%s['\"]" cmd)
9783 (setq cmd (replace-match "'%s'" t t cmd)))
9784 (setq cmd (format cmd file))
9785 (save-window-excursion
9786 (shell-command (concat cmd " &"))))
9787 ((or (stringp cmd)
9788 (eq cmd 'emacs))
9789 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
9790 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
9791 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9792 (if line (goto-line line)
9793 (if search (org-link-search search))))
9794 ((consp cmd)
9795 (eval cmd))
9796 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9797 (and (org-mode-p) (eq old-mode 'org-mode)
9798 (or (not (equal old-buffer (current-buffer)))
9799 (not (equal old-pos (point))))
9800 (org-mark-ring-push old-pos old-buffer))))
9801
9802 (defun org-default-apps ()
9803 "Return the default applications for this operating system."
9804 (cond
9805 ((eq system-type 'darwin)
9806 org-file-apps-defaults-macosx)
9807 ((eq system-type 'windows-nt)
9808 org-file-apps-defaults-windowsnt)
9809 (t org-file-apps-defaults-gnu)))
9810
9811 (defun org-expand-file-name (path)
9812 "Replace special path abbreviations and expand the file name."
9813 (expand-file-name path))
9814
9815 (defun org-file-remote-p (file)
9816 "Test whether FILE specifies a location on a remote system.
9817 Return non-nil if the location is indeed remote.
9818
9819 For example, the filename \"/user@host:/foo\" specifies a location
9820 on the system \"/user@host:\"."
9821 (cond ((fboundp 'file-remote-p)
9822 (file-remote-p file))
9823 ((fboundp 'tramp-handle-file-remote-p)
9824 (tramp-handle-file-remote-p file))
9825 ((and (boundp 'ange-ftp-name-format)
9826 (string-match (car ange-ftp-name-format) file))
9827 t)
9828 (t nil)))
9829
9830 (defvar org-insert-link-history nil
9831 "Minibuffer history for links inserted with `org-insert-link'.")
9832
9833 (defvar org-stored-links nil
9834 "Contains the links stored with `org-store-link'.")
9835
9836 ;;;###autoload
9837 (defun org-store-link (arg)
9838 "\\<org-mode-map>Store an org-link to the current location.
9839 This link can later be inserted into an org-buffer with
9840 \\[org-insert-link].
9841 For some link types, a prefix arg is interpreted:
9842 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9843 For file links, arg negates `org-context-in-file-links'."
9844 (interactive "P")
9845 (let (link cpltxt desc description search txt (pos (point)))
9846 (cond
9847
9848 ((eq major-mode 'bbdb-mode)
9849 (setq cpltxt (concat
9850 "bbdb:"
9851 (or (bbdb-record-name (bbdb-current-record))
9852 (bbdb-record-company (bbdb-current-record))))
9853 link (org-make-link cpltxt)))
9854
9855 ((eq major-mode 'Info-mode)
9856 (setq link (org-make-link "info:"
9857 (file-name-nondirectory Info-current-file)
9858 ":" Info-current-node))
9859 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9860 ":" Info-current-node)))
9861
9862 ((eq major-mode 'calendar-mode)
9863 (let ((cd (calendar-cursor-to-date)))
9864 (setq link
9865 (format-time-string
9866 (car org-time-stamp-formats)
9867 (apply 'encode-time
9868 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9869 nil nil nil))))))
9870
9871 ((or (eq major-mode 'vm-summary-mode)
9872 (eq major-mode 'vm-presentation-mode))
9873 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9874 (vm-follow-summary-cursor)
9875 (save-excursion
9876 (vm-select-folder-buffer)
9877 (let* ((message (car vm-message-pointer))
9878 (folder buffer-file-name)
9879 (subject (vm-su-subject message))
9880 (author (vm-su-full-name message))
9881 (message-id (vm-su-message-id message)))
9882 (setq message-id (org-remove-angle-brackets message-id))
9883 (setq folder (abbreviate-file-name folder))
9884 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9885 folder)
9886 (setq folder (replace-match "" t t folder)))
9887 (setq cpltxt (concat author " on: " subject))
9888 (setq link (org-make-link "vm:" folder "#" message-id)))))
9889
9890 ((eq major-mode 'wl-summary-mode)
9891 (let* ((msgnum (wl-summary-message-number))
9892 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9893 msgnum 'message-id))
9894 (wl-message-entity (elmo-msgdb-overview-get-entity
9895 msgnum (wl-summary-buffer-msgdb)))
9896 (author (wl-summary-line-from)) ; FIXME: correct?
9897 (subject "???")) ; FIXME:
9898 (setq message-id (org-remove-angle-brackets message-id))
9899 (setq cpltxt (concat author " on: " subject))
9900 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9901 "#" message-id))))
9902
9903 ((or (equal major-mode 'mh-folder-mode)
9904 (equal major-mode 'mh-show-mode))
9905 (let ((from-header (org-mhe-get-header "From:"))
9906 (to-header (org-mhe-get-header "To:"))
9907 (subject (org-mhe-get-header "Subject:")))
9908 (setq cpltxt (concat from-header " on: " subject))
9909 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9910 (org-remove-angle-brackets
9911 (org-mhe-get-header "Message-Id:"))))))
9912
9913 ((eq major-mode 'rmail-mode)
9914 (save-excursion
9915 (save-restriction
9916 (rmail-narrow-to-non-pruned-header)
9917 (let ((folder buffer-file-name)
9918 (message-id (mail-fetch-field "message-id"))
9919 (author (mail-fetch-field "from"))
9920 (subject (mail-fetch-field "subject")))
9921 (setq message-id (org-remove-angle-brackets message-id))
9922 (setq cpltxt (concat author " on: " subject))
9923 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9924
9925 ((eq major-mode 'gnus-group-mode)
9926 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9927 (gnus-group-group-name)) ; version
9928 ((fboundp 'gnus-group-name)
9929 (gnus-group-name))
9930 (t "???"))))
9931 (setq cpltxt (concat
9932 (if (org-xor arg org-usenet-links-prefer-google)
9933 "http://groups.google.com/groups?group="
9934 "gnus:")
9935 group)
9936 link (org-make-link cpltxt))))
9937
9938 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9939 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9940 (gnus-summary-beginning-of-article)
9941 (let* ((group (car gnus-article-current))
9942 (article (cdr gnus-article-current))
9943 (header (gnus-summary-article-header article))
9944 (author (mail-header-from header))
9945 (message-id (mail-header-id header))
9946 (date (mail-header-date header))
9947 (subject (gnus-summary-subject-string)))
9948 (setq cpltxt (concat author " on: " subject))
9949 (if (org-xor arg org-usenet-links-prefer-google)
9950 (setq link
9951 (concat
9952 cpltxt "\n "
9953 (format "http://groups.google.com/groups?as_umsgid=%s"
9954 (org-fixup-message-id-for-http message-id))))
9955 (setq link (org-make-link "gnus:" group
9956 "#" (number-to-string article))))))
9957
9958 ((eq major-mode 'w3-mode)
9959 (setq cpltxt (url-view-url t)
9960 link (org-make-link cpltxt)))
9961 ((eq major-mode 'w3m-mode)
9962 (setq cpltxt (or w3m-current-title w3m-current-url)
9963 link (org-make-link w3m-current-url)))
9964
9965 ((setq search (run-hook-with-args-until-success
9966 'org-create-file-search-functions))
9967 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9968 "::" search))
9969 (setq cpltxt (or description link)))
9970
9971 ((eq major-mode 'image-mode)
9972 (setq cpltxt (concat "file:"
9973 (abbreviate-file-name buffer-file-name))
9974 link (org-make-link cpltxt)))
9975
9976 ((org-mode-p)
9977 ;; Just link to current headline
9978 (setq cpltxt (concat "file:"
9979 (abbreviate-file-name buffer-file-name)))
9980 ;; Add a context search string
9981 (when (org-xor org-context-in-file-links arg)
9982 ;; Check if we are on a target
9983 (if (save-excursion
9984 (skip-chars-forward "^>\n\r")
9985 (and (re-search-backward "<<" nil t)
9986 (looking-at "<<\\(.*?\\)>>")
9987 (<= (match-beginning 0) pos)
9988 (>= (match-end 0) pos)))
9989 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9990 (setq txt (cond
9991 ((org-on-heading-p) nil)
9992 ((org-region-active-p)
9993 (buffer-substring (region-beginning) (region-end)))
9994 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9995 (when (or (null txt) (string-match "\\S-" txt))
9996 (setq cpltxt
9997 (concat cpltxt "::"
9998 (if org-file-link-context-use-camel-case
9999 (org-make-org-heading-camel txt)
10000 (org-make-org-heading-search-string txt)))
10001 desc "NONE"))))
10002 (if (string-match "::\\'" cpltxt)
10003 (setq cpltxt (substring cpltxt 0 -2)))
10004 (setq link (org-make-link cpltxt)))
10005
10006 (buffer-file-name
10007 ;; Just link to this file here.
10008 (setq cpltxt (concat "file:"
10009 (abbreviate-file-name buffer-file-name)))
10010 ;; Add a context string
10011 (when (org-xor org-context-in-file-links arg)
10012 (setq txt (if (org-region-active-p)
10013 (buffer-substring (region-beginning) (region-end))
10014 (buffer-substring (point-at-bol) (point-at-eol))))
10015 ;; Only use search option if there is some text.
10016 (when (string-match "\\S-" txt)
10017 (setq cpltxt
10018 (concat cpltxt "::"
10019 (if org-file-link-context-use-camel-case
10020 (org-make-org-heading-camel txt)
10021 (org-make-org-heading-search-string txt)))
10022 desc "NONE")))
10023 (setq link (org-make-link cpltxt)))
10024
10025 ((interactive-p)
10026 (error "Cannot link to a buffer which is not visiting a file"))
10027
10028 (t (setq link nil)))
10029
10030 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10031 (setq link (or link cpltxt)
10032 desc (or desc cpltxt))
10033 (if (equal desc "NONE") (setq desc nil))
10034
10035 (if (and (interactive-p) link)
10036 (progn
10037 (setq org-stored-links
10038 (cons (list cpltxt link desc) org-stored-links))
10039 (message "Stored: %s" (or cpltxt link)))
10040 (org-make-link-string link desc))))
10041
10042 (defun org-make-org-heading-search-string (&optional string heading)
10043 "Make search string for STRING or current headline."
10044 (interactive)
10045 (let ((s (or string (org-get-heading))))
10046 (unless (and string (not heading))
10047 ;; We are using a headline, clean up garbage in there.
10048 (if (string-match org-todo-regexp s)
10049 (setq s (replace-match "" t t s)))
10050 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10051 (setq s (replace-match "" t t s)))
10052 (setq s (org-trim s))
10053 (if (string-match (concat "^\\(" org-quote-string "\\|"
10054 org-comment-string "\\)") s)
10055 (setq s (replace-match "" t t s)))
10056 (while (string-match org-ts-regexp s)
10057 (setq s (replace-match "" t t s))))
10058 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10059 (setq s (replace-match " " t t s)))
10060 (or string (setq s (concat "*" s))) ; Add * for headlines
10061 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10062
10063 (defun org-make-org-heading-camel (&optional string heading)
10064 "Make a CamelCase string for STRING or the current headline."
10065 (interactive)
10066 (let ((s (or string (org-get-heading))))
10067 (unless (and string (not heading))
10068 ;; We are using a headline, clean up garbage in there.
10069 (if (string-match org-todo-regexp s)
10070 (setq s (replace-match "" t t s)))
10071 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10072 (setq s (replace-match "" t t s)))
10073 (setq s (org-trim s))
10074 (if (string-match (concat "^\\(" org-quote-string "\\|"
10075 org-comment-string "\\)") s)
10076 (setq s (replace-match "" t t s)))
10077 (while (string-match org-ts-regexp s)
10078 (setq s (replace-match "" t t s))))
10079 (while (string-match "[^a-zA-Z_ \t]+" s)
10080 (setq s (replace-match " " t t s)))
10081 (or string (setq s (concat "*" s))) ; Add * for headlines
10082 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
10083
10084 (defun org-make-link (&rest strings)
10085 "Concatenate STRINGS, format resulting string with `org-link-format'."
10086 (format org-link-format (apply 'concat strings)))
10087
10088 (defun org-make-link-string (link &optional description)
10089 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10090 (if (eq org-link-style 'plain)
10091 (if (equal description link)
10092 link
10093 (concat description "\n" link))
10094 (when (stringp description)
10095 ;; Remove brackets from the description, they are fatal.
10096 (while (string-match "\\[\\|\\]" description)
10097 (setq description (replace-match "" t t description))))
10098 (when (equal (org-link-escape link) description)
10099 ;; No description needed, it is identical
10100 (setq description nil))
10101 (when (and (not description)
10102 (not (equal link (org-link-escape link))))
10103 (setq description link))
10104 (concat "[[" (org-link-escape link) "]"
10105 (if description (concat "[" description "]") "")
10106 "]")))
10107
10108 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
10109 "Association list of escapes for some characters problematic in links.")
10110
10111 (defun org-link-escape (text)
10112 "Escape charaters in TEXT that are problematic for links."
10113 (when text
10114 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10115 org-link-escape-chars "\\|")))
10116 (while (string-match re text)
10117 (setq text
10118 (replace-match
10119 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10120 t t text)))
10121 text)))
10122
10123 (defun org-link-unescape (text)
10124 "Reverse the action of `org-link-escape'."
10125 (when text
10126 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10127 org-link-escape-chars "\\|")))
10128 (while (string-match re text)
10129 (setq text
10130 (replace-match
10131 (car (rassoc (match-string 0 text) org-link-escape-chars))
10132 t t text)))
10133 text)))
10134
10135 (defun org-xor (a b)
10136 "Exclusive or."
10137 (if a (not b) b))
10138
10139 (defun org-get-header (header)
10140 "Find a header field in the current buffer."
10141 (save-excursion
10142 (goto-char (point-min))
10143 (let ((case-fold-search t) s)
10144 (cond
10145 ((eq header 'from)
10146 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10147 (setq s (match-string 1)))
10148 (while (string-match "\"" s)
10149 (setq s (replace-match "" t t s)))
10150 (if (string-match "[<(].*" s)
10151 (setq s (replace-match "" t t s))))
10152 ((eq header 'message-id)
10153 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10154 (setq s (match-string 1))))
10155 ((eq header 'subject)
10156 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10157 (setq s (match-string 1)))))
10158 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10159 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10160 s)))
10161
10162
10163 (defun org-fixup-message-id-for-http (s)
10164 "Replace special characters in a message id, so it can be used in an http query."
10165 (while (string-match "<" s)
10166 (setq s (replace-match "%3C" t t s)))
10167 (while (string-match ">" s)
10168 (setq s (replace-match "%3E" t t s)))
10169 (while (string-match "@" s)
10170 (setq s (replace-match "%40" t t s)))
10171 s)
10172
10173 (defun org-insert-link (&optional complete-file)
10174 "Insert a link. At the prompt, enter the link.
10175
10176 Completion can be used to select a link previously stored with
10177 `org-store-link'. When the empty string is entered (i.e. if you just
10178 press RET at the prompt), the link defaults to the most recently
10179 stored link. As SPC triggers completion in the minibuffer, you need to
10180 use M-SPC or C-q SPC to force the insertion of a space character.
10181
10182 You will also be prompted for a description, and if one is given, it will
10183 be displayed in the buffer instead of the link.
10184
10185 If there is already a link at point, this command will allow you to edit link
10186 and description parts.
10187
10188 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10189 selected using completion. The path to the file will be relative to
10190 the current directory if the file is in the current directory or a
10191 subdirectory. Otherwise, the link will be the absolute path as
10192 completed in the minibuffer (i.e. normally ~/path/to/file).
10193
10194 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10195 is in the current directory or below.
10196 With three \\[universal-argument] prefixes, negate the meaning of
10197 `org-keep-stored-link-after-insertion'."
10198 (interactive "P")
10199 (let (link desc entry remove file (pos (point)))
10200 (cond
10201 ((save-excursion
10202 (skip-chars-forward "^]\n\r")
10203 (and (re-search-backward "\\[\\[" nil t)
10204 (looking-at org-bracket-link-regexp)
10205 (<= (match-beginning 0) pos)
10206 (>= (match-end 0) pos)))
10207 ;; We do have a link at point, and we are going to edit it.
10208 (setq remove (list (match-beginning 0) (match-end 0)))
10209 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10210 (setq link (read-string "Link: "
10211 (org-link-unescape
10212 (org-match-string-no-properties 1)))))
10213 ((equal complete-file '(4))
10214 ;; Completing read for file names.
10215 (setq file (read-file-name "File: "))
10216 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10217 (pwd1 (file-name-as-directory (abbreviate-file-name
10218 (expand-file-name ".")))))
10219 (cond
10220 ((equal complete-file '(16))
10221 (setq link (org-make-link
10222 "file:"
10223 (abbreviate-file-name (expand-file-name file)))))
10224 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10225 (setq link (org-make-link "file:" (match-string 1 file))))
10226 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10227 (expand-file-name file))
10228 (setq link (org-make-link
10229 "file:" (match-string 1 (expand-file-name file)))))
10230 (t (setq link (org-make-link "file:" file))))))
10231 (t
10232 ;; Read link, with completion for stored links.
10233 (setq link (org-completing-read
10234 "Link: " org-stored-links nil nil nil
10235 org-insert-link-history
10236 (or (car (car org-stored-links)))))
10237 (setq entry (assoc link org-stored-links))
10238 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10239 (not org-keep-stored-link-after-insertion))
10240 (setq org-stored-links (delq (assoc link org-stored-links)
10241 org-stored-links)))
10242 (setq link (if entry (nth 1 entry) link)
10243 desc (or desc (nth 2 entry)))))
10244
10245 (if (string-match org-plain-link-re link)
10246 ;; URL-like link, normalize the use of angular brackets.
10247 (setq link (org-make-link (org-remove-angle-brackets link))))
10248
10249 ;; Check if we are linking to the current file with a search option
10250 ;; If yes, simplify the link by using only the search option.
10251 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
10252 (let* ((path (match-string 1 link))
10253 (case-fold-search nil)
10254 (search (match-string 2 link)))
10255 (save-match-data
10256 (if (equal (file-truename buffer-file-name) (file-truename path))
10257 ;; We are linking to this same file, with a search option
10258 (setq link search)))))
10259
10260 ;; Check if we can/should use a relative path. If yes, simplify the link
10261 (when (string-match "\\<file:\\(.*\\)" link)
10262 (let* ((path (match-string 1 link))
10263 (case-fold-search nil))
10264 (cond
10265 ((eq org-link-file-path-type 'absolute)
10266 (setq path (abbreviate-file-name (expand-file-name path))))
10267 ((eq org-link-file-path-type 'noabbrev)
10268 (setq path (expand-file-name path)))
10269 ((eq org-link-file-path-type 'relative)
10270 (setq path (file-relative-name path)))
10271 (t
10272 (save-match-data
10273 (if (string-match (concat "^" (regexp-quote
10274 (file-name-as-directory
10275 (expand-file-name "."))))
10276 (expand-file-name path))
10277 ;; We are linking a file with relative path name.
10278 (setq path (substring (expand-file-name path)
10279 (match-end 0)))))))
10280 (setq link (concat "file:" path))))
10281
10282 (setq desc (read-string "Description: " desc))
10283 (unless (string-match "\\S-" desc) (setq desc nil))
10284 (if remove (apply 'delete-region remove))
10285 (insert (org-make-link-string link desc))))
10286
10287 (defun org-completing-read (&rest args)
10288 (let ((minibuffer-local-completion-map
10289 (copy-keymap minibuffer-local-completion-map)))
10290 (define-key minibuffer-local-completion-map " " 'self-insert-command)
10291 (apply 'completing-read args)))
10292
10293 ;;; Hooks for remember.el
10294
10295 (defvar org-finish-function nil)
10296
10297 ;;;###autoload
10298 (defun org-remember-annotation ()
10299 "Return a link to the current location as an annotation for remember.el.
10300 If you are using Org-mode files as target for data storage with
10301 remember.el, then the annotations should include a link compatible with the
10302 conventions in Org-mode. This function returns such a link."
10303 (org-store-link nil))
10304
10305 (defconst org-remember-help
10306 "Select a destination location for the note.
10307 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10308 RET at beg-of-buf -> Append to file as level 2 headline
10309 RET on headline -> Store as sublevel entry to current headline
10310 <left>/<right> -> before/after current headline, same headings level")
10311
10312 ;;;###autoload
10313 (defun org-remember-apply-template ()
10314 "Initialize *remember* buffer with template, invoke `org-mode'.
10315 This function should be placed into `remember-mode-hook' and in fact requires
10316 to be run from that hook to fucntion properly."
10317 (if org-remember-templates
10318
10319 (let* ((entry (if (= (length org-remember-templates) 1)
10320 (cdar org-remember-templates)
10321 (message "Select template: %s"
10322 (mapconcat
10323 (lambda (x) (char-to-string (car x)))
10324 org-remember-templates " "))
10325 (cdr (assoc (read-char-exclusive) org-remember-templates))))
10326 (tpl (car entry))
10327 (file (if (consp (cdr entry)) (nth 1 entry)))
10328 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10329 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10330 (v-u (concat "[" (substring v-t 1 -1) "]"))
10331 (v-U (concat "[" (substring v-T 1 -1) "]"))
10332 (v-a annotation) ; defined in `remember-mode'
10333 (v-i initial) ; defined in `remember-mode'
10334 (v-n user-full-name)
10335 )
10336 (unless tpl (setq tpl "") (message "No template") (ding))
10337 (insert tpl) (goto-char (point-min))
10338 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
10339 (when (and initial (equal (match-string 0) "%i"))
10340 (save-match-data
10341 (let* ((lead (buffer-substring
10342 (point-at-bol) (match-beginning 0))))
10343 (setq v-i (mapconcat 'identity
10344 (org-split-string initial "\n")
10345 (concat "\n" lead))))))
10346 (replace-match
10347 (or (eval (intern (concat "v-" (match-string 1)))) "")
10348 t t))
10349 (let ((org-startup-folded nil)
10350 (org-startup-with-deadline-check nil))
10351 (org-mode))
10352 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10353 (org-set-local 'org-default-notes-file file))
10354 (goto-char (point-min))
10355 (if (re-search-forward "%\\?" nil t) (replace-match "")))
10356 (let ((org-startup-folded nil)
10357 (org-startup-with-deadline-check nil))
10358 (org-mode)))
10359 (org-set-local 'org-finish-function 'remember-buffer))
10360
10361 ;;;###autoload
10362 (defun org-remember-handler ()
10363 "Store stuff from remember.el into an org file.
10364 First prompts for an org file. If the user just presses return, the value
10365 of `org-default-notes-file' is used.
10366 Then the command offers the headings tree of the selected file in order to
10367 file the text at a specific location.
10368 You can either immediately press RET to get the note appended to the
10369 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10370 find a better place. Then press RET or <left> or <right> in insert the note.
10371
10372 Key Cursor position Note gets inserted
10373 -----------------------------------------------------------------------------
10374 RET buffer-start as level 2 heading at end of file
10375 RET on headline as sublevel of the heading at cursor
10376 RET no heading at cursor position, level taken from context.
10377 Or use prefix arg to specify level manually.
10378 <left> on headline as same level, before current heading
10379 <right> on headline as same level, after current heading
10380
10381 So the fastest way to store the note is to press RET RET to append it to
10382 the default file. This way your current train of thought is not
10383 interrupted, in accordance with the principles of remember.el. But with
10384 little extra effort, you can push it directly to the correct location.
10385
10386 Before being stored away, the function ensures that the text has a
10387 headline, i.e. a first line that starts with a \"*\". If not, a headline
10388 is constructed from the current date and some additional data.
10389
10390 If the variable `org-adapt-indentation' is non-nil, the entire text is
10391 also indented so that it starts in the same column as the headline
10392 \(i.e. after the stars).
10393
10394 See also the variable `org-reverse-note-order'."
10395 (catch 'quit
10396 (let* ((txt (buffer-substring (point-min) (point-max)))
10397 (fastp current-prefix-arg)
10398 (file (if fastp org-default-notes-file (org-get-org-file)))
10399 (visiting (find-buffer-visiting file))
10400 (org-startup-with-deadline-check nil)
10401 (org-startup-folded nil)
10402 (org-startup-align-all-tables nil)
10403 spos level indent reversed)
10404 ;; Modify text so that it becomes a nice subtree which can be inserted
10405 ;; into an org tree.
10406 (let* ((lines (split-string txt "\n"))
10407 first)
10408 ;; remove empty lines at the beginning
10409 (while (and lines (string-match "^[ \t]*\n" (car lines)))
10410 (setq lines (cdr lines)))
10411 (setq first (car lines) lines (cdr lines))
10412 (if (string-match "^\\*+" first)
10413 ;; Is already a headline
10414 (setq indent nil)
10415 ;; We need to add a headline: Use time and first buffer line
10416 (setq lines (cons first lines)
10417 first (concat "* " (current-time-string)
10418 " (" (remember-buffer-desc) ")")
10419 indent " "))
10420 (if (and org-adapt-indentation indent)
10421 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10422 (setq txt (concat first "\n"
10423 (mapconcat 'identity lines "\n"))))
10424 ;; Find the file
10425 (if (not visiting)
10426 (find-file-noselect file))
10427 (with-current-buffer (get-file-buffer file)
10428 (save-excursion (and (goto-char (point-min))
10429 (not (re-search-forward "^\\* " nil t))
10430 (insert "\n* Notes\n")))
10431 (setq reversed (org-notes-order-reversed-p))
10432 (save-excursion
10433 (save-restriction
10434 (widen)
10435 ;; Ask the User for a location
10436 (setq spos (if fastp 1 (org-get-location
10437 (current-buffer)
10438 org-remember-help)))
10439 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10440 ; not handle this note
10441 (goto-char spos)
10442 (cond ((bobp)
10443 ;; Put it at the start or end, as level 2
10444 (save-restriction
10445 (widen)
10446 (goto-char (if reversed (point-min) (point-max)))
10447 (if (not (bolp)) (newline))
10448 (org-paste-subtree 2 txt)))
10449 ((and (org-on-heading-p nil) (not current-prefix-arg))
10450 ;; Put it below this entry, at the beg/end of the subtree
10451 (org-back-to-heading)
10452 (setq level (funcall outline-level))
10453 (if reversed
10454 (outline-end-of-heading)
10455 (outline-end-of-subtree))
10456 (if (not (bolp)) (newline))
10457 (beginning-of-line 1)
10458 (org-paste-subtree (1+ level) txt))
10459 (t
10460 ;; Put it right there, with automatic level determined by
10461 ;; org-paste-subtree or from prefix arg
10462 (org-paste-subtree current-prefix-arg txt)))
10463 (when remember-save-after-remembering
10464 (save-buffer)
10465 (if (not visiting) (kill-buffer (current-buffer)))))))))
10466 t) ;; return t to indicate that we took care of this note.
10467
10468 (defun org-get-org-file ()
10469 "Read a filename, with default directory `org-directory'."
10470 (let ((default (or org-default-notes-file remember-data-file)))
10471 (read-file-name (format "File name [%s]: " default)
10472 (file-name-as-directory org-directory)
10473 default)))
10474
10475 (defun org-notes-order-reversed-p ()
10476 "Check if the current file should receive notes in reversed order."
10477 (cond
10478 ((not org-reverse-note-order) nil)
10479 ((eq t org-reverse-note-order) t)
10480 ((not (listp org-reverse-note-order)) nil)
10481 (t (catch 'exit
10482 (let ((all org-reverse-note-order)
10483 entry)
10484 (while (setq entry (pop all))
10485 (if (string-match (car entry) buffer-file-name)
10486 (throw 'exit (cdr entry))))
10487 nil)))))
10488
10489 ;;; Tables
10490
10491 ;; Watch out: Here we are talking about two different kind of tables.
10492 ;; Most of the code is for the tables created with the Org-mode table editor.
10493 ;; Sometimes, we talk about tables created and edited with the table.el
10494 ;; Emacs package. We call the former org-type tables, and the latter
10495 ;; table.el-type tables.
10496
10497
10498 (defun org-before-change-function (beg end)
10499 "Every change indicates that a table might need an update."
10500 (setq org-table-may-need-update t))
10501
10502 (defconst org-table-line-regexp "^[ \t]*|"
10503 "Detects an org-type table line.")
10504 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
10505 "Detects an org-type table line.")
10506 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
10507 "Detects a table line marked for automatic recalculation.")
10508 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
10509 "Detects a table line marked for automatic recalculation.")
10510 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
10511 "Detects a table line marked for automatic recalculation.")
10512 (defconst org-table-hline-regexp "^[ \t]*|-"
10513 "Detects an org-type table hline.")
10514 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
10515 "Detects a table-type table hline.")
10516 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
10517 "Detects an org-type or table-type table.")
10518 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
10519 "Searching from within a table (any type) this finds the first line
10520 outside the table.")
10521 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
10522 "Searching from within a table (any type) this finds the first line
10523 outside the table.")
10524
10525 (defun org-table-create-with-table.el ()
10526 "Use the table.el package to insert a new table.
10527 If there is already a table at point, convert between Org-mode tables
10528 and table.el tables."
10529 (interactive)
10530 (require 'table)
10531 (cond
10532 ((org-at-table.el-p)
10533 (if (y-or-n-p "Convert table to Org-mode table? ")
10534 (org-table-convert)))
10535 ((org-at-table-p)
10536 (if (y-or-n-p "Convert table to table.el table? ")
10537 (org-table-convert)))
10538 (t (call-interactively 'table-insert))))
10539
10540 (defun org-table-create-or-convert-from-region (arg)
10541 "Convert region to table, or create an empty table.
10542 If there is an active region, convert it to a table. If there is no such
10543 region, create an empty table."
10544 (interactive "P")
10545 (if (org-region-active-p)
10546 (org-table-convert-region (region-beginning) (region-end) arg)
10547 (org-table-create arg)))
10548
10549 (defun org-table-create (&optional size)
10550 "Query for a size and insert a table skeleton.
10551 SIZE is a string Columns x Rows like for example \"3x2\"."
10552 (interactive "P")
10553 (unless size
10554 (setq size (read-string
10555 (concat "Table size Columns x Rows [e.g. "
10556 org-table-default-size "]: ")
10557 "" nil org-table-default-size)))
10558
10559 (let* ((pos (point))
10560 (indent (make-string (current-column) ?\ ))
10561 (split (org-split-string size " *x *"))
10562 (rows (string-to-number (nth 1 split)))
10563 (columns (string-to-number (car split)))
10564 (line (concat (apply 'concat indent "|" (make-list columns " |"))
10565 "\n")))
10566 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
10567 (point-at-bol) (point)))
10568 (beginning-of-line 1)
10569 (newline))
10570 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
10571 (dotimes (i rows) (insert line))
10572 (goto-char pos)
10573 (if (> rows 1)
10574 ;; Insert a hline after the first row.
10575 (progn
10576 (end-of-line 1)
10577 (insert "\n|-")
10578 (goto-char pos)))
10579 (org-table-align)))
10580
10581 (defun org-table-convert-region (beg0 end0 &optional nspace)
10582 "Convert region to a table.
10583 The region goes from BEG0 to END0, but these borders will be moved
10584 slightly, to make sure a beginning of line in the first line is included.
10585 When NSPACE is non-nil, it indicates the minimum number of spaces that
10586 separate columns (default: just one space)."
10587 (interactive "rP")
10588 (let* ((beg (min beg0 end0))
10589 (end (max beg0 end0))
10590 (tabsep t)
10591 re)
10592 (goto-char beg)
10593 (beginning-of-line 1)
10594 (setq beg (move-marker (make-marker) (point)))
10595 (goto-char end)
10596 (if (bolp) (backward-char 1) (end-of-line 1))
10597 (setq end (move-marker (make-marker) (point)))
10598 ;; Lets see if this is tab-separated material. If every nonempty line
10599 ;; contains a tab, we will assume that it is tab-separated material
10600 (if nspace
10601 (setq tabsep nil)
10602 (goto-char beg)
10603 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
10604 (if nspace (setq tabsep nil))
10605 (if tabsep
10606 (setq re "^\\|\t")
10607 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
10608 (max 1 (prefix-numeric-value nspace)))))
10609 (goto-char beg)
10610 (while (re-search-forward re end t)
10611 (replace-match "|" t t))
10612 (goto-char beg)
10613 (insert " ")
10614 (org-table-align)))
10615
10616 (defun org-table-import (file arg)
10617 "Import FILE as a table.
10618 The file is assumed to be tab-separated. Such files can be produced by most
10619 spreadsheet and database applications. If no tabs (at least one per line)
10620 are found, lines will be split on whitespace into fields."
10621 (interactive "f\nP")
10622 (or (bolp) (newline))
10623 (let ((beg (point))
10624 (pm (point-max)))
10625 (insert-file-contents file)
10626 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
10627
10628 (defun org-table-export ()
10629 "Export table as a tab-separated file.
10630 Such a file can be imported into a spreadsheet program like Excel."
10631 (interactive)
10632 (let* ((beg (org-table-begin))
10633 (end (org-table-end))
10634 (table (buffer-substring beg end))
10635 (file (read-file-name "Export table to: "))
10636 buf)
10637 (unless (or (not (file-exists-p file))
10638 (y-or-n-p (format "Overwrite file %s? " file)))
10639 (error "Abort"))
10640 (with-current-buffer (find-file-noselect file)
10641 (setq buf (current-buffer))
10642 (erase-buffer)
10643 (fundamental-mode)
10644 (insert table)
10645 (goto-char (point-min))
10646 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
10647 (replace-match "" t t)
10648 (end-of-line 1))
10649 (goto-char (point-min))
10650 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
10651 (replace-match "" t t)
10652 (goto-char (min (1+ (point)) (point-max))))
10653 (goto-char (point-min))
10654 (while (re-search-forward "^-[-+]*$" nil t)
10655 (replace-match "")
10656 (if (looking-at "\n")
10657 (delete-char 1)))
10658 (goto-char (point-min))
10659 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
10660 (replace-match "\t" t t))
10661 (save-buffer))
10662 (kill-buffer buf)))
10663
10664 (defvar org-table-aligned-begin-marker (make-marker)
10665 "Marker at the beginning of the table last aligned.
10666 Used to check if cursor still is in that table, to minimize realignment.")
10667 (defvar org-table-aligned-end-marker (make-marker)
10668 "Marker at the end of the table last aligned.
10669 Used to check if cursor still is in that table, to minimize realignment.")
10670 (defvar org-table-last-alignment nil
10671 "List of flags for flushright alignment, from the last re-alignment.
10672 This is being used to correctly align a single field after TAB or RET.")
10673 (defvar org-table-last-column-widths nil
10674 "List of max width of fields in each column.
10675 This is being used to correctly align a single field after TAB or RET.")
10676
10677 (defvar org-last-recalc-line nil)
10678 (defconst org-narrow-column-arrow "=>"
10679 "Used as display property in narrowed table columns.")
10680
10681 (defun org-table-align ()
10682 "Align the table at point by aligning all vertical bars."
10683 (interactive)
10684 (let* (
10685 ;; Limits of table
10686 (beg (org-table-begin))
10687 (end (org-table-end))
10688 ;; Current cursor position
10689 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10690 (colpos (org-table-current-column))
10691 (winstart (window-start))
10692 lines (new "") lengths l typenums ty fields maxfields i
10693 column
10694 (indent "") cnt frac
10695 rfmt hfmt
10696 (spaces '(1 . 1))
10697 (sp1 (car spaces))
10698 (sp2 (cdr spaces))
10699 (rfmt1 (concat
10700 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
10701 (hfmt1 (concat
10702 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
10703 emptystrings links narrow fmax f1 len c e)
10704 (untabify beg end)
10705 (remove-text-properties beg end '(org-cwidth t display t))
10706 ;; Check if we have links
10707 (goto-char beg)
10708 (setq links (re-search-forward org-bracket-link-regexp end t))
10709 ;; Make sure the link properties are right
10710 (when links (goto-char beg) (while (org-activate-bracket-links end)))
10711 ;; Check if we are narrowing any columns
10712 (goto-char beg)
10713 (setq narrow (and org-format-transports-properties-p
10714 (re-search-forward "<[0-9]+>" end t)))
10715 ;; Get the rows
10716 (setq lines (org-split-string
10717 (buffer-substring beg end) "\n"))
10718 ;; Store the indentation of the first line
10719 (if (string-match "^ *" (car lines))
10720 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
10721 ;; Mark the hlines by setting the corresponding element to nil
10722 ;; At the same time, we remove trailing space.
10723 (setq lines (mapcar (lambda (l)
10724 (if (string-match "^ *|-" l)
10725 nil
10726 (if (string-match "[ \t]+$" l)
10727 (substring l 0 (match-beginning 0))
10728 l)))
10729 lines))
10730 ;; Get the data fields by splitting the lines.
10731 (setq fields (mapcar
10732 (lambda (l)
10733 (org-split-string l " *| *"))
10734 (delq nil (copy-sequence lines))))
10735 ;; How many fields in the longest line?
10736 (condition-case nil
10737 (setq maxfields (apply 'max (mapcar 'length fields)))
10738 (error
10739 (kill-region beg end)
10740 (org-table-create org-table-default-size)
10741 (error "Empty table - created default table")))
10742 ;; A list of empty string to fill any short rows on output
10743 (setq emptystrings (make-list maxfields ""))
10744 ;; Check for special formatting.
10745 (setq i -1)
10746 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
10747 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
10748 ;; Check if there is an explicit width specified
10749 (when (and org-table-limit-column-width narrow)
10750 (setq c column fmax nil)
10751 (while c
10752 (setq e (pop c))
10753 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
10754 (setq fmax (string-to-number (match-string 1 e)) c nil)))
10755 ;; Find fields that are wider than fmax, and shorten them
10756 (when fmax
10757 (loop for xx in column do
10758 (when (and (stringp xx)
10759 (> (org-string-width xx) fmax))
10760 (org-add-props xx nil
10761 'help-echo
10762 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
10763 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
10764 (unless (> f1 1)
10765 (error "Cannot narrow field starting with wide link \"%s\""
10766 (match-string 0 xx)))
10767 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
10768 (add-text-properties (- f1 2) f1
10769 (list 'display org-narrow-column-arrow)
10770 xx)))))
10771 ;; Get the maximum width for each column
10772 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
10773 ;; Get the fraction of numbers, to decide about alignment of the column
10774 (setq cnt 0 frac 0.0)
10775 (loop for x in column do
10776 (if (equal x "")
10777 nil
10778 (setq frac ( / (+ (* frac cnt)
10779 (if (string-match org-table-number-regexp x) 1 0))
10780 (setq cnt (1+ cnt))))))
10781 (push (>= frac org-table-number-fraction) typenums))
10782 (setq lengths (nreverse lengths) typenums (nreverse typenums))
10783
10784 ;; Store the alignment of this table, for later editing of single fields
10785 (setq org-table-last-alignment typenums
10786 org-table-last-column-widths lengths)
10787
10788 ;; With invisible characters, `format' does not get the field width right
10789 ;; So we need to make these fields wide by hand.
10790 (when links
10791 (loop for i from 0 upto (1- maxfields) do
10792 (setq len (nth i lengths))
10793 (loop for j from 0 upto (1- (length fields)) do
10794 (setq c (nthcdr i (car (nthcdr j fields))))
10795 (if (and (stringp (car c))
10796 (string-match org-bracket-link-regexp (car c))
10797 (< (org-string-width (car c)) len))
10798 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
10799
10800 ;; Compute the formats needed for output of the table
10801 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
10802 (while (setq l (pop lengths))
10803 (setq ty (if (pop typenums) "" "-")) ; number types flushright
10804 (setq rfmt (concat rfmt (format rfmt1 ty l))
10805 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
10806 (setq rfmt (concat rfmt "\n")
10807 hfmt (concat (substring hfmt 0 -1) "|\n"))
10808
10809 (setq new (mapconcat
10810 (lambda (l)
10811 (if l (apply 'format rfmt
10812 (append (pop fields) emptystrings))
10813 hfmt))
10814 lines ""))
10815 ;; Replace the old one
10816 (delete-region beg end)
10817 (move-marker end nil)
10818 (move-marker org-table-aligned-begin-marker (point))
10819 (insert new)
10820 (move-marker org-table-aligned-end-marker (point))
10821 (when (and orgtbl-mode (not (org-mode-p)))
10822 (goto-char org-table-aligned-begin-marker)
10823 (while (org-hide-wide-columns org-table-aligned-end-marker)))
10824 ;; Try to move to the old location (approximately)
10825 (goto-line linepos)
10826 (set-window-start (selected-window) winstart 'noforce)
10827 (org-table-goto-column colpos)
10828 (setq org-table-may-need-update nil)
10829 ))
10830
10831 (defun org-string-width (s)
10832 "Compute width of string, ignoring invisible characters.
10833 This ignores character with invisibility property `org-link', and also
10834 characters with property `org-cwidth', because these will become invisible
10835 upon the next fontification round."
10836 (let (b)
10837 (when (or (eq t buffer-invisibility-spec)
10838 (assq 'org-link buffer-invisibility-spec))
10839 (while (setq b (text-property-any 0 (length s)
10840 'invisible 'org-link s))
10841 (setq s (concat (substring s 0 b)
10842 (substring s (or (next-single-property-change
10843 b 'invisible s) (length s)))))))
10844 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
10845 (setq s (concat (substring s 0 b)
10846 (substring s (or (next-single-property-change
10847 b 'org-cwidth s) (length s))))))
10848 (string-width s)))
10849
10850 (defun org-table-begin (&optional table-type)
10851 "Find the beginning of the table and return its position.
10852 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
10853 (save-excursion
10854 (if (not (re-search-backward
10855 (if table-type org-table-any-border-regexp
10856 org-table-border-regexp)
10857 nil t))
10858 (progn (goto-char (point-min)) (point))
10859 (goto-char (match-beginning 0))
10860 (beginning-of-line 2)
10861 (point))))
10862
10863 (defun org-table-end (&optional table-type)
10864 "Find the end of the table and return its position.
10865 With argument TABLE-TYPE, go to the end of a table.el-type table."
10866 (save-excursion
10867 (if (not (re-search-forward
10868 (if table-type org-table-any-border-regexp
10869 org-table-border-regexp)
10870 nil t))
10871 (goto-char (point-max))
10872 (goto-char (match-beginning 0)))
10873 (point-marker)))
10874
10875 (defun org-table-justify-field-maybe (&optional new)
10876 "Justify the current field, text to left, number to right.
10877 Optional argument NEW may specify text to replace the current field content."
10878 (cond
10879 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
10880 ((org-at-table-hline-p))
10881 ((and (not new)
10882 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
10883 (current-buffer)))
10884 (< (point) org-table-aligned-begin-marker)
10885 (>= (point) org-table-aligned-end-marker)))
10886 ;; This is not the same table, force a full re-align
10887 (setq org-table-may-need-update t))
10888 (t ;; realign the current field, based on previous full realign
10889 (let* ((pos (point)) s
10890 (col (org-table-current-column))
10891 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
10892 l f n o e)
10893 (when (> col 0)
10894 (skip-chars-backward "^|\n")
10895 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
10896 (progn
10897 (setq s (match-string 1)
10898 o (match-string 0)
10899 l (max 1 (- (match-end 0) (match-beginning 0) 3))
10900 e (not (= (match-beginning 2) (match-end 2))))
10901 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
10902 l (if e "|" (setq org-table-may-need-update t) ""))
10903 n (format f s))
10904 (if new
10905 (if (<= (length new) l) ;; FIXME: length -> str-width?
10906 (setq n (format f new))
10907 (setq n (concat new "|") org-table-may-need-update t)))
10908 (or (equal n o)
10909 (let (org-table-may-need-update)
10910 (replace-match n))))
10911 (setq org-table-may-need-update t))
10912 (goto-char pos))))))
10913
10914 (defun org-table-next-field ()
10915 "Go to the next field in the current table, creating new lines as needed.
10916 Before doing so, re-align the table if necessary."
10917 (interactive)
10918 (org-table-maybe-eval-formula)
10919 (org-table-maybe-recalculate-line)
10920 (if (and org-table-automatic-realign
10921 org-table-may-need-update)
10922 (org-table-align))
10923 (let ((end (org-table-end)))
10924 (if (org-at-table-hline-p)
10925 (end-of-line 1))
10926 (condition-case nil
10927 (progn
10928 (re-search-forward "|" end)
10929 (if (looking-at "[ \t]*$")
10930 (re-search-forward "|" end))
10931 (if (and (looking-at "-")
10932 org-table-tab-jumps-over-hlines
10933 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
10934 (goto-char (match-beginning 1)))
10935 (if (looking-at "-")
10936 (progn
10937 (beginning-of-line 0)
10938 (org-table-insert-row 'below))
10939 (if (looking-at " ") (forward-char 1))))
10940 (error
10941 (org-table-insert-row 'below)))))
10942
10943 (defun org-table-previous-field ()
10944 "Go to the previous field in the table.
10945 Before doing so, re-align the table if necessary."
10946 (interactive)
10947 (org-table-justify-field-maybe)
10948 (org-table-maybe-recalculate-line)
10949 (if (and org-table-automatic-realign
10950 org-table-may-need-update)
10951 (org-table-align))
10952 (if (org-at-table-hline-p)
10953 (end-of-line 1))
10954 (re-search-backward "|" (org-table-begin))
10955 (re-search-backward "|" (org-table-begin))
10956 (while (looking-at "|\\(-\\|[ \t]*$\\)")
10957 (re-search-backward "|" (org-table-begin)))
10958 (if (looking-at "| ?")
10959 (goto-char (match-end 0))))
10960
10961 (defun org-table-next-row ()
10962 "Go to the next row (same column) in the current table.
10963 Before doing so, re-align the table if necessary."
10964 (interactive)
10965 (org-table-maybe-eval-formula)
10966 (org-table-maybe-recalculate-line)
10967 (if (or (looking-at "[ \t]*$")
10968 (save-excursion (skip-chars-backward " \t") (bolp)))
10969 (newline)
10970 (if (and org-table-automatic-realign
10971 org-table-may-need-update)
10972 (org-table-align))
10973 (let ((col (org-table-current-column)))
10974 (beginning-of-line 2)
10975 (if (or (not (org-at-table-p))
10976 (org-at-table-hline-p))
10977 (progn
10978 (beginning-of-line 0)
10979 (org-table-insert-row 'below)))
10980 (org-table-goto-column col)
10981 (skip-chars-backward "^|\n\r")
10982 (if (looking-at " ") (forward-char 1)))))
10983
10984 (defun org-table-copy-down (n)
10985 "Copy a field down in the current column.
10986 If the field at the cursor is empty, copy into it the content of the nearest
10987 non-empty field above. With argument N, use the Nth non-empty field.
10988 If the current field is not empty, it is copied down to the next row, and
10989 the cursor is moved with it. Therefore, repeating this command causes the
10990 column to be filled row-by-row.
10991 If the variable `org-table-copy-increment' is non-nil and the field is an
10992 integer, it will be incremented while copying."
10993 (interactive "p")
10994 (let* ((colpos (org-table-current-column))
10995 (field (org-table-get-field))
10996 (non-empty (string-match "[^ \t]" field))
10997 (beg (org-table-begin))
10998 txt)
10999 (org-table-check-inside-data-field)
11000 (if non-empty
11001 (progn
11002 (setq txt (org-trim field))
11003 (org-table-next-row)
11004 (org-table-blank-field))
11005 (save-excursion
11006 (setq txt
11007 (catch 'exit
11008 (while (progn (beginning-of-line 1)
11009 (re-search-backward org-table-dataline-regexp
11010 beg t))
11011 (org-table-goto-column colpos t)
11012 (if (and (looking-at
11013 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
11014 (= (setq n (1- n)) 0))
11015 (throw 'exit (match-string 1))))))))
11016 (if txt
11017 (progn
11018 (if (and org-table-copy-increment
11019 (string-match "^[0-9]+$" txt))
11020 (setq txt (format "%d" (+ (string-to-number txt) 1))))
11021 (insert txt)
11022 (org-table-maybe-recalculate-line)
11023 (org-table-align))
11024 (error "No non-empty field found"))))
11025
11026 (defun org-table-check-inside-data-field ()
11027 "Is point inside a table data field?
11028 I.e. not on a hline or before the first or after the last column?
11029 This actually throws an error, so it aborts the current command."
11030 (if (or (not (org-at-table-p))
11031 (= (org-table-current-column) 0)
11032 (org-at-table-hline-p)
11033 (looking-at "[ \t]*$"))
11034 (error "Not in table data field")))
11035
11036 (defvar org-table-clip nil
11037 "Clipboard for table regions.")
11038
11039 (defun org-table-blank-field ()
11040 "Blank the current table field or active region."
11041 (interactive)
11042 (org-table-check-inside-data-field)
11043 (if (and (interactive-p) (org-region-active-p))
11044 (let (org-table-clip)
11045 (org-table-cut-region (region-beginning) (region-end)))
11046 (skip-chars-backward "^|")
11047 (backward-char 1)
11048 (if (looking-at "|[^|\n]+")
11049 (let* ((pos (match-beginning 0))
11050 (match (match-string 0))
11051 (len (org-string-width match)))
11052 (replace-match (concat "|" (make-string (1- len) ?\ )))
11053 (goto-char (+ 2 pos))
11054 (substring match 1)))))
11055
11056 (defun org-table-get-field (&optional n replace)
11057 "Return the value of the field in column N of current row.
11058 N defaults to current field.
11059 If REPLACE is a string, replace field with this value. The return value
11060 is always the old value."
11061 (and n (org-table-goto-column n))
11062 (skip-chars-backward "^|\n")
11063 (backward-char 1)
11064 (if (looking-at "|[^|\r\n]*")
11065 (let* ((pos (match-beginning 0))
11066 (val (buffer-substring (1+ pos) (match-end 0))))
11067 (if replace
11068 (replace-match (concat "|" replace)))
11069 (goto-char (min (point-at-eol) (+ 2 pos)))
11070 val)
11071 (forward-char 1) ""))
11072
11073 (defun org-table-current-column ()
11074 "Find out which column we are in.
11075 When called interactively, column is also displayed in echo area."
11076 (interactive)
11077 (if (interactive-p) (org-table-check-inside-data-field))
11078 (save-excursion
11079 (let ((cnt 0) (pos (point)))
11080 (beginning-of-line 1)
11081 (while (search-forward "|" pos t)
11082 (setq cnt (1+ cnt)))
11083 (if (interactive-p) (message "This is table column %d" cnt))
11084 cnt)))
11085
11086 (defun org-table-goto-column (n &optional on-delim force)
11087 "Move the cursor to the Nth column in the current table line.
11088 With optional argument ON-DELIM, stop with point before the left delimiter
11089 of the field.
11090 If there are less than N fields, just go to after the last delimiter.
11091 However, when FORCE is non-nil, create new columns if necessary."
11092 (interactive "p")
11093 (let ((pos (point-at-eol)))
11094 (beginning-of-line 1)
11095 (when (> n 0)
11096 (while (and (> (setq n (1- n)) -1)
11097 (or (search-forward "|" pos t)
11098 (and force
11099 (progn (end-of-line 1)
11100 (skip-chars-backward "^|")
11101 (insert " | "))))))
11102 ; (backward-char 2) t)))))
11103 (when (and force (not (looking-at ".*|")))
11104 (save-excursion (end-of-line 1) (insert " | ")))
11105 (if on-delim
11106 (backward-char 1)
11107 (if (looking-at " ") (forward-char 1))))))
11108
11109 (defun org-at-table-p (&optional table-type)
11110 "Return t if the cursor is inside an org-type table.
11111 If TABLE-TYPE is non-nil, also check for table.el-type tables."
11112 (if org-enable-table-editor
11113 (save-excursion
11114 (beginning-of-line 1)
11115 (looking-at (if table-type org-table-any-line-regexp
11116 org-table-line-regexp)))
11117 nil))
11118
11119 (defun org-at-table.el-p ()
11120 "Return t if and only if we are at a table.el table."
11121 (and (org-at-table-p 'any)
11122 (save-excursion
11123 (goto-char (org-table-begin 'any))
11124 (looking-at org-table1-hline-regexp))))
11125
11126 (defun org-table-recognize-table.el ()
11127 "If there is a table.el table nearby, recognize it and move into it."
11128 (if org-table-tab-recognizes-table.el
11129 (if (org-at-table.el-p)
11130 (progn
11131 (beginning-of-line 1)
11132 (if (looking-at org-table-dataline-regexp)
11133 nil
11134 (if (looking-at org-table1-hline-regexp)
11135 (progn
11136 (beginning-of-line 2)
11137 (if (looking-at org-table-any-border-regexp)
11138 (beginning-of-line -1)))))
11139 (if (re-search-forward "|" (org-table-end t) t)
11140 (progn
11141 (require 'table)
11142 (if (table--at-cell-p (point))
11143 t
11144 (message "recognizing table.el table...")
11145 (table-recognize-table)
11146 (message "recognizing table.el table...done")))
11147 (error "This should not happen..."))
11148 t)
11149 nil)
11150 nil))
11151
11152 (defun org-at-table-hline-p ()
11153 "Return t if the cursor is inside a hline in a table."
11154 (if org-enable-table-editor
11155 (save-excursion
11156 (beginning-of-line 1)
11157 (looking-at org-table-hline-regexp))
11158 nil))
11159
11160 (defun org-table-insert-column ()
11161 "Insert a new column into the table."
11162 (interactive)
11163 (if (not (org-at-table-p))
11164 (error "Not at a table"))
11165 (org-table-find-dataline)
11166 (let* ((col (max 1 (org-table-current-column)))
11167 (beg (org-table-begin))
11168 (end (org-table-end))
11169 ;; Current cursor position
11170 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11171 (colpos col))
11172 (goto-char beg)
11173 (while (< (point) end)
11174 (if (org-at-table-hline-p)
11175 nil
11176 (org-table-goto-column col t)
11177 (insert "| "))
11178 (beginning-of-line 2))
11179 (move-marker end nil)
11180 (goto-line linepos)
11181 (org-table-goto-column colpos)
11182 (org-table-align)
11183 (org-table-modify-formulas 'insert col)))
11184
11185 (defun org-table-find-dataline ()
11186 "Find a dataline in the current table, which is needed for column commands."
11187 (if (and (org-at-table-p)
11188 (not (org-at-table-hline-p)))
11189 t
11190 (let ((col (current-column))
11191 (end (org-table-end)))
11192 (move-to-column col)
11193 (while (and (< (point) end)
11194 (or (not (= (current-column) col))
11195 (org-at-table-hline-p)))
11196 (beginning-of-line 2)
11197 (move-to-column col))
11198 (if (and (org-at-table-p)
11199 (not (org-at-table-hline-p)))
11200 t
11201 (error
11202 "Please position cursor in a data line for column operations")))))
11203
11204 (defun org-table-delete-column ()
11205 "Delete a column from the table."
11206 (interactive)
11207 (if (not (org-at-table-p))
11208 (error "Not at a table"))
11209 (org-table-find-dataline)
11210 (org-table-check-inside-data-field)
11211 (let* ((col (org-table-current-column))
11212 (beg (org-table-begin))
11213 (end (org-table-end))
11214 ;; Current cursor position
11215 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11216 (colpos col))
11217 (goto-char beg)
11218 (while (< (point) end)
11219 (if (org-at-table-hline-p)
11220 nil
11221 (org-table-goto-column col t)
11222 (and (looking-at "|[^|\n]+|")
11223 (replace-match "|")))
11224 (beginning-of-line 2))
11225 (move-marker end nil)
11226 (goto-line linepos)
11227 (org-table-goto-column colpos)
11228 (org-table-align)
11229 (org-table-modify-formulas 'remove col)))
11230
11231 (defun org-table-move-column-right ()
11232 "Move column to the right."
11233 (interactive)
11234 (org-table-move-column nil))
11235 (defun org-table-move-column-left ()
11236 "Move column to the left."
11237 (interactive)
11238 (org-table-move-column 'left))
11239
11240 (defun org-table-move-column (&optional left)
11241 "Move the current column to the right. With arg LEFT, move to the left."
11242 (interactive "P")
11243 (if (not (org-at-table-p))
11244 (error "Not at a table"))
11245 (org-table-find-dataline)
11246 (org-table-check-inside-data-field)
11247 (let* ((col (org-table-current-column))
11248 (col1 (if left (1- col) col))
11249 (beg (org-table-begin))
11250 (end (org-table-end))
11251 ;; Current cursor position
11252 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11253 (colpos (if left (1- col) (1+ col))))
11254 (if (and left (= col 1))
11255 (error "Cannot move column further left"))
11256 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
11257 (error "Cannot move column further right"))
11258 (goto-char beg)
11259 (while (< (point) end)
11260 (if (org-at-table-hline-p)
11261 nil
11262 (org-table-goto-column col1 t)
11263 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
11264 (replace-match "|\\2|\\1|")))
11265 (beginning-of-line 2))
11266 (move-marker end nil)
11267 (goto-line linepos)
11268 (org-table-goto-column colpos)
11269 (org-table-align)
11270 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
11271
11272 (defun org-table-move-row-down ()
11273 "Move table row down."
11274 (interactive)
11275 (org-table-move-row nil))
11276 (defun org-table-move-row-up ()
11277 "Move table row up."
11278 (interactive)
11279 (org-table-move-row 'up))
11280
11281 (defun org-table-move-row (&optional up)
11282 "Move the current table line down. With arg UP, move it up."
11283 (interactive "P")
11284 (let ((col (current-column))
11285 (pos (point))
11286 (tonew (if up 0 2))
11287 txt)
11288 (beginning-of-line tonew)
11289 (if (not (org-at-table-p))
11290 (progn
11291 (goto-char pos)
11292 (error "Cannot move row further")))
11293 (goto-char pos)
11294 (beginning-of-line 1)
11295 (setq pos (point))
11296 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
11297 (delete-region (point) (1+ (point-at-eol)))
11298 (beginning-of-line tonew)
11299 (insert txt)
11300 (beginning-of-line 0)
11301 (move-to-column col)))
11302
11303 (defun org-table-insert-row (&optional arg)
11304 "Insert a new row above the current line into the table.
11305 With prefix ARG, insert below the current line."
11306 (interactive "P")
11307 (if (not (org-at-table-p))
11308 (error "Not at a table"))
11309 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
11310 (new (org-table-clean-line line)))
11311 ;; Fix the first field if necessary
11312 (if (string-match "^[ \t]*| *[#$] *|" line)
11313 (setq new (replace-match (match-string 0 line) t t new)))
11314 (beginning-of-line (if arg 2 1))
11315 (let (org-table-may-need-update) (insert-before-markers new "\n"))
11316 (beginning-of-line 0)
11317 (re-search-forward "| ?" (point-at-eol) t)
11318 (and org-table-may-need-update (org-table-align))))
11319
11320 (defun org-table-insert-hline (&optional arg)
11321 "Insert a horizontal-line below the current line into the table.
11322 With prefix ARG, insert above the current line."
11323 (interactive "P")
11324 (if (not (org-at-table-p))
11325 (error "Not at a table"))
11326 (let ((line (org-table-clean-line
11327 (buffer-substring (point-at-bol) (point-at-eol))))
11328 (col (current-column)))
11329 (while (string-match "|\\( +\\)|" line)
11330 (setq line (replace-match
11331 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
11332 ?-) "|") t t line)))
11333 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
11334 (beginning-of-line (if arg 1 2))
11335 (insert line "\n")
11336 (beginning-of-line (if arg 1 -1))
11337 (move-to-column col)))
11338
11339 (defun org-table-clean-line (s)
11340 "Convert a table line S into a string with only \"|\" and space.
11341 In particular, this does handle wide and invisible characters."
11342 (if (string-match "^[ \t]*|-" s)
11343 ;; It's a hline, just map the characters
11344 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
11345 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
11346 (setq s (replace-match
11347 (concat "|" (make-string (org-string-width (match-string 1 s))
11348 ?\ ) "|")
11349 t t s)))
11350 s))
11351
11352 (defun org-table-kill-row ()
11353 "Delete the current row or horizontal line from the table."
11354 (interactive)
11355 (if (not (org-at-table-p))
11356 (error "Not at a table"))
11357 (let ((col (current-column)))
11358 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
11359 (if (not (org-at-table-p)) (beginning-of-line 0))
11360 (move-to-column col)))
11361
11362 (defun org-table-sort-lines (beg end numericp)
11363 "Sort table lines in region.
11364 Point and mark define the first and last line to include. Both point and
11365 mark should be in the column that is used for sorting. For example, to
11366 sort according to column 3, put the mark in the first line to sort, in
11367 table column 3. Put point into the last line to be included in the sorting,
11368 also in table column 3. The command will prompt for the sorting method
11369 \(n for numerical, a for alphanumeric)."
11370 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
11371 (setq numericp (string-match "[nN]" numericp))
11372 (org-table-align) ;; Just to be safe
11373 (let* (bcol ecol cmp column lns)
11374 (goto-char beg)
11375 (org-table-check-inside-data-field)
11376 (setq column (org-table-current-column)
11377 beg (move-marker (make-marker) (point-at-bol)))
11378 (goto-char end)
11379 (org-table-check-inside-data-field)
11380 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
11381 (untabify beg end)
11382 (goto-char beg)
11383 (org-table-goto-column column)
11384 (skip-chars-backward "^|")
11385 (setq bcol (current-column))
11386 (org-table-goto-column (1+ column))
11387 (skip-chars-backward "^|")
11388 (setq ecol (1- (current-column)))
11389 (setq cmp (if numericp
11390 (lambda (a b) (< (car a) (car b)))
11391 (lambda (a b) (string< (car a) (car b)))))
11392 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
11393 (org-split-string (buffer-substring beg end) "\n")))
11394 (if numericp
11395 (setq lns (mapcar (lambda(x)
11396 (cons (string-to-number (car x)) (cdr x)))
11397 lns)))
11398 (delete-region beg end)
11399 (move-marker beg nil)
11400 (move-marker end nil)
11401 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
11402 (message "%d lines sorted %s based on column %d"
11403 (length lns)
11404 (if numericp "numerically" "alphabetically") column)))
11405
11406 (defun org-table-cut-region (beg end)
11407 "Copy region in table to the clipboard and blank all relevant fields."
11408 (interactive "r")
11409 (org-table-copy-region beg end 'cut))
11410
11411 (defun org-table-copy-region (beg end &optional cut)
11412 "Copy rectangular region in table to clipboard.
11413 A special clipboard is used which can only be accessed
11414 with `org-table-paste-rectangle'."
11415 (interactive "rP")
11416 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
11417 region cols
11418 (rpl (if cut " " nil)))
11419 (goto-char beg)
11420 (org-table-check-inside-data-field)
11421 (setq l01 (count-lines (point-min) (point))
11422 c01 (org-table-current-column))
11423 (goto-char end)
11424 (org-table-check-inside-data-field)
11425 (setq l02 (count-lines (point-min) (point))
11426 c02 (org-table-current-column))
11427 (setq l1 (min l01 l02) l2 (max l01 l02)
11428 c1 (min c01 c02) c2 (max c01 c02))
11429 (catch 'exit
11430 (while t
11431 (catch 'nextline
11432 (if (> l1 l2) (throw 'exit t))
11433 (goto-line l1)
11434 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
11435 (setq cols nil ic1 c1 ic2 c2)
11436 (while (< ic1 (1+ ic2))
11437 (push (org-table-get-field ic1 rpl) cols)
11438 (setq ic1 (1+ ic1)))
11439 (push (nreverse cols) region)
11440 (setq l1 (1+ l1)))))
11441 (setq org-table-clip (nreverse region))
11442 (if cut (org-table-align))
11443 org-table-clip))
11444
11445 (defun org-table-paste-rectangle ()
11446 "Paste a rectangular region into a table.
11447 The upper right corner ends up in the current field. All involved fields
11448 will be overwritten. If the rectangle does not fit into the present table,
11449 the table is enlarged as needed. The process ignores horizontal separator
11450 lines."
11451 (interactive)
11452 (unless (and org-table-clip (listp org-table-clip))
11453 (error "First cut/copy a region to paste!"))
11454 (org-table-check-inside-data-field)
11455 (let* ((clip org-table-clip)
11456 (line (count-lines (point-min) (point)))
11457 (col (org-table-current-column))
11458 (org-enable-table-editor t)
11459 (org-table-automatic-realign nil)
11460 c cols field)
11461 (while (setq cols (pop clip))
11462 (while (org-at-table-hline-p) (beginning-of-line 2))
11463 (if (not (org-at-table-p))
11464 (progn (end-of-line 0) (org-table-next-field)))
11465 (setq c col)
11466 (while (setq field (pop cols))
11467 (org-table-goto-column c nil 'force)
11468 (org-table-get-field nil field)
11469 (setq c (1+ c)))
11470 (beginning-of-line 2))
11471 (goto-line line)
11472 (org-table-goto-column col)
11473 (org-table-align)))
11474
11475 (defun org-table-convert ()
11476 "Convert from `org-mode' table to table.el and back.
11477 Obviously, this only works within limits. When an Org-mode table is
11478 converted to table.el, all horizontal separator lines get lost, because
11479 table.el uses these as cell boundaries and has no notion of horizontal lines.
11480 A table.el table can be converted to an Org-mode table only if it does not
11481 do row or column spanning. Multiline cells will become multiple cells.
11482 Beware, Org-mode does not test if the table can be successfully converted - it
11483 blindly applies a recipe that works for simple tables."
11484 (interactive)
11485 (require 'table)
11486 (if (org-at-table.el-p)
11487 ;; convert to Org-mode table
11488 (let ((beg (move-marker (make-marker) (org-table-begin t)))
11489 (end (move-marker (make-marker) (org-table-end t))))
11490 (table-unrecognize-region beg end)
11491 (goto-char beg)
11492 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
11493 (replace-match ""))
11494 (goto-char beg))
11495 (if (org-at-table-p)
11496 ;; convert to table.el table
11497 (let ((beg (move-marker (make-marker) (org-table-begin)))
11498 (end (move-marker (make-marker) (org-table-end))))
11499 ;; first, get rid of all horizontal lines
11500 (goto-char beg)
11501 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
11502 (replace-match ""))
11503 ;; insert a hline before first
11504 (goto-char beg)
11505 (org-table-insert-hline 'above)
11506 (beginning-of-line -1)
11507 ;; insert a hline after each line
11508 (while (progn (beginning-of-line 3) (< (point) end))
11509 (org-table-insert-hline))
11510 (goto-char beg)
11511 (setq end (move-marker end (org-table-end)))
11512 ;; replace "+" at beginning and ending of hlines
11513 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
11514 (replace-match "\\1+-"))
11515 (goto-char beg)
11516 (while (re-search-forward "-|[ \t]*$" end t)
11517 (replace-match "-+"))
11518 (goto-char beg)))))
11519
11520 (defun org-table-wrap-region (arg)
11521 "Wrap several fields in a column like a paragraph.
11522 This is useful if you'd like to spread the contents of a field over several
11523 lines, in order to keep the table compact.
11524
11525 If there is an active region, and both point and mark are in the same column,
11526 the text in the column is wrapped to minimum width for the given number of
11527 lines. Generally, this makes the table more compact. A prefix ARG may be
11528 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
11529 formats the selected text to two lines. If the region was longer than two
11530 lines, the remaining lines remain empty. A negative prefix argument reduces
11531 the current number of lines by that amount. The wrapped text is pasted back
11532 into the table. If you formatted it to more lines than it was before, fields
11533 further down in the table get overwritten - so you might need to make space in
11534 the table first.
11535
11536 If there is no region, the current field is split at the cursor position and
11537 the text fragment to the right of the cursor is prepended to the field one
11538 line down.
11539
11540 If there is no region, but you specify a prefix ARG, the current field gets
11541 blank, and the content is appended to the field above."
11542 (interactive "P")
11543 (org-table-check-inside-data-field)
11544 (if (org-region-active-p)
11545 ;; There is a region: fill as a paragraph
11546 (let ((beg (region-beginning))
11547 nlines)
11548 (org-table-cut-region (region-beginning) (region-end))
11549 (if (> (length (car org-table-clip)) 1)
11550 (error "Region must be limited to single column"))
11551 (setq nlines (if arg
11552 (if (< arg 1)
11553 (+ (length org-table-clip) arg)
11554 arg)
11555 (length org-table-clip)))
11556 (setq org-table-clip
11557 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
11558 nil nlines)))
11559 (goto-char beg)
11560 (org-table-paste-rectangle))
11561 ;; No region, split the current field at point
11562 (if arg
11563 ;; combine with field above
11564 (let ((s (org-table-blank-field))
11565 (col (org-table-current-column)))
11566 (beginning-of-line 0)
11567 (while (org-at-table-hline-p) (beginning-of-line 0))
11568 (org-table-goto-column col)
11569 (skip-chars-forward "^|")
11570 (skip-chars-backward " ")
11571 (insert " " (org-trim s))
11572 (org-table-align))
11573 ;; split field
11574 (when (looking-at "\\([^|]+\\)+|")
11575 (let ((s (match-string 1)))
11576 (replace-match " |")
11577 (goto-char (match-beginning 0))
11578 (org-table-next-row)
11579 (insert (org-trim s) " ")
11580 (org-table-align))))))
11581
11582 (defvar org-field-marker nil)
11583
11584 (defun org-table-edit-field (arg)
11585 "Edit table field in a different window.
11586 This is mainly useful for fields that contain hidden parts.
11587 When called with a \\[universal-argument] prefix, just make the full field visible so that
11588 it can be edited in place."
11589 (interactive "P")
11590 (if arg
11591 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
11592 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
11593 (remove-text-properties b e '(org-cwidth t invisible t
11594 display t intangible t))
11595 (if (and (boundp 'font-lock-mode) font-lock-mode)
11596 (font-lock-fontify-block)))
11597 (let ((pos (move-marker (make-marker) (point)))
11598 (field (org-table-get-field))
11599 (cw (current-window-configuration))
11600 p)
11601 (switch-to-buffer-other-window "*Org tmp*")
11602 (erase-buffer)
11603 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
11604 (org-mode)
11605 (goto-char (setq p (point-max)))
11606 (insert (org-trim field))
11607 (remove-text-properties p (point-max)
11608 '(invisible t org-cwidth t display t
11609 intangible t))
11610 (goto-char p)
11611 (org-set-local 'org-finish-function
11612 'org-table-finish-edit-field)
11613 (org-set-local 'org-window-configuration cw)
11614 (org-set-local 'org-field-marker pos)
11615 (message "Edit and finish with C-c C-c"))))
11616
11617 (defun org-table-finish-edit-field ()
11618 "Finish editing a table data field.
11619 Remove all newline characters, insert the result into the table, realign
11620 the table and kill the editing buffer."
11621 (let ((pos org-field-marker)
11622 (cw org-window-configuration)
11623 (cb (current-buffer))
11624 text)
11625 (goto-char (point-min))
11626 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
11627 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
11628 (replace-match " "))
11629 (setq text (org-trim (buffer-string)))
11630 (set-window-configuration cw)
11631 (kill-buffer cb)
11632 (select-window (get-buffer-window (marker-buffer pos)))
11633 (goto-char pos)
11634 (move-marker pos nil)
11635 (org-table-check-inside-data-field)
11636 (org-table-get-field nil text)
11637 (org-table-align)
11638 (message "New field value inserted")))
11639
11640 (defun org-trim (s)
11641 "Remove whitespace at beginning and end of string."
11642 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
11643 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
11644 s)
11645
11646 (defun org-wrap (string &optional width lines)
11647 "Wrap string to either a number of lines, or a width in characters.
11648 If WIDTH is non-nil, the string is wrapped to that width, however many lines
11649 that costs. If there is a word longer than WIDTH, the text is actually
11650 wrapped to the length of that word.
11651 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
11652 many lines, whatever width that takes.
11653 The return value is a list of lines, without newlines at the end."
11654 (let* ((words (org-split-string string "[ \t\n]+"))
11655 (maxword (apply 'max (mapcar 'org-string-width words)))
11656 w ll)
11657 (cond (width
11658 (org-do-wrap words (max maxword width)))
11659 (lines
11660 (setq w maxword)
11661 (setq ll (org-do-wrap words maxword))
11662 (if (<= (length ll) lines)
11663 ll
11664 (setq ll words)
11665 (while (> (length ll) lines)
11666 (setq w (1+ w))
11667 (setq ll (org-do-wrap words w)))
11668 ll))
11669 (t (error "Cannot wrap this")))))
11670
11671
11672 (defun org-do-wrap (words width)
11673 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
11674 (let (lines line)
11675 (while words
11676 (setq line (pop words))
11677 (while (and words (< (+ (length line) (length (car words))) width))
11678 (setq line (concat line " " (pop words))))
11679 (setq lines (push line lines)))
11680 (nreverse lines)))
11681
11682 (defun org-split-string (string &optional separators)
11683 "Splits STRING into substrings at SEPARATORS.
11684 No empty strings are returned if there are matches at the beginning
11685 and end of string."
11686 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
11687 (start 0)
11688 notfirst
11689 (list nil))
11690 (while (and (string-match rexp string
11691 (if (and notfirst
11692 (= start (match-beginning 0))
11693 (< start (length string)))
11694 (1+ start) start))
11695 (< (match-beginning 0) (length string)))
11696 (setq notfirst t)
11697 (or (eq (match-beginning 0) 0)
11698 (and (eq (match-beginning 0) (match-end 0))
11699 (eq (match-beginning 0) start))
11700 (setq list
11701 (cons (substring string start (match-beginning 0))
11702 list)))
11703 (setq start (match-end 0)))
11704 (or (eq start (length string))
11705 (setq list
11706 (cons (substring string start)
11707 list)))
11708 (nreverse list)))
11709
11710 (defun org-table-map-tables (function)
11711 "Apply FUNCTION to the start of all tables in the buffer."
11712 (save-excursion
11713 (save-restriction
11714 (widen)
11715 (goto-char (point-min))
11716 (while (re-search-forward org-table-any-line-regexp nil t)
11717 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
11718 (beginning-of-line 1)
11719 (if (looking-at org-table-line-regexp)
11720 (save-excursion (funcall function)))
11721 (re-search-forward org-table-any-border-regexp nil 1))))
11722 (message "Mapping tables: done"))
11723
11724 (defun org-table-sum (&optional beg end nlast)
11725 "Sum numbers in region of current table column.
11726 The result will be displayed in the echo area, and will be available
11727 as kill to be inserted with \\[yank].
11728
11729 If there is an active region, it is interpreted as a rectangle and all
11730 numbers in that rectangle will be summed. If there is no active
11731 region and point is located in a table column, sum all numbers in that
11732 column.
11733
11734 If at least one number looks like a time HH:MM or HH:MM:SS, all other
11735 numbers are assumed to be times as well (in decimal hours) and the
11736 numbers are added as such.
11737
11738 If NLAST is a number, only the NLAST fields will actually be summed."
11739 (interactive)
11740 (save-excursion
11741 (let (col (timecnt 0) diff h m s org-table-clip)
11742 (cond
11743 ((and beg end)) ; beg and end given explicitly
11744 ((org-region-active-p)
11745 (setq beg (region-beginning) end (region-end)))
11746 (t
11747 (setq col (org-table-current-column))
11748 (goto-char (org-table-begin))
11749 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
11750 (error "No table data"))
11751 (org-table-goto-column col)
11752 ;not needed? (skip-chars-backward "^|")
11753 (setq beg (point))
11754 (goto-char (org-table-end))
11755 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
11756 (error "No table data"))
11757 (org-table-goto-column col)
11758 ;not needed? (skip-chars-forward "^|")
11759 (setq end (point))))
11760 (let* ((items (apply 'append (org-table-copy-region beg end)))
11761 (items1 (cond ((not nlast) items)
11762 ((>= nlast (length items)) items)
11763 (t (setq items (reverse items))
11764 (setcdr (nthcdr (1- nlast) items) nil)
11765 (nreverse items))))
11766 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
11767 items1)))
11768 (res (apply '+ numbers))
11769 (sres (if (= timecnt 0)
11770 (format "%g" res)
11771 (setq diff (* 3600 res)
11772 h (floor (/ diff 3600)) diff (mod diff 3600)
11773 m (floor (/ diff 60)) diff (mod diff 60)
11774 s diff)
11775 (format "%d:%02d:%02d" h m s))))
11776 (kill-new sres)
11777 (if (interactive-p)
11778 (message "%s"
11779 (substitute-command-keys
11780 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
11781 (length numbers) sres))))
11782 sres))))
11783
11784 (defun org-table-get-number-for-summing (s)
11785 (let (n)
11786 (if (string-match "^ *|? *" s)
11787 (setq s (replace-match "" nil nil s)))
11788 (if (string-match " *|? *$" s)
11789 (setq s (replace-match "" nil nil s)))
11790 (setq n (string-to-number s))
11791 (cond
11792 ((and (string-match "0" s)
11793 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
11794 ((string-match "\\`[ \t]+\\'" s) nil)
11795 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
11796 (let ((h (string-to-number (or (match-string 1 s) "0")))
11797 (m (string-to-number (or (match-string 2 s) "0")))
11798 (s (string-to-number (or (match-string 4 s) "0"))))
11799 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
11800 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
11801 ((equal n 0) nil)
11802 (t n))))
11803
11804 (defun org-table-get-vertical-vector (desc &optional tbeg col)
11805 "Get a calc vector from a column, accorting to descriptor DESC.
11806 Optional arguments TBEG and COL can give the beginning of the table and
11807 the current column, to avoid unnecessary parsing."
11808 (save-excursion
11809 (or tbeg (setq tbeg (org-table-begin)))
11810 (or col (setq col (org-table-current-column)))
11811 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
11812 (cond
11813 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
11814 (setq n1 (- (match-end 1) (match-beginning 1)))
11815 (if (match-beginning 3)
11816 (setq n2 (- (match-end 2) (match-beginning 3))))
11817 (setq n (if n2 (max n1 n2) n1))
11818 (setq n1 (if n2 (min n1 n2)))
11819 (setq nn n)
11820 (while (and (> nn 0)
11821 (re-search-backward org-table-hline-regexp tbeg t))
11822 (push (org-current-line) hline-list)
11823 (setq nn (1- nn)))
11824 (setq hline-list (nreverse hline-list))
11825 (goto-line (nth (1- n) hline-list))
11826 (when (re-search-forward org-table-dataline-regexp)
11827 (org-table-goto-column col)
11828 (setq beg (point)))
11829 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
11830 (when (re-search-backward org-table-dataline-regexp)
11831 (org-table-goto-column col)
11832 (setq end (point)))
11833 (setq l (apply 'append (org-table-copy-region beg end)))
11834 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
11835 (if (equal x "") "0" x))
11836 l ",") "]"))
11837 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
11838 (setq n1 (string-to-number (match-string 1 desc))
11839 n2 (string-to-number (match-string 2 desc)))
11840 (beginning-of-line 1)
11841 (save-excursion
11842 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
11843 (org-table-goto-column col)
11844 (setq beg (point))))
11845 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
11846 (org-table-goto-column col)
11847 (setq end (point)))
11848 (setq l (apply 'append (org-table-copy-region beg end)))
11849 (concat "[" (mapconcat
11850 (lambda (x) (setq x (org-trim x))
11851 (if (equal x "") "0" x))
11852 l ",") "]"))
11853 ((string-match "\\([0-9]+\\)" desc)
11854 (beginning-of-line 1)
11855 (when (re-search-backward org-table-dataline-regexp tbeg t
11856 (string-to-number (match-string 0 desc)))
11857 (org-table-goto-column col)
11858 (org-trim (org-table-get-field))))))))
11859
11860 (defvar org-table-formula-history nil)
11861
11862 (defvar org-table-column-names nil
11863 "Alist with column names, derived from the `!' line.")
11864 (defvar org-table-column-name-regexp nil
11865 "Regular expression matching the current column names.")
11866 (defvar org-table-local-parameters nil
11867 "Alist with parameter names, derived from the `$' line.")
11868 (defvar org-table-named-field-locations nil
11869 "Alist with locations of named fields.")
11870
11871 (defun org-table-get-formula (&optional equation named)
11872 "Read a formula from the minibuffer, offer stored formula as default."
11873 (let* ((name (car (rassoc (list (org-current-line)
11874 (org-table-current-column))
11875 org-table-named-field-locations)))
11876 (scol (if named
11877 (if name name
11878 (error "Not in a named field"))
11879 (int-to-string (org-table-current-column))))
11880 (dummy (and name (not named)
11881 (not (y-or-n-p "Replace named-field formula with column equation? " ))
11882 (error "Abort")))
11883 (org-table-may-need-update nil)
11884 (stored-list (org-table-get-stored-formulas))
11885 (stored (cdr (assoc scol stored-list)))
11886 (eq (cond
11887 ((and stored equation (string-match "^ *=? *$" equation))
11888 stored)
11889 ((stringp equation)
11890 equation)
11891 (t (read-string
11892 (format "%s formula $%s=" (if named "Field" "Column") scol)
11893 (or stored "") 'org-table-formula-history
11894 ;stored
11895 ))))
11896 mustsave)
11897 (when (not (string-match "\\S-" eq))
11898 ;; remove formula
11899 (setq stored-list (delq (assoc scol stored-list) stored-list))
11900 (org-table-store-formulas stored-list)
11901 (error "Formula removed"))
11902 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
11903 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
11904 (if (and name (not named))
11905 ;; We set the column equation, delete the named one.
11906 (setq stored-list (delq (assoc name stored-list) stored-list)
11907 mustsave t))
11908 (if stored
11909 (setcdr (assoc scol stored-list) eq)
11910 (setq stored-list (cons (cons scol eq) stored-list)))
11911 (if (or mustsave (not (equal stored eq)))
11912 (org-table-store-formulas stored-list))
11913 eq))
11914
11915 (defun org-table-store-formulas (alist)
11916 "Store the list of formulas below the current table."
11917 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
11918 (save-excursion
11919 (goto-char (org-table-end))
11920 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
11921 (delete-region (point) (match-end 0)))
11922 (insert "#+TBLFM: "
11923 (mapconcat (lambda (x)
11924 (concat "$" (car x) "=" (cdr x)))
11925 alist "::")
11926 "\n")))
11927
11928 (defun org-table-get-stored-formulas ()
11929 "Return an alist with the stored formulas directly after current table."
11930 (interactive)
11931 (let (scol eq eq-alist strings string seen)
11932 (save-excursion
11933 (goto-char (org-table-end))
11934 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
11935 (setq strings (org-split-string (match-string 2) " *:: *"))
11936 (while (setq string (pop strings))
11937 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
11938 (setq scol (match-string 1 string)
11939 eq (match-string 2 string)
11940 eq-alist (cons (cons scol eq) eq-alist))
11941 (if (member scol seen)
11942 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
11943 (push scol seen))))))
11944 (nreverse eq-alist)))
11945
11946 (defun org-table-modify-formulas (action &rest columns)
11947 "Modify the formulas stored below the current table.
11948 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
11949 expected, for the other actions only a single column number is needed."
11950 (let ((list (org-table-get-stored-formulas))
11951 (nmax (length (org-split-string
11952 (buffer-substring (point-at-bol) (point-at-eol))
11953 "|")))
11954 col col1 col2 scol si sc1 sc2)
11955 (cond
11956 ((null list)) ; No action needed if there are no stored formulas
11957 ((eq action 'remove)
11958 (setq col (car columns)
11959 scol (int-to-string col))
11960 (org-table-replace-in-formulas list scol "INVALID")
11961 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
11962 (loop for i from (1+ col) upto nmax by 1 do
11963 (setq si (int-to-string i))
11964 (org-table-replace-in-formulas list si (int-to-string (1- i)))
11965 (if (assoc si list) (setcar (assoc si list)
11966 (int-to-string (1- i))))))
11967 ((eq action 'insert)
11968 (setq col (car columns))
11969 (loop for i from nmax downto col by 1 do
11970 (setq si (int-to-string i))
11971 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
11972 (if (assoc si list) (setcar (assoc si list)
11973 (int-to-string (1+ i))))))
11974 ((eq action 'swap)
11975 (setq col1 (car columns) col2 (nth 1 columns)
11976 sc1 (int-to-string col1) sc2 (int-to-string col2))
11977 ;; Hopefully, ZqZtZ will never be a name in a table
11978 (org-table-replace-in-formulas list sc1 "ZqZtZ")
11979 (org-table-replace-in-formulas list sc2 sc1)
11980 (org-table-replace-in-formulas list "ZqZtZ" sc2)
11981 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
11982 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
11983 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
11984 (t (error "Invalid action in `org-table-modify-formulas'")))
11985 (if list (org-table-store-formulas list))))
11986
11987 (defun org-table-replace-in-formulas (list s1 s2)
11988 (let (elt re s)
11989 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
11990 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
11991 re (concat (regexp-quote s1) "\\>"))
11992 (while (setq elt (pop list))
11993 (setq s (cdr elt))
11994 (while (string-match re s)
11995 (setq s (replace-match s2 t t s)))
11996 (setcdr elt s))))
11997
11998 (defun org-table-get-specials ()
11999 "Get the column names and local parameters for this table."
12000 (save-excursion
12001 (let ((beg (org-table-begin)) (end (org-table-end))
12002 names name fields fields1 field cnt c v line col)
12003 (setq org-table-column-names nil
12004 org-table-local-parameters nil
12005 org-table-named-field-locations nil)
12006 (goto-char beg)
12007 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
12008 (setq names (org-split-string (match-string 1) " *| *")
12009 cnt 1)
12010 (while (setq name (pop names))
12011 (setq cnt (1+ cnt))
12012 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
12013 (push (cons name (int-to-string cnt)) org-table-column-names))))
12014 (setq org-table-column-names (nreverse org-table-column-names))
12015 (setq org-table-column-name-regexp
12016 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
12017 (goto-char beg)
12018 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
12019 (setq fields (org-split-string (match-string 1) " *| *"))
12020 (while (setq field (pop fields))
12021 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
12022 (push (cons (match-string 1 field) (match-string 2 field))
12023 org-table-local-parameters))))
12024 (goto-char beg)
12025 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
12026 (setq c (match-string 1)
12027 fields (org-split-string (match-string 2) " *| *"))
12028 (save-excursion
12029 (beginning-of-line (if (equal c "_") 2 0))
12030 (setq line (org-current-line) col 1)
12031 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
12032 (setq fields1 (org-split-string (match-string 1) " *| *"))))
12033 (while (and fields1 (setq field (pop fields)))
12034 (setq v (pop fields1) col (1+ col))
12035 (when (and (stringp field) (stringp v)
12036 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
12037 (push (cons field v) org-table-local-parameters)
12038 (push (list field line col) org-table-named-field-locations)))))))
12039
12040 (defun org-this-word ()
12041 ;; Get the current word
12042 (save-excursion
12043 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
12044 (end (progn (skip-chars-forward "^ \t\n") (point))))
12045 (buffer-substring-no-properties beg end))))
12046
12047 (defun org-table-maybe-eval-formula ()
12048 "Check if the current field starts with \"=\" or \":=\".
12049 If yes, store the formula and apply it."
12050 ;; We already know we are in a table. Get field will only return a formula
12051 ;; when appropriate. It might return a separator line, but no problem.
12052 (when org-table-formula-evaluate-inline
12053 (let* ((field (org-trim (or (org-table-get-field) "")))
12054 named eq)
12055 (when (string-match "^:?=\\(.*\\)" field)
12056 (setq named (equal (string-to-char field) ?:)
12057 eq (match-string 1 field))
12058 (if (fboundp 'calc-eval)
12059 (org-table-eval-formula (if named '(4) nil) eq))))))
12060
12061 (defvar org-recalc-commands nil
12062 "List of commands triggering the recalculation of a line.
12063 Will be filled automatically during use.")
12064
12065 (defvar org-recalc-marks
12066 '((" " . "Unmarked: no special line, no automatic recalculation")
12067 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
12068 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
12069 ("!" . "Column name definition line. Reference in formula as $name.")
12070 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
12071 ("_" . "Names for values in row below this one.")
12072 ("^" . "Names for values in row above this one.")))
12073
12074 (defun org-table-rotate-recalc-marks (&optional newchar)
12075 "Rotate the recalculation mark in the first column.
12076 If in any row, the first field is not consistent with a mark,
12077 insert a new column for the markers.
12078 When there is an active region, change all the lines in the region,
12079 after prompting for the marking character.
12080 After each change, a message will be displayed indicating the meaning
12081 of the new mark."
12082 (interactive)
12083 (unless (org-at-table-p) (error "Not at a table"))
12084 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
12085 (beg (org-table-begin))
12086 (end (org-table-end))
12087 (l (org-current-line))
12088 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
12089 (l2 (if (org-region-active-p) (org-current-line (region-end))))
12090 (have-col
12091 (save-excursion
12092 (goto-char beg)
12093 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
12094 (col (org-table-current-column))
12095 (forcenew (car (assoc newchar org-recalc-marks)))
12096 epos new)
12097 (when l1
12098 (message "Change region to what mark? Type # * ! $ or SPC: ")
12099 (setq newchar (char-to-string (read-char-exclusive))
12100 forcenew (car (assoc newchar org-recalc-marks))))
12101 (if (and newchar (not forcenew))
12102 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
12103 newchar))
12104 (if l1 (goto-line l1))
12105 (save-excursion
12106 (beginning-of-line 1)
12107 (unless (looking-at org-table-dataline-regexp)
12108 (error "Not at a table data line")))
12109 (unless have-col
12110 (org-table-goto-column 1)
12111 (org-table-insert-column)
12112 (org-table-goto-column (1+ col)))
12113 (setq epos (point-at-eol))
12114 (save-excursion
12115 (beginning-of-line 1)
12116 (org-table-get-field
12117 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
12118 (concat " "
12119 (setq new (or forcenew
12120 (cadr (member (match-string 1) marks))))
12121 " ")
12122 " # ")))
12123 (if (and l1 l2)
12124 (progn
12125 (goto-line l1)
12126 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
12127 (and (looking-at org-table-dataline-regexp)
12128 (org-table-get-field 1 (concat " " new " "))))
12129 (goto-line l1)))
12130 (if (not (= epos (point-at-eol))) (org-table-align))
12131 (goto-line l)
12132 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
12133
12134 (defun org-table-maybe-recalculate-line ()
12135 "Recompute the current line if marked for it, and if we haven't just done it."
12136 (interactive)
12137 (and org-table-allow-automatic-line-recalculation
12138 (not (and (memq last-command org-recalc-commands)
12139 (equal org-last-recalc-line (org-current-line))))
12140 (save-excursion (beginning-of-line 1)
12141 (looking-at org-table-auto-recalculate-regexp))
12142 (fboundp 'calc-eval)
12143 (org-table-recalculate) t))
12144
12145 (defvar org-table-formula-debug nil
12146 "Non-nil means, debug table formulas.
12147 When nil, simply write \"#ERROR\" in corrupted fields.")
12148
12149 (defvar modes)
12150 (defsubst org-set-calc-mode (var &optional value)
12151 (if (stringp var)
12152 (setq var (assoc var '(("D" calc-angle-mode deg)
12153 ("R" calc-angle-mode rad)
12154 ("F" calc-prefer-frac t)
12155 ("S" calc-symbolic-mode t)))
12156 value (nth 2 var) var (nth 1 var)))
12157 (if (memq var modes)
12158 (setcar (cdr (memq var modes)) value)
12159 (cons var (cons value modes)))
12160 modes)
12161
12162 (defun org-table-eval-formula (&optional arg equation
12163 suppress-align suppress-const
12164 suppress-store)
12165 "Replace the table field value at the cursor by the result of a calculation.
12166
12167 This function makes use of Dave Gillespie's Calc package, in my view the
12168 most exciting program ever written for GNU Emacs. So you need to have Calc
12169 installed in order to use this function.
12170
12171 In a table, this command replaces the value in the current field with the
12172 result of a formula. It also installs the formula as the \"current\" column
12173 formula, by storing it in a special line below the table. When called
12174 with a `C-u' prefix, the current field must ba a named field, and the
12175 formula is installed as valid in only this specific field.
12176
12177 When called, the command first prompts for a formula, which is read in
12178 the minibuffer. Previously entered formulas are available through the
12179 history list, and the last used formula is offered as a default.
12180 These stored formulas are adapted correctly when moving, inserting, or
12181 deleting columns with the corresponding commands.
12182
12183 The formula can be any algebraic expression understood by the Calc package.
12184 For details, see the Org-mode manual.
12185
12186 This function can also be called from Lisp programs and offers
12187 additional arguments: EQUATION can be the formula to apply. If this
12188 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
12189 used to speed-up recursive calls by by-passing unnecessary aligns.
12190 SUPPRESS-CONST suppresses the interpretation of constants in the
12191 formula, assuming that this has been done already outside the function.
12192 SUPPRESS-STORE means the formula should not be stored, either because
12193 it is already stored, or because it is a modified equation that should
12194 not overwrite the stored one."
12195 (interactive "P")
12196 (require 'calc)
12197 (org-table-check-inside-data-field)
12198 (org-table-get-specials)
12199 (let* (fields
12200 (ndown (if (integerp arg) arg 1))
12201 (org-table-automatic-realign nil)
12202 (case-fold-search nil)
12203 (down (> ndown 1))
12204 (formula (if (and equation suppress-store)
12205 equation
12206 (org-table-get-formula equation (equal arg '(4)))))
12207 (n0 (org-table-current-column))
12208 (modes (copy-sequence org-calc-default-modes))
12209 n form fmt x ev orig c lispp)
12210 ;; Parse the format string. Since we have a lot of modes, this is
12211 ;; a lot of work. However, I think calc still uses most of the time.
12212 (if (string-match ";" formula)
12213 (let ((tmp (org-split-string formula ";")))
12214 (setq formula (car tmp)
12215 fmt (concat (cdr (assoc "%" org-table-local-parameters))
12216 (nth 1 tmp)))
12217 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
12218 (setq c (string-to-char (match-string 1 fmt))
12219 n (string-to-number (match-string 2 fmt)))
12220 (if (= c ?p)
12221 (setq modes (org-set-calc-mode 'calc-internal-prec n))
12222 (setq modes (org-set-calc-mode
12223 'calc-float-format
12224 (list (cdr (assoc c '((?n . float) (?f . fix)
12225 (?s . sci) (?e . eng))))
12226 n))))
12227 (setq fmt (replace-match "" t t fmt)))
12228 (while (string-match "[DRFS]" fmt)
12229 (setq modes (org-set-calc-mode (match-string 0 fmt)))
12230 (setq fmt (replace-match "" t t fmt)))
12231 (unless (string-match "\\S-" fmt)
12232 (setq fmt nil))))
12233 (if (and (not suppress-const) org-table-formula-use-constants)
12234 (setq formula (org-table-formula-substitute-names formula)))
12235 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
12236 (while (> ndown 0)
12237 (setq fields (org-split-string
12238 (buffer-substring
12239 (point-at-bol) (point-at-eol)) " *| *"))
12240 (if org-table-formula-numbers-only
12241 (setq fields (mapcar
12242 (lambda (x) (number-to-string (string-to-number x)))
12243 fields)))
12244 (setq ndown (1- ndown))
12245 (setq form (copy-sequence formula)
12246 lispp (equal (substring form 0 2) "'("))
12247 ;; Insert the references to fields in same row
12248 (while (string-match "\\$\\([0-9]+\\)?" form)
12249 (setq n (if (match-beginning 1)
12250 (string-to-number (match-string 1 form))
12251 n0)
12252 x (nth (1- n) fields))
12253 (unless x (error "Invalid field specifier \"%s\""
12254 (match-string 0 form)))
12255 (if (equal x "") (setq x "0"))
12256 (setq form (replace-match
12257 (if lispp x (concat "(" x ")"))
12258 t t form)))
12259 ;; Insert ranges in current column
12260 (while (string-match "\\&[-I0-9]+" form)
12261 (setq form (replace-match
12262 (save-match-data
12263 (org-table-get-vertical-vector (match-string 0 form)
12264 nil n0))
12265 t t form)))
12266 (if lispp
12267 (setq ev (eval (eval (read form)))
12268 ev (if (numberp ev) (number-to-string ev) ev))
12269 (setq ev (calc-eval (cons form modes)
12270 (if org-table-formula-numbers-only 'num))))
12271
12272 (when org-table-formula-debug
12273 (with-output-to-temp-buffer "*Help*"
12274 (princ (format "Substitution history of formula
12275 Orig: %s
12276 $xyz-> %s
12277 $1-> %s\n" orig formula form))
12278 (if (listp ev)
12279 (princ (format " %s^\nError: %s"
12280 (make-string (car ev) ?\-) (nth 1 ev)))
12281 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
12282 ev (or fmt "NONE")
12283 (if fmt (format fmt (string-to-number ev)) ev)))))
12284 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
12285 (unless (and (interactive-p) (not ndown))
12286 (unless (let (inhibit-redisplay)
12287 (y-or-n-p "Debugging Formula. Continue to next? "))
12288 (org-table-align)
12289 (error "Abort"))
12290 (delete-window (get-buffer-window "*Help*"))
12291 (message "")))
12292 (if (listp ev) (setq fmt nil ev "#ERROR"))
12293 (org-table-justify-field-maybe
12294 (if fmt (format fmt (string-to-number ev)) ev))
12295 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
12296 (call-interactively 'org-return)
12297 (setq ndown 0)))
12298 (and down (org-table-maybe-recalculate-line))
12299 (or suppress-align (and org-table-may-need-update
12300 (org-table-align)))))
12301
12302 (defun org-table-recalculate (&optional all noalign)
12303 "Recalculate the current table line by applying all stored formulas.
12304 With prefix arg ALL, do this for all lines in the table."
12305 (interactive "P")
12306 (or (memq this-command org-recalc-commands)
12307 (setq org-recalc-commands (cons this-command org-recalc-commands)))
12308 (unless (org-at-table-p) (error "Not at a table"))
12309 (org-table-get-specials)
12310 (let* ((eqlist (sort (org-table-get-stored-formulas)
12311 (lambda (a b) (string< (car a) (car b)))))
12312 (inhibit-redisplay t)
12313 (line-re org-table-dataline-regexp)
12314 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
12315 (thiscol (org-table-current-column))
12316 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
12317 ;; Insert constants in all formulas
12318 (setq eqlist
12319 (mapcar (lambda (x)
12320 (setcdr x (org-table-formula-substitute-names (cdr x)))
12321 x)
12322 eqlist))
12323 ;; Split the equation list
12324 (while (setq eq (pop eqlist))
12325 (if (<= (string-to-char (car eq)) ?9)
12326 (push eq eqlnum)
12327 (push eq eqlname)))
12328 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
12329 (if all
12330 (progn
12331 (setq end (move-marker (make-marker) (1+ (org-table-end))))
12332 (goto-char (setq beg (org-table-begin)))
12333 (if (re-search-forward org-table-calculate-mark-regexp end t)
12334 ;; This is a table with marked lines, only compute selected lines
12335 (setq line-re org-table-recalculate-regexp)
12336 ;; Move forward to the first non-header line
12337 (if (and (re-search-forward org-table-dataline-regexp end t)
12338 (re-search-forward org-table-hline-regexp end t)
12339 (re-search-forward org-table-dataline-regexp end t))
12340 (setq beg (match-beginning 0))
12341 nil))) ;; just leave beg where it is
12342 (setq beg (point-at-bol)
12343 end (move-marker (make-marker) (1+ (point-at-eol)))))
12344 (goto-char beg)
12345 (and all (message "Re-applying formulas to full table..."))
12346 (while (re-search-forward line-re end t)
12347 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
12348 ;; Unprotected line, recalculate
12349 (and all (message "Re-applying formulas to full table...(line %d)"
12350 (setq cnt (1+ cnt))))
12351 (setq org-last-recalc-line (org-current-line))
12352 (setq eql eqlnum)
12353 (while (setq entry (pop eql))
12354 (goto-line org-last-recalc-line)
12355 (org-table-goto-column (string-to-number (car entry)) nil 'force)
12356 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
12357 (goto-line thisline)
12358 (org-table-goto-column thiscol)
12359 (or noalign (and org-table-may-need-update (org-table-align))
12360 (and all (message "Re-applying formulas to %d lines...done" cnt)))
12361 ;; Now do the names fields
12362 (while (setq eq (pop eqlname))
12363 (setq name (car eq)
12364 a (assoc name org-table-named-field-locations))
12365 (when a
12366 (message "Re-applying formula to named field: %s" name)
12367 (goto-line (nth 1 a))
12368 (org-table-goto-column (nth 2 a))
12369 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
12370 ;; back to initial position
12371 (goto-line thisline)
12372 (org-table-goto-column thiscol)
12373 (or noalign (and org-table-may-need-update (org-table-align))
12374 (and all (message "Re-applying formulas...done")))))
12375
12376 (defun org-table-formula-substitute-names (f)
12377 "Replace $const with values in string F."
12378 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
12379 ;; First, check for column names
12380 (while (setq start (string-match org-table-column-name-regexp f start))
12381 (setq start (1+ start))
12382 (setq a (assoc (match-string 1 f) org-table-column-names))
12383 (setq f (replace-match (concat "$" (cdr a)) t t f)))
12384 ;; Expand ranges to vectors
12385 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
12386 (setq n1 (string-to-number (match-string 1 f))
12387 n2 (string-to-number (match-string 2 f))
12388 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
12389 s (concat "[($" (number-to-string (1- nn1)) ")"))
12390 (loop for i from nn1 upto nn2 do
12391 (setq s (concat s ",($" (int-to-string i) ")")))
12392 (setq s (concat s "]"))
12393 (if (< n2 n1) (setq s (concat "rev(" s ")")))
12394 (setq f (replace-match s t t f)))
12395 ;; Parameters and constants
12396 (setq start 0)
12397 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
12398 (setq start (1+ start))
12399 (if (setq a (save-match-data
12400 (org-table-get-constant (match-string 1 f))))
12401 (setq f (replace-match (concat "(" a ")") t t f))))
12402 (if org-table-formula-debug
12403 (put-text-property 0 (length f) :orig-formula f1 f))
12404 f))
12405
12406 (defun org-table-get-constant (const)
12407 "Find the value for a parameter or constant in a formula.
12408 Parameters get priority."
12409 (or (cdr (assoc const org-table-local-parameters))
12410 (cdr (assoc const org-table-formula-constants))
12411 (and (fboundp 'constants-get) (constants-get const))
12412 "#UNDEFINED_NAME"))
12413
12414 (defvar org-edit-formulas-map (make-sparse-keymap))
12415 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
12416 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
12417 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
12418
12419 (defvar org-pos)
12420
12421 (defun org-table-edit-formulas ()
12422 "Edit the formulas of the current table in a separate buffer."
12423 (interactive)
12424 (unless (org-at-table-p)
12425 (error "Not at a table"))
12426 (org-table-get-specials)
12427 (let ((eql (org-table-get-stored-formulas))
12428 (pos (move-marker (make-marker) (point)))
12429 (wc (current-window-configuration))
12430 entry loc s)
12431 (switch-to-buffer-other-window "*Edit Formulas*")
12432 (erase-buffer)
12433 (fundamental-mode)
12434 (org-set-local 'org-pos pos)
12435 (org-set-local 'org-window-configuration wc)
12436 (use-local-map org-edit-formulas-map)
12437 (setq s "# Edit formulas and finish with `C-c C-c'.
12438 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
12439 # Use `C-c ?' to get information about $name at point.
12440 # To cancel editing, press `C-c C-q'.\n")
12441 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12442 (insert s)
12443 (while (setq entry (pop eql))
12444 (when (setq loc (assoc (car entry) org-table-named-field-locations))
12445 (setq s (format "# Named formula, referring to column %d in line %d\n"
12446 (nth 2 loc) (nth 1 loc)))
12447 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12448 (insert s))
12449 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
12450 (remove-text-properties 0 (length s) '(face nil) s)
12451 (insert s))
12452 (goto-char (point-min))
12453 (message "Edit formulas and finish with `C-c C-c'.")))
12454
12455 (defun org-show-variable ()
12456 "Show the location/value of the $ expression at point."
12457 (interactive)
12458 (let (var (pos org-pos) (win (selected-window)) e)
12459 (save-excursion
12460 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
12461 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
12462 (setq var (match-string 1))
12463 (error "No variable at point")))
12464 (cond
12465 ((setq e (assoc var org-table-named-field-locations))
12466 (switch-to-buffer-other-window (marker-buffer pos))
12467 (goto-line (nth 1 e))
12468 (org-table-goto-column (nth 2 e))
12469 (select-window win)
12470 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
12471 ((setq e (assoc var org-table-column-names))
12472 (switch-to-buffer-other-window (marker-buffer pos))
12473 (goto-char pos)
12474 (goto-char (org-table-begin))
12475 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
12476 (org-table-end) t)
12477 (progn
12478 (goto-char (match-beginning 1))
12479 (message "Named column (column %s)" (cdr e)))
12480 (error "Column name not found"))
12481 (select-window win))
12482 ((string-match "^[0-9]$" var)
12483 ;; column number
12484 (switch-to-buffer-other-window (marker-buffer pos))
12485 (goto-char pos)
12486 (goto-char (org-table-begin))
12487 (recenter 1)
12488 (if (re-search-forward org-table-dataline-regexp
12489 (org-table-end) t)
12490 (progn
12491 (goto-char (match-beginning 0))
12492 (org-table-goto-column (string-to-number var))
12493 (message "Column %s" var))
12494 (error "Column name not found"))
12495 (select-window win))
12496 ((setq e (assoc var org-table-local-parameters))
12497 (switch-to-buffer-other-window (marker-buffer pos))
12498 (goto-char pos)
12499 (goto-char (org-table-begin))
12500 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
12501 (progn
12502 (goto-char (match-beginning 1))
12503 (message "Local parameter."))
12504 (error "Parameter not found"))
12505 (select-window win))
12506 (t
12507 (cond
12508 ((setq e (assoc var org-table-formula-constants))
12509 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
12510 ((setq e (and (fboundp 'constants-get) (constants-get var)))
12511 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
12512 (t (error "Undefined name $%s" var)))))))
12513
12514 (defun org-finish-edit-formulas (&optional arg)
12515 "Parse the buffer for formula definitions and install them.
12516 With prefix ARG, apply the new formulas to the table."
12517 (interactive "P")
12518 (let ((pos org-pos) eql)
12519 (goto-char (point-min))
12520 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
12521 (push (cons (match-string 1) (match-string 2)) eql))
12522 (set-window-configuration org-window-configuration)
12523 (select-window (get-buffer-window (marker-buffer pos)))
12524 (goto-char pos)
12525 (unless (org-at-table-p)
12526 (error "Lost table position - cannot install formulae"))
12527 (org-table-store-formulas eql)
12528 (move-marker pos nil)
12529 (kill-buffer "*Edit Formulas*")
12530 (if arg
12531 (org-table-recalculate 'all)
12532 (message "New formulas installed - press C-u C-c C-c to apply."))))
12533
12534 (defun org-abort-edit-formulas ()
12535 "Abort editing formulas, without installing the changes."
12536 (interactive)
12537 (let ((pos org-pos))
12538 (set-window-configuration org-window-configuration)
12539 (select-window (get-buffer-window (marker-buffer pos)))
12540 (goto-char pos)
12541 (message "Formula editing aborted without installing changes")))
12542
12543 ;;; The orgtbl minor mode
12544
12545 ;; Define a minor mode which can be used in other modes in order to
12546 ;; integrate the org-mode table editor.
12547
12548 ;; This is really a hack, because the org-mode table editor uses several
12549 ;; keys which normally belong to the major mode, for example the TAB and
12550 ;; RET keys. Here is how it works: The minor mode defines all the keys
12551 ;; necessary to operate the table editor, but wraps the commands into a
12552 ;; function which tests if the cursor is currently inside a table. If that
12553 ;; is the case, the table editor command is executed. However, when any of
12554 ;; those keys is used outside a table, the function uses `key-binding' to
12555 ;; look up if the key has an associated command in another currently active
12556 ;; keymap (minor modes, major mode, global), and executes that command.
12557 ;; There might be problems if any of the keys used by the table editor is
12558 ;; otherwise used as a prefix key.
12559
12560 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
12561 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
12562 ;; addresses this by checking explicitly for both bindings.
12563
12564 ;; The optimized version (see variable `orgtbl-optimized') takes over
12565 ;; all keys which are bound to `self-insert-command' in the *global map*.
12566 ;; Some modes bind other commands to simple characters, for example
12567 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
12568 ;; active, this binding is ignored inside tables and replaced with a
12569 ;; modified self-insert.
12570
12571 (defvar orgtbl-mode nil
12572 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
12573 table editor in arbitrary modes.")
12574 (make-variable-buffer-local 'orgtbl-mode)
12575
12576 (defvar orgtbl-mode-map (make-keymap)
12577 "Keymap for `orgtbl-mode'.")
12578
12579 ;;;###autoload
12580 (defun turn-on-orgtbl ()
12581 "Unconditionally turn on `orgtbl-mode'."
12582 (orgtbl-mode 1))
12583
12584 ;;;###autoload
12585 (defun orgtbl-mode (&optional arg)
12586 "The `org-mode' table editor as a minor mode for use in other modes."
12587 (interactive)
12588 (if (org-mode-p)
12589 ;; Exit without error, in case some hook functions calls this
12590 ;; by accident in org-mode.
12591 (message "Orgtbl-mode is not useful in org-mode, command ignored")
12592 (setq orgtbl-mode
12593 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
12594 (if orgtbl-mode
12595 (progn
12596 (and (orgtbl-setup) (defun orgtbl-setup () nil))
12597 ;; Make sure we are first in minor-mode-map-alist
12598 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
12599 (and c (setq minor-mode-map-alist
12600 (cons c (delq c minor-mode-map-alist)))))
12601 (org-set-local (quote org-table-may-need-update) t)
12602 (org-add-hook 'before-change-functions 'org-before-change-function
12603 nil 'local)
12604 (org-set-local 'org-old-auto-fill-inhibit-regexp
12605 auto-fill-inhibit-regexp)
12606 (org-set-local 'auto-fill-inhibit-regexp
12607 (if auto-fill-inhibit-regexp
12608 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
12609 "[ \t]*|"))
12610 (org-add-to-invisibility-spec '(org-cwidth))
12611 (easy-menu-add orgtbl-mode-menu)
12612 (run-hooks 'orgtbl-mode-hook))
12613 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
12614 (org-cleanup-narrow-column-properties)
12615 (org-remove-from-invisibility-spec '(org-cwidth))
12616 (remove-hook 'before-change-functions 'org-before-change-function t)
12617 (easy-menu-remove orgtbl-mode-menu)
12618 (force-mode-line-update 'all))))
12619
12620 (defun org-cleanup-narrow-column-properties ()
12621 "Remove all properties related to narrow-column invisibility."
12622 (let ((s 1))
12623 (while (setq s (text-property-any s (point-max)
12624 'display org-narrow-column-arrow))
12625 (remove-text-properties s (1+ s) '(display t)))
12626 (setq s 1)
12627 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
12628 (remove-text-properties s (1+ s) '(org-cwidth t)))
12629 (setq s 1)
12630 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
12631 (remove-text-properties s (1+ s) '(invisible t)))))
12632
12633 ;; Install it as a minor mode.
12634 (put 'orgtbl-mode :included t)
12635 (put 'orgtbl-mode :menu-tag "Org Table Mode")
12636 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
12637
12638 (defun orgtbl-make-binding (fun n &rest keys)
12639 "Create a function for binding in the table minor mode.
12640 FUN is the command to call inside a table. N is used to create a unique
12641 command name. KEYS are keys that should be checked in for a command
12642 to execute outside of tables."
12643 (eval
12644 (list 'defun
12645 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
12646 '(arg)
12647 (concat "In tables, run `" (symbol-name fun) "'.\n"
12648 "Outside of tables, run the binding of `"
12649 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
12650 "'.")
12651 '(interactive "p")
12652 (list 'if
12653 '(org-at-table-p)
12654 (list 'call-interactively (list 'quote fun))
12655 (list 'let '(orgtbl-mode)
12656 (list 'call-interactively
12657 (append '(or)
12658 (mapcar (lambda (k)
12659 (list 'key-binding k))
12660 keys)
12661 '('orgtbl-error))))))))
12662
12663 (defun orgtbl-error ()
12664 "Error when there is no default binding for a table key."
12665 (interactive)
12666 (error "This key is has no function outside tables"))
12667
12668 (defun orgtbl-setup ()
12669 "Setup orgtbl keymaps."
12670 (let ((nfunc 0)
12671 (bindings
12672 (list
12673 '([(meta shift left)] org-table-delete-column)
12674 '([(meta left)] org-table-move-column-left)
12675 '([(meta right)] org-table-move-column-right)
12676 '([(meta shift right)] org-table-insert-column)
12677 '([(meta shift up)] org-table-kill-row)
12678 '([(meta shift down)] org-table-insert-row)
12679 '([(meta up)] org-table-move-row-up)
12680 '([(meta down)] org-table-move-row-down)
12681 '("\C-c\C-w" org-table-cut-region)
12682 '("\C-c\M-w" org-table-copy-region)
12683 '("\C-c\C-y" org-table-paste-rectangle)
12684 '("\C-c-" org-table-insert-hline)
12685 ; '([(shift tab)] org-table-previous-field)
12686 '("\C-m" org-table-next-row)
12687 (list (org-key 'S-return) 'org-table-copy-down)
12688 '([(meta return)] org-table-wrap-region)
12689 '("\C-c\C-q" org-table-wrap-region)
12690 '("\C-c?" org-table-current-column)
12691 '("\C-c " org-table-blank-field)
12692 '("\C-c+" org-table-sum)
12693 '("\C-c=" org-table-eval-formula)
12694 '("\C-c'" org-table-edit-formulas)
12695 '("\C-c`" org-table-edit-field)
12696 '("\C-c*" org-table-recalculate)
12697 '("\C-c|" org-table-create-or-convert-from-region)
12698 '("\C-c^" org-table-sort-lines)
12699 '([(control ?#)] org-table-rotate-recalc-marks)))
12700 elt key fun cmd)
12701 (while (setq elt (pop bindings))
12702 (setq nfunc (1+ nfunc))
12703 (setq key (car elt)
12704 fun (nth 1 elt)
12705 cmd (orgtbl-make-binding fun nfunc key))
12706 (define-key orgtbl-mode-map key cmd))
12707 ;; Special treatment needed for TAB and RET
12708 (define-key orgtbl-mode-map [(return)]
12709 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
12710 (define-key orgtbl-mode-map "\C-m"
12711 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
12712 (define-key orgtbl-mode-map [(tab)]
12713 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
12714 (define-key orgtbl-mode-map "\C-i"
12715 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
12716 (define-key orgtbl-mode-map "\C-i"
12717 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
12718 (define-key orgtbl-mode-map "\C-c\C-c"
12719 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
12720 (when orgtbl-optimized
12721 ;; If the user wants maximum table support, we need to hijack
12722 ;; some standard editing functions
12723 (org-remap orgtbl-mode-map
12724 'self-insert-command 'orgtbl-self-insert-command
12725 'delete-char 'org-delete-char
12726 'delete-backward-char 'org-delete-backward-char)
12727 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
12728 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
12729 '("OrgTbl"
12730 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
12731 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
12732 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
12733 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
12734 "--"
12735 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
12736 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
12737 ["Copy Field from Above"
12738 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
12739 "--"
12740 ("Column"
12741 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
12742 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
12743 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
12744 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
12745 "--"
12746 ["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])
12747 ("Row"
12748 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
12749 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
12750 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
12751 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
12752 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
12753 "--"
12754 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
12755 ("Rectangle"
12756 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
12757 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
12758 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
12759 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
12760 "--"
12761 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
12762 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12763 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
12764 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
12765 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
12766 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
12767 ["Sum Column/Rectangle" org-table-sum
12768 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
12769 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
12770 ["Debug Formulas"
12771 (setq org-table-formula-debug (not org-table-formula-debug))
12772 :style toggle :selected org-table-formula-debug]
12773 ))
12774 t)
12775
12776 (defun orgtbl-tab (arg)
12777 "Justification and field motion for `orgtbl-mode'."
12778 (interactive "P")
12779 (if arg (org-table-edit-field t)
12780 (org-table-justify-field-maybe)
12781 (org-table-next-field)))
12782
12783 (defun orgtbl-ret ()
12784 "Justification and field motion for `orgtbl-mode'."
12785 (interactive)
12786 (org-table-justify-field-maybe)
12787 (org-table-next-row))
12788
12789 (defun orgtbl-self-insert-command (N)
12790 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12791 If the cursor is in a table looking at whitespace, the whitespace is
12792 overwritten, and the table is not marked as requiring realignment."
12793 (interactive "p")
12794 (if (and (org-at-table-p)
12795 (or
12796 (and org-table-auto-blank-field
12797 (member last-command
12798 '(orgtbl-hijacker-command-100
12799 orgtbl-hijacker-command-101
12800 orgtbl-hijacker-command-102
12801 orgtbl-hijacker-command-103
12802 orgtbl-hijacker-command-104
12803 orgtbl-hijacker-command-105))
12804 (org-table-blank-field))
12805 t)
12806 (eq N 1)
12807 (looking-at "[^|\n]* +|"))
12808 (let (org-table-may-need-update)
12809 (goto-char (1- (match-end 0)))
12810 (delete-backward-char 1)
12811 (goto-char (match-beginning 0))
12812 (self-insert-command N))
12813 (setq org-table-may-need-update t)
12814 (let (orgtbl-mode)
12815 (call-interactively (key-binding (vector last-input-event))))))
12816
12817 (defun org-force-self-insert (N)
12818 "Needed to enforce self-insert under remapping."
12819 (interactive "p")
12820 (self-insert-command N))
12821
12822 ;;; Exporting
12823
12824 (defconst org-level-max 20)
12825
12826 (defvar org-export-html-preamble nil
12827 "Preamble, to be inserted just after <body>. Set by publishing functions.")
12828 (defvar org-export-html-postamble nil
12829 "Preamble, to be inserted just before </body>. Set by publishing functions.")
12830 (defvar org-export-html-auto-preamble t
12831 "Should default preamble be inserted? Set by publishing functions.")
12832 (defvar org-export-html-auto-postamble t
12833 "Should default postamble be inserted? Set by publishing functions.")
12834
12835 (defconst org-export-plist-vars
12836 '((:language . org-export-default-language)
12837 (:headline-levels . org-export-headline-levels)
12838 (:section-numbers . org-export-with-section-numbers)
12839 (:table-of-contents . org-export-with-toc)
12840 (:archived-trees . org-export-with-archived-trees)
12841 (:emphasize . org-export-with-emphasize)
12842 (:sub-superscript . org-export-with-sub-superscripts)
12843 (:TeX-macros . org-export-with-TeX-macros)
12844 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
12845 (:fixed-width . org-export-with-fixed-width)
12846 (:timestamps . org-export-with-timestamps)
12847 (:tables . org-export-with-tables)
12848 (:table-auto-headline . org-export-highlight-first-table-line)
12849 (:style . org-export-html-style)
12850 (:convert-org-links . org-export-html-link-org-files-as-html)
12851 (:inline-images . org-export-html-inline-images)
12852 (:expand-quoted-html . org-export-html-expand)
12853 (:timestamp . org-export-html-with-timestamp)
12854 (:publishing-directory . org-export-publishing-directory)
12855 (:preamble . org-export-html-preamble)
12856 (:postamble . org-export-html-postamble)
12857 (:auto-preamble . org-export-html-auto-preamble)
12858 (:auto-postamble . org-export-html-auto-postamble)
12859 (:author . user-full-name)
12860 (:email . user-mail-address)))
12861
12862 (defun org-default-export-plist ()
12863 "Return the property list with default settings for the export variables."
12864 (let ((l org-export-plist-vars) rtn e)
12865 (while (setq e (pop l))
12866 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
12867 rtn))
12868
12869 (defun org-infile-export-plist ()
12870 "Return the property list with file-local settings for export."
12871 (save-excursion
12872 (goto-char 0)
12873 (let ((re (org-make-options-regexp
12874 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12875 p key val text options)
12876 (while (re-search-forward re nil t)
12877 (setq key (org-match-string-no-properties 1)
12878 val (org-match-string-no-properties 2))
12879 (cond
12880 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
12881 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
12882 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
12883 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
12884 ((string-equal key "TEXT")
12885 (setq text (if text (concat text "\n" val) val)))
12886 ((string-equal key "OPTIONS") (setq options val))))
12887 (setq p (plist-put p :text text))
12888 (when options
12889 (let ((op '(("H" . :headline-levels)
12890 ("num" . :section-numbers)
12891 ("toc" . :table-of-contents)
12892 ("\\n" . :preserve-breaks)
12893 ("@" . :expand-quoted-html)
12894 (":" . :fixed-width)
12895 ("|" . :tables)
12896 ("^" . :sub-superscript)
12897 ("*" . :emphasize)
12898 ("TeX" . :TeX-macros)
12899 ("LaTeX" . :LaTeX-fragments)))
12900 o)
12901 (while (setq o (pop op))
12902 (if (string-match (concat (regexp-quote (car o))
12903 ":\\([^ \t\n\r;,.]*\\)")
12904 options)
12905 (setq p (plist-put p (cdr o)
12906 (car (read-from-string
12907 (match-string 1 options)))))))))
12908 p)))
12909
12910 (defun org-combine-plists (&rest plists)
12911 "Create a single property list from all plists in PLISTS.
12912 The process starts by copying the last list, and then setting properties
12913 from the other lists. Settings in the first list are the most significant
12914 ones and overrule settings in the other lists."
12915 (let ((rtn (copy-sequence (pop plists)))
12916 p v ls)
12917 (while plists
12918 (setq ls (pop plists))
12919 (while ls
12920 (setq p (pop ls) v (pop ls))
12921 (setq rtn (plist-put rtn p v))))
12922 rtn))
12923
12924 (defun org-export-directory (type plist)
12925 (let* ((val (plist-get plist :publishing-directory))
12926 (dir (if (listp val)
12927 (or (cdr (assoc type val)) ".")
12928 val)))
12929 dir))
12930
12931 (defun org-export-find-first-heading-line (list)
12932 "Remove all lines from LIST which are before the first headline."
12933 (let ((orig-list list)
12934 (re (concat "^" outline-regexp)))
12935 (while (and list
12936 (not (string-match re (car list))))
12937 (pop list))
12938 (or list orig-list)))
12939
12940 (defun org-skip-comments (lines)
12941 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
12942 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
12943 (re2 "^\\(\\*+\\)[ \t\n\r]")
12944 rtn line level)
12945 (while (setq line (pop lines))
12946 (cond
12947 ((and (string-match re1 line)
12948 (setq level (- (match-end 1) (match-beginning 1))))
12949 ;; Beginning of a COMMENT subtree. Skip it.
12950 (while (and (setq line (pop lines))
12951 (or (not (string-match re2 line))
12952 (> (- (match-end 1) (match-beginning 1)) level))))
12953 (setq lines (cons line lines)))
12954 ((string-match "^#" line)
12955 ;; an ordinary comment line
12956 )
12957 ((and org-export-table-remove-special-lines
12958 (string-match "^[ \t]*|" line)
12959 (or (string-match "^[ \t]*| *[!_^] *|" line)
12960 (and (string-match "| *<[0-9]+> *|" line)
12961 (not (string-match "| *[^ <|]" line)))))
12962 ;; a special table line that should be removed
12963 )
12964 (t (setq rtn (cons line rtn)))))
12965 (nreverse rtn)))
12966
12967 (defun org-export (&optional arg)
12968 (interactive)
12969 (let ((help "[t] insert the export option template
12970 \[v] limit export to visible part of outline tree
12971
12972 \[a] export as ASCII
12973 \[h] export as HTML
12974 \[b] export as HTML and browse immediately
12975 \[x] export as XOXO
12976
12977 \[i] export current file as iCalendar file
12978 \[I] export all agenda files as iCalendar files
12979 \[c] export agenda files into combined iCalendar file
12980
12981 \[F] publish current file
12982 \[P] publish current project
12983 \[X] publish... (project will be prompted for)
12984 \[A] publish all projects")
12985 (cmds
12986 '((?t . org-insert-export-options-template)
12987 (?v . org-export-visible)
12988 (?a . org-export-as-ascii)
12989 (?h . org-export-as-html)
12990 (?b . org-export-as-html-and-open)
12991 (?x . org-export-as-xoxo)
12992 (?i . org-export-icalendar-this-file)
12993 (?I . org-export-icalendar-all-agenda-files)
12994 (?c . org-export-icalendar-combine-agenda-files)
12995 (?F . org-publish-current-file)
12996 (?P . org-publish-current-project)
12997 (?X . org-publish)
12998 (?A . org-publish-all)))
12999 r1 r2 ass)
13000 (save-window-excursion
13001 (delete-other-windows)
13002 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
13003 (princ help))
13004 (message "Select command: ")
13005 (setq r1 (read-char-exclusive)))
13006 (setq r2 (if (< r1 27) (+ r1 96) r1))
13007 (if (setq ass (assq r2 cmds))
13008 (call-interactively (cdr ass))
13009 (error "No command associated with key %c" r1))))
13010
13011 ;; ASCII
13012
13013 (defconst org-html-entities
13014 '(("nbsp")
13015 ("iexcl")
13016 ("cent")
13017 ("pound")
13018 ("curren")
13019 ("yen")
13020 ("brvbar")
13021 ("sect")
13022 ("uml")
13023 ("copy")
13024 ("ordf")
13025 ("laquo")
13026 ("not")
13027 ("shy")
13028 ("reg")
13029 ("macr")
13030 ("deg")
13031 ("plusmn")
13032 ("sup2")
13033 ("sup3")
13034 ("acute")
13035 ("micro")
13036 ("para")
13037 ("middot")
13038 ("odot"."o")
13039 ("star"."*")
13040 ("cedil")
13041 ("sup1")
13042 ("ordm")
13043 ("raquo")
13044 ("frac14")
13045 ("frac12")
13046 ("frac34")
13047 ("iquest")
13048 ("Agrave")
13049 ("Aacute")
13050 ("Acirc")
13051 ("Atilde")
13052 ("Auml")
13053 ("Aring") ("AA"."&Aring;")
13054 ("AElig")
13055 ("Ccedil")
13056 ("Egrave")
13057 ("Eacute")
13058 ("Ecirc")
13059 ("Euml")
13060 ("Igrave")
13061 ("Iacute")
13062 ("Icirc")
13063 ("Iuml")
13064 ("ETH")
13065 ("Ntilde")
13066 ("Ograve")
13067 ("Oacute")
13068 ("Ocirc")
13069 ("Otilde")
13070 ("Ouml")
13071 ("times")
13072 ("Oslash")
13073 ("Ugrave")
13074 ("Uacute")
13075 ("Ucirc")
13076 ("Uuml")
13077 ("Yacute")
13078 ("THORN")
13079 ("szlig")
13080 ("agrave")
13081 ("aacute")
13082 ("acirc")
13083 ("atilde")
13084 ("auml")
13085 ("aring")
13086 ("aelig")
13087 ("ccedil")
13088 ("egrave")
13089 ("eacute")
13090 ("ecirc")
13091 ("euml")
13092 ("igrave")
13093 ("iacute")
13094 ("icirc")
13095 ("iuml")
13096 ("eth")
13097 ("ntilde")
13098 ("ograve")
13099 ("oacute")
13100 ("ocirc")
13101 ("otilde")
13102 ("ouml")
13103 ("divide")
13104 ("oslash")
13105 ("ugrave")
13106 ("uacute")
13107 ("ucirc")
13108 ("uuml")
13109 ("yacute")
13110 ("thorn")
13111 ("yuml")
13112 ("fnof")
13113 ("Alpha")
13114 ("Beta")
13115 ("Gamma")
13116 ("Delta")
13117 ("Epsilon")
13118 ("Zeta")
13119 ("Eta")
13120 ("Theta")
13121 ("Iota")
13122 ("Kappa")
13123 ("Lambda")
13124 ("Mu")
13125 ("Nu")
13126 ("Xi")
13127 ("Omicron")
13128 ("Pi")
13129 ("Rho")
13130 ("Sigma")
13131 ("Tau")
13132 ("Upsilon")
13133 ("Phi")
13134 ("Chi")
13135 ("Psi")
13136 ("Omega")
13137 ("alpha")
13138 ("beta")
13139 ("gamma")
13140 ("delta")
13141 ("epsilon")
13142 ("varepsilon"."&epsilon;")
13143 ("zeta")
13144 ("eta")
13145 ("theta")
13146 ("iota")
13147 ("kappa")
13148 ("lambda")
13149 ("mu")
13150 ("nu")
13151 ("xi")
13152 ("omicron")
13153 ("pi")
13154 ("rho")
13155 ("sigmaf") ("varsigma"."&sigmaf;")
13156 ("sigma")
13157 ("tau")
13158 ("upsilon")
13159 ("phi")
13160 ("chi")
13161 ("psi")
13162 ("omega")
13163 ("thetasym") ("vartheta"."&thetasym;")
13164 ("upsih")
13165 ("piv")
13166 ("bull") ("bullet"."&bull;")
13167 ("hellip") ("dots"."&hellip;")
13168 ("prime")
13169 ("Prime")
13170 ("oline")
13171 ("frasl")
13172 ("weierp")
13173 ("image")
13174 ("real")
13175 ("trade")
13176 ("alefsym")
13177 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
13178 ("uarr") ("uparrow"."&uarr;")
13179 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
13180 ("darr")("downarrow"."&darr;")
13181 ("harr") ("leftrightarrow"."&harr;")
13182 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
13183 ("lArr") ("Leftarrow"."&lArr;")
13184 ("uArr") ("Uparrow"."&uArr;")
13185 ("rArr") ("Rightarrow"."&rArr;")
13186 ("dArr") ("Downarrow"."&dArr;")
13187 ("hArr") ("Leftrightarrow"."&hArr;")
13188 ("forall")
13189 ("part") ("partial"."&part;")
13190 ("exist") ("exists"."&exist;")
13191 ("empty") ("emptyset"."&empty;")
13192 ("nabla")
13193 ("isin") ("in"."&isin;")
13194 ("notin")
13195 ("ni")
13196 ("prod")
13197 ("sum")
13198 ("minus")
13199 ("lowast") ("ast"."&lowast;")
13200 ("radic")
13201 ("prop") ("proptp"."&prop;")
13202 ("infin") ("infty"."&infin;")
13203 ("ang") ("angle"."&ang;")
13204 ("and") ("vee"."&and;")
13205 ("or") ("wedge"."&or;")
13206 ("cap")
13207 ("cup")
13208 ("int")
13209 ("there4")
13210 ("sim")
13211 ("cong") ("simeq"."&cong;")
13212 ("asymp")("approx"."&asymp;")
13213 ("ne") ("neq"."&ne;")
13214 ("equiv")
13215 ("le")
13216 ("ge")
13217 ("sub") ("subset"."&sub;")
13218 ("sup") ("supset"."&sup;")
13219 ("nsub")
13220 ("sube")
13221 ("supe")
13222 ("oplus")
13223 ("otimes")
13224 ("perp")
13225 ("sdot") ("cdot"."&sdot;")
13226 ("lceil")
13227 ("rceil")
13228 ("lfloor")
13229 ("rfloor")
13230 ("lang")
13231 ("rang")
13232 ("loz") ("Diamond"."&loz;")
13233 ("spades") ("spadesuit"."&spades;")
13234 ("clubs") ("clubsuit"."&clubs;")
13235 ("hearts") ("diamondsuit"."&hearts;")
13236 ("diams") ("diamondsuit"."&diams;")
13237 ("quot")
13238 ("amp")
13239 ("lt")
13240 ("gt")
13241 ("OElig")
13242 ("oelig")
13243 ("Scaron")
13244 ("scaron")
13245 ("Yuml")
13246 ("circ")
13247 ("tilde")
13248 ("ensp")
13249 ("emsp")
13250 ("thinsp")
13251 ("zwnj")
13252 ("zwj")
13253 ("lrm")
13254 ("rlm")
13255 ("ndash")
13256 ("mdash")
13257 ("lsquo")
13258 ("rsquo")
13259 ("sbquo")
13260 ("ldquo")
13261 ("rdquo")
13262 ("bdquo")
13263 ("dagger")
13264 ("Dagger")
13265 ("permil")
13266 ("lsaquo")
13267 ("rsaquo")
13268 ("euro")
13269
13270 ("arccos"."arccos")
13271 ("arcsin"."arcsin")
13272 ("arctan"."arctan")
13273 ("arg"."arg")
13274 ("cos"."cos")
13275 ("cosh"."cosh")
13276 ("cot"."cot")
13277 ("coth"."coth")
13278 ("csc"."csc")
13279 ("deg"."deg")
13280 ("det"."det")
13281 ("dim"."dim")
13282 ("exp"."exp")
13283 ("gcd"."gcd")
13284 ("hom"."hom")
13285 ("inf"."inf")
13286 ("ker"."ker")
13287 ("lg"."lg")
13288 ("lim"."lim")
13289 ("liminf"."liminf")
13290 ("limsup"."limsup")
13291 ("ln"."ln")
13292 ("log"."log")
13293 ("max"."max")
13294 ("min"."min")
13295 ("Pr"."Pr")
13296 ("sec"."sec")
13297 ("sin"."sin")
13298 ("sinh"."sinh")
13299 ("sup"."sup")
13300 ("tan"."tan")
13301 ("tanh"."tanh")
13302 )
13303 "Entities for TeX->HTML translation.
13304 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
13305 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
13306 In that case, \"\\ent\" will be translated to \"&other;\".
13307 The list contains HTML entities for Latin-1, Greek and other symbols.
13308 It is supplemented by a number of commonly used TeX macros with appropriate
13309 translations. There is currently no way for users to extend this.")
13310
13311 (defun org-cleaned-string-for-export (string &rest parameters)
13312 "Cleanup a buffer substring so that links can be created safely."
13313 (interactive)
13314 (let* ((re-radio (and org-target-link-regexp
13315 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
13316 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
13317 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
13318 (re-archive (concat ":" org-archive-tag ":"))
13319 rtn)
13320 (save-excursion
13321 (set-buffer (get-buffer-create " org-mode-tmp"))
13322 (erase-buffer)
13323 (insert string)
13324 (let ((org-inhibit-startup t)) (org-mode))
13325
13326 ;; Get rid of archived trees
13327 (when (not (eq org-export-with-archived-trees t))
13328 (goto-char (point-min))
13329 (while (re-search-forward re-archive nil t)
13330 (if (not (org-on-heading-p))
13331 (org-end-of-subtree t)
13332 (beginning-of-line 1)
13333 (delete-region
13334 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
13335 (org-end-of-subtree)))))
13336
13337 ;; Find targets in comments and move them out of comments,
13338 ;; but mark them as targets that should be invisible
13339 (goto-char (point-min))
13340 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
13341 (replace-match "\\1(INVISIBLE)"))
13342
13343 ;; Find matches for radio targets and turn them into internal links
13344 (goto-char (point-min))
13345 (when re-radio
13346 (while (re-search-forward re-radio nil t)
13347 (replace-match "\\1[[\\2]]")))
13348
13349 ;; Find all links that contain a newline and put them into a single line
13350 (goto-char (point-min))
13351 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
13352 (replace-match "\\1 \\3")
13353 (goto-char (match-beginning 0)))
13354
13355 ;; Convert LaTeX fragments to images
13356 (when (memq :LaTeX-fragments parameters)
13357 (org-format-latex
13358 (concat "ltxpng/" (file-name-sans-extension
13359 (file-name-nondirectory
13360 org-current-export-file)))
13361 org-current-export-dir nil "Creating LaTeX image %s"))
13362 (message "Exporting...")
13363
13364 ;; Normalize links: Convert angle and plain links into bracket links
13365 (goto-char (point-min))
13366 (while (re-search-forward re-plain-link nil t)
13367 (replace-match
13368 (concat
13369 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13370 t t))
13371 (goto-char (point-min))
13372 (while (re-search-forward re-angle-link nil t)
13373 (replace-match
13374 (concat
13375 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13376 t t))
13377
13378 ;; Find multiline emphasis and put them into single line
13379 (when (memq :emph-multiline parameters)
13380 (goto-char (point-min))
13381 (while (re-search-forward org-emph-re nil t)
13382 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
13383 (goto-char (1- (match-end 0)))))
13384
13385 ;; Remove comments
13386 (goto-char (point-min))
13387 (while (re-search-forward "^#.*\n?" nil t)
13388 (replace-match ""))
13389 (setq rtn (buffer-string)))
13390 (kill-buffer " org-mode-tmp")
13391 rtn))
13392
13393 (defun org-solidify-link-text (s &optional alist)
13394 "Take link text and make a safe target out of it."
13395 (save-match-data
13396 (let* ((rtn
13397 (mapconcat
13398 'identity
13399 (org-split-string s "[ \t\r\n]+") "--"))
13400 (a (assoc rtn alist)))
13401 (or (cdr a) rtn))))
13402
13403 (defun org-convert-to-odd-levels ()
13404 "Convert an org-mode file with all levels allowed to one with odd levels.
13405 This will leave level 1 alone, convert level 2 to level 3, level 3 to
13406 level 5 etc."
13407 (interactive)
13408 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
13409 (let ((org-odd-levels-only nil) n)
13410 (save-excursion
13411 (goto-char (point-min))
13412 (while (re-search-forward "^\\*\\*+" nil t)
13413 (setq n (1- (length (match-string 0))))
13414 (while (>= (setq n (1- n)) 0)
13415 (org-demote))
13416 (end-of-line 1))))))
13417
13418
13419 (defun org-convert-to-oddeven-levels ()
13420 "Convert an org-mode file with only odd levels to one with odd and even levels.
13421 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
13422 section with an even level, conversion would destroy the structure of the file. An error
13423 is signaled in this case."
13424 (interactive)
13425 (goto-char (point-min))
13426 ;; First check if there are no even levels
13427 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
13428 (org-show-hierarchy-above)
13429 (error "Not all levels are odd in this file. Conversion not possible."))
13430 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
13431 (let ((org-odd-levels-only nil) n)
13432 (save-excursion
13433 (goto-char (point-min))
13434 (while (re-search-forward "^\\*\\*+" nil t)
13435 (setq n (/ (length (match-string 0)) 2))
13436 (while (>= (setq n (1- n)) 0)
13437 (org-promote))
13438 (end-of-line 1))))))
13439
13440 (defun org-tr-level (n)
13441 "Make N odd if required."
13442 (if org-odd-levels-only (1+ (/ n 2)) n))
13443
13444 (defvar org-last-level nil) ; dynamically scoped variable
13445 (defvar org-ascii-current-indentation nil) ; For communication
13446
13447 (defun org-export-as-ascii (arg)
13448 "Export the outline as a pretty ASCII file.
13449 If there is an active region, export only the region.
13450 The prefix ARG specifies how many levels of the outline should become
13451 underlined headlines. The default is 3."
13452 (interactive "P")
13453 (setq-default org-todo-line-regexp org-todo-line-regexp)
13454 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13455 (org-infile-export-plist)))
13456 (region
13457 (buffer-substring
13458 (if (org-region-active-p) (region-beginning) (point-min))
13459 (if (org-region-active-p) (region-end) (point-max))))
13460 (lines (org-export-find-first-heading-line
13461 (org-skip-comments
13462 (org-split-string
13463 (org-cleaned-string-for-export region)
13464 "[\r\n]"))))
13465 (org-ascii-current-indentation '(0 . 0))
13466 (org-startup-with-deadline-check nil)
13467 (level 0) line txt
13468 (umax nil)
13469 (case-fold-search nil)
13470 (filename (concat (file-name-as-directory
13471 (org-export-directory :ascii opt-plist))
13472 (file-name-sans-extension
13473 (file-name-nondirectory buffer-file-name))
13474 ".txt"))
13475 (buffer (find-file-noselect filename))
13476 (levels-open (make-vector org-level-max nil))
13477 (odd org-odd-levels-only)
13478 (date (format-time-string "%Y/%m/%d" (current-time)))
13479 (time (format-time-string "%X" (org-current-time)))
13480 (author (plist-get opt-plist :author))
13481 (title (or (plist-get opt-plist :title)
13482 (file-name-sans-extension
13483 (file-name-nondirectory buffer-file-name))))
13484 (email (plist-get opt-plist :email))
13485 (language (plist-get opt-plist :language))
13486 (text nil)
13487 (todo nil)
13488 (lang-words nil))
13489
13490 (setq org-last-level 1)
13491 (org-init-section-numbers)
13492
13493 (find-file-noselect filename)
13494
13495 (setq lang-words (or (assoc language org-export-language-setup)
13496 (assoc "en" org-export-language-setup)))
13497 (if org-export-ascii-show-new-buffer
13498 (switch-to-buffer-other-window buffer)
13499 (set-buffer buffer))
13500 (erase-buffer)
13501 (fundamental-mode)
13502 ;; create local variables for all options, to make sure all called
13503 ;; functions get the correct information
13504 (mapcar (lambda (x)
13505 (set (make-local-variable (cdr x))
13506 (plist-get opt-plist (car x))))
13507 org-export-plist-vars)
13508 (org-set-local 'org-odd-levels-only odd)
13509 (setq umax (if arg (prefix-numeric-value arg)
13510 org-export-headline-levels))
13511
13512 ;; File header
13513 (if title (org-insert-centered title ?=))
13514 (insert "\n")
13515 (if (or author email)
13516 (insert (concat (nth 1 lang-words) ": " (or author "")
13517 (if email (concat " <" email ">") "")
13518 "\n")))
13519 (if (and date time)
13520 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
13521 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
13522
13523 (insert "\n\n")
13524
13525 (if org-export-with-toc
13526 (progn
13527 (insert (nth 3 lang-words) "\n"
13528 (make-string (length (nth 3 lang-words)) ?=) "\n")
13529 (mapcar '(lambda (line)
13530 (if (string-match org-todo-line-regexp
13531 line)
13532 ;; This is a headline
13533 (progn
13534 (setq level (- (match-end 1) (match-beginning 1))
13535 level (org-tr-level level)
13536 txt (match-string 3 line)
13537 todo
13538 (or (and org-export-mark-todo-in-toc
13539 (match-beginning 2)
13540 (not (equal (match-string 2 line)
13541 org-done-string)))
13542 ; TODO, not DONE
13543 (and org-export-mark-todo-in-toc
13544 (= level umax)
13545 (org-search-todo-below
13546 line lines level))))
13547 (setq txt (org-html-expand-for-ascii txt))
13548
13549 (if org-export-with-section-numbers
13550 (setq txt (concat (org-section-number level)
13551 " " txt)))
13552 (if (<= level umax)
13553 (progn
13554 (insert
13555 (make-string (* (1- level) 4) ?\ )
13556 (format (if todo "%s (*)\n" "%s\n") txt))
13557 (setq org-last-level level))
13558 ))))
13559 lines)))
13560
13561 (org-init-section-numbers)
13562 (while (setq line (pop lines))
13563 ;; Remove the quoted HTML tags.
13564 (setq line (org-html-expand-for-ascii line))
13565 ;; Remove targets
13566 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
13567 (setq line (replace-match "" t t line)))
13568 ;; Replace internal links
13569 (while (string-match org-bracket-link-regexp line)
13570 (setq line (replace-match
13571 (if (match-end 3) "[\\3]" "[\\1]")
13572 t nil line)))
13573 (cond
13574 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13575 ;; a Headline
13576 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13577 txt (match-string 2 line))
13578 (org-ascii-level-start level txt umax lines))
13579 (t
13580 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
13581 (normal-mode)
13582 (save-buffer)
13583 ;; remove display and invisible chars
13584 (let (beg end)
13585 (goto-char (point-min))
13586 (while (setq beg (next-single-property-change (point) 'display))
13587 (setq end (next-single-property-change beg 'display))
13588 (delete-region beg end)
13589 (goto-char beg)
13590 (insert "=>"))
13591 (goto-char (point-min))
13592 (while (setq beg (next-single-property-change (point) 'org-cwidth))
13593 (setq end (next-single-property-change beg 'org-cwidth))
13594 (delete-region beg end)
13595 (goto-char beg)))
13596 (goto-char (point-min))))
13597
13598 (defun org-search-todo-below (line lines level)
13599 "Search the subtree below LINE for any TODO entries."
13600 (let ((rest (cdr (memq line lines)))
13601 (re org-todo-line-regexp)
13602 line lv todo)
13603 (catch 'exit
13604 (while (setq line (pop rest))
13605 (if (string-match re line)
13606 (progn
13607 (setq lv (- (match-end 1) (match-beginning 1))
13608 todo (and (match-beginning 2)
13609 (not (equal (match-string 2 line)
13610 org-done-string))))
13611 ; TODO, not DONE
13612 (if (<= lv level) (throw 'exit nil))
13613 (if todo (throw 'exit t))))))))
13614
13615 (defun org-html-expand-for-ascii (line)
13616 "Handle quoted HTML for ASCII export."
13617 (if org-export-html-expand
13618 (while (string-match "@<[^<>\n]*>" line)
13619 ;; We just remove the tags for now.
13620 (setq line (replace-match "" nil nil line))))
13621 line)
13622
13623 (defun org-insert-centered (s &optional underline)
13624 "Insert the string S centered and underline it with character UNDERLINE."
13625 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
13626 (insert (make-string ind ?\ ) s "\n")
13627 (if underline
13628 (insert (make-string ind ?\ )
13629 (make-string (string-width s) underline)
13630 "\n"))))
13631
13632 (defun org-ascii-level-start (level title umax &optional lines)
13633 "Insert a new level in ASCII export."
13634 (let (char (n (- level umax 1)) (ind 0))
13635 (if (> level umax)
13636 (progn
13637 (insert (make-string (* 2 n) ?\ )
13638 (char-to-string (nth (% n (length org-export-ascii-bullets))
13639 org-export-ascii-bullets))
13640 " " title "\n")
13641 ;; find the indentation of the next non-empty line
13642 (catch 'stop
13643 (while lines
13644 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
13645 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
13646 (throw 'stop (setq ind (org-get-indentation (car lines)))))
13647 (pop lines)))
13648 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
13649 (if (or (not (equal (char-before) ?\n))
13650 (not (equal (char-before (1- (point))) ?\n)))
13651 (insert "\n"))
13652 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
13653 (if org-export-with-section-numbers
13654 (setq title (concat (org-section-number level) " " title)))
13655 (insert title "\n" (make-string (string-width title) char) "\n")
13656 (setq org-ascii-current-indentation '(0 . 0)))))
13657
13658 (defun org-export-visible (type arg)
13659 "Create a copy of the visible part of the current buffer, and export it.
13660 The copy is created in a temporary buffer and removed after use.
13661 TYPE is the final key (as a string) that also select the export command in
13662 the `C-c C-e' export dispatcher.
13663 As a special case, if the you type SPC at the prompt, the temporary
13664 org-mode file will not be removed but presented to you so that you can
13665 continue to use it. The prefix arg ARG is passed through to the exporting
13666 command."
13667 (interactive
13668 (list (progn
13669 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
13670 (read-char-exclusive))
13671 current-prefix-arg))
13672 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
13673 (error "Invalid export key"))
13674 (let* ((binding (cdr (assoc type
13675 '((?a . org-export-as-ascii)
13676 (?\C-a . org-export-as-ascii)
13677 (?b . org-export-as-html-and-open)
13678 (?\C-b . org-export-as-html-and-open)
13679 (?h . org-export-as-html)
13680 (?x . org-export-as-xoxo)))))
13681 (keepp (equal type ?\ ))
13682 (file buffer-file-name)
13683 (buffer (get-buffer-create "*Org Export Visible*"))
13684 s e)
13685 (with-current-buffer buffer (erase-buffer))
13686 (save-excursion
13687 (setq s (goto-char (point-min)))
13688 (while (not (= (point) (point-max)))
13689 (goto-char (org-find-invisible))
13690 (append-to-buffer buffer s (point))
13691 (setq s (goto-char (org-find-visible))))
13692 (goto-char (point-min))
13693 (unless keepp
13694 ;; Copy all comment lines to the end, to make sure #+ settings are
13695 ;; still available for the second export step. Kind of a hack, but
13696 ;; does do the trick.
13697 (if (looking-at "#[^\r\n]*")
13698 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
13699 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
13700 (append-to-buffer buffer (1+ (match-beginning 0))
13701 (min (point-max) (1+ (match-end 0))))))
13702 (set-buffer buffer)
13703 (let ((buffer-file-name file)
13704 (org-inhibit-startup t))
13705 (org-mode)
13706 (show-all)
13707 (unless keepp (funcall binding arg))))
13708 (if (not keepp)
13709 (kill-buffer buffer)
13710 (switch-to-buffer-other-window buffer)
13711 (goto-char (point-min)))))
13712
13713 (defun org-find-visible ()
13714 (let ((s (point)))
13715 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13716 (get-char-property s 'invisible)))
13717 s))
13718 (defun org-find-invisible ()
13719 (let ((s (point)))
13720 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13721 (not (get-char-property s 'invisible))))
13722 s))
13723
13724 ;; HTML
13725
13726 (defun org-get-current-options ()
13727 "Return a string with current options as keyword options.
13728 Does include HTML export options as well as TODO and CATEGORY stuff."
13729 (format
13730 "#+TITLE: %s
13731 #+AUTHOR: %s
13732 #+EMAIL: %s
13733 #+LANGUAGE: %s
13734 #+TEXT: Some descriptive text to be emitted. Several lines OK.
13735 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
13736 #+CATEGORY: %s
13737 #+SEQ_TODO: %s
13738 #+TYP_TODO: %s
13739 #+STARTUP: %s %s %s %s %s %s
13740 #+TAGS: %s
13741 #+ARCHIVE: %s
13742 "
13743 (buffer-name) (user-full-name) user-mail-address org-export-default-language
13744 org-export-headline-levels
13745 org-export-with-section-numbers
13746 org-export-with-toc
13747 org-export-preserve-breaks
13748 org-export-html-expand
13749 org-export-with-fixed-width
13750 org-export-with-tables
13751 org-export-with-sub-superscripts
13752 org-export-with-emphasize
13753 org-export-with-TeX-macros
13754 org-export-with-LaTeX-fragments
13755 (file-name-nondirectory buffer-file-name)
13756 (if (equal org-todo-interpretation 'sequence)
13757 (mapconcat 'identity org-todo-keywords " ")
13758 "TODO FEEDBACK VERIFY DONE")
13759 (if (equal org-todo-interpretation 'type)
13760 (mapconcat 'identity org-todo-keywords " ")
13761 "Me Jason Marie DONE")
13762 (cdr (assoc org-startup-folded
13763 '((nil . "showall") (t . "overview") (content . "content"))))
13764 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
13765 (if org-odd-levels-only "odd" "oddeven")
13766 (if org-hide-leading-stars "hidestars" "showstars")
13767 (if org-startup-align-all-tables "align" "noalign")
13768 (if org-log-done "logging" "nologging")
13769 (if org-tag-alist (mapconcat 'car org-tag-alist " ") "")
13770 org-archive-location
13771 ))
13772
13773 (defun org-insert-export-options-template ()
13774 "Insert into the buffer a template with information for exporting."
13775 (interactive)
13776 (if (not (bolp)) (newline))
13777 (let ((s (org-get-current-options)))
13778 (and (string-match "#\\+CATEGORY" s)
13779 (setq s (substring s 0 (match-beginning 0))))
13780 (insert s)))
13781
13782 (defun org-toggle-fixed-width-section (arg)
13783 "Toggle the fixed-width export.
13784 If there is no active region, the QUOTE keyword at the current headline is
13785 inserted or removed. When present, it causes the text between this headline
13786 and the next to be exported as fixed-width text, and unmodified.
13787 If there is an active region, this command adds or removes a colon as the
13788 first character of this line. If the first character of a line is a colon,
13789 this line is also exported in fixed-width font."
13790 (interactive "P")
13791 (let* ((cc 0)
13792 (regionp (org-region-active-p))
13793 (beg (if regionp (region-beginning) (point)))
13794 (end (if regionp (region-end)))
13795 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13796 (re "[ \t]*\\(:\\)")
13797 off)
13798 (if regionp
13799 (save-excursion
13800 (goto-char beg)
13801 (setq cc (current-column))
13802 (beginning-of-line 1)
13803 (setq off (looking-at re))
13804 (while (> nlines 0)
13805 (setq nlines (1- nlines))
13806 (beginning-of-line 1)
13807 (cond
13808 (arg
13809 (move-to-column cc t)
13810 (insert ":\n")
13811 (forward-line -1))
13812 ((and off (looking-at re))
13813 (replace-match "" t t nil 1))
13814 ((not off) (move-to-column cc t) (insert ":")))
13815 (forward-line 1)))
13816 (save-excursion
13817 (org-back-to-heading)
13818 (if (looking-at (concat outline-regexp
13819 "\\( +\\<" org-quote-string "\\>\\)"))
13820 (replace-match "" t t nil 1)
13821 (if (looking-at outline-regexp)
13822 (progn
13823 (goto-char (match-end 0))
13824 (insert " " org-quote-string))))))))
13825
13826 (defun org-export-as-html-and-open (arg)
13827 "Export the outline as HTML and immediately open it with a browser.
13828 If there is an active region, export only the region.
13829 The prefix ARG specifies how many levels of the outline should become
13830 headlines. The default is 3. Lower levels will become bulleted lists."
13831 (interactive "P")
13832 (org-export-as-html arg 'hidden)
13833 (org-open-file buffer-file-name))
13834
13835 (defun org-export-as-html-batch ()
13836 "Call `org-export-as-html', may be used in batch processing as
13837 emacs --batch
13838 --load=$HOME/lib/emacs/org.el
13839 --eval \"(setq org-export-headline-levels 2)\"
13840 --visit=MyFile --funcall org-export-as-html-batch"
13841 (org-export-as-html org-export-headline-levels 'hidden))
13842
13843 (defun org-export-as-html (arg &optional hidden ext-plist)
13844 "Export the outline as a pretty HTML file.
13845 If there is an active region, export only the region.
13846 The prefix ARG specifies how many levels of the outline should become
13847 headlines. The default is 3. Lower levels will become bulleted lists.
13848 When HIDDEN is non-nil, don't display the HTML buffer.
13849 EXT-PLIST is a property list with external parameters overriding
13850 org-mode's default settings, but still inferior to file-local settings."
13851 (interactive "P")
13852 (message "Exporting...")
13853 (setq-default org-todo-line-regexp org-todo-line-regexp)
13854 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
13855 (setq-default org-done-string org-done-string)
13856 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13857 ext-plist
13858 (org-infile-export-plist)))
13859
13860 (style (plist-get opt-plist :style))
13861 (link-validate (plist-get opt-plist :link-validation-function))
13862 valid
13863 (odd org-odd-levels-only)
13864 (region-p (org-region-active-p))
13865 (region
13866 (buffer-substring
13867 (if region-p (region-beginning) (point-min))
13868 (if region-p (region-end) (point-max))))
13869 ;; The following two are dynamically scoped into other
13870 ;; routines below.
13871 (org-current-export-dir (org-export-directory :html opt-plist))
13872 (org-current-export-file buffer-file-name)
13873 (all_lines
13874 (org-skip-comments (org-split-string
13875 (org-cleaned-string-for-export
13876 region :emph-multiline
13877 (if (plist-get opt-plist :LaTeX-fragments)
13878 :LaTeX-fragments))
13879 "[\r\n]")))
13880 (lines (org-export-find-first-heading-line all_lines))
13881 (level 0) (line "") (origline "") txt todo
13882 (umax nil)
13883 (filename (concat (file-name-as-directory
13884 (org-export-directory :html opt-plist))
13885 (file-name-sans-extension
13886 (file-name-nondirectory buffer-file-name))
13887 ".html"))
13888 (current-dir (file-name-directory buffer-file-name))
13889 (buffer (find-file-noselect filename))
13890 (levels-open (make-vector org-level-max nil))
13891 (date (format-time-string "%Y/%m/%d" (current-time)))
13892 (time (format-time-string "%X" (org-current-time)))
13893 (author (plist-get opt-plist :author))
13894 (title (or (plist-get opt-plist :title)
13895 (file-name-sans-extension
13896 (file-name-nondirectory buffer-file-name))))
13897 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
13898 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
13899 (inquote nil)
13900 (infixed nil)
13901 (in-local-list nil)
13902 (local-list-num nil)
13903 (local-list-indent nil)
13904 (llt org-plain-list-ordered-item-terminator)
13905 (email (plist-get opt-plist :email))
13906 (language (plist-get opt-plist :language))
13907 (text (plist-get opt-plist :text))
13908 (lang-words nil)
13909 (target-alist nil) tg
13910 (head-count 0) cnt
13911 (start 0)
13912 (coding-system (and (fboundp 'coding-system-get)
13913 (boundp 'buffer-file-coding-system)
13914 buffer-file-coding-system))
13915 (coding-system-for-write (or coding-system coding-system-for-write))
13916 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
13917 (charset (and coding-system
13918 (coding-system-get coding-system 'mime-charset)))
13919 table-open type
13920 table-buffer table-orig-buffer
13921 ind start-is-num starter
13922 rpl path desc descp desc1 desc2 link
13923 )
13924 (message "Exporting...")
13925
13926 (setq org-last-level 1)
13927 (org-init-section-numbers)
13928
13929 ;; Get the language-dependent settings
13930 (setq lang-words (or (assoc language org-export-language-setup)
13931 (assoc "en" org-export-language-setup)))
13932
13933 ;; Switch to the output buffer
13934 (if (or hidden (not org-export-html-show-new-buffer))
13935 (set-buffer buffer)
13936 (switch-to-buffer-other-window buffer))
13937 (erase-buffer)
13938 (fundamental-mode)
13939 (let ((case-fold-search nil)
13940 (org-odd-levels-only odd))
13941 ;; create local variables for all options, to make sure all called
13942 ;; functions get the correct information
13943 (mapcar (lambda (x)
13944 (set (make-local-variable (cdr x))
13945 (plist-get opt-plist (car x))))
13946 org-export-plist-vars)
13947 (setq umax (if arg (prefix-numeric-value arg)
13948 org-export-headline-levels))
13949
13950 ;; File header
13951 (insert (format
13952 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
13953 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
13954 <html xmlns=\"http://www.w3.org/1999/xhtml\"
13955 lang=\"%s\" xml:lang=\"%s\">
13956 <head>
13957 <title>%s</title>
13958 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
13959 <meta name=\"generator\" content=\"Org-mode\"/>
13960 <meta name=\"generated\" content=\"%s %s\"/>
13961 <meta name=\"author\" content=\"%s\"/>
13962 %s
13963 </head><body>
13964 "
13965 language language (org-html-expand title) (or charset "iso-8859-1")
13966 date time author style))
13967
13968
13969 (insert (or (plist-get opt-plist :preamble) ""))
13970
13971 (when (plist-get opt-plist :auto-preamble)
13972 (if title (insert (format org-export-html-title-format
13973 (org-html-expand title))))
13974 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
13975
13976 (if org-export-with-toc
13977 (progn
13978 (insert (format "<h%d>%s</h%d>\n"
13979 org-export-html-toplevel-hlevel
13980 (nth 3 lang-words)
13981 org-export-html-toplevel-hlevel))
13982 (insert "<ul>\n<li>")
13983 (setq lines
13984 (mapcar '(lambda (line)
13985 (if (string-match org-todo-line-regexp line)
13986 ;; This is a headline
13987 (progn
13988 (setq level (- (match-end 1) (match-beginning 1))
13989 level (org-tr-level level)
13990 txt (save-match-data
13991 (org-html-expand
13992 (org-export-cleanup-toc-line
13993 (match-string 3 line))))
13994 todo
13995 (or (and org-export-mark-todo-in-toc
13996 (match-beginning 2)
13997 (not (equal (match-string 2 line)
13998 org-done-string)))
13999 ; TODO, not DONE
14000 (and org-export-mark-todo-in-toc
14001 (= level umax)
14002 (org-search-todo-below
14003 line lines level))))
14004 (if org-export-with-section-numbers
14005 (setq txt (concat (org-section-number level)
14006 " " txt)))
14007 (if (<= level umax)
14008 (progn
14009 (setq head-count (+ head-count 1))
14010 (if (> level org-last-level)
14011 (progn
14012 (setq cnt (- level org-last-level))
14013 (while (>= (setq cnt (1- cnt)) 0)
14014 (insert "\n<ul>\n<li>"))
14015 (insert "\n")))
14016 (if (< level org-last-level)
14017 (progn
14018 (setq cnt (- org-last-level level))
14019 (while (>= (setq cnt (1- cnt)) 0)
14020 (insert "</li>\n</ul>"))
14021 (insert "\n")))
14022 ;; Check for targets
14023 (while (string-match org-target-regexp line)
14024 (setq tg (match-string 1 line)
14025 line (replace-match
14026 (concat "@<span class=\"target\">" tg "@</span> ")
14027 t t line))
14028 (push (cons (org-solidify-link-text tg)
14029 (format "sec-%d" head-count))
14030 target-alist))
14031 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
14032 (setq txt (replace-match "" t t txt)))
14033 (insert
14034 (format
14035 (if todo
14036 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
14037 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
14038 head-count txt))
14039
14040 (setq org-last-level level))
14041 )))
14042 line)
14043 lines))
14044 (while (> org-last-level 0)
14045 (setq org-last-level (1- org-last-level))
14046 (insert "</li>\n</ul>\n"))
14047 ))
14048 (setq head-count 0)
14049 (org-init-section-numbers)
14050
14051 (while (setq line (pop lines) origline line)
14052 (catch 'nextline
14053
14054 ;; end of quote section?
14055 (when (and inquote (string-match "^\\*+" line))
14056 (insert "</pre>\n")
14057 (setq inquote nil))
14058 ;; inside a quote section?
14059 (when inquote
14060 (insert (org-html-protect line) "\n")
14061 (throw 'nextline nil))
14062
14063 ;; verbatim lines
14064 (when (and org-export-with-fixed-width
14065 (string-match "^[ \t]*:\\(.*\\)" line))
14066 (when (not infixed)
14067 (setq infixed t)
14068 (insert "<pre>\n"))
14069 (insert (org-html-protect (match-string 1 line)) "\n")
14070 (when (and lines
14071 (not (string-match "^[ \t]*\\(:.*\\)"
14072 (car lines))))
14073 (setq infixed nil)
14074 (insert "</pre>\n"))
14075 (throw 'nextline nil))
14076
14077
14078 ;; make targets to anchors
14079 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
14080 (cond
14081 ((match-end 2)
14082 (setq line (replace-match
14083 (concat "@<a name=\""
14084 (org-solidify-link-text (match-string 1 line))
14085 "\">\\nbsp@</a>")
14086 t t line)))
14087 ((and org-export-with-toc (equal (string-to-char line) ?*))
14088 (setq line (replace-match
14089 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
14090 ; (concat "@<i>" (match-string 1 line) "@</i> ")
14091 t t line)))
14092 (t
14093 (setq line (replace-match
14094 (concat "@<a name=\""
14095 (org-solidify-link-text (match-string 1 line))
14096 "\" class=\"target\">" (match-string 1 line) "@</a> ")
14097 t t line)))))
14098
14099 (setq line (org-html-handle-time-stamps line))
14100
14101 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
14102 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
14103 ;; Also handle sub_superscripts and checkboxes
14104 (setq line (org-html-expand line))
14105
14106 ;; Format the links
14107 (setq start 0)
14108 (while (string-match org-bracket-link-analytic-regexp line start)
14109 (setq start (match-beginning 0))
14110 (setq type (if (match-end 2) (match-string 2 line) "internal"))
14111 (setq path (match-string 3 line))
14112 (setq desc1 (if (match-end 5) (match-string 5 line))
14113 desc2 (if (match-end 2) (concat type ":" path) path)
14114 descp (and desc1 (not (equal desc1 desc2)))
14115 desc (or desc1 desc2))
14116 ;; FIXME: do we need to unescape here somewhere?
14117 (cond
14118 ((equal type "internal")
14119 (setq rpl
14120 (concat
14121 "<a href=\"#"
14122 (org-solidify-link-text path target-alist)
14123 "\">" desc "</a>")))
14124 ((member type '("http" "https" "ftp" "mailto" "news"))
14125 ;; standard URL
14126 (setq link (concat type ":" path))
14127 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
14128 ((string= type "file")
14129 ;; FILE link
14130 (let* ((filename path)
14131 (abs-p (file-name-absolute-p filename))
14132 thefile file-is-image-p search)
14133 (save-match-data
14134 (if (string-match "::\\(.*\\)" filename)
14135 (setq search (match-string 1 filename)
14136 filename (replace-match "" t nil filename)))
14137 (setq valid
14138 (if (functionp link-validate)
14139 (funcall link-validate filename current-dir)
14140 t))
14141 (setq file-is-image-p
14142 (string-match (org-image-file-name-regexp) filename))
14143 (setq thefile (if abs-p (expand-file-name filename) filename))
14144 (when (and org-export-html-link-org-files-as-html
14145 (string-match "\\.org$" thefile))
14146 (setq thefile (concat (substring thefile 0
14147 (match-beginning 0))
14148 ".html"))
14149 (if (and search
14150 ;; make sure this is can be used as target search
14151 (not (string-match "^[0-9]*$" search))
14152 (not (string-match "^\\*" search))
14153 (not (string-match "^/.*/$" search)))
14154 (setq thefile (concat thefile "#"
14155 (org-solidify-link-text
14156 (org-link-unescape search)))))
14157 (when (string-match "^file:" desc)
14158 (setq desc (replace-match "" t t desc))
14159 (if (string-match "\\.org$" desc)
14160 (setq desc (replace-match "" t t desc))))))
14161 (setq rpl (if (and file-is-image-p
14162 (or (eq t org-export-html-inline-images)
14163 (and org-export-html-inline-images
14164 (not descp))))
14165 (concat "<img src=\"" thefile "\"/>")
14166 (concat "<a href=\"" thefile "\">" desc "</a>")))
14167 (if (not valid) (setq rpl desc))))
14168 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
14169 (setq rpl (concat "<i>&lt;" type ":"
14170 (save-match-data (org-link-unescape path))
14171 "&gt;</i>"))))
14172 (setq line (replace-match rpl t t line)
14173 start (+ start (length rpl))))
14174 ;; TODO items
14175 (if (and (string-match org-todo-line-regexp line)
14176 (match-beginning 2))
14177 (if (equal (match-string 2 line) org-done-string)
14178 (setq line (replace-match
14179 "<span class=\"done\">\\2</span>"
14180 t nil line 2))
14181 (setq line (replace-match "<span class=\"todo\">\\2</span>"
14182 t nil line 2))))
14183
14184 (cond
14185 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14186 ;; This is a headline
14187 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14188 txt (match-string 2 line))
14189 (if (string-match quote-re0 txt)
14190 (setq txt (replace-match "" t t txt)))
14191 (if (<= level umax) (setq head-count (+ head-count 1)))
14192 (when in-local-list
14193 ;; Close any local lists before inserting a new header line
14194 (while local-list-num
14195 (org-close-li)
14196 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14197 (pop local-list-num))
14198 (setq local-list-indent nil
14199 in-local-list nil))
14200 (org-html-level-start level txt umax
14201 (and org-export-with-toc (<= level umax))
14202 head-count)
14203 ;; QUOTES
14204 (when (string-match quote-re line)
14205 (insert "<pre>")
14206 (setq inquote t)))
14207
14208 ((and org-export-with-tables
14209 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
14210 (if (not table-open)
14211 ;; New table starts
14212 (setq table-open t table-buffer nil table-orig-buffer nil))
14213 ;; Accumulate lines
14214 (setq table-buffer (cons line table-buffer)
14215 table-orig-buffer (cons origline table-orig-buffer))
14216 (when (or (not lines)
14217 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
14218 (car lines))))
14219 (setq table-open nil
14220 table-buffer (nreverse table-buffer)
14221 table-orig-buffer (nreverse table-orig-buffer))
14222 (org-close-par-maybe)
14223 (insert (org-format-table-html table-buffer table-orig-buffer))))
14224 (t
14225 ;; Normal lines
14226 (when (string-match
14227 (cond
14228 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14229 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14230 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14231 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
14232 line)
14233 (setq ind (org-get-string-indentation line)
14234 start-is-num (match-beginning 4)
14235 starter (if (match-beginning 2)
14236 (substring (match-string 2 line) 0 -1))
14237 line (substring line (match-beginning 5)))
14238 (unless (string-match "[^ \t]" line)
14239 ;; empty line. Pretend indentation is large.
14240 (setq ind (1+ (or (car local-list-indent) 1))))
14241 (while (and in-local-list
14242 (or (and (= ind (car local-list-indent))
14243 (not starter))
14244 (< ind (car local-list-indent))))
14245 (org-close-li)
14246 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14247 (pop local-list-num) (pop local-list-indent)
14248 (setq in-local-list local-list-indent))
14249 (cond
14250 ((and starter
14251 (or (not in-local-list)
14252 (> ind (car local-list-indent))))
14253 ;; Start new (level of ) list
14254 (org-close-par-maybe)
14255 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
14256 (push start-is-num local-list-num)
14257 (push ind local-list-indent)
14258 (setq in-local-list t))
14259 (starter
14260 ;; continue current list
14261 (org-close-li)
14262 (insert "<li>\n")))
14263 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
14264 (setq line
14265 (replace-match
14266 (if (equal (match-string 1 line) "X")
14267 "<b>[X]</b>"
14268 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
14269 t t line))))
14270
14271 ;; Empty lines start a new paragraph. If hand-formatted lists
14272 ;; are not fully interpreted, lines starting with "-", "+", "*"
14273 ;; also start a new paragraph.
14274 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
14275
14276 ;; Check if the line break needs to be conserved
14277 (cond
14278 ((string-match "\\\\\\\\[ \t]*$" line)
14279 (setq line (replace-match "<br/>" t t line)))
14280 (org-export-preserve-breaks
14281 (setq line (concat line "<br/>"))))
14282
14283 (insert line "\n")))))
14284
14285 ;; Properly close all local lists and other lists
14286 (when inquote (insert "</pre>\n"))
14287 (when in-local-list
14288 ;; Close any local lists before inserting a new header line
14289 (while local-list-num
14290 (org-close-li)
14291 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
14292 (pop local-list-num))
14293 (setq local-list-indent nil
14294 in-local-list nil))
14295 (org-html-level-start 1 nil umax
14296 (and org-export-with-toc (<= level umax))
14297 head-count)
14298
14299 (when (plist-get opt-plist :auto-postamble)
14300 (when author
14301 (insert "<p class=\"author\"> "
14302 (nth 1 lang-words) ": " author "\n")
14303 (when email
14304 (insert "<a href=\"mailto:" email "\">&lt;"
14305 email "&gt;</a>\n"))
14306 (insert "</p>\n"))
14307 (when (and date time)
14308 (insert "<p class=\"date\"> "
14309 (nth 2 lang-words) ": "
14310 date " " time "</p>\n")))
14311
14312 (if org-export-html-with-timestamp
14313 (insert org-export-html-html-helper-timestamp))
14314 (insert (or (plist-get opt-plist :postamble) ""))
14315 (insert "</body>\n</html>\n")
14316 (normal-mode)
14317 ;; remove empty paragraphs and lists
14318 (goto-char (point-min))
14319 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
14320 (replace-match ""))
14321 (goto-char (point-min))
14322 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
14323 (replace-match ""))
14324 (save-buffer)
14325 (goto-char (point-min))
14326 (message "Exporting... done"))))
14327
14328
14329 (defun org-format-table-html (lines olines)
14330 "Find out which HTML converter to use and return the HTML code."
14331 (if (string-match "^[ \t]*|" (car lines))
14332 ;; A normal org table
14333 (org-format-org-table-html lines)
14334 ;; Table made by table.el - test for spanning
14335 (let* ((hlines (delq nil (mapcar
14336 (lambda (x)
14337 (if (string-match "^[ \t]*\\+-" x) x
14338 nil))
14339 lines)))
14340 (first (car hlines))
14341 (ll (and (string-match "\\S-+" first)
14342 (match-string 0 first)))
14343 (re (concat "^[ \t]*" (regexp-quote ll)))
14344 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
14345 hlines))))
14346 (if (and (not spanning)
14347 (not org-export-prefer-native-exporter-for-tables))
14348 ;; We can use my own converter with HTML conversions
14349 (org-format-table-table-html lines)
14350 ;; Need to use the code generator in table.el, with the original text.
14351 (org-format-table-table-html-using-table-generate-source olines)))))
14352
14353 (defun org-format-org-table-html (lines)
14354 "Format a table into HTML."
14355 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14356 (setq lines (nreverse lines))
14357 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14358 (setq lines (nreverse lines))
14359 (when org-export-table-remove-special-lines
14360 ;; Check if the table has a marking column. If yes remove the
14361 ;; column and the special lines
14362 (let* ((special
14363 (not
14364 (memq nil
14365 (mapcar
14366 (lambda (x)
14367 (or (string-match "^[ \t]*|-" x)
14368 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
14369 lines)))))
14370 (if special
14371 (setq lines
14372 (delq nil
14373 (mapcar
14374 (lambda (x)
14375 (if (string-match "^[ \t]*| *[!_^] *|" x)
14376 nil ; ignore this line
14377 (and (or (string-match "^[ \t]*|-+\\+" x)
14378 (string-match "^[ \t]*|[^|]*|" x))
14379 (replace-match "|" t t x))))
14380 lines))))))
14381
14382 (let ((head (and org-export-highlight-first-table-line
14383 (delq nil (mapcar
14384 (lambda (x) (string-match "^[ \t]*|-" x))
14385 (cdr lines)))))
14386 line fields html)
14387 (setq html (concat org-export-html-table-tag "\n"))
14388 (while (setq line (pop lines))
14389 (catch 'next-line
14390 (if (string-match "^[ \t]*|-" line)
14391 (progn
14392 (setq head nil) ;; head ends here, first time around
14393 ;; ignore this line
14394 (throw 'next-line t)))
14395 ;; Break the line into fields
14396 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14397 (setq html (concat
14398 html
14399 "<tr>"
14400 (mapconcat (lambda (x)
14401 (if head
14402 (concat "<th>" x "</th>")
14403 (concat "<td>" x "</td>")))
14404 fields "")
14405 "</tr>\n"))))
14406 (setq html (concat html "</table>\n"))
14407 html))
14408
14409 (defun org-fake-empty-table-line (line)
14410 "Replace everything except \"|\" with spaces."
14411 (let ((i (length line))
14412 (newstr (copy-sequence line)))
14413 (while (> i 0)
14414 (setq i (1- i))
14415 (if (not (eq (aref newstr i) ?|))
14416 (aset newstr i ?\ )))
14417 newstr))
14418
14419 (defun org-format-table-table-html (lines)
14420 "Format a table generated by table.el into HTML.
14421 This conversion does *not* use `table-generate-source' from table.el.
14422 This has the advantage that Org-mode's HTML conversions can be used.
14423 But it has the disadvantage, that no cell- or row-spanning is allowed."
14424 (let (line field-buffer
14425 (head org-export-highlight-first-table-line)
14426 fields html empty)
14427 (setq html (concat org-export-html-table-tag "\n"))
14428 (while (setq line (pop lines))
14429 (setq empty "&nbsp;")
14430 (catch 'next-line
14431 (if (string-match "^[ \t]*\\+-" line)
14432 (progn
14433 (if field-buffer
14434 (progn
14435 (setq html (concat
14436 html
14437 "<tr>"
14438 (mapconcat
14439 (lambda (x)
14440 (if (equal x "") (setq x empty))
14441 (if head
14442 (concat "<th>" x "</th>\n")
14443 (concat "<td>" x "</td>\n")))
14444 field-buffer "\n")
14445 "</tr>\n"))
14446 (setq head nil)
14447 (setq field-buffer nil)))
14448 ;; Ignore this line
14449 (throw 'next-line t)))
14450 ;; Break the line into fields and store the fields
14451 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14452 (if field-buffer
14453 (setq field-buffer (mapcar
14454 (lambda (x)
14455 (concat x "<br/>" (pop fields)))
14456 field-buffer))
14457 (setq field-buffer fields))))
14458 (setq html (concat html "</table>\n"))
14459 html))
14460
14461 (defun org-format-table-table-html-using-table-generate-source (lines)
14462 "Format a table into html, using `table-generate-source' from table.el.
14463 This has the advantage that cell- or row-spanning is allowed.
14464 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
14465 (require 'table)
14466 (with-current-buffer (get-buffer-create " org-tmp1 ")
14467 (erase-buffer)
14468 (insert (mapconcat 'identity lines "\n"))
14469 (goto-char (point-min))
14470 (if (not (re-search-forward "|[^+]" nil t))
14471 (error "Error processing table"))
14472 (table-recognize-table)
14473 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
14474 (table-generate-source 'html " org-tmp2 ")
14475 (set-buffer " org-tmp2 ")
14476 (buffer-substring (point-min) (point-max))))
14477
14478 (defun org-html-handle-time-stamps (s)
14479 "Format time stamps in string S, or remove them."
14480 (catch 'exit
14481 (let (r b)
14482 (while (string-match org-maybe-keyword-time-regexp s)
14483 ;; FIXME: is it good to never export CLOCK, or do we need control?
14484 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
14485 (throw 'exit ""))
14486 (or b (setq b (substring s 0 (match-beginning 0))))
14487 (if (not org-export-with-timestamps)
14488 (setq r (concat r (substring s 0 (match-beginning 0)))
14489 s (substring s (match-end 0)))
14490 (setq r (concat
14491 r (substring s 0 (match-beginning 0))
14492 (if (match-end 1)
14493 (format "@<span class=\"timestamp-kwd\">%s @</span>"
14494 (match-string 1 s)))
14495 (format " @<span class=\"timestamp\">%s@</span>"
14496 (substring (match-string 3 s) 1 -1)))
14497 s (substring s (match-end 0)))))
14498 ;; Line break if line started and ended with time stamp stuff
14499 (if (not r)
14500 s
14501 (setq r (concat r s))
14502 (unless (string-match "\\S-" (concat b s))
14503 (setq r (concat r "@<br/>")))
14504 r))))
14505
14506 (defun org-html-protect (s)
14507 ;; convert & to &amp;, < to &lt; and > to &gt;
14508 (let ((start 0))
14509 (while (string-match "&" s start)
14510 (setq s (replace-match "&amp;" t t s)
14511 start (1+ (match-beginning 0))))
14512 (while (string-match "<" s)
14513 (setq s (replace-match "&lt;" t t s)))
14514 (while (string-match ">" s)
14515 (setq s (replace-match "&gt;" t t s))))
14516 s)
14517
14518 (defun org-export-cleanup-toc-line (s)
14519 "Remove tags and time staps from lines going into the toc."
14520 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
14521 (setq s (replace-match "" t t s)))
14522 (when org-export-remove-timestamps-from-toc
14523 (while (string-match org-maybe-keyword-time-regexp s)
14524 (setq s (replace-match "" t t s))))
14525 s)
14526
14527 (defun org-html-expand (string)
14528 "Prepare STRING for HTML export. Applies all active conversions.
14529 If there are links in the string, don't modify these."
14530 (let* (m s l res)
14531 (while (setq m (string-match org-bracket-link-regexp string))
14532 (setq s (substring string 0 m)
14533 l (match-string 0 string)
14534 string (substring string (match-end 0)))
14535 (push (org-html-do-expand s) res)
14536 (push l res))
14537 (push (org-html-do-expand string) res)
14538 (apply 'concat (nreverse res))))
14539
14540 (defun org-html-do-expand (s)
14541 "Apply all active conversions to translate special ASCII to HTML."
14542 (setq s (org-html-protect s))
14543 (if org-export-html-expand
14544 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
14545 (setq s (replace-match "<\\1>" t nil s))))
14546 (if org-export-with-emphasize
14547 (setq s (org-export-html-convert-emphasize s)))
14548 (if org-export-with-sub-superscripts
14549 (setq s (org-export-html-convert-sub-super s)))
14550 (if org-export-with-TeX-macros
14551 (let ((start 0) wd ass)
14552 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
14553 (setq wd (match-string 1 s))
14554 (if (setq ass (assoc wd org-html-entities))
14555 (setq s (replace-match (or (cdr ass)
14556 (concat "&" (car ass) ";"))
14557 t t s))
14558 (setq start (+ start (length wd)))))))
14559 s)
14560
14561 (defun org-create-multibrace-regexp (left right n)
14562 "Create a regular expression which will match a balanced sexp.
14563 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
14564 as single character strings.
14565 The regexp returned will match the entire expression including the
14566 delimiters. It will also define a single group which contains the
14567 match except for the outermost delimiters. The maximum depth of
14568 stacked delimiters is N. Escaping delimiters is not possible."
14569 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
14570 (or "\\|")
14571 (re nothing)
14572 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
14573 (while (> n 1)
14574 (setq n (1- n)
14575 re (concat re or next)
14576 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
14577 (concat left "\\(" re "\\)" right)))
14578
14579 (defvar org-match-substring-regexp
14580 (concat
14581 "\\([^\\]\\)\\([_^]\\)\\("
14582 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
14583 "\\|"
14584 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
14585 "\\|"
14586 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
14587 "The regular expression matching a sub- or superscript.")
14588
14589 (defun org-export-html-convert-sub-super (string)
14590 "Convert sub- and superscripts in STRING to HTML."
14591 (let (key c)
14592 (while (string-match org-match-substring-regexp string)
14593 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
14594 (setq c (or (match-string 8 string)
14595 (match-string 6 string)
14596 (match-string 5 string)))
14597 (setq string (replace-match
14598 (concat (match-string 1 string)
14599 "<" key ">" c "</" key ">")
14600 t t string)))
14601 (while (string-match "\\\\\\([_^]\\)" string)
14602 (setq string (replace-match (match-string 1 string) t t string))))
14603 string)
14604
14605 (defun org-export-html-convert-emphasize (string)
14606 "Apply emphasis."
14607 (while (string-match org-emph-re string)
14608 (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)))
14609 string)
14610
14611 (defvar org-par-open nil)
14612 (defun org-open-par ()
14613 "Insert <p>, but first close previous paragraph if any."
14614 (org-close-par-maybe)
14615 (insert "\n<p>")
14616 (setq org-par-open t))
14617 (defun org-close-par-maybe ()
14618 "Close paragraph if there is one open."
14619 (when org-par-open
14620 (insert "</p>")
14621 (setq org-par-open nil)))
14622 (defun org-close-li ()
14623 "Close <li> if necessary."
14624 (org-close-par-maybe)
14625 (insert "</li>\n"))
14626 ; (when (save-excursion
14627 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
14628 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
14629 ; (insert "</li>"))))
14630
14631 (defun org-html-level-start (level title umax with-toc head-count)
14632 "Insert a new level in HTML export.
14633 When TITLE is nil, just close all open levels."
14634 (org-close-par-maybe)
14635 (let ((l (1+ (max level umax))))
14636 (while (<= l org-level-max)
14637 (if (aref levels-open (1- l))
14638 (progn
14639 (org-html-level-close l)
14640 (aset levels-open (1- l) nil)))
14641 (setq l (1+ l)))
14642 (when title
14643 ;; If title is nil, this means this function is called to close
14644 ;; all levels, so the rest is done only if title is given
14645 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14646 (setq title (replace-match
14647 (if org-export-with-tags
14648 (save-match-data
14649 (concat
14650 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
14651 (mapconcat 'identity (org-split-string
14652 (match-string 1 title) ":")
14653 "&nbsp;")
14654 "</span>"))
14655 "")
14656 t t title)))
14657 (if (> level umax)
14658 (progn
14659 (if (aref levels-open (1- level))
14660 (progn
14661 (org-close-li)
14662 (insert "<li>" title "<br/>\n"))
14663 (aset levels-open (1- level) t)
14664 (org-close-par-maybe)
14665 (insert "<ul>\n<li>" title "<br/>\n")))
14666 (if org-export-with-section-numbers
14667 (setq title (concat (org-section-number level) " " title)))
14668 (setq level (+ level org-export-html-toplevel-hlevel -1))
14669 (if with-toc
14670 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
14671 level head-count title level))
14672 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
14673 (org-open-par)))))
14674
14675 (defun org-html-level-close (&rest args)
14676 "Terminate one level in HTML export."
14677 (org-close-li)
14678 (insert "</ul>"))
14679
14680 ;; Variable holding the vector with section numbers
14681 (defvar org-section-numbers (make-vector org-level-max 0))
14682
14683 (defun org-init-section-numbers ()
14684 "Initialize the vector for the section numbers."
14685 (let* ((level -1)
14686 (numbers (nreverse (org-split-string "" "\\.")))
14687 (depth (1- (length org-section-numbers)))
14688 (i depth) number-string)
14689 (while (>= i 0)
14690 (if (> i level)
14691 (aset org-section-numbers i 0)
14692 (setq number-string (or (car numbers) "0"))
14693 (if (string-match "\\`[A-Z]\\'" number-string)
14694 (aset org-section-numbers i
14695 (- (string-to-char number-string) ?A -1))
14696 (aset org-section-numbers i (string-to-number number-string)))
14697 (pop numbers))
14698 (setq i (1- i)))))
14699
14700 (defun org-section-number (&optional level)
14701 "Return a string with the current section number.
14702 When LEVEL is non-nil, increase section numbers on that level."
14703 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
14704 (when level
14705 (when (> level -1)
14706 (aset org-section-numbers
14707 level (1+ (aref org-section-numbers level))))
14708 (setq idx (1+ level))
14709 (while (<= idx depth)
14710 (if (not (= idx 1))
14711 (aset org-section-numbers idx 0))
14712 (setq idx (1+ idx))))
14713 (setq idx 0)
14714 (while (<= idx depth)
14715 (setq n (aref org-section-numbers idx))
14716 (setq string (concat string (if (not (string= string "")) "." "")
14717 (int-to-string n)))
14718 (setq idx (1+ idx)))
14719 (save-match-data
14720 (if (string-match "\\`\\([@0]\\.\\)+" string)
14721 (setq string (replace-match "" t nil string)))
14722 (if (string-match "\\(\\.0\\)+\\'" string)
14723 (setq string (replace-match "" t nil string))))
14724 string))
14725
14726
14727 ;;;###autoload
14728 (defun org-export-icalendar-this-file ()
14729 "Export current file as an iCalendar file.
14730 The iCalendar file will be located in the same directory as the Org-mode
14731 file, but with extension `.ics'."
14732 (interactive)
14733 (org-export-icalendar nil buffer-file-name))
14734
14735 (defun org-export-as-xoxo-insert-into (buffer &rest output)
14736 (with-current-buffer buffer
14737 (apply 'insert output)))
14738
14739 (defun org-export-as-xoxo (&optional buffer)
14740 "Export the org buffer as XOXO.
14741 The XOXO buffer is named *xoxo-<source buffer name>*"
14742 (interactive (list (current-buffer)))
14743 ;; A quickie abstraction
14744
14745 ;; Output everything as XOXO
14746 (with-current-buffer (get-buffer buffer)
14747 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
14748 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14749 (org-infile-export-plist)))
14750 (filename (concat (file-name-as-directory
14751 (org-export-directory :xoxo opt-plist))
14752 (file-name-sans-extension
14753 (file-name-nondirectory buffer-file-name))
14754 ".html"))
14755 (out (find-file-noselect filename))
14756 (last-level 1)
14757 (hanging-li nil))
14758 ;; Check the output buffer is empty.
14759 (with-current-buffer out (erase-buffer))
14760 ;; Kick off the output
14761 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
14762 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
14763 (let* ((hd (match-string-no-properties 1))
14764 (level (length hd))
14765 (text (concat
14766 (match-string-no-properties 2)
14767 (save-excursion
14768 (goto-char (match-end 0))
14769 (let ((str ""))
14770 (catch 'loop
14771 (while 't
14772 (forward-line)
14773 (if (looking-at "^[ \t]\\(.*\\)")
14774 (setq str (concat str (match-string-no-properties 1)))
14775 (throw 'loop str)))))))))
14776
14777 ;; Handle level rendering
14778 (cond
14779 ((> level last-level)
14780 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
14781
14782 ((< level last-level)
14783 (dotimes (- (- last-level level) 1)
14784 (if hanging-li
14785 (org-export-as-xoxo-insert-into out "</li>\n"))
14786 (org-export-as-xoxo-insert-into out "</ol>\n"))
14787 (when hanging-li
14788 (org-export-as-xoxo-insert-into out "</li>\n")
14789 (setq hanging-li nil)))
14790
14791 ((equal level last-level)
14792 (if hanging-li
14793 (org-export-as-xoxo-insert-into out "</li>\n")))
14794 )
14795
14796 (setq last-level level)
14797
14798 ;; And output the new li
14799 (setq hanging-li 't)
14800 (if (equal ?+ (elt text 0))
14801 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
14802 (org-export-as-xoxo-insert-into out "<li>" text))))
14803
14804 ;; Finally finish off the ol
14805 (dotimes (- last-level 1)
14806 (if hanging-li
14807 (org-export-as-xoxo-insert-into out "</li>\n"))
14808 (org-export-as-xoxo-insert-into out "</ol>\n"))
14809
14810 ;; Finish the buffer off and clean it up.
14811 (switch-to-buffer-other-window out)
14812 (indent-region (point-min) (point-max) nil)
14813 (save-buffer)
14814 (goto-char (point-min))
14815 )))
14816
14817 ;;;###autoload
14818 (defun org-export-icalendar-all-agenda-files ()
14819 "Export all files in `org-agenda-files' to iCalendar .ics files.
14820 Each iCalendar file will be located in the same directory as the Org-mode
14821 file, but with extension `.ics'."
14822 (interactive)
14823 (apply 'org-export-icalendar nil (org-agenda-files t)))
14824
14825 ;;;###autoload
14826 (defun org-export-icalendar-combine-agenda-files ()
14827 "Export all files in `org-agenda-files' to a single combined iCalendar file.
14828 The file is stored under the name `org-combined-agenda-icalendar-file'."
14829 (interactive)
14830 (apply 'org-export-icalendar t (org-agenda-files t)))
14831
14832 (defun org-export-icalendar (combine &rest files)
14833 "Create iCalendar files for all elements of FILES.
14834 If COMBINE is non-nil, combine all calendar entries into a single large
14835 file and store it under the name `org-combined-agenda-icalendar-file'."
14836 (save-excursion
14837 (let* ((dir (org-export-directory
14838 :ical (list :publishing-directory
14839 org-export-publishing-directory)))
14840 file ical-file ical-buffer category started org-agenda-new-buffers)
14841
14842 (when combine
14843 (setq ical-file
14844 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
14845 org-combined-agenda-icalendar-file
14846 (expand-file-name org-combined-agenda-icalendar-file dir))
14847 ical-buffer (org-get-agenda-file-buffer ical-file))
14848 (set-buffer ical-buffer) (erase-buffer))
14849 (while (setq file (pop files))
14850 (catch 'nextfile
14851 (org-check-agenda-file file)
14852 (set-buffer (org-get-agenda-file-buffer file))
14853 (unless combine
14854 (setq ical-file (concat (file-name-as-directory dir)
14855 (file-name-sans-extension
14856 (file-name-nondirectory buffer-file-name))
14857 ".ics"))
14858 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
14859 (with-current-buffer ical-buffer (erase-buffer)))
14860 (setq category (or org-category
14861 (file-name-sans-extension
14862 (file-name-nondirectory buffer-file-name))))
14863 (if (symbolp category) (setq category (symbol-name category)))
14864 (let ((standard-output ical-buffer))
14865 (if combine
14866 (and (not started) (setq started t)
14867 (org-start-icalendar-file org-icalendar-combined-name))
14868 (org-start-icalendar-file category))
14869 (org-print-icalendar-entries combine category)
14870 (when (or (and combine (not files)) (not combine))
14871 (org-finish-icalendar-file)
14872 (set-buffer ical-buffer)
14873 (save-buffer)
14874 (run-hooks 'org-after-save-iCalendar-file-hook)))))
14875 (org-release-buffers org-agenda-new-buffers))))
14876
14877 (defvar org-after-save-iCalendar-file-hook nil
14878 "Hook run after an iCalendar file has been saved.
14879 The iCalendar buffer is still current when this hook is run.
14880 A good way to use this is to tell a desktop calenndar application to re-read
14881 the iCalendar file.")
14882
14883 (defun org-print-icalendar-entries (&optional combine category)
14884 "Print iCalendar entries for the current Org-mode file to `standard-output'.
14885 When COMBINE is non nil, add the category to each line."
14886 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
14887 (dts (org-ical-ts-to-string
14888 (format-time-string (cdr org-time-stamp-formats) (current-time))
14889 "DTSTART"))
14890 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
14891 (save-excursion
14892 (goto-char (point-min))
14893 (while (re-search-forward org-ts-regexp nil t)
14894 (setq pos (match-beginning 0)
14895 ts (match-string 0)
14896 inc t
14897 hd (org-get-heading))
14898 (if (looking-at re2)
14899 (progn
14900 (goto-char (match-end 0))
14901 (setq ts2 (match-string 1) inc nil))
14902 (setq ts2 ts
14903 tmp (buffer-substring (max (point-min)
14904 (- pos org-ds-keyword-length))
14905 pos)
14906 deadlinep (string-match org-deadline-regexp tmp)
14907 scheduledp (string-match org-scheduled-regexp tmp)
14908 ;; donep (org-entry-is-done-p)
14909 ))
14910 (if (or (string-match org-tr-regexp hd)
14911 (string-match org-ts-regexp hd))
14912 (setq hd (replace-match "" t t hd)))
14913 (if combine
14914 (setq hd (concat hd " (category " category ")")))
14915 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
14916 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
14917 (princ (format "BEGIN:VEVENT
14918 %s
14919 %s
14920 SUMMARY:%s
14921 END:VEVENT\n"
14922 (org-ical-ts-to-string ts "DTSTART")
14923 (org-ical-ts-to-string ts2 "DTEND" inc)
14924 hd)))
14925 (when org-icalendar-include-todo
14926 (goto-char (point-min))
14927 (while (re-search-forward org-todo-line-regexp nil t)
14928 (setq state (match-string 1))
14929 (unless (equal state org-done-string)
14930 (setq hd (match-string 3))
14931 (if (string-match org-priority-regexp hd)
14932 (setq pri (string-to-char (match-string 2 hd))
14933 hd (concat (substring hd 0 (match-beginning 1))
14934 (substring hd (- (match-end 1)))))
14935 (setq pri org-default-priority))
14936 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
14937 (- org-lowest-priority ?A))))))
14938
14939 (princ (format "BEGIN:VTODO
14940 %s
14941 SUMMARY:%s
14942 SEQUENCE:1
14943 PRIORITY:%d
14944 END:VTODO\n"
14945 dts hd pri))))))))
14946
14947 (defun org-start-icalendar-file (name)
14948 "Start an iCalendar file by inserting the header."
14949 (let ((user user-full-name)
14950 (name (or name "unknown"))
14951 (timezone (cadr (current-time-zone))))
14952 (princ
14953 (format "BEGIN:VCALENDAR
14954 VERSION:2.0
14955 X-WR-CALNAME:%s
14956 PRODID:-//%s//Emacs with Org-mode//EN
14957 X-WR-TIMEZONE:%s
14958 CALSCALE:GREGORIAN\n" name user timezone))))
14959
14960 (defun org-finish-icalendar-file ()
14961 "Finish an iCalendar file by inserting the END statement."
14962 (princ "END:VCALENDAR\n"))
14963
14964 (defun org-ical-ts-to-string (s keyword &optional inc)
14965 "Take a time string S and convert it to iCalendar format.
14966 KEYWORD is added in front, to make a complete line like DTSTART....
14967 When INC is non-nil, increase the hour by two (if time string contains
14968 a time), or the day by one (if it does not contain a time)."
14969 (let ((t1 (org-parse-time-string s 'nodefault))
14970 t2 fmt have-time time)
14971 (if (and (car t1) (nth 1 t1) (nth 2 t1))
14972 (setq t2 t1 have-time t)
14973 (setq t2 (org-parse-time-string s)))
14974 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
14975 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
14976 (when inc
14977 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
14978 (setq time (encode-time s mi h d m y)))
14979 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
14980 (concat keyword (format-time-string fmt time))))
14981
14982 ;;; LaTeX stuff
14983
14984 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14985 "Keymap for the minor `org-cdlatex-mode'.")
14986
14987 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14988 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14989 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14990 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14991 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14992
14993 (defvar org-cdlatex-texmathp-advice-is-done nil
14994 "Flag remembering if we have applied the advice to texmathp already.")
14995
14996 (define-minor-mode org-cdlatex-mode
14997 "Toggle the minor `org-cdlatex-mode'.
14998 This mode supports entering LaTeX environment and math in LaTeX fragments
14999 in Org-mode.
15000 \\{org-cdlatex-mode-map}"
15001 nil " OCDL" nil
15002 (when org-cdlatex-mode (require 'cdlatex))
15003 (unless org-cdlatex-texmathp-advice-is-done
15004 (setq org-cdlatex-texmathp-advice-is-done t)
15005 (defadvice texmathp (around org-math-always-on activate)
15006 "Always return t in org-mode buffers.
15007 This is because we want to insert math symbols without dollars even outside
15008 the LaTeX math segments. If Orgmode thinks that point is actually inside
15009 en embedded LaTeX fragement, let texmathp do its job.
15010 \\[org-cdlatex-mode-map]"
15011 (interactive)
15012 (let (p)
15013 (cond
15014 ((not (org-mode-p)) ad-do-it)
15015 ((eq this-command 'cdlatex-math-symbol)
15016 (setq ad-return-value t
15017 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15018 (t
15019 (let ((p (org-inside-LaTeX-fragment-p)))
15020 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15021 (setq ad-return-value t
15022 texmathp-why '("Org-mode embedded math" . 0))
15023 (if p ad-do-it)))))))))
15024
15025 (defun turn-on-org-cdlatex ()
15026 "Unconditionally turn on `org-cdlatex-mode'."
15027 (org-cdlatex-mode 1))
15028
15029 (defun org-inside-LaTeX-fragment-p ()
15030 "Test if point is inside a LaTeX fragment.
15031 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15032 sequence appearing also before point.
15033 Even though the matchers for math are configurable, this function assumes
15034 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15035 delimiters are skipped when they have been removed by customization.
15036 The return value is nil, or a cons cell with the delimiter and
15037 and the position of this delimiter.
15038
15039 This function does a reasonably good job, but can locally be fooled by
15040 for example currency specifications. For example it will assume being in
15041 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15042 fragments that are properly closed, but during editing, we have to live
15043 with the uncertainty caused by missing closing delimiters. This function
15044 looks only before point, not after."
15045 (catch 'exit
15046 (let ((pos (point))
15047 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15048 (lim (progn
15049 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15050 (point)))
15051 dd-on str (start 0) m re)
15052 (goto-char pos)
15053 (when dodollar
15054 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15055 re (nth 1 (assoc "$" org-latex-regexps)))
15056 (while (string-match re str start)
15057 (cond
15058 ((= (match-end 0) (length str))
15059 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
15060 ((= (match-end 0) (- (length str) 5))
15061 (throw 'exit nil))
15062 (t (setq start (match-end 0))))))
15063 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15064 (goto-char pos)
15065 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15066 (and (match-beginning 2) (throw 'exit nil))
15067 ;; count $$
15068 (while (re-search-backward "\\$\\$" lim t)
15069 (setq dd-on (not dd-on)))
15070 (goto-char pos)
15071 (if dd-on (cons "$$" m))))))
15072
15073
15074 (defun org-try-cdlatex-tab ()
15075 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15076 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15077 - inside a LaTeX fragment, or
15078 - after the first word in a line, where an abbreviation expansion could
15079 insert a LaTeX environment."
15080 ;; FIXME: This may still need refinement.
15081 (when org-cdlatex-mode
15082 (cond
15083 ((save-excursion
15084 (skip-chars-backward "a-zA-Z0-9*")
15085 (skip-chars-backward " \t")
15086 (bolp))
15087 (cdlatex-tab) t)
15088 ((org-inside-LaTeX-fragment-p)
15089 (cdlatex-tab) t)
15090 (t nil))))
15091
15092 (defun org-cdlatex-underscore-caret (&optional arg)
15093 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15094 Revert to the normal definition outside of these fragments."
15095 (interactive "P")
15096 (if (org-inside-LaTeX-fragment-p)
15097 (call-interactively 'cdlatex-sub-superscript)
15098 (let (org-cdlatex-mode)
15099 (call-interactively (key-binding (vector last-input-event))))))
15100
15101 (defun org-cdlatex-math-modify (&optional arg)
15102 "Execute `cdlatex-math-modify' in LaTeX fragments.
15103 Revert to the normal definition outside of these fragments."
15104 (interactive "P")
15105 (if (org-inside-LaTeX-fragment-p)
15106 (call-interactively 'cdlatex-math-modify)
15107 (let (org-cdlatex-mode)
15108 (call-interactively (key-binding (vector last-input-event))))))
15109
15110 (defvar org-latex-fragment-image-overlays nil
15111 "List of overlays carrying the images of latex fragments.")
15112 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15113
15114 (defun org-remove-latex-fragment-image-overlays ()
15115 "Remove all overlays with LaTeX fragment images in current buffer."
15116 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15117 (setq org-latex-fragment-image-overlays nil))
15118
15119 (defun org-preview-latex-fragment (&optional subtree)
15120 "Preview the LaTeX fragment at point, or all locally or globally.
15121 If the cursor is in a LaTeX fragment, create the image and overlay
15122 it over the source code. If there is no fragment at point, display
15123 all fragments in the current text, from one headline to the next. With
15124 prefix SUBTREE, display all fragments in the current subtree. With a
15125 double prefix `C-u C-u', or when the cursor is before the first headline,
15126 display all fragments in the buffer.
15127 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15128 (interactive "P")
15129 (org-remove-latex-fragment-image-overlays)
15130 (save-excursion
15131 (save-restriction
15132 (let (beg end at msg)
15133 (cond
15134 ((or (equal subtree '(16))
15135 (not (save-excursion
15136 (re-search-backward (concat "^" outline-regexp) nil t))))
15137 (setq beg (point-min) end (point-max)
15138 msg "Creating images for buffer...%s"))
15139 ((equal subtree '(4))
15140 (org-back-to-heading)
15141 (setq beg (point) end (org-end-of-subtree)
15142 msg "Creating images for subtree...%s"))
15143 (t
15144 (if (setq at (org-inside-LaTeX-fragment-p))
15145 (goto-char (max (point-min) (- (cdr at) 2)))
15146 (org-back-to-heading))
15147 (setq beg (point) end (progn (outline-next-heading) (point))
15148 msg (if at "Creating image...%s"
15149 "Creating images for entry...%s"))))
15150 (message msg "")
15151 (narrow-to-region beg end)
15152 (org-format-latex
15153 (concat "ltxpng/" (file-name-sans-extension
15154 (file-name-nondirectory
15155 buffer-file-name)))
15156 default-directory 'overlays msg at)
15157 (message msg "done. Use `C-c C-c' to remove images.")))))
15158
15159 (defvar org-latex-regexps
15160 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15161 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15162 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15163 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
15164 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15165 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
15166 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
15167 "Regular expressions for matching embedded LaTeX.")
15168
15169 (defun org-format-latex (prefix &optional dir overlays msg at)
15170 "Replace LaTeX fragments with links to an image, and produce images."
15171 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15172 (let* ((prefixnodir (file-name-nondirectory prefix))
15173 (absprefix (expand-file-name prefix dir))
15174 (todir (file-name-directory absprefix))
15175 (opt org-format-latex-options)
15176 (matchers (plist-get opt :matchers))
15177 (re-list org-latex-regexps)
15178 (cnt 0) txt link beg end re e oldfiles
15179 m n block linkfile movefile ov)
15180 ;; Make sure the directory exists
15181 (or (file-directory-p todir) (make-directory todir))
15182 ;; Check if there are old images files with this prefix, and remove them
15183 (setq oldfiles (directory-files
15184 todir 'full
15185 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
15186 (while oldfiles (delete-file (pop oldfiles)))
15187 ;; Check the different regular expressions
15188 (while (setq e (pop re-list))
15189 (setq m (car e) re (nth 1 e) n (nth 2 e)
15190 block (if (nth 3 e) "\n\n" ""))
15191 (when (member m matchers)
15192 (goto-char (point-min))
15193 (while (re-search-forward re nil t)
15194 (when (or (not at) (equal (cdr at) (match-beginning n)))
15195 (setq txt (match-string n)
15196 beg (match-beginning n) end (match-end n)
15197 cnt (1+ cnt)
15198 linkfile (format "%s_%04d.png" prefix cnt)
15199 movefile (format "%s_%04d.png" absprefix cnt)
15200 link (concat block "[[file:" linkfile "]]" block))
15201 (if msg (message msg cnt))
15202 (goto-char beg)
15203 (org-create-formula-image
15204 txt movefile opt)
15205 (if overlays
15206 (progn
15207 (setq ov (org-make-overlay beg end))
15208 (if (featurep 'xemacs)
15209 (progn
15210 (org-overlay-put ov 'invisible t)
15211 (org-overlay-put
15212 ov 'end-glyph
15213 (make-glyph (vector 'png :file movefile))))
15214 (org-overlay-put
15215 ov 'display
15216 (list 'image :type 'png :file movefile :ascent 'center)))
15217 (push ov org-latex-fragment-image-overlays)
15218 (goto-char end))
15219 (delete-region beg end)
15220 (insert link))))))))
15221
15222 ;; This function borrows from Ganesh Swami's latex2png.el
15223 (defun org-create-formula-image (string tofile options)
15224 (let* ((tmpdir (if (featurep 'xemacs)
15225 (temp-directory)
15226 temporary-file-directory))
15227 (texfilebase (make-temp-name
15228 (expand-file-name "orgtex" tmpdir)))
15229
15230 ;(texfilebase (make-temp-file "orgtex"))
15231 ; (dummy (delete-file texfilebase))
15232 (texfile (concat texfilebase ".tex"))
15233 (dvifile (concat texfilebase ".dvi"))
15234 (pngfile (concat texfilebase ".png"))
15235 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15236 (fg (or (plist-get options :foreground) "Black"))
15237 (bg (or (plist-get options :background) "Transparent")))
15238 (with-temp-file texfile
15239 (insert "\\documentclass{article}
15240 \\usepackage{fullpage}
15241 \\usepackage{amssymb}
15242 \\usepackage[usenames]{color}
15243 \\usepackage{amsmath}
15244 \\usepackage{latexsym}
15245 \\usepackage[mathscr]{eucal}
15246 \\pagestyle{empty}
15247 \\begin{document}\n" string "\n\\end{document}\n"))
15248 (let ((dir default-directory))
15249 (condition-case nil
15250 (progn
15251 (cd tmpdir)
15252 (call-process "latex" nil nil nil texfile))
15253 (error nil))
15254 (cd dir))
15255 (if (not (file-exists-p dvifile))
15256 (progn (message "Failed to create dvi file from %s" texfile) nil)
15257 (call-process "dvipng" nil nil nil
15258 "-E" "-fg" fg "-bg" bg
15259 "-x" scale "-y" scale "-T" "tight"
15260 "-o" pngfile
15261 dvifile)
15262 (if (not (file-exists-p pngfile))
15263 (progn (message "Failed to create png file from %s" texfile) nil)
15264 ;; Use the requested file name and clean up
15265 (copy-file pngfile tofile 'replace)
15266 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15267 (delete-file (concat texfilebase e)))
15268 pngfile))))
15269
15270 ;;; Key bindings
15271
15272 ;; - Bindings in Org-mode map are currently
15273 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
15274 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
15275 ;; e (?) useful from outline-mode
15276 ;; i k @ expendable from outline-mode
15277 ;; 0123456789 % & ()_{} " ` free
15278
15279 ;; Make `C-c C-x' a prefix key
15280 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
15281
15282 ;; TAB key with modifiers
15283 (define-key org-mode-map "\C-i" 'org-cycle)
15284 (define-key org-mode-map [(tab)] 'org-cycle)
15285 (define-key org-mode-map [(meta tab)] 'org-complete)
15286 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
15287 ;; The following line is necessary under Suse GNU/Linux
15288 (unless (featurep 'xemacs)
15289 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
15290 (define-key org-mode-map [(shift tab)] 'org-shifttab)
15291
15292 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
15293 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
15294 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15295 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
15296 (define-key org-mode-map [(meta return)] 'org-meta-return)
15297 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
15298 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
15299
15300 ;; Cursor keys with modifiers
15301 (define-key org-mode-map [(meta left)] 'org-metaleft)
15302 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
15303 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
15304 (define-key org-mode-map [(meta right)] 'org-metaright)
15305 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
15306 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
15307 (define-key org-mode-map [(meta up)] 'org-metaup)
15308 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
15309 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
15310 (define-key org-mode-map [(meta down)] 'org-metadown)
15311 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
15312 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
15313
15314 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15315 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
15316 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
15317 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
15318 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
15319 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
15320 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
15321 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
15322 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
15323 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
15324 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
15325 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
15326 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
15327 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
15328 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
15329 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
15330
15331 ;; All the other keys
15332
15333 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15334 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
15335 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
15336 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
15337 (define-key org-mode-map "\C-c\C-j" 'org-goto)
15338 (define-key org-mode-map "\C-c\C-t" 'org-todo)
15339 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
15340 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
15341 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
15342 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15343 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
15344 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
15345 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
15346 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
15347 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
15348 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
15349 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
15350 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
15351 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
15352 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
15353 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15354 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15355 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15356 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15357 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
15358 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
15359 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15360 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
15361 (define-key org-mode-map "\C-c]" 'org-remove-file)
15362 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
15363 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
15364 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
15365 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15366 (define-key org-mode-map "\C-m" 'org-return)
15367 (define-key org-mode-map "\C-c?" 'org-table-current-column)
15368 (define-key org-mode-map "\C-c " 'org-table-blank-field)
15369 (define-key org-mode-map "\C-c+" 'org-table-sum)
15370 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
15371 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
15372 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
15373 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15374 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
15375 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15376 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
15377 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
15378 (define-key org-mode-map "\C-c\C-e" 'org-export)
15379 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15380
15381 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
15382 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15383 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15384 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15385
15386 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15387 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15388 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15389 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15390 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15391 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15392 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15393 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15394
15395 (when (featurep 'xemacs)
15396 (define-key org-mode-map 'button3 'popup-mode-menu))
15397
15398 (defsubst org-table-p () (org-at-table-p))
15399
15400 (defun org-self-insert-command (N)
15401 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15402 If the cursor is in a table looking at whitespace, the whitespace is
15403 overwritten, and the table is not marked as requiring realignment."
15404 (interactive "p")
15405 (if (and (org-table-p)
15406 (progn
15407 ;; check if we blank the field, and if that triggers align
15408 (and org-table-auto-blank-field
15409 (member last-command
15410 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
15411 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15412 ;; got extra space, this field does not determine column width
15413 (let (org-table-may-need-update) (org-table-blank-field))
15414 ;; no extra space, this field may determine column width
15415 (org-table-blank-field)))
15416 t)
15417 (eq N 1)
15418 (looking-at "[^|\n]* |"))
15419 (let (org-table-may-need-update)
15420 (goto-char (1- (match-end 0)))
15421 (delete-backward-char 1)
15422 (goto-char (match-beginning 0))
15423 (self-insert-command N))
15424 (setq org-table-may-need-update t)
15425 (self-insert-command N)))
15426
15427 (defun org-delete-backward-char (N)
15428 "Like `delete-backward-char', insert whitespace at field end in tables.
15429 When deleting backwards, in tables this function will insert whitespace in
15430 front of the next \"|\" separator, to keep the table aligned. The table will
15431 still be marked for re-alignment if the field did fill the entire column,
15432 because, in this case the deletion might narrow the column."
15433 (interactive "p")
15434 (if (and (org-table-p)
15435 (eq N 1)
15436 (string-match "|" (buffer-substring (point-at-bol) (point)))
15437 (looking-at ".*?|"))
15438 (let ((pos (point))
15439 (noalign (looking-at "[^|\n\r]* |"))
15440 (c org-table-may-need-update))
15441 (backward-delete-char N)
15442 (skip-chars-forward "^|")
15443 (insert " ")
15444 (goto-char (1- pos))
15445 ;; noalign: if there were two spaces at the end, this field
15446 ;; does not determine the width of the column.
15447 (if noalign (setq org-table-may-need-update c)))
15448 (backward-delete-char N)))
15449
15450 (defun org-delete-char (N)
15451 "Like `delete-char', but insert whitespace at field end in tables.
15452 When deleting characters, in tables this function will insert whitespace in
15453 front of the next \"|\" separator, to keep the table aligned. The table will
15454 still be marked for re-alignment if the field did fill the entire column,
15455 because, in this case the deletion might narrow the column."
15456 (interactive "p")
15457 (if (and (org-table-p)
15458 (not (bolp))
15459 (not (= (char-after) ?|))
15460 (eq N 1))
15461 (if (looking-at ".*?|")
15462 (let ((pos (point))
15463 (noalign (looking-at "[^|\n\r]* |"))
15464 (c org-table-may-need-update))
15465 (replace-match (concat
15466 (substring (match-string 0) 1 -1)
15467 " |"))
15468 (goto-char pos)
15469 ;; noalign: if there were two spaces at the end, this field
15470 ;; does not determine the width of the column.
15471 (if noalign (setq org-table-may-need-update c)))
15472 (delete-char N))
15473 (delete-char N)))
15474
15475 ;; How to do this: Measure non-white length of current string
15476 ;; If equal to column width, we should realign.
15477
15478 (defun org-remap (map &rest commands)
15479 "In MAP, remap the functions given in COMMANDS.
15480 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15481 (let (new old)
15482 (while commands
15483 (setq old (pop commands) new (pop commands))
15484 (if (fboundp 'command-remapping)
15485 (define-key map (vector 'remap old) new)
15486 (substitute-key-definition old new map global-map)))))
15487
15488 (when (eq org-enable-table-editor 'optimized)
15489 ;; If the user wants maximum table support, we need to hijack
15490 ;; some standard editing functions
15491 (org-remap org-mode-map
15492 'self-insert-command 'org-self-insert-command
15493 'delete-char 'org-delete-char
15494 'delete-backward-char 'org-delete-backward-char)
15495 (define-key org-mode-map "|" 'org-force-self-insert))
15496
15497 (defun org-shiftcursor-error ()
15498 "Throw an error because Shift-Cursor command was applied in wrong context."
15499 (error "This command is active in special context like tables, headlines or timestamps"))
15500
15501 (defun org-shifttab (&optional arg)
15502 "Global visibility cycling or move to previous table field.
15503 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15504 on context.
15505 See the individual commands for more information."
15506 (interactive "P")
15507 (cond
15508 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15509 (t (call-interactively 'org-global-cycle))))
15510
15511 (defun org-shiftmetaleft ()
15512 "Promote subtree or delete table column.
15513 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
15514 See the individual commands for more information."
15515 (interactive)
15516 (cond
15517 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15518 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15519 ((org-at-item-p) (call-interactively 'org-outdent-item))
15520 (t (org-shiftcursor-error))))
15521
15522 (defun org-shiftmetaright ()
15523 "Demote subtree or insert table column.
15524 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
15525 See the individual commands for more information."
15526 (interactive)
15527 (cond
15528 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15529 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15530 ((org-at-item-p) (call-interactively 'org-indent-item))
15531 (t (org-shiftcursor-error))))
15532
15533 (defun org-shiftmetaup (&optional arg)
15534 "Move subtree up or kill table row.
15535 Calls `org-move-subtree-up' or `org-table-kill-row' or
15536 `org-move-item-up' depending on context. See the individual commands
15537 for more information."
15538 (interactive "P")
15539 (cond
15540 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15541 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15542 ((org-at-item-p) (call-interactively 'org-move-item-up))
15543 (t (org-shiftcursor-error))))
15544 (defun org-shiftmetadown (&optional arg)
15545 "Move subtree down or insert table row.
15546 Calls `org-move-subtree-down' or `org-table-insert-row' or
15547 `org-move-item-down', depending on context. See the individual
15548 commands for more information."
15549 (interactive "P")
15550 (cond
15551 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15552 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15553 ((org-at-item-p) (call-interactively 'org-move-item-down))
15554 (t (org-shiftcursor-error))))
15555
15556 (defun org-metaleft (&optional arg)
15557 "Promote heading or move table column to left.
15558 Calls `org-do-promote' or `org-table-move-column', depending on context.
15559 With no specific context, calls the Emacs default `backward-word'.
15560 See the individual commands for more information."
15561 (interactive "P")
15562 (cond
15563 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15564 ((or (org-on-heading-p) (org-region-active-p))
15565 (call-interactively 'org-do-promote))
15566 (t (call-interactively 'backward-word))))
15567
15568 (defun org-metaright (&optional arg)
15569 "Demote subtree or move table column to right.
15570 Calls `org-do-demote' or `org-table-move-column', depending on context.
15571 With no specific context, calls the Emacs default `forward-word'.
15572 See the individual commands for more information."
15573 (interactive "P")
15574 (cond
15575 ((org-at-table-p) (call-interactively 'org-table-move-column))
15576 ((or (org-on-heading-p) (org-region-active-p))
15577 (call-interactively 'org-do-demote))
15578 (t (call-interactively 'forward-word))))
15579
15580 (defun org-metaup (&optional arg)
15581 "Move subtree up or move table row up.
15582 Calls `org-move-subtree-up' or `org-table-move-row' or
15583 `org-move-item-up', depending on context. See the individual commands
15584 for more information."
15585 (interactive "P")
15586 (cond
15587 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15588 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15589 ((org-at-item-p) (call-interactively 'org-move-item-up))
15590 (t (org-shiftcursor-error))))
15591
15592 (defun org-metadown (&optional arg)
15593 "Move subtree down or move table row down.
15594 Calls `org-move-subtree-down' or `org-table-move-row' or
15595 `org-move-item-down', depending on context. See the individual
15596 commands for more information."
15597 (interactive "P")
15598 (cond
15599 ((org-at-table-p) (call-interactively 'org-table-move-row))
15600 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15601 ((org-at-item-p) (call-interactively 'org-move-item-down))
15602 (t (org-shiftcursor-error))))
15603
15604 (defun org-shiftup (&optional arg)
15605 "Increase item in timestamp or increase priority of current headline.
15606 Calls `org-timestamp-up' or `org-priority-up', depending on context.
15607 See the individual commands for more information."
15608 (interactive "P")
15609 (cond
15610 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
15611 ((org-on-heading-p) (call-interactively 'org-priority-up))
15612 ((org-at-item-p) (call-interactively 'org-previous-item))
15613 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
15614
15615 (defun org-shiftdown (&optional arg)
15616 "Decrease item in timestamp or decrease priority of current headline.
15617 Calls `org-timestamp-down' or `org-priority-down', depending on context.
15618 See the individual commands for more information."
15619 (interactive "P")
15620 (cond
15621 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
15622 ((org-on-heading-p) (call-interactively 'org-priority-down))
15623 (t (call-interactively 'org-next-item))))
15624
15625 (defun org-shiftright ()
15626 "Next TODO keyword or timestamp one day later, depending on context."
15627 (interactive)
15628 (cond
15629 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15630 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
15631 (t (org-shiftcursor-error))))
15632
15633 (defun org-shiftleft ()
15634 "Previous TODO keyword or timestamp one day earlier, depending on context."
15635 (interactive)
15636 (cond
15637 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15638 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
15639 (t (org-shiftcursor-error))))
15640
15641 (defun org-copy-special ()
15642 "Copy region in table or copy current subtree.
15643 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15644 See the individual commands for more information."
15645 (interactive)
15646 (call-interactively
15647 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15648
15649 (defun org-cut-special ()
15650 "Cut region in table or cut current subtree.
15651 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15652 See the individual commands for more information."
15653 (interactive)
15654 (call-interactively
15655 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15656
15657 (defun org-paste-special (arg)
15658 "Paste rectangular region into table, or past subtree relative to level.
15659 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15660 See the individual commands for more information."
15661 (interactive "P")
15662 (if (org-at-table-p)
15663 (org-table-paste-rectangle)
15664 (org-paste-subtree arg)))
15665
15666 (defun org-ctrl-c-ctrl-c (&optional arg)
15667 "Set tags in headline, or update according to changed information at point.
15668
15669 This command does many different things, depending on context:
15670
15671 - If the cursor is in a headline, prompt for tags and insert them
15672 into the current line, aligned to `org-tags-column'. When called
15673 with prefix arg, realign all tags in the current buffer.
15674
15675 - If the cursor is in one of the special #+KEYWORD lines, this
15676 triggers scanning the buffer for these lines and updating the
15677 information.
15678
15679 - If the cursor is inside a table, realign the table. This command
15680 works even if the automatic table editor has been turned off.
15681
15682 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15683 the entire table.
15684
15685 - If the cursor is inside a table created by the table.el package,
15686 activate that table.
15687
15688 - If the current buffer is a remember buffer, close note and file it.
15689 with a prefix argument, file it without further interaction to the default
15690 location.
15691
15692 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15693 links in this buffer.
15694
15695 - If the cursor is on a numbered item in a plain list, renumber the
15696 ordered list."
15697 (interactive "P")
15698 (let ((org-enable-table-editor t))
15699 (cond
15700 ((or org-clock-overlays org-occur-highlights
15701 org-latex-fragment-image-overlays)
15702 (org-remove-clock-overlays)
15703 (org-remove-occur-highlights)
15704 (org-remove-latex-fragment-image-overlays)
15705 (message "Temporary highlights/overlays removed from current buffer"))
15706 ((and (local-variable-p 'org-finish-function (current-buffer))
15707 (fboundp org-finish-function))
15708 (funcall org-finish-function))
15709 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15710 ((org-on-heading-p) (call-interactively 'org-set-tags))
15711 ((org-at-table.el-p)
15712 (require 'table)
15713 (beginning-of-line 1)
15714 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15715 (call-interactively 'table-recognize-table))
15716 ((org-at-table-p)
15717 (org-table-maybe-eval-formula)
15718 (if arg
15719 (call-interactively 'org-table-recalculate)
15720 (org-table-maybe-recalculate-line))
15721 (call-interactively 'org-table-align))
15722 ((org-at-item-checkbox-p)
15723 (call-interactively 'org-toggle-checkbox))
15724 ((org-at-item-p)
15725 (call-interactively 'org-renumber-ordered-list))
15726 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
15727 (cond
15728 ((equal (match-string 1) "TBLFM")
15729 ;; Recalculate the table before this line
15730 (save-excursion
15731 (beginning-of-line 1)
15732 (skip-chars-backward " \r\n\t")
15733 (if (org-at-table-p)
15734 (org-call-with-arg 'org-table-recalculate t))))
15735 (t
15736 (call-interactively 'org-mode-restart))))
15737 (t (error "C-c C-c can do nothing useful at this location.")))))
15738
15739 (defun org-mode-restart ()
15740 "Restart Org-mode, to scan again for special lines.
15741 Also updates the keyword regular expressions."
15742 (interactive)
15743 (let ((org-inhibit-startup t)) (org-mode))
15744 (message "Org-mode restarted to refresh keyword and special line setup"))
15745
15746 (defun org-return ()
15747 "Goto next table row or insert a newline.
15748 Calls `org-table-next-row' or `newline', depending on context.
15749 See the individual commands for more information."
15750 (interactive)
15751 (cond
15752 ((org-at-table-p)
15753 (org-table-justify-field-maybe)
15754 (call-interactively 'org-table-next-row))
15755 (t (newline))))
15756
15757 (defun org-meta-return (&optional arg)
15758 "Insert a new heading or wrap a region in a table.
15759 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15760 See the individual commands for more information."
15761 (interactive "P")
15762 (cond
15763 ((org-at-table-p)
15764 (call-interactively 'org-table-wrap-region))
15765 (t (call-interactively 'org-insert-heading))))
15766
15767 ;;; Menu entries
15768
15769 ;; Define the Org-mode menus
15770 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15771 '("Tbl"
15772 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
15773 ["Next Field" org-cycle (org-at-table-p)]
15774 ["Previous Field" org-shifttab (org-at-table-p)]
15775 ["Next Row" org-return (org-at-table-p)]
15776 "--"
15777 ["Blank Field" org-table-blank-field (org-at-table-p)]
15778 ["Edit Field" org-table-edit-field (org-at-table-p)]
15779 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15780 "--"
15781 ("Column"
15782 ["Move Column Left" org-metaleft (org-at-table-p)]
15783 ["Move Column Right" org-metaright (org-at-table-p)]
15784 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15785 ["Insert Column" org-shiftmetaright (org-at-table-p)]
15786 "--"
15787 ["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])
15788 ("Row"
15789 ["Move Row Up" org-metaup (org-at-table-p)]
15790 ["Move Row Down" org-metadown (org-at-table-p)]
15791 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15792 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15793 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15794 "--"
15795 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
15796 ("Rectangle"
15797 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15798 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15799 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15800 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15801 "--"
15802 ("Calculate"
15803 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15804 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15805 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
15806 "--"
15807 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15808 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15809 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15810 "--"
15811 ["Sum Column/Rectangle" org-table-sum
15812 (or (org-at-table-p) (org-region-active-p))]
15813 ["Which Column?" org-table-current-column (org-at-table-p)])
15814 ["Debug Formulas"
15815 (setq org-table-formula-debug (not org-table-formula-debug))
15816 :style toggle :selected org-table-formula-debug]
15817 "--"
15818 ["Create" org-table-create (and (not (org-at-table-p))
15819 org-enable-table-editor)]
15820 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15821 ["Import from File" org-table-import (not (org-at-table-p))]
15822 ["Export to File" org-table-export (org-at-table-p)]
15823 "--"
15824 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15825
15826 (easy-menu-define org-org-menu org-mode-map "Org menu"
15827 '("Org"
15828 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
15829 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
15830 ["Sparse Tree" org-occur t]
15831 ["Show All" show-all t]
15832 "--"
15833 ["New Heading" org-insert-heading t]
15834 ("Navigate Headings"
15835 ["Up" outline-up-heading t]
15836 ["Next" outline-next-visible-heading t]
15837 ["Previous" outline-previous-visible-heading t]
15838 ["Next Same Level" outline-forward-same-level t]
15839 ["Previous Same Level" outline-backward-same-level t]
15840 "--"
15841 ["Jump" org-goto t])
15842 ("Edit Structure"
15843 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15844 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15845 "--"
15846 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15847 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15848 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15849 "--"
15850 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15851 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15852 ["Demote Heading" org-metaright (not (org-at-table-p))]
15853 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15854 "--"
15855 ["Convert to odd levels" org-convert-to-odd-levels t]
15856 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15857 ("Archive"
15858 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15859 ["Check and Tag Children" (org-toggle-archive-tag (4))
15860 :active t :keys "C-u C-c C-x C-a"]
15861 ["Sparse trees open ARCHIVE trees"
15862 (setq org-sparse-tree-open-archived-trees
15863 (not org-sparse-tree-open-archived-trees))
15864 :style toggle :selected org-sparse-tree-open-archived-trees]
15865 ["Cycling opens ARCHIVE trees"
15866 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15867 :style toggle :selected org-cycle-open-archived-trees]
15868 ["Agenda includes ARCHIVE trees"
15869 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
15870 :style toggle :selected (not org-agenda-skip-archived-trees)]
15871 "--"
15872 ["Move Subtree to Archive" org-archive-subtree t]
15873 ["Check and Move Children" (org-archive-subtree '(4))
15874 :active t :keys "C-u C-c $"])
15875 "--"
15876 ("TODO Lists"
15877 ["TODO/DONE/-" org-todo t]
15878 ("Select keyword"
15879 ["Next keyword" org-shiftright (org-on-heading-p)]
15880 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15881 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
15882 ["Show TODO Tree" org-show-todo-tree t]
15883 ["Global TODO list" org-todo-list t]
15884 "--"
15885 ["Set Priority" org-priority t]
15886 ["Priority Up" org-shiftup t]
15887 ["Priority Down" org-shiftdown t])
15888 ("Dates and Scheduling"
15889 ["Timestamp" org-time-stamp t]
15890 ["Timestamp (inactive)" org-time-stamp-inactive t]
15891 ("Change Date"
15892 ["1 Day Later" org-timestamp-up-day t]
15893 ["1 Day Earlier" org-timestamp-down-day t]
15894 ["1 ... Later" org-shiftup t]
15895 ["1 ... Earlier" org-shiftdown t])
15896 ["Compute Time Range" org-evaluate-time-range t]
15897 ["Schedule Item" org-schedule t]
15898 ["Deadline" org-deadline t]
15899 "--"
15900 ["Goto Calendar" org-goto-calendar t]
15901 ["Date from Calendar" org-date-from-calendar t])
15902 ("Logging work"
15903 ["Clock in" org-clock-in t]
15904 ["Clock out" org-clock-out t]
15905 ["Clock cancel" org-clock-cancel t]
15906 ["Display times" org-clock-display t]
15907 ["Create clock table" org-clock-report t]
15908 "--"
15909 ["Record DONE time"
15910 (progn (setq org-log-done (not org-log-done))
15911 (message "Switching to %s will %s record a timestamp"
15912 org-done-string
15913 (if org-log-done "automatically" "not")))
15914 :style toggle :selected org-log-done])
15915 "--"
15916 ["Agenda Command" org-agenda t]
15917 ("File List for Agenda")
15918 ("Special views current file"
15919 ["TODO Tree" org-show-todo-tree t]
15920 ["Check Deadlines" org-check-deadlines t]
15921 ["Timeline" org-timeline t]
15922 ["Tags Tree" org-tags-sparse-tree t])
15923 "--"
15924 ("Hyperlinks"
15925 ["Store Link (Global)" org-store-link t]
15926 ["Insert Link" org-insert-link t]
15927 ["Follow Link" org-open-at-point t]
15928 "--"
15929 ["Descriptive Links"
15930 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15931 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
15932 ["Literal Links"
15933 (progn
15934 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15935 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
15936 "--"
15937 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
15938 (save-excursion (goto-char (point-min))
15939 (re-search-forward "<[a-z]+:" nil t))])
15940 "--"
15941 ["Export/Publish" org-export t]
15942 ("LaTeX"
15943 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15944 :selected org-cdlatex-mode]
15945 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15946 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15947 ["Modify math symbol" org-cdlatex-math-modify
15948 (org-inside-LaTeX-fragment-p)]
15949 ["Export LaTeX fragments as images"
15950 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
15951 :style toggle :selected org-export-with-LaTeX-fragments])
15952 "--"
15953 ("Documentation"
15954 ["Show Version" org-version t]
15955 ["Info Documentation" org-info t])
15956 ("Customize"
15957 ["Browse Org Group" org-customize t]
15958 "--"
15959 ["Expand This Menu" org-create-customize-menu
15960 (fboundp 'customize-menu-create)])
15961 "--"
15962 ["Refresh setup" org-mode-restart t]
15963 ))
15964
15965 (defun org-info (&optional node)
15966 "Read documentation for Org-mode in the info system.
15967 With optional NODE, go directly to that node."
15968 (interactive)
15969 (require 'info)
15970 (Info-goto-node (format "(org)%s" (or node ""))))
15971
15972 (defun org-install-agenda-files-menu ()
15973 (let ((bl (buffer-list)))
15974 (save-excursion
15975 (while bl
15976 (set-buffer (pop bl))
15977 (if (org-mode-p) (setq bl nil)))
15978 (when (org-mode-p)
15979 (easy-menu-change
15980 '("Org") "File List for Agenda"
15981 (append
15982 (list
15983 ["Edit File List" (org-edit-agenda-file-list) t]
15984 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15985 ["Remove Current File from List" org-remove-file t]
15986 ["Cycle through agenda files" org-cycle-agenda-files t]
15987 "--")
15988 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15989
15990 ;;; Documentation
15991
15992 (defun org-customize ()
15993 "Call the customize function with org as argument."
15994 (interactive)
15995 (customize-browse 'org))
15996
15997 (defun org-create-customize-menu ()
15998 "Create a full customization menu for Org-mode, insert it into the menu."
15999 (interactive)
16000 (if (fboundp 'customize-menu-create)
16001 (progn
16002 (easy-menu-change
16003 '("Org") "Customize"
16004 `(["Browse Org group" org-customize t]
16005 "--"
16006 ,(customize-menu-create 'org)
16007 ["Set" Custom-set t]
16008 ["Save" Custom-save t]
16009 ["Reset to Current" Custom-reset-current t]
16010 ["Reset to Saved" Custom-reset-saved t]
16011 ["Reset to Standard Settings" Custom-reset-standard t]))
16012 (message "\"Org\"-menu now contains full customization menu"))
16013 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16014
16015 ;;; Miscellaneous stuff
16016
16017 (defun org-context ()
16018 "Return a list of contexts of the current cursor position.
16019 If several contexts apply, all are returned.
16020 Each context entry is a list with a symbol naming the context, and
16021 two positions indicating start and end of the context. Possible
16022 contexts are:
16023
16024 :headline anywhere in a headline
16025 :headline-stars on the leading stars in a headline
16026 :todo-keyword on a TODO keyword (including DONE) in a headline
16027 :tags on the TAGS in a headline
16028 :priority on the priority cookie in a headline
16029 :item on the first line of a plain list item
16030 :item-bullet on the bullet/number of a plain list item
16031 :checkbox on the checkbox in a plain list item
16032 :table in an org-mode table
16033 :table-special on a special filed in a table
16034 :table-table in a table.el table
16035 :link on a hyperline
16036 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16037 :target on a <<target>>
16038 :radio-target on a <<<radio-target>>>
16039 :latex-fragment on a LaTeX fragment
16040 :latex-preview on a LaTeX fragment with overlayed preview image
16041
16042 This function expects the position to be visible because it uses font-lock
16043 faces as a help to recognize the following contexts: :table-special, :link,
16044 and :keyword."
16045 (let* ((f (get-text-property (point) 'face))
16046 (faces (if (listp f) f (list f)))
16047 (p (point)) clist o)
16048 ;; First the large context
16049 (cond
16050 ((org-on-heading-p)
16051 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16052 (when (progn
16053 (beginning-of-line 1)
16054 (looking-at org-todo-line-tags-regexp))
16055 (push (org-point-in-group p 1 :headline-stars) clist)
16056 (push (org-point-in-group p 2 :todo-keyword) clist)
16057 (push (org-point-in-group p 4 :tags) clist))
16058 (goto-char p)
16059 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
16060 (if (looking-at "\\[#[A-Z]\\]")
16061 (push (org-point-in-group p 0 :priority) clist)))
16062
16063 ((org-at-item-p)
16064 (push (org-point-in-group p 2 :item-bullet) clist)
16065 (push (list :item (point-at-bol)
16066 (save-excursion (org-end-of-item) (point)))
16067 clist)
16068 (and (org-at-item-checkbox-p)
16069 (push (org-point-in-group p 0 :checkbox) clist)))
16070
16071 ((org-at-table-p)
16072 (push (list :table (org-table-begin) (org-table-end)) clist)
16073 (if (memq 'org-formula faces)
16074 (push (list :table-special
16075 (previous-single-property-change p 'face)
16076 (next-single-property-change p 'face)) clist)))
16077 ((org-at-table-p 'any)
16078 (push (list :table-table) clist)))
16079 (goto-char p)
16080
16081 ;; Now the small context
16082 (cond
16083 ((org-at-timestamp-p)
16084 (push (org-point-in-group p 0 :timestamp) clist))
16085 ((memq 'org-link faces)
16086 (push (list :link
16087 (previous-single-property-change p 'face)
16088 (next-single-property-change p 'face)) clist))
16089 ((memq 'org-special-keyword faces)
16090 (push (list :keyword
16091 (previous-single-property-change p 'face)
16092 (next-single-property-change p 'face)) clist))
16093 ((org-on-target-p)
16094 (push (org-point-in-group p 0 :target) clist)
16095 (goto-char (1- (match-beginning 0)))
16096 (if (looking-at org-radio-target-regexp)
16097 (push (org-point-in-group p 0 :radio-target) clist))
16098 (goto-char p))
16099 ((setq o (car (delq nil
16100 (mapcar
16101 (lambda (x)
16102 (if (memq x org-latex-fragment-image-overlays) x))
16103 (org-overlays-at (point))))))
16104 (push (list :latex-fragment
16105 (org-overlay-start o) (org-overlay-end o)) clist)
16106 (push (list :latex-preview
16107 (org-overlay-start o) (org-overlay-end o)) clist))
16108 ((org-inside-LaTeX-fragment-p)
16109 ;; FIXME: positions wring.
16110 (push (list :latex-fragment (point) (point)) clist)))
16111
16112 (setq clist (nreverse (delq nil clist)))
16113 clist))
16114
16115 (defun org-point-in-group (point group &optional context)
16116 "Check if POINT is in match-group GROUP.
16117 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16118 match. If the match group does ot exist or point is not inside it,
16119 return nil."
16120 (and (match-beginning group)
16121 (>= point (match-beginning group))
16122 (<= point (match-end group))
16123 (if context
16124 (list context (match-beginning group) (match-end group))
16125 t)))
16126
16127 (defun org-move-line-down (arg)
16128 "Move the current line down. With prefix argument, move it past ARG lines."
16129 (interactive "p")
16130 (let ((col (current-column))
16131 beg end pos)
16132 (beginning-of-line 1) (setq beg (point))
16133 (beginning-of-line 2) (setq end (point))
16134 (beginning-of-line (+ 1 arg))
16135 (setq pos (move-marker (make-marker) (point)))
16136 (insert (delete-and-extract-region beg end))
16137 (goto-char pos)
16138 (move-to-column col)))
16139
16140 (defun org-move-line-up (arg)
16141 "Move the current line up. With prefix argument, move it past ARG lines."
16142 (interactive "p")
16143 (let ((col (current-column))
16144 beg end pos)
16145 (beginning-of-line 1) (setq beg (point))
16146 (beginning-of-line 2) (setq end (point))
16147 (beginning-of-line (- arg))
16148 (setq pos (move-marker (make-marker) (point)))
16149 (insert (delete-and-extract-region beg end))
16150 (goto-char pos)
16151 (move-to-column col)))
16152
16153 ;; Paragraph filling stuff.
16154 ;; We want this to be just right, so use the full arsenal.
16155
16156 (defun org-set-autofill-regexps ()
16157 (interactive)
16158 ;; In the paragraph separator we include headlines, because filling
16159 ;; text in a line directly attached to a headline would otherwise
16160 ;; fill the headline as well.
16161 (org-set-local 'comment-start-skip "^#+[ \t]*")
16162 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
16163 ;; The paragraph starter includes hand-formatted lists.
16164 (org-set-local 'paragraph-start
16165 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
16166 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16167 ;; But only if the user has not turned off tables or fixed-width regions
16168 (org-set-local
16169 'auto-fill-inhibit-regexp
16170 (concat "\\*\\|#"
16171 "\\|[ \t]*" org-keyword-time-regexp
16172 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16173 (concat
16174 "\\|[ \t]*["
16175 (if org-enable-table-editor "|" "")
16176 (if org-enable-fixed-width-editor ":" "")
16177 "]"))))
16178 ;; We use our own fill-paragraph function, to make sure that tables
16179 ;; and fixed-width regions are not wrapped. That function will pass
16180 ;; through to `fill-paragraph' when appropriate.
16181 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16182 ; Adaptive filling: To get full control, first make sure that
16183 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16184 (org-set-local 'adaptive-fill-regexp "\000")
16185 (org-set-local 'adaptive-fill-function
16186 'org-adaptive-fill-function))
16187
16188 (defun org-fill-paragraph (&optional justify)
16189 "Re-align a table, pass through to fill-paragraph if no table."
16190 (let ((table-p (org-at-table-p))
16191 (table.el-p (org-at-table.el-p)))
16192 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
16193 (table.el-p t) ; skip table.el tables
16194 (table-p (org-table-align) t) ; align org-mode tables
16195 (t nil)))) ; call paragraph-fill
16196
16197 ;; For reference, this is the default value of adaptive-fill-regexp
16198 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16199
16200 (defun org-adaptive-fill-function ()
16201 "Return a fill prefix for org-mode files.
16202 In particular, this makes sure hanging paragraphs for hand-formatted lists
16203 work correctly."
16204 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
16205 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
16206
16207 ;; Functions needed for Emacs/XEmacs region compatibility
16208
16209 (defun org-add-hook (hook function &optional append local)
16210 "Add-hook, compatible with both Emacsen."
16211 (if (and local (featurep 'xemacs))
16212 (add-local-hook hook function append)
16213 (add-hook hook function append local)))
16214
16215 (defun org-region-active-p ()
16216 "Is `transient-mark-mode' on and the region active?
16217 Works on both Emacs and XEmacs."
16218 (if org-ignore-region
16219 nil
16220 (if (featurep 'xemacs)
16221 (and zmacs-regions (region-active-p))
16222 (and transient-mark-mode mark-active))))
16223
16224 (defun org-add-to-invisibility-spec (arg)
16225 "Add elements to `buffer-invisibility-spec'.
16226 See documentation for `buffer-invisibility-spec' for the kind of elements
16227 that can be added."
16228 (cond
16229 ((fboundp 'add-to-invisibility-spec)
16230 (add-to-invisibility-spec arg))
16231 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
16232 (setq buffer-invisibility-spec (list arg)))
16233 (t
16234 (setq buffer-invisibility-spec
16235 (cons arg buffer-invisibility-spec)))))
16236
16237 (defun org-remove-from-invisibility-spec (arg)
16238 "Remove elements from `buffer-invisibility-spec'."
16239 (if (fboundp 'remove-from-invisibility-spec)
16240 (remove-from-invisibility-spec arg)
16241 (if (consp buffer-invisibility-spec)
16242 (setq buffer-invisibility-spec
16243 (delete arg buffer-invisibility-spec)))))
16244
16245 (defun org-in-invisibility-spec-p (arg)
16246 "Is ARG a member of `buffer-invisibility-spec'?"
16247 (if (consp buffer-invisibility-spec)
16248 (member arg buffer-invisibility-spec)
16249 nil))
16250
16251 (defun org-image-file-name-regexp ()
16252 "Return regexp matching the file names of images."
16253 (if (fboundp 'image-file-name-regexp)
16254 (image-file-name-regexp)
16255 (let ((image-file-name-extensions
16256 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16257 "xbm" "xpm" "pbm" "pgm" "ppm")))
16258 (concat "\\."
16259 (regexp-opt (nconc (mapcar 'upcase
16260 image-file-name-extensions)
16261 image-file-name-extensions)
16262 t)
16263 "\\'"))))
16264
16265 ;; Functions extending outline functionality
16266
16267 ;; C-a should go to the beginning of a *visible* line, also in the
16268 ;; new outline.el. I guess this should be patched into Emacs?
16269 (defun org-beginning-of-line ()
16270 "Go to the beginning of the current line. If that is invisible, continue
16271 to a visible line beginning. This makes the function of C-a more intuitive."
16272 (interactive)
16273 (beginning-of-line 1)
16274 (if (bobp)
16275 nil
16276 (backward-char 1)
16277 (if (org-invisible-p)
16278 (while (and (not (bobp)) (org-invisible-p))
16279 (backward-char 1)
16280 (beginning-of-line 1))
16281 (forward-char 1))))
16282
16283 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16284
16285 (defun org-invisible-p ()
16286 "Check if point is at a character currently not visible."
16287 ;; Early versions of noutline don't have `outline-invisible-p'.
16288 (if (fboundp 'outline-invisible-p)
16289 (outline-invisible-p)
16290 (get-char-property (point) 'invisible)))
16291
16292 (defun org-invisible-p2 ()
16293 "Check if point is at a character currently not visible."
16294 (save-excursion
16295 (if (and (eolp) (not (bobp))) (backward-char 1))
16296 ;; Early versions of noutline don't have `outline-invisible-p'.
16297 (if (fboundp 'outline-invisible-p)
16298 (outline-invisible-p)
16299 (get-char-property (point) 'invisible))))
16300
16301 (defalias 'org-back-to-heading 'outline-back-to-heading)
16302 (defalias 'org-on-heading-p 'outline-on-heading-p)
16303
16304 (defun org-on-target-p ()
16305 (let ((pos (point)))
16306 (save-excursion
16307 (skip-chars-forward "<")
16308 (and (re-search-backward "<<" nil t)
16309 (or (looking-at org-radio-target-regexp)
16310 (looking-at org-target-regexp))
16311 (<= (match-beginning 0) pos)
16312 (>= (1+ (match-end 0)) pos)))))
16313
16314 (defun org-up-heading-all (arg)
16315 "Move to the heading line of which the present line is a subheading.
16316 This function considers both visible and invisible heading lines.
16317 With argument, move up ARG levels."
16318 (if (fboundp 'outline-up-heading-all)
16319 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16320 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16321
16322 (defun org-show-hidden-entry ()
16323 "Show an entry where even the heading is hidden."
16324 (save-excursion
16325 (org-show-entry)))
16326
16327 (defun org-flag-heading (flag &optional entry)
16328 "Flag the current heading. FLAG non-nil means make invisible.
16329 When ENTRY is non-nil, show the entire entry."
16330 (save-excursion
16331 (org-back-to-heading t)
16332 ;; Check if we should show the entire entry
16333 (if entry
16334 (progn
16335 (org-show-entry)
16336 (save-excursion
16337 (and (outline-next-heading)
16338 (org-flag-heading nil))))
16339 (outline-flag-region (max 1 (1- (point)))
16340 (save-excursion (outline-end-of-heading) (point))
16341 flag))))
16342
16343 (defun org-end-of-subtree (&optional invisible-OK)
16344 ;; This is an exact copy of the original function, but it uses
16345 ;; `org-back-to-heading', to make it work also in invisible
16346 ;; trees. And is uses an invisible-OK argument.
16347 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16348 (org-back-to-heading invisible-OK)
16349 (let ((first t)
16350 (level (funcall outline-level)))
16351 (while (and (not (eobp))
16352 (or first (> (funcall outline-level) level)))
16353 (setq first nil)
16354 (outline-next-heading))
16355 (if (memq (preceding-char) '(?\n ?\^M))
16356 (progn
16357 ;; Go to end of line before heading
16358 (forward-char -1)
16359 (if (memq (preceding-char) '(?\n ?\^M))
16360 ;; leave blank line before heading
16361 (forward-char -1)))))
16362 (point))
16363
16364 (defun org-show-subtree ()
16365 "Show everything after this heading at deeper levels."
16366 (outline-flag-region
16367 (point)
16368 (save-excursion
16369 (outline-end-of-subtree) (outline-next-heading) (point))
16370 nil))
16371
16372 (defun org-show-entry ()
16373 "Show the body directly following this heading.
16374 Show the heading too, if it is currently invisible."
16375 (interactive)
16376 (save-excursion
16377 (org-back-to-heading t)
16378 (outline-flag-region
16379 (max 1 (1- (point)))
16380 (save-excursion
16381 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
16382 (or (match-beginning 1) (point-max)))
16383 nil)))
16384
16385 (defun org-make-options-regexp (kwds)
16386 "Make a regular expression for keyword lines."
16387 (concat
16388 "^"
16389 "#?[ \t]*\\+\\("
16390 (mapconcat 'regexp-quote kwds "\\|")
16391 "\\):[ \t]*"
16392 "\\(.+\\)"))
16393
16394 ;; Make `bookmark-jump' show the jump location if it was hidden.
16395 (eval-after-load "bookmark"
16396 '(if (boundp 'bookmark-after-jump-hook)
16397 ;; We can use the hook
16398 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16399 ;; Hook not available, use advice
16400 (defadvice bookmark-jump (after org-make-visible activate)
16401 "Make the position visible."
16402 (org-bookmark-jump-unhide))))
16403
16404 (defun org-bookmark-jump-unhide ()
16405 "Unhide the current position, to show the bookmark location."
16406 (and (org-mode-p)
16407 (or (org-invisible-p)
16408 (save-excursion (goto-char (max (point-min) (1- (point))))
16409 (org-invisible-p)))
16410 (org-show-hierarchy-above)))
16411
16412 ;;; Experimental code
16413
16414
16415 ;;; Finish up
16416
16417 (provide 'org)
16418
16419 (run-hooks 'org-load-hook)
16420
16421 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16422 ;;; org.el ends here