]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-file-remote-p): Get regexp from list.
[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 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 'keymap org-mouse-map
3144 ))
3145 t)))
3146
3147 (defun org-activate-angle-links (limit)
3148 "Run through the buffer and add overlays to links."
3149 (if (re-search-forward org-angle-link-re limit t)
3150 (progn
3151 (add-text-properties (match-beginning 0) (match-end 0)
3152 (list 'mouse-face 'highlight
3153 'keymap org-mouse-map
3154 ))
3155 t)))
3156
3157 (defun org-activate-bracket-links (limit)
3158 "Run through the buffer and add overlays to bracketed links."
3159 (if (re-search-forward org-bracket-link-regexp limit t)
3160 (let* ((help (concat "LINK: "
3161 (org-match-string-no-properties 1)))
3162 ;; FIXME: above we should remove the escapes.
3163 ;; but that requires another match, protecting match data,
3164 ;; a lot of overhead for font-lock.
3165 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
3166 'keymap org-mouse-map 'mouse-face 'highlight
3167 'help-echo help))
3168 (vp (list 'rear-nonsticky t
3169 'keymap org-mouse-map 'mouse-face 'highlight
3170 'help-echo help)))
3171 ;; We need to remove the invisible property here. Table narrowing
3172 ;; may have made some of this invisible.
3173 (remove-text-properties (match-beginning 0) (match-end 0)
3174 '(invisible nil))
3175 (if (match-end 3)
3176 (progn
3177 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3178 (add-text-properties (match-beginning 3) (match-end 3) vp)
3179 (add-text-properties (match-end 3) (match-end 0) ip))
3180 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3181 (add-text-properties (match-beginning 1) (match-end 1) vp)
3182 (add-text-properties (match-end 1) (match-end 0) ip))
3183 t)))
3184
3185 (defun org-activate-dates (limit)
3186 "Run through the buffer and add overlays to dates."
3187 (if (re-search-forward org-tsr-regexp limit t)
3188 (progn
3189 (add-text-properties (match-beginning 0) (match-end 0)
3190 (list 'mouse-face 'highlight
3191 'keymap org-mouse-map))
3192 t)))
3193
3194 (defvar org-target-link-regexp nil
3195 "Regular expression matching radio targets in plain text.")
3196 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3197 "Regular expression matching a link target.")
3198 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3199 "Regular expression matching a link target.")
3200
3201 (defun org-activate-target-links (limit)
3202 "Run through the buffer and add overlays to target matches."
3203 (when org-target-link-regexp
3204 (let ((case-fold-search t))
3205 (if (re-search-forward org-target-link-regexp limit t)
3206 (progn
3207 (add-text-properties (match-beginning 0) (match-end 0)
3208 (list 'mouse-face 'highlight
3209 'keymap org-mouse-map
3210 'help-echo "Radio target link"
3211 'org-linked-text t))
3212 t)))))
3213
3214 (defun org-update-radio-target-regexp ()
3215 "Find all radio targets in this file and update the regular expression."
3216 (interactive)
3217 (when (memq 'radio org-activate-links)
3218 (setq org-target-link-regexp
3219 (org-make-target-link-regexp (org-all-targets 'radio)))
3220 (org-restart-font-lock)))
3221
3222 (defun org-hide-wide-columns (limit)
3223 (let (s e)
3224 (setq s (text-property-any (point) (or limit (point-max))
3225 'org-cwidth t))
3226 (when s
3227 (setq e (next-single-property-change s 'org-cwidth))
3228 (add-text-properties s e '(invisible org-cwidth intangible t))
3229 (goto-char e)
3230 t)))
3231
3232 (defun org-restart-font-lock ()
3233 "Restart font-lock-mode, to force refontification."
3234 (when (and (boundp 'font-lock-mode) font-lock-mode)
3235 (font-lock-mode -1)
3236 (font-lock-mode 1)))
3237
3238 (defun org-all-targets (&optional radio)
3239 "Return a list of all targets in this file.
3240 With optional argument RADIO, only find radio targets."
3241 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3242 rtn)
3243 (save-excursion
3244 (goto-char (point-min))
3245 (while (re-search-forward re nil t)
3246 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3247 rtn)))
3248
3249 (defun org-make-target-link-regexp (targets)
3250 "Make regular expression matching all strings in TARGETS.
3251 The regular expression finds the targets also if there is a line break
3252 between words."
3253 (and targets
3254 (concat
3255 "\\<\\("
3256 (mapconcat
3257 (lambda (x)
3258 (while (string-match " +" x)
3259 (setq x (replace-match "\\s-+" t t x)))
3260 x)
3261 targets
3262 "\\|")
3263 "\\)\\>")))
3264
3265 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3266 "Matches CamelCase words, possibly with a star before it.")
3267
3268 (defun org-activate-camels (limit)
3269 "Run through the buffer and add overlays to dates."
3270 (if (re-search-forward org-camel-regexp limit t)
3271 (progn
3272 (add-text-properties (match-beginning 0) (match-end 0)
3273 (list 'mouse-face 'highlight
3274 'keymap org-mouse-map))
3275 t)))
3276
3277 (defun org-activate-tags (limit)
3278 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3279 (progn
3280 (add-text-properties (match-beginning 1) (match-end 1)
3281 (list 'mouse-face 'highlight
3282 'keymap org-mouse-map))
3283 t)))
3284
3285 (defun org-font-lock-level ()
3286 (save-excursion
3287 (org-back-to-heading t)
3288 (- (match-end 0) (match-beginning 0))))
3289
3290 (defun org-outline-level ()
3291 (save-excursion
3292 (looking-at outline-regexp)
3293 (if (match-beginning 1)
3294 (+ (org-get-string-indentation (match-string 1)) 1000)
3295 (- (match-end 0) (match-beginning 0)))))
3296
3297 (defvar org-font-lock-keywords nil)
3298
3299 (defun org-set-font-lock-defaults ()
3300 (let* ((em org-fontify-emphasized-text)
3301 (lk org-activate-links)
3302 (org-font-lock-extra-keywords
3303 ;; Headlines
3304 (list
3305 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3306 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3307 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3308 (1 'org-table))
3309 ;; Links
3310 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3311 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3312 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3313 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3314 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3315 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3316 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3317 (if org-table-limit-column-width
3318 '(org-hide-wide-columns (0 nil append)))
3319 ;; TODO lines
3320 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3321 '(1 'org-todo t))
3322 ;; Priorities
3323 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3324 ;; Special keywords
3325 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3326 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3327 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3328 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3329 ;; Emphasis
3330 (if em '(org-do-emphasis-faces))
3331 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3332 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3333 2 'bold prepend)
3334 ;; COMMENT
3335 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3336 "\\|" org-quote-string "\\)\\>")
3337 '(1 'org-special-keyword t))
3338 '("^#.*" (0 'font-lock-comment-face t))
3339 ;; DONE
3340 (if org-fontify-done-headline
3341 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3342 '(1 'org-done t) '(2 'org-headline-done t))
3343 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3344 '(1 'org-done t)))
3345 ;; Table stuff
3346 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3347 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3348 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3349 (if org-format-transports-properties-p
3350 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3351 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3352 )))
3353 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3354 ;; Now set the full font-lock-keywords
3355 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3356 (org-set-local 'font-lock-defaults
3357 '(org-font-lock-keywords t nil nil backward-paragraph))
3358 (kill-local-variable 'font-lock-keywords) nil))
3359
3360 (defvar org-m nil)
3361 (defvar org-l nil)
3362 (defvar org-f nil)
3363 (defun org-get-level-face (n)
3364 "Get the right face for match N in font-lock matching of healdines."
3365 (setq org-l (- (match-end 2) (match-beginning 1)))
3366 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3367 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3368 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3369 (cond
3370 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3371 ((eq n 2) org-f)
3372 (t (if org-level-color-stars-only nil org-f))))
3373
3374 (defun org-unfontify-region (beg end &optional maybe_loudly)
3375 "Remove fontification and activation overlays from links."
3376 (font-lock-default-unfontify-region beg end)
3377 (let* ((buffer-undo-list t)
3378 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3379 (inhibit-modification-hooks t)
3380 deactivate-mark buffer-file-name buffer-file-truename)
3381 (remove-text-properties beg end
3382 '(mouse-face nil keymap nil org-linked-text nil
3383 invisible nil intangible nil))))
3384 ;;; Visibility cycling
3385
3386 (defvar org-cycle-global-status nil)
3387 (make-variable-buffer-local 'org-cycle-global-status)
3388 (defvar org-cycle-subtree-status nil)
3389 (make-variable-buffer-local 'org-cycle-subtree-status)
3390
3391 ;;;###autoload
3392 (defun org-cycle (&optional arg)
3393 "Visibility cycling for Org-mode.
3394
3395 - When this function is called with a prefix argument, rotate the entire
3396 buffer through 3 states (global cycling)
3397 1. OVERVIEW: Show only top-level headlines.
3398 2. CONTENTS: Show all headlines of all levels, but no body text.
3399 3. SHOW ALL: Show everything.
3400
3401 - When point is at the beginning of a headline, rotate the subtree started
3402 by this line through 3 different states (local cycling)
3403 1. FOLDED: Only the main headline is shown.
3404 2. CHILDREN: The main headline and the direct children are shown.
3405 From this state, you can move to one of the children
3406 and zoom in further.
3407 3. SUBTREE: Show the entire subtree, including body text.
3408
3409 - When there is a numeric prefix, go up to a heading with level ARG, do
3410 a `show-subtree' and return to the previous cursor position. If ARG
3411 is negative, go up that many levels.
3412
3413 - When point is not at the beginning of a headline, execute
3414 `indent-relative', like TAB normally does. See the option
3415 `org-cycle-emulate-tab' for details.
3416
3417 - Special case: if point is the the beginning of the buffer and there is
3418 no headline in line 1, this function will act as if called with prefix arg."
3419 (interactive "P")
3420
3421 (let* ((outline-regexp
3422 (if org-cycle-include-plain-lists
3423 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
3424 outline-regexp))
3425 (bob-special (and org-cycle-global-at-bob (bobp)
3426 (not (looking-at outline-regexp))))
3427 (org-cycle-hook
3428 (if bob-special
3429 (delq 'org-optimize-window-after-visibility-change
3430 (copy-sequence org-cycle-hook))
3431 org-cycle-hook))
3432 (pos (point)))
3433
3434 (if (or bob-special (equal arg '(4)))
3435 ;; special case: use global cycling
3436 (setq arg t))
3437
3438 (cond
3439
3440 ((org-at-table-p 'any)
3441 ;; Enter the table or move to the next field in the table
3442 (or (org-table-recognize-table.el)
3443 (progn
3444 (if arg (org-table-edit-field t)
3445 (org-table-justify-field-maybe)
3446 (call-interactively 'org-table-next-field)))))
3447
3448 ((eq arg t) ;; Global cycling
3449
3450 (cond
3451 ((and (eq last-command this-command)
3452 (eq org-cycle-global-status 'overview))
3453 ;; We just created the overview - now do table of contents
3454 ;; This can be slow in very large buffers, so indicate action
3455 (message "CONTENTS...")
3456 (org-content)
3457 (message "CONTENTS...done")
3458 (setq org-cycle-global-status 'contents)
3459 (run-hook-with-args 'org-cycle-hook 'contents))
3460
3461 ((and (eq last-command this-command)
3462 (eq org-cycle-global-status 'contents))
3463 ;; We just showed the table of contents - now show everything
3464 (show-all)
3465 (message "SHOW ALL")
3466 (setq org-cycle-global-status 'all)
3467 (run-hook-with-args 'org-cycle-hook 'all))
3468
3469 (t
3470 ;; Default action: go to overview
3471 (org-overview)
3472 (message "OVERVIEW")
3473 (setq org-cycle-global-status 'overview)
3474 (run-hook-with-args 'org-cycle-hook 'overview))))
3475
3476 ((integerp arg)
3477 ;; Show-subtree, ARG levels up from here.
3478 (save-excursion
3479 (org-back-to-heading)
3480 (outline-up-heading (if (< arg 0) (- arg)
3481 (- (funcall outline-level) arg)))
3482 (org-show-subtree)))
3483
3484 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3485 ;; At a heading: rotate between three different views
3486 (org-back-to-heading)
3487 (let ((goal-column 0) eoh eol eos)
3488 ;; First, some boundaries
3489 (save-excursion
3490 (org-back-to-heading)
3491 (save-excursion
3492 (beginning-of-line 2)
3493 (while (and (not (eobp)) ;; this is like `next-line'
3494 (get-char-property (1- (point)) 'invisible))
3495 (beginning-of-line 2)) (setq eol (point)))
3496 (outline-end-of-heading) (setq eoh (point))
3497 (org-end-of-subtree t) (setq eos (point))
3498 (outline-next-heading))
3499 ;; Find out what to do next and set `this-command'
3500 (cond
3501 ((and (= eos eoh)
3502 ;; Nothing is hidden behind this heading
3503 (message "EMPTY ENTRY")
3504 (setq org-cycle-subtree-status nil)))
3505 ((>= eol eos)
3506 ;; Entire subtree is hidden in one line: open it
3507 (org-show-entry)
3508 (show-children)
3509 (message "CHILDREN")
3510 (setq org-cycle-subtree-status 'children)
3511 (run-hook-with-args 'org-cycle-hook 'children))
3512 ((and (eq last-command this-command)
3513 (eq org-cycle-subtree-status 'children))
3514 ;; We just showed the children, now show everything.
3515 (org-show-subtree)
3516 (message "SUBTREE")
3517 (setq org-cycle-subtree-status 'subtree)
3518 (run-hook-with-args 'org-cycle-hook 'subtree))
3519 (t
3520 ;; Default action: hide the subtree.
3521 (hide-subtree)
3522 (message "FOLDED")
3523 (setq org-cycle-subtree-status 'folded)
3524 (run-hook-with-args 'org-cycle-hook 'folded)))))
3525
3526 ;; TAB emulation
3527 (buffer-read-only (org-back-to-heading))
3528
3529 ((org-try-cdlatex-tab))
3530
3531 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3532 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3533 (or (and (eq org-cycle-emulate-tab 'white)
3534 (= (match-end 0) (point-at-eol)))
3535 (and (eq org-cycle-emulate-tab 'whitestart)
3536 (>= (match-end 0) pos))))
3537 t
3538 (eq org-cycle-emulate-tab t))
3539 (if (and (looking-at "[ \n\r\t]")
3540 (string-match "^[ \t]*$" (buffer-substring
3541 (point-at-bol) (point))))
3542 (progn
3543 (beginning-of-line 1)
3544 (and (looking-at "[ \t]+") (replace-match ""))))
3545 (indent-relative))
3546
3547 (t (save-excursion
3548 (org-back-to-heading)
3549 (org-cycle))))))
3550
3551 ;;;###autoload
3552 (defun org-global-cycle (&optional arg)
3553 "Cycle the global visibility. For details see `org-cycle'."
3554 (interactive "P")
3555 (if (integerp arg)
3556 (progn
3557 (show-all)
3558 (hide-sublevels arg)
3559 (setq org-cycle-global-status 'contents))
3560 (org-cycle '(4))))
3561
3562 (defun org-overview ()
3563 "Switch to overview mode, shoing only top-level headlines.
3564 Really, this shows all headlines with level equal or greater than the level
3565 of the first headline in the buffer. This is important, because if the
3566 first headline is not level one, then (hide-sublevels 1) gives confusing
3567 results."
3568 (interactive)
3569 (hide-sublevels (save-excursion
3570 (goto-char (point-min))
3571 (if (re-search-forward (concat "^" outline-regexp) nil t)
3572 (progn
3573 (goto-char (match-beginning 0))
3574 (funcall outline-level))
3575 1))))
3576
3577 ;; FIXME: allow an argument to give a limiting level for this.
3578 (defun org-content ()
3579 "Show all headlines in the buffer, like a table of contents"
3580 (interactive)
3581 (save-excursion
3582 ;; Visit all headings and show their offspring
3583 (goto-char (point-max))
3584 (catch 'exit
3585 (while (and (progn (condition-case nil
3586 (outline-previous-visible-heading 1)
3587 (error (goto-char (point-min))))
3588 t)
3589 (looking-at outline-regexp))
3590 (show-branches)
3591 (if (bobp) (throw 'exit nil))))))
3592
3593
3594 (defun org-optimize-window-after-visibility-change (state)
3595 "Adjust the window after a change in outline visibility.
3596 This function is the default value of the hook `org-cycle-hook'."
3597 (when (get-buffer-window (current-buffer))
3598 (cond
3599 ((eq state 'overview) (org-first-headline-recenter 1))
3600 ((eq state 'content) nil)
3601 ((eq state 'all) nil)
3602 ((eq state 'folded) nil)
3603 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3604 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3605
3606 (defun org-subtree-end-visible-p ()
3607 "Is the end of the current subtree visible?"
3608 (pos-visible-in-window-p
3609 (save-excursion (org-end-of-subtree t) (point))))
3610
3611 (defun org-first-headline-recenter (&optional N)
3612 "Move cursor to the first headline and recenter the headline.
3613 Optional argument N means, put the headline into the Nth line of the window."
3614 (goto-char (point-min))
3615 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3616 (beginning-of-line)
3617 (recenter (prefix-numeric-value N))))
3618
3619 (defvar org-goto-window-configuration nil)
3620 (defvar org-goto-marker nil)
3621 (defvar org-goto-map (make-sparse-keymap))
3622 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3623 (while (setq cmd (pop cmds))
3624 (substitute-key-definition cmd cmd org-goto-map global-map)))
3625 (define-key org-goto-map "\C-m" 'org-goto-ret)
3626 (define-key org-goto-map [(left)] 'org-goto-left)
3627 (define-key org-goto-map [(right)] 'org-goto-right)
3628 (define-key org-goto-map [(?q)] 'org-goto-quit)
3629 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3630 (define-key org-goto-map "\C-i" 'org-cycle)
3631 (define-key org-goto-map [(tab)] 'org-cycle)
3632 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3633 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3634 (define-key org-goto-map "n" 'outline-next-visible-heading)
3635 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3636 (define-key org-goto-map "f" 'outline-forward-same-level)
3637 (define-key org-goto-map "b" 'outline-backward-same-level)
3638 (define-key org-goto-map "u" 'outline-up-heading)
3639 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3640 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3641 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3642 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3643 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3644 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3645 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3646
3647 (defconst org-goto-help
3648 "Select a location to jump to, press RET
3649 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3650
3651 (defun org-goto ()
3652 "Go to a different location of the document, keeping current visibility.
3653
3654 When you want to go to a different location in a document, the fastest way
3655 is often to fold the entire buffer and then dive into the tree. This
3656 method has the disadvantage, that the previous location will be folded,
3657 which may not be what you want.
3658
3659 This command works around this by showing a copy of the current buffer in
3660 overview mode. You can dive into the tree in that copy, to find the
3661 location you want to reach. When pressing RET, the command returns to the
3662 original buffer in which the visibility is still unchanged. It then jumps
3663 to the new location, making it and the headline hierarchy above it visible."
3664 (interactive)
3665 (let* ((org-goto-start-pos (point))
3666 (selected-point
3667 (org-get-location (current-buffer) org-goto-help)))
3668 (if selected-point
3669 (progn
3670 (org-mark-ring-push org-goto-start-pos)
3671 (goto-char selected-point)
3672 (if (or (org-invisible-p) (org-invisible-p2))
3673 (org-show-hierarchy-above)))
3674 (error "Quit"))))
3675
3676 (defun org-get-location (buf help)
3677 "Let the user select a location in the Org-mode buffer BUF.
3678 This function uses a recursive edit. It returns the selected position
3679 or nil."
3680 (let (org-selected-point)
3681 (save-excursion
3682 (save-window-excursion
3683 (delete-other-windows)
3684 (switch-to-buffer (get-buffer-create "*org-goto*"))
3685 (with-output-to-temp-buffer "*Help*"
3686 (princ help))
3687 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3688 (setq buffer-read-only nil)
3689 (erase-buffer)
3690 (insert-buffer-substring buf)
3691 (let ((org-startup-truncated t)
3692 (org-startup-folded t)
3693 (org-startup-align-all-tables nil)
3694 (org-startup-with-deadline-check nil))
3695 (org-mode))
3696 (setq buffer-read-only t)
3697 (if (boundp 'org-goto-start-pos)
3698 (goto-char org-goto-start-pos)
3699 (goto-char (point-min)))
3700 (org-beginning-of-line)
3701 (message "Select location and press RET")
3702 ;; now we make sure that during selection, ony very few keys work
3703 ;; and that it is impossible to switch to another window.
3704 (let ((gm (current-global-map))
3705 (overriding-local-map org-goto-map))
3706 (unwind-protect
3707 (progn
3708 (use-global-map org-goto-map)
3709 (recursive-edit))
3710 (use-global-map gm)))))
3711 (kill-buffer "*org-goto*")
3712 org-selected-point))
3713
3714 (defun org-goto-ret (&optional arg)
3715 "Finish `org-goto' by going to the new location."
3716 (interactive "P")
3717 (setq org-selected-point (point)
3718 current-prefix-arg arg)
3719 (throw 'exit nil))
3720
3721 (defun org-goto-left ()
3722 "Finish `org-goto' by going to the new location."
3723 (interactive)
3724 (if (org-on-heading-p)
3725 (progn
3726 (beginning-of-line 1)
3727 (setq org-selected-point (point)
3728 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3729 (throw 'exit nil))
3730 (error "Not on a heading")))
3731
3732 (defun org-goto-right ()
3733 "Finish `org-goto' by going to the new location."
3734 (interactive)
3735 (if (org-on-heading-p)
3736 (progn
3737 (outline-end-of-subtree)
3738 (or (eobp) (forward-char 1))
3739 (setq org-selected-point (point)
3740 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3741 (throw 'exit nil))
3742 (error "Not on a heading")))
3743
3744 (defun org-goto-quit ()
3745 "Finish `org-goto' without cursor motion."
3746 (interactive)
3747 (setq org-selected-point nil)
3748 (throw 'exit nil))
3749
3750 ;;; Promotion, Demotion, Inserting new headlines
3751
3752 (defvar org-ignore-region nil
3753 "To temporarily disable the active region.")
3754
3755 (defun org-insert-heading (&optional force-heading)
3756 "Insert a new heading or item with same depth at point.
3757 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3758 If point is at the beginning of a headline, insert a sibling before the
3759 current headline. If point is in the middle of a headline, split the headline
3760 at that position and make the rest of the headline part of the sibling below
3761 the current headline."
3762 (interactive "P")
3763 (if (= (buffer-size) 0)
3764 (insert "\n* ")
3765 (when (or force-heading (not (org-insert-item)))
3766 (let* ((head (save-excursion
3767 (condition-case nil
3768 (progn
3769 (org-back-to-heading)
3770 (match-string 0))
3771 (error "*"))))
3772 pos)
3773 (cond
3774 ((and (org-on-heading-p) (bolp)
3775 (save-excursion (backward-char 1) (not (org-invisible-p))))
3776 (open-line 1))
3777 ((and (bolp) (save-excursion
3778 (backward-char 1) (not (org-invisible-p))))
3779 nil)
3780 (t (newline)))
3781 (insert head) (just-one-space)
3782 (setq pos (point))
3783 (end-of-line 1)
3784 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3785 (run-hooks 'org-insert-heading-hook)))))
3786
3787 (defun org-insert-item (&optional checkbox)
3788 "Insert a new item at the current level.
3789 Return t when things worked, nil when we are not in an item."
3790 (when (save-excursion
3791 (condition-case nil
3792 (progn
3793 (org-beginning-of-item)
3794 (org-at-item-p)
3795 t)
3796 (error nil)))
3797 (let* ((bul (match-string 0))
3798 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3799 (match-end 0)))
3800 pos)
3801 (cond
3802 ((and (org-at-item-p) (<= (point) eow))
3803 ;; before the bullet
3804 (beginning-of-line 1)
3805 (open-line 1))
3806 ((<= (point) eow)
3807 (beginning-of-line 1))
3808 (t (newline)))
3809 (insert bul (if checkbox "[ ]" ""))
3810 (just-one-space)
3811 (setq pos (point))
3812 (end-of-line 1)
3813 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3814 (org-maybe-renumber-ordered-list)
3815 t))
3816
3817 (defun org-insert-todo-heading (arg)
3818 "Insert a new heading with the same level and TODO state as current heading.
3819 If the heading has no TODO state, or if the state is DONE, use the first
3820 state (TODO by default). Also with prefix arg, force first state."
3821 (interactive "P")
3822 (when (not (org-insert-item 'checkbox))
3823 (org-insert-heading)
3824 (save-excursion
3825 (org-back-to-heading)
3826 (outline-previous-heading)
3827 (looking-at org-todo-line-regexp))
3828 (if (or arg
3829 (not (match-beginning 2))
3830 (equal (match-string 2) org-done-string))
3831 (insert (car org-todo-keywords) " ")
3832 (insert (match-string 2) " "))))
3833
3834 (defun org-promote-subtree ()
3835 "Promote the entire subtree.
3836 See also `org-promote'."
3837 (interactive)
3838 (save-excursion
3839 (org-map-tree 'org-promote)))
3840
3841 (defun org-demote-subtree ()
3842 "Demote the entire subtree. See `org-demote'.
3843 See also `org-promote'."
3844 (interactive)
3845 (save-excursion
3846 (org-map-tree 'org-demote)))
3847
3848 (defun org-do-promote ()
3849 "Promote the current heading higher up the tree.
3850 If the region is active in `transient-mark-mode', promote all headings
3851 in the region."
3852 (interactive)
3853 (save-excursion
3854 (if (org-region-active-p)
3855 (org-map-region 'org-promote (region-beginning) (region-end))
3856 (org-promote)))
3857 (org-fix-position-after-promote))
3858
3859 (defun org-do-demote ()
3860 "Demote the current heading lower down the tree.
3861 If the region is active in `transient-mark-mode', demote all headings
3862 in the region."
3863 (interactive)
3864 (save-excursion
3865 (if (org-region-active-p)
3866 (org-map-region 'org-demote (region-beginning) (region-end))
3867 (org-demote)))
3868 (org-fix-position-after-promote))
3869
3870 (defun org-fix-position-after-promote ()
3871 "Make sure that after pro/demotion cursor position is right."
3872 (and (equal (char-after) ?\ )
3873 (equal (char-before) ?*)
3874 (forward-char 1)))
3875
3876 (defun org-get-legal-level (level change)
3877 "Rectify a level change under the influence of `org-odd-levels-only'
3878 LEVEL is a current level, CHANGE is by how much the level should be
3879 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3880 even level numbers will become the next higher odd number."
3881 (if org-odd-levels-only
3882 (cond ((not change) (1+ (* 2 (/ level 2))))
3883 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3884 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3885 (max 1 (+ level change))))
3886
3887 (defun org-promote ()
3888 "Promote the current heading higher up the tree.
3889 If the region is active in `transient-mark-mode', promote all headings
3890 in the region."
3891 (org-back-to-heading t)
3892 (let* ((level (save-match-data (funcall outline-level)))
3893 (up-head (make-string (org-get-legal-level level -1) ?*))
3894 (diff (abs (- level (length up-head)))))
3895 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3896 (replace-match up-head nil t)
3897 ;; Fixup tag positioning
3898 (and org-auto-align-tags (org-set-tags nil t))
3899 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
3900
3901 (defun org-demote ()
3902 "Demote the current heading lower down the tree.
3903 If the region is active in `transient-mark-mode', demote all headings
3904 in the region."
3905 (org-back-to-heading t)
3906 (let* ((level (save-match-data (funcall outline-level)))
3907 (down-head (make-string (org-get-legal-level level 1) ?*))
3908 (diff (abs (- level (length down-head)))))
3909 (replace-match down-head nil t)
3910 ;; Fixup tag positioning
3911 (and org-auto-align-tags (org-set-tags nil t))
3912 (if org-adapt-indentation (org-fixup-indentation diff))))
3913
3914 (defun org-map-tree (fun)
3915 "Call FUN for every heading underneath the current one."
3916 (org-back-to-heading)
3917 (let ((level (funcall outline-level)))
3918 (save-excursion
3919 (funcall fun)
3920 (while (and (progn
3921 (outline-next-heading)
3922 (> (funcall outline-level) level))
3923 (not (eobp)))
3924 (funcall fun)))))
3925
3926 (defun org-map-region (fun beg end)
3927 "Call FUN for every heading between BEG and END."
3928 (let ((org-ignore-region t))
3929 (save-excursion
3930 (setq end (copy-marker end))
3931 (goto-char beg)
3932 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3933 (< (point) end))
3934 (funcall fun))
3935 (while (and (progn
3936 (outline-next-heading)
3937 (< (point) end))
3938 (not (eobp)))
3939 (funcall fun)))))
3940
3941 (defun org-fixup-indentation (diff)
3942 "Change the indentation in the current entry by DIFF
3943 However, if any line in the current entry has no indentation, or if it
3944 would end up with no indentation after the change, nothing at all is done."
3945 (save-excursion
3946 (let ((end (save-excursion (outline-next-heading)
3947 (point-marker)))
3948 (prohibit (if (> diff 0)
3949 "^\\S-"
3950 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
3951 col)
3952 (unless (save-excursion (re-search-forward prohibit end t))
3953 (while (re-search-forward "^[ \t]+" end t)
3954 (goto-char (match-end 0))
3955 (setq col (current-column))
3956 (if (< diff 0) (replace-match ""))
3957 (indent-to (+ diff col))))
3958 (move-marker end nil))))
3959
3960 ;;; Vertical tree motion, cutting and pasting of subtrees
3961
3962 (defun org-move-subtree-up (&optional arg)
3963 "Move the current subtree up past ARG headlines of the same level."
3964 (interactive "p")
3965 (org-move-subtree-down (- (prefix-numeric-value arg))))
3966
3967 (defun org-move-subtree-down (&optional arg)
3968 "Move the current subtree down past ARG headlines of the same level."
3969 (interactive "p")
3970 (setq arg (prefix-numeric-value arg))
3971 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3972 'outline-get-last-sibling))
3973 (ins-point (make-marker))
3974 (cnt (abs arg))
3975 beg end txt folded)
3976 ;; Select the tree
3977 (org-back-to-heading)
3978 (setq beg (point))
3979 (save-match-data
3980 (save-excursion (outline-end-of-heading)
3981 (setq folded (org-invisible-p)))
3982 (outline-end-of-subtree))
3983 (outline-next-heading)
3984 (setq end (point))
3985 ;; Find insertion point, with error handling
3986 (goto-char beg)
3987 (while (> cnt 0)
3988 (or (and (funcall movfunc) (looking-at outline-regexp))
3989 (progn (goto-char beg)
3990 (error "Cannot move past superior level or buffer limit")))
3991 (setq cnt (1- cnt)))
3992 (if (> arg 0)
3993 ;; Moving forward - still need to move over subtree
3994 (progn (outline-end-of-subtree)
3995 (outline-next-heading)
3996 (if (not (or (looking-at (concat "^" outline-regexp))
3997 (bolp)))
3998 (newline))))
3999 (move-marker ins-point (point))
4000 (setq txt (buffer-substring beg end))
4001 (delete-region beg end)
4002 (insert txt)
4003 (goto-char ins-point)
4004 (if folded (hide-subtree))
4005 (move-marker ins-point nil)))
4006
4007 (defvar org-subtree-clip ""
4008 "Clipboard for cut and paste of subtrees.
4009 This is actually only a copy of the kill, because we use the normal kill
4010 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4011
4012 (defvar org-subtree-clip-folded nil
4013 "Was the last copied subtree folded?
4014 This is used to fold the tree back after pasting.")
4015
4016 (defun org-cut-subtree ()
4017 "Cut the current subtree into the clipboard.
4018 This is a short-hand for marking the subtree and then cutting it."
4019 (interactive)
4020 (org-copy-subtree 'cut))
4021
4022 (defun org-copy-subtree (&optional cut)
4023 "Cut the current subtree into the clipboard.
4024 This is a short-hand for marking the subtree and then copying it.
4025 If CUT is non nil, actually cut the subtree."
4026 (interactive)
4027 (let (beg end folded)
4028 (org-back-to-heading)
4029 (setq beg (point))
4030 (save-match-data
4031 (save-excursion (outline-end-of-heading)
4032 (setq folded (org-invisible-p)))
4033 (outline-end-of-subtree))
4034 (if (equal (char-after) ?\n) (forward-char 1))
4035 (setq end (point))
4036 (goto-char beg)
4037 (when (> end beg)
4038 (setq org-subtree-clip-folded folded)
4039 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4040 (setq org-subtree-clip (current-kill 0))
4041 (message "%s: Subtree with %d characters"
4042 (if cut "Cut" "Copied")
4043 (length org-subtree-clip)))))
4044
4045 (defun org-paste-subtree (&optional level tree)
4046 "Paste the clipboard as a subtree, with modification of headline level.
4047 The entire subtree is promoted or demoted in order to match a new headline
4048 level. By default, the new level is derived from the visible headings
4049 before and after the insertion point, and taken to be the inferior headline
4050 level of the two. So if the previous visible heading is level 3 and the
4051 next is level 4 (or vice versa), level 4 will be used for insertion.
4052 This makes sure that the subtree remains an independent subtree and does
4053 not swallow low level entries.
4054
4055 You can also force a different level, either by using a numeric prefix
4056 argument, or by inserting the heading marker by hand. For example, if the
4057 cursor is after \"*****\", then the tree will be shifted to level 5.
4058
4059 If you want to insert the tree as is, just use \\[yank].
4060
4061 If optional TREE is given, use this text instead of the kill ring."
4062 (interactive "P")
4063 (unless (org-kill-is-subtree-p tree)
4064 (error
4065 (substitute-command-keys
4066 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4067 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4068 (^re (concat "^\\(" outline-regexp "\\)"))
4069 (re (concat "\\(" outline-regexp "\\)"))
4070 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4071
4072 (old-level (if (string-match ^re txt)
4073 (- (match-end 0) (match-beginning 0))
4074 -1))
4075 (force-level (cond (level (prefix-numeric-value level))
4076 ((string-match
4077 ^re_ (buffer-substring (point-at-bol) (point)))
4078 (- (match-end 0) (match-beginning 0)))
4079 (t nil)))
4080 (previous-level (save-excursion
4081 (condition-case nil
4082 (progn
4083 (outline-previous-visible-heading 1)
4084 (if (looking-at re)
4085 (- (match-end 0) (match-beginning 0))
4086 1))
4087 (error 1))))
4088 (next-level (save-excursion
4089 (condition-case nil
4090 (progn
4091 (outline-next-visible-heading 1)
4092 (if (looking-at re)
4093 (- (match-end 0) (match-beginning 0))
4094 1))
4095 (error 1))))
4096 (new-level (or force-level (max previous-level next-level)))
4097 (shift (if (or (= old-level -1)
4098 (= new-level -1)
4099 (= old-level new-level))
4100 0
4101 (- new-level old-level)))
4102 (shift1 shift)
4103 (delta (if (> shift 0) -1 1))
4104 (func (if (> shift 0) 'org-demote 'org-promote))
4105 (org-odd-levels-only nil)
4106 beg end)
4107 ;; Remove the forces level indicator
4108 (if force-level
4109 (delete-region (point-at-bol) (point)))
4110 ;; Make sure we start at the beginning of an empty line
4111 (if (not (bolp)) (insert "\n"))
4112 (if (not (looking-at "[ \t]*$"))
4113 (progn (insert "\n") (backward-char 1)))
4114 ;; Paste
4115 (setq beg (point))
4116 (if (string-match "[ \t\r\n]+\\'" txt)
4117 (setq txt (replace-match "\n" t t txt)))
4118 (insert txt)
4119 (setq end (point))
4120 (if (looking-at "[ \t\r\n]+")
4121 (replace-match "\n"))
4122 (goto-char beg)
4123 ;; Shift if necessary
4124 (if (= shift 0)
4125 (message "Pasted at level %d, without shift" new-level)
4126 (save-restriction
4127 (narrow-to-region beg end)
4128 (while (not (= shift 0))
4129 (org-map-region func (point-min) (point-max))
4130 (setq shift (+ delta shift)))
4131 (goto-char (point-min))
4132 (message "Pasted at level %d, with shift by %d levels"
4133 new-level shift1)))
4134 (if (and kill-ring
4135 (eq org-subtree-clip (current-kill 0))
4136 org-subtree-clip-folded)
4137 ;; The tree was folded before it was killed/copied
4138 (hide-subtree))))
4139
4140 (defun org-kill-is-subtree-p (&optional txt)
4141 "Check if the current kill is an outline subtree, or a set of trees.
4142 Returns nil if kill does not start with a headline, or if the first
4143 headline level is not the largest headline level in the tree.
4144 So this will actually accept several entries of equal levels as well,
4145 which is OK for `org-paste-subtree'.
4146 If optional TXT is given, check this string instead of the current kill."
4147 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4148 (start-level (and kill
4149 (string-match (concat "\\`" outline-regexp) kill)
4150 (- (match-end 0) (match-beginning 0))))
4151 (re (concat "^" outline-regexp))
4152 (start 1))
4153 (if (not start-level)
4154 nil ;; does not even start with a heading
4155 (catch 'exit
4156 (while (setq start (string-match re kill (1+ start)))
4157 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4158 (throw 'exit nil)))
4159 t))))
4160
4161 (defun org-narrow-to-subtree ()
4162 "Narrow buffer to the current subtree."
4163 (interactive)
4164 (save-excursion
4165 (narrow-to-region
4166 (progn (org-back-to-heading) (point))
4167 (progn (org-end-of-subtree t) (point)))))
4168
4169 ;;; Plain list items
4170
4171 (defun org-at-item-p ()
4172 "Is point in a line starting a hand-formatted item?"
4173 (let ((llt org-plain-list-ordered-item-terminator))
4174 (save-excursion
4175 (goto-char (point-at-bol))
4176 (looking-at
4177 (cond
4178 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4179 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4180 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4181 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4182
4183 (defun org-at-item-checkbox-p ()
4184 "Is point at a line starting a plain-list item with a checklet?"
4185 (and (org-at-item-p)
4186 (save-excursion
4187 (goto-char (match-end 0))
4188 (skip-chars-forward " \t")
4189 (looking-at "\\[[ X]\\]"))))
4190
4191 (defun org-toggle-checkbox (&optional arg)
4192 "Toggle the checkbox in the current line."
4193 (interactive "P")
4194 (catch 'exit
4195 (let (beg end status (firstnew 'unknown))
4196 (cond
4197 ((org-region-active-p)
4198 (setq beg (region-beginning) end (region-end)))
4199 ((org-on-heading-p)
4200 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4201 ((org-at-item-checkbox-p)
4202 (save-excursion
4203 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4204 (throw 'exit t))
4205 (t (error "Not at a checkbox or heading, and no active region")))
4206 (save-excursion
4207 (goto-char beg)
4208 (while (< (point) end)
4209 (when (org-at-item-checkbox-p)
4210 (setq status (equal (match-string 0) "[X]"))
4211 (when (eq firstnew 'unknown)
4212 (setq firstnew (not status)))
4213 (replace-match
4214 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4215 (beginning-of-line 2))))))
4216
4217 (defun org-get-indentation (&optional line)
4218 "Get the indentation of the current line, interpreting tabs.
4219 When LINE is given, assume it represents a line and compute its indentation."
4220 (if line
4221 (if (string-match "^ *" (org-remove-tabs line))
4222 (match-end 0))
4223 (save-excursion
4224 (beginning-of-line 1)
4225 (skip-chars-forward " \t")
4226 (current-column))))
4227
4228 (defun org-remove-tabs (s &optional width)
4229 "Replace tabulators in S with spaces.
4230 Assumes that s is a single line, starting in column 0."
4231 (setq width (or width tab-width))
4232 (while (string-match "\t" s)
4233 (setq s (replace-match
4234 (make-string
4235 (- (* width (/ (+ (match-beginning 0) width) width))
4236 (match-beginning 0)) ?\ )
4237 t t s)))
4238 s)
4239
4240 ;; FIXME: document properly.
4241 (defun org-fix-indentation (line ind)
4242 "If the current indenation is smaller than ind1, leave it alone.
4243 If it is larger than ind, reduce it by ind."
4244 (let* ((l (org-remove-tabs line))
4245 (i (org-get-indentation l))
4246 (i1 (car ind)) (i2 (cdr ind)))
4247 (if (>= i i2) (setq l (substring line i2)))
4248 (if (> i1 0)
4249 (concat (make-string i1 ?\ ) l)
4250 l)))
4251
4252 (defun org-beginning-of-item ()
4253 "Go to the beginning of the current hand-formatted item.
4254 If the cursor is not in an item, throw an error."
4255 (interactive)
4256 (let ((pos (point))
4257 (limit (save-excursion (org-back-to-heading)
4258 (beginning-of-line 2) (point)))
4259 ind ind1)
4260 (if (org-at-item-p)
4261 (beginning-of-line 1)
4262 (beginning-of-line 1)
4263 (skip-chars-forward " \t")
4264 (setq ind (current-column))
4265 (if (catch 'exit
4266 (while t
4267 (beginning-of-line 0)
4268 (if (< (point) limit) (throw 'exit nil))
4269 (unless (looking-at "[ \t]*$")
4270 (skip-chars-forward " \t")
4271 (setq ind1 (current-column))
4272 (if (< ind1 ind)
4273 (throw 'exit (org-at-item-p))))))
4274 nil
4275 (goto-char pos)
4276 (error "Not in an item")))))
4277
4278 (defun org-end-of-item ()
4279 "Go to the end of the current hand-formatted item.
4280 If the cursor is not in an item, throw an error."
4281 (interactive)
4282 (let ((pos (point))
4283 (limit (save-excursion (outline-next-heading) (point)))
4284 (ind (save-excursion
4285 (org-beginning-of-item)
4286 (skip-chars-forward " \t")
4287 (current-column)))
4288 ind1)
4289 (if (catch 'exit
4290 (while t
4291 (beginning-of-line 2)
4292 (if (>= (point) limit) (throw 'exit t))
4293 (unless (looking-at "[ \t]*$")
4294 (skip-chars-forward " \t")
4295 (setq ind1 (current-column))
4296 (if (<= ind1 ind) (throw 'exit t)))))
4297 (beginning-of-line 1)
4298 (goto-char pos)
4299 (error "Not in an item"))))
4300
4301 (defun org-next-item ()
4302 "Move to the beginning of the next item in the current plain list.
4303 Error if not at a plain list, or if this is the last item in the list."
4304 (interactive)
4305 (let (ind ind1 (pos (point)))
4306 (org-beginning-of-item)
4307 (setq ind (org-get-indentation))
4308 (org-end-of-item)
4309 (setq ind1 (org-get-indentation))
4310 (unless (and (org-at-item-p) (= ind ind1))
4311 (goto-char pos)
4312 (error "On last item"))))
4313
4314 (defun org-previous-item ()
4315 "Move to the beginning of the previous item in the current plain list.
4316 Error if not at a plain list, or if this is the last item in the list."
4317 (interactive)
4318 (let (beg ind (pos (point)))
4319 (org-beginning-of-item)
4320 (setq beg (point))
4321 (setq ind (org-get-indentation))
4322 (goto-char beg)
4323 (catch 'exit
4324 (while t
4325 (beginning-of-line 0)
4326 (if (looking-at "[ \t]*$")
4327 nil
4328 (if (<= (org-get-indentation) ind)
4329 (throw 'exit t)))))
4330 (condition-case nil
4331 (org-beginning-of-item)
4332 (error (goto-char pos)
4333 (error "On first item")))))
4334
4335 (defun org-move-item-down ()
4336 "Move the plain list item at point down, i.e. swap with following item.
4337 Subitems (items with larger indentation) are considered part of the item,
4338 so this really moves item trees."
4339 (interactive)
4340 (let (beg end ind ind1 (pos (point)) txt)
4341 (org-beginning-of-item)
4342 (setq beg (point))
4343 (setq ind (org-get-indentation))
4344 (org-end-of-item)
4345 (setq end (point))
4346 (setq ind1 (org-get-indentation))
4347 (if (and (org-at-item-p) (= ind ind1))
4348 (progn
4349 (org-end-of-item)
4350 (setq txt (buffer-substring beg end))
4351 (save-excursion
4352 (delete-region beg end))
4353 (setq pos (point))
4354 (insert txt)
4355 (goto-char pos)
4356 (org-maybe-renumber-ordered-list))
4357 (goto-char pos)
4358 (error "Cannot move this item further down"))))
4359
4360 (defun org-move-item-up (arg)
4361 "Move the plain list item at point up, i.e. swap with previous item.
4362 Subitems (items with larger indentation) are considered part of the item,
4363 so this really moves item trees."
4364 (interactive "p")
4365 (let (beg end ind ind1 (pos (point)) txt)
4366 (org-beginning-of-item)
4367 (setq beg (point))
4368 (setq ind (org-get-indentation))
4369 (org-end-of-item)
4370 (setq end (point))
4371 (goto-char beg)
4372 (catch 'exit
4373 (while t
4374 (beginning-of-line 0)
4375 (if (looking-at "[ \t]*$")
4376 nil
4377 (if (<= (setq ind1 (org-get-indentation)) ind)
4378 (throw 'exit t)))))
4379 (condition-case nil
4380 (org-beginning-of-item)
4381 (error (goto-char beg)
4382 (error "Cannot move this item further up")))
4383 (setq ind1 (org-get-indentation))
4384 (if (and (org-at-item-p) (= ind ind1))
4385 (progn
4386 (setq txt (buffer-substring beg end))
4387 (save-excursion
4388 (delete-region beg end))
4389 (setq pos (point))
4390 (insert txt)
4391 (goto-char pos)
4392 (org-maybe-renumber-ordered-list))
4393 (goto-char pos)
4394 (error "Cannot move this item further up"))))
4395
4396 (defun org-maybe-renumber-ordered-list ()
4397 "Renumber the ordered list at point if setup allows it.
4398 This tests the user option `org-auto-renumber-ordered-lists' before
4399 doing the renumbering."
4400 (and org-auto-renumber-ordered-lists
4401 (org-at-item-p)
4402 (match-beginning 3)
4403 (org-renumber-ordered-list 1)))
4404
4405 (defun org-get-string-indentation (s)
4406 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4407 (let ((n -1) (i 0) (w tab-width) c)
4408 (catch 'exit
4409 (while (< (setq n (1+ n)) (length s))
4410 (setq c (aref s n))
4411 (cond ((= c ?\ ) (setq i (1+ i)))
4412 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4413 (t (throw 'exit t)))))
4414 i))
4415
4416 (defun org-renumber-ordered-list (arg)
4417 "Renumber an ordered plain list.
4418 Cursor needs to be in the first line of an item, the line that starts
4419 with something like \"1.\" or \"2)\"."
4420 (interactive "p")
4421 (unless (and (org-at-item-p)
4422 (match-beginning 3))
4423 (error "This is not an ordered list"))
4424 (let ((line (org-current-line))
4425 (col (current-column))
4426 (ind (org-get-string-indentation
4427 (buffer-substring (point-at-bol) (match-beginning 3))))
4428 ;; (term (substring (match-string 3) -1))
4429 ind1 (n (1- arg)))
4430 ;; find where this list begins
4431 (catch 'exit
4432 (while t
4433 (catch 'next
4434 (beginning-of-line 0)
4435 (if (looking-at "[ \t]*$") (throw 'next t))
4436 (skip-chars-forward " \t") (setq ind1 (current-column))
4437 (if (or (< ind1 ind)
4438 (and (= ind1 ind)
4439 (not (org-at-item-p))))
4440 (throw 'exit t)))))
4441 ;; Walk forward and replace these numbers
4442 (catch 'exit
4443 (while t
4444 (catch 'next
4445 (beginning-of-line 2)
4446 (if (eobp) (throw 'exit nil))
4447 (if (looking-at "[ \t]*$") (throw 'next nil))
4448 (skip-chars-forward " \t") (setq ind1 (current-column))
4449 (if (> ind1 ind) (throw 'next t))
4450 (if (< ind1 ind) (throw 'exit t))
4451 (if (not (org-at-item-p)) (throw 'exit nil))
4452 (if (not (match-beginning 3))
4453 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4454 (delete-region (match-beginning 3) (1- (match-end 3)))
4455 (goto-char (match-beginning 3))
4456 (insert (format "%d" (setq n (1+ n)))))))
4457 (goto-line line)
4458 (move-to-column col)))
4459
4460 (defvar org-last-indent-begin-marker (make-marker))
4461 (defvar org-last-indent-end-marker (make-marker))
4462
4463 (defun org-outdent-item (arg)
4464 "Outdent a local list item."
4465 (interactive "p")
4466 (org-indent-item (- arg)))
4467
4468 (defun org-indent-item (arg)
4469 "Indent a local list item."
4470 (interactive "p")
4471 (unless (org-at-item-p)
4472 (error "Not on an item"))
4473 (save-excursion
4474 (let (beg end ind ind1)
4475 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4476 (setq beg org-last-indent-begin-marker
4477 end org-last-indent-end-marker)
4478 (org-beginning-of-item)
4479 (setq beg (move-marker org-last-indent-begin-marker (point)))
4480 (org-end-of-item)
4481 (setq end (move-marker org-last-indent-end-marker (point))))
4482 (goto-char beg)
4483 (skip-chars-forward " \t") (setq ind (current-column))
4484 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4485 (while (< (point) end)
4486 (beginning-of-line 1)
4487 (skip-chars-forward " \t") (setq ind1 (current-column))
4488 (delete-region (point-at-bol) (point))
4489 (indent-to-column (+ ind1 arg))
4490 (beginning-of-line 2)))))
4491
4492 ;;; Archiving
4493
4494 (defun org-archive-subtree (&optional find-done)
4495 "Move the current subtree to the archive.
4496 The archive can be a certain top-level heading in the current file, or in
4497 a different file. The tree will be moved to that location, the subtree
4498 heading be marked DONE, and the current time will be added.
4499
4500 When called with prefix argument FIND-DONE, find whole trees without any
4501 open TODO items and archive them (after getting confirmation from the user).
4502 If the cursor is not at a headline when this comand is called, try all level
4503 1 trees. If the cursor is on a headline, only try the direct children of
4504 this heading. "
4505 (interactive "P")
4506 (if find-done
4507 (org-archive-all-done)
4508 ;; Save all relevant TODO keyword-relatex variables
4509
4510 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4511 (tr-org-todo-keywords org-todo-keywords)
4512 (tr-org-todo-interpretation org-todo-interpretation)
4513 (tr-org-done-string org-done-string)
4514 (tr-org-todo-regexp org-todo-regexp)
4515 (tr-org-todo-line-regexp org-todo-line-regexp)
4516 (this-buffer (current-buffer))
4517 file heading buffer level newfile-p)
4518 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4519 (progn
4520 (setq file (format (match-string 1 org-archive-location)
4521 (file-name-nondirectory buffer-file-name))
4522 heading (match-string 2 org-archive-location)))
4523 (error "Invalid `org-archive-location'"))
4524 (if (> (length file) 0)
4525 (setq newfile-p (not (file-exists-p file))
4526 buffer (find-file-noselect file))
4527 (setq buffer (current-buffer)))
4528 (unless buffer
4529 (error "Cannot access file \"%s\"" file))
4530 (if (and (> (length heading) 0)
4531 (string-match "^\\*+" heading))
4532 (setq level (match-end 0))
4533 (setq heading nil level 0))
4534 (save-excursion
4535 ;; We first only copy, in case something goes wrong
4536 ;; we need to protect this-command, to avoid kill-region sets it,
4537 ;; which would lead to duplication of subtrees
4538 (let (this-command) (org-copy-subtree))
4539 (set-buffer buffer)
4540 ;; Enforce org-mode for the archive buffer
4541 (if (not (org-mode-p))
4542 ;; Force the mode for future visits.
4543 (let ((org-insert-mode-line-in-empty-file t))
4544 (call-interactively 'org-mode)))
4545 (when newfile-p
4546 (goto-char (point-max))
4547 (insert (format "\nArchived entries from file %s\n\n"
4548 (buffer-file-name this-buffer))))
4549 ;; Force the TODO keywords of the original buffer
4550 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4551 (org-todo-keywords tr-org-todo-keywords)
4552 (org-todo-interpretation tr-org-todo-interpretation)
4553 (org-done-string tr-org-done-string)
4554 (org-todo-regexp tr-org-todo-regexp)
4555 (org-todo-line-regexp tr-org-todo-line-regexp))
4556 (goto-char (point-min))
4557 (if heading
4558 (progn
4559 (if (re-search-forward
4560 (concat "\\(^\\|\r\\)"
4561 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4562 nil t)
4563 (goto-char (match-end 0))
4564 ;; Heading not found, just insert it at the end
4565 (goto-char (point-max))
4566 (or (bolp) (insert "\n"))
4567 (insert "\n" heading "\n")
4568 (end-of-line 0))
4569 ;; Make the subtree visible
4570 (show-subtree)
4571 (org-end-of-subtree t)
4572 (skip-chars-backward " \t\r\n")
4573 (and (looking-at "[ \t\r\n]*")
4574 (replace-match "\n\n")))
4575 ;; No specific heading, just go to end of file.
4576 (goto-char (point-max)) (insert "\n"))
4577 ;; Paste
4578 (org-paste-subtree (1+ level))
4579 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4580 (if org-archive-mark-done
4581 (org-todo (length org-todo-keywords)))
4582 ;; Move cursor to right after the TODO keyword
4583 (when org-archive-stamp-time
4584 (beginning-of-line 1)
4585 (looking-at org-todo-line-regexp)
4586 (goto-char (or (match-end 2) (match-beginning 3)))
4587 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4588 (org-current-time))
4589 ")"))
4590 ;; Save the buffer, if it is not the same buffer.
4591 (if (not (eq this-buffer buffer)) (save-buffer))))
4592 ;; Here we are back in the original buffer. Everything seems to have
4593 ;; worked. So now cut the tree and finish up.
4594 (let (this-command) (org-cut-subtree))
4595 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4596 (message "Subtree archived %s"
4597 (if (eq this-buffer buffer)
4598 (concat "under heading: " heading)
4599 (concat "in file: " (abbreviate-file-name file)))))))
4600
4601 (defun org-archive-all-done (&optional tag)
4602 "Archive sublevels of the current tree without open TODO items.
4603 If the cursor is not on a headline, try all level 1 trees. If
4604 it is on a headline, try all direct children.
4605 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4606 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4607 (rea (concat ".*:" org-archive-tag ":"))
4608 (begm (make-marker))
4609 (endm (make-marker))
4610 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4611 "Move subtree to archive (no open TODO items)? "))
4612 beg end (cntarch 0))
4613 (if (org-on-heading-p)
4614 (progn
4615 (setq re1 (concat "^" (regexp-quote
4616 (make-string
4617 (1+ (- (match-end 0) (match-beginning 0)))
4618 ?*))
4619 " "))
4620 (move-marker begm (point))
4621 (move-marker endm (org-end-of-subtree)))
4622 (setq re1 "^* ")
4623 (move-marker begm (point-min))
4624 (move-marker endm (point-max)))
4625 (save-excursion
4626 (goto-char begm)
4627 (while (re-search-forward re1 endm t)
4628 (setq beg (match-beginning 0)
4629 end (save-excursion (org-end-of-subtree t) (point)))
4630 (goto-char beg)
4631 (if (re-search-forward re end t)
4632 (goto-char end)
4633 (goto-char beg)
4634 (if (and (or (not tag) (not (looking-at rea)))
4635 (y-or-n-p question))
4636 (progn
4637 (if tag
4638 (org-toggle-tag org-archive-tag 'on)
4639 (org-archive-subtree))
4640 (setq cntarch (1+ cntarch)))
4641 (goto-char end)))))
4642 (message "%d trees archived" cntarch)))
4643
4644 (defun org-cycle-hide-archived-subtrees (state)
4645 "Re-hide all archived subtrees after a visibility state change."
4646 (when (and (not org-cycle-open-archived-trees)
4647 (not (memq state '(overview folded))))
4648 (save-excursion
4649 (let* ((globalp (memq state '(contents all)))
4650 (beg (if globalp (point-min) (point)))
4651 (end (if globalp (point-max) (org-end-of-subtree))))
4652 (org-hide-archived-subtrees beg end)))))
4653
4654 (defun org-hide-archived-subtrees (beg end)
4655 "Re-hide all archived subtrees after a visibility state change."
4656 (save-excursion
4657 (let* ((re (concat ":" org-archive-tag ":")))
4658 (goto-char beg)
4659 (while (re-search-forward re end t)
4660 (and (org-on-heading-p) (hide-subtree))
4661 (org-end-of-subtree)))))
4662
4663 (defun org-toggle-tag (tag &optional onoff)
4664 "Toggle the tag TAG for the current line.
4665 If ONOFF is `on' or `off', don't toggle but set to this state."
4666 (unless (org-on-heading-p) (error "Not on headling"))
4667 (let (res current)
4668 (save-excursion
4669 (beginning-of-line)
4670 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
4671 (point-at-eol) t)
4672 (progn
4673 (setq current (match-string 1))
4674 (replace-match ""))
4675 (setq current ""))
4676 (setq current (nreverse (org-split-string current ":")))
4677 (cond
4678 ((eq onoff 'on)
4679 (setq res t)
4680 (or (member tag current) (push tag current)))
4681 ((eq onoff 'off)
4682 (or (not (member tag current)) (setq current (delete tag current))))
4683 (t (if (member tag current)
4684 (setq current (delete tag current))
4685 (setq res t)
4686 (push tag current))))
4687 (end-of-line 1)
4688 (when current
4689 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
4690 (org-set-tags nil t))
4691 res))
4692
4693 (defun org-toggle-archive-tag (&optional arg)
4694 "Toggle the archive tag for the current headline.
4695 With prefix ARG, check all children of current headline and offer tagging
4696 the children that do not contain any open TODO items."
4697 (interactive "P")
4698 (if arg
4699 (org-archive-all-done 'tag)
4700 (let (set)
4701 (save-excursion
4702 (org-back-to-heading t)
4703 (setq set (org-toggle-tag org-archive-tag))
4704 (when set (hide-subtree)))
4705 (and set (beginning-of-line 1))
4706 (message "Subtree %s" (if set "archived" "unarchived")))))
4707
4708 (defun org-prepare-agenda-buffers (files)
4709 "Create buffers for all agenda files, protect archived trees and comments."
4710 (interactive)
4711 (let ((pa '(:org-archived t))
4712 (pc '(:org-comment t))
4713 (pall '(:org-archived t :org-comment t))
4714 (rea (concat ":" org-archive-tag ":"))
4715 bmp file re)
4716 (save-excursion
4717 (while (setq file (pop files))
4718 (org-check-agenda-file file)
4719 (set-buffer (org-get-agenda-file-buffer file))
4720 (widen)
4721 (setq bmp (buffer-modified-p))
4722 (save-excursion
4723 (remove-text-properties (point-min) (point-max) pall)
4724 (when org-agenda-skip-archived-trees
4725 (goto-char (point-min))
4726 (while (re-search-forward rea nil t)
4727 (if (org-on-heading-p)
4728 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
4729 (goto-char (point-min))
4730 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
4731 (while (re-search-forward re nil t)
4732 (add-text-properties
4733 (match-beginning 0) (org-end-of-subtree t) pc)))
4734 (set-buffer-modified-p bmp)))))
4735
4736 (defun org-agenda-skip ()
4737 "Throw to `:skip' in places that should be skipped."
4738 (let ((p (point-at-bol)))
4739 (and org-agenda-skip-archived-trees
4740 (get-text-property p :org-archived)
4741 (org-end-of-subtree)
4742 (throw :skip t))
4743 (and (get-text-property p :org-comment)
4744 (org-end-of-subtree)
4745 (throw :skip t))
4746 (if (equal (char-after p) ?#) (throw :skip t))))
4747
4748 (defun org-agenda-toggle-archive-tag ()
4749 "Toggle the archive tag for the current entry."
4750 (interactive)
4751 (org-agenda-check-no-diary)
4752 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
4753 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
4754 (org-agenda-error)))
4755 (buffer (marker-buffer hdmarker))
4756 (pos (marker-position hdmarker))
4757 (buffer-read-only nil)
4758 newhead)
4759 (with-current-buffer buffer
4760 (widen)
4761 (goto-char pos)
4762 (org-show-hidden-entry)
4763 (save-excursion
4764 (and (outline-next-heading)
4765 (org-flag-heading nil))) ; show the next heading
4766 (call-interactively 'org-toggle-archive-tag)
4767 (end-of-line 1)
4768 (setq newhead (org-get-heading)))
4769 (org-agenda-change-all-lines newhead hdmarker)
4770 (beginning-of-line 1)))
4771
4772 ;;; Dynamic blocks
4773
4774 (defun org-find-dblock (name)
4775 "Find the first dynamic block with name NAME in the buffer.
4776 If not found, stay at current position and return nil."
4777 (let (pos)
4778 (save-excursion
4779 (goto-char (point-min))
4780 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
4781 nil t)
4782 (match-beginning 0))))
4783 (if pos (goto-char pos))
4784 pos))
4785
4786 (defconst org-dblock-start-re
4787 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
4788 "Matches the startline of a dynamic block, with parameters.")
4789
4790 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
4791 "Matches the end of a dyhamic block.")
4792
4793 (defun org-create-dblock (plist)
4794 "Create a dynamic block section, with parameters taken from PLIST.
4795 PLIST must containe a :name entry which is used as name of the block."
4796 (unless (bolp) (newline))
4797 (let ((name (plist-get plist :name)))
4798 (insert "#+BEGIN: " name)
4799 (while plist
4800 (if (eq (car plist) :name)
4801 (setq plist (cddr plist))
4802 (insert " " (prin1-to-string (pop plist)))))
4803 (insert "\n\n#+END:\n")
4804 (beginning-of-line -2)))
4805
4806 (defun org-prepare-dblock ()
4807 "Prepare dynamic block for refresh.
4808 This empties the block, puts the cursor at the insert position and returns
4809 the property list including an extra property :name with the block name."
4810 (unless (looking-at org-dblock-start-re)
4811 (error "Not at a dynamic block"))
4812 (let* ((begdel (1+ (match-end 0)))
4813 (name (match-string 1))
4814 (params (append (list :name name)
4815 (read (concat "(" (match-string 3) ")")))))
4816 (unless (re-search-forward org-dblock-end-re nil t)
4817 (error "Dynamic block not terminated"))
4818 (delete-region begdel (match-beginning 0))
4819 (goto-char begdel)
4820 (open-line 1)
4821 params))
4822
4823 (defun org-map-dblocks (&optional command)
4824 "Apply COMMAND to all dynamic blocks in the current buffer.
4825 If COMMAND is not given, use `org-update-dblock'."
4826 (let ((cmd (or command 'org-update-dblock))
4827 pos)
4828 (save-excursion
4829 (goto-char (point-min))
4830 (while (re-search-forward org-dblock-start-re nil t)
4831 (goto-char (setq pos (match-beginning 0)))
4832 (condition-case nil
4833 (funcall cmd)
4834 (error (message "Error during update of dynamic block")))
4835 (goto-char pos)
4836 (unless (re-search-forward org-dblock-end-re nil t)
4837 (error "Dynamic block not terminated"))))))
4838
4839 (defun org-dblock-update (&optional arg)
4840 "User command for updating dynamic blocks.
4841 Update the dynamic block at point. With prefix ARG, update all dynamic
4842 blocks in the buffer."
4843 (interactive "P")
4844 (if arg
4845 (org-update-all-dblocks)
4846 (or (looking-at org-dblock-start-re)
4847 (org-beginning-of-dblock))
4848 (org-update-dblock)))
4849
4850 (defun org-update-dblock ()
4851 "Update the dynamic block at point
4852 This means to empty the block, parse for parameters and then call
4853 the correct writing function."
4854 (let* ((pos (point))
4855 (params (org-prepare-dblock))
4856 (name (plist-get params :name))
4857 (cmd (intern (concat "org-dblock-write:" name))))
4858 (funcall cmd params)
4859 (goto-char pos)))
4860
4861 (defun org-beginning-of-dblock ()
4862 "Find the beginning of the dynamic block at point.
4863 Error if there is no scuh block at point."
4864 (let ((pos (point))
4865 beg)
4866 (end-of-line 1)
4867 (if (and (re-search-backward org-dblock-start-re nil t)
4868 (setq beg (match-beginning 0))
4869 (re-search-forward org-dblock-end-re nil t)
4870 (> (match-end 0) pos))
4871 (goto-char beg)
4872 (goto-char pos)
4873 (error "Not in a dynamic block"))))
4874
4875 (defun org-update-all-dblocks ()
4876 "Update all dynamic blocks in the buffer.
4877 This function can be used in a hook."
4878 (when (org-mode-p)
4879 (org-map-dblocks 'org-update-dblock)))
4880
4881
4882 ;;; Completion
4883
4884 (defun org-complete (&optional arg)
4885 "Perform completion on word at point.
4886 At the beginning of a headline, this completes TODO keywords as given in
4887 `org-todo-keywords'.
4888 If the current word is preceded by a backslash, completes the TeX symbols
4889 that are supported for HTML support.
4890 If the current word is preceded by \"#+\", completes special words for
4891 setting file options.
4892 At all other locations, this simply calls `ispell-complete-word'."
4893 (interactive "P")
4894 (catch 'exit
4895 (let* ((end (point))
4896 (beg1 (save-excursion
4897 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4898 (skip-chars-backward "a-zA-Z_@0-9")
4899 (point)))
4900 (beg (save-excursion
4901 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4902 (skip-chars-backward "a-zA-Z0-9_:$")
4903 (point)))
4904 (confirm (lambda (x) (stringp (car x))))
4905 (camel (equal (char-before beg) ?*))
4906 (tag (equal (char-before beg1) ?:))
4907 (texp (equal (char-before beg) ?\\))
4908 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
4909 beg)
4910 "#+"))
4911 (completion-ignore-case opt)
4912 (type nil)
4913 (tbl nil)
4914 (table (cond
4915 (opt
4916 (setq type :opt)
4917 (mapcar (lambda (x)
4918 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
4919 (cons (match-string 2 x) (match-string 1 x)))
4920 (org-split-string (org-get-current-options) "\n")))
4921 (texp
4922 (setq type :tex)
4923 org-html-entities)
4924 ((string-match "\\`\\*+[ \t]*\\'"
4925 (buffer-substring (point-at-bol) beg))
4926 (setq type :todo)
4927 (mapcar 'list org-todo-keywords))
4928 (camel
4929 (setq type :camel)
4930 (save-excursion
4931 (goto-char (point-min))
4932 (while (re-search-forward org-todo-line-regexp nil t)
4933 (push (list
4934 (if org-file-link-context-use-camel-case
4935 (org-make-org-heading-camel (match-string 3) t)
4936 (org-make-org-heading-search-string
4937 (match-string 3) t)))
4938 tbl)))
4939 tbl)
4940 (tag (setq type :tag beg beg1)
4941 (or org-tag-alist (org-get-buffer-tags)))
4942 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
4943 (pattern (buffer-substring-no-properties beg end))
4944 (completion (try-completion pattern table confirm)))
4945 (cond ((eq completion t)
4946 (if (equal type :opt)
4947 (insert (substring (cdr (assoc (upcase pattern) table))
4948 (length pattern)))))
4949 ((null completion)
4950 (message "Can't find completion for \"%s\"" pattern)
4951 (ding))
4952 ((not (string= pattern completion))
4953 (delete-region beg end)
4954 (if (string-match " +$" completion)
4955 (setq completion (replace-match "" t t completion)))
4956 (insert completion)
4957 (if (get-buffer-window "*Completions*")
4958 (delete-window (get-buffer-window "*Completions*")))
4959 (if (assoc completion table)
4960 (if (eq type :todo) (insert " ")
4961 (if (eq type :tag) (insert ":"))))
4962 (if (and (equal type :opt) (assoc completion table))
4963 (message "%s" (substitute-command-keys
4964 "Press \\[org-complete] again to insert example settings"))))
4965 (t
4966 (message "Making completion list...")
4967 (let ((list (sort (all-completions pattern table confirm)
4968 'string<)))
4969 (with-output-to-temp-buffer "*Completions*"
4970 (condition-case nil
4971 ;; Protection needed for XEmacs and emacs 21
4972 (display-completion-list list pattern)
4973 (error (display-completion-list list)))))
4974 (message "Making completion list...%s" "done"))))))
4975
4976 ;;; Comments, TODO and DEADLINE
4977
4978 (defun org-toggle-comment ()
4979 "Change the COMMENT state of an entry."
4980 (interactive)
4981 (save-excursion
4982 (org-back-to-heading)
4983 (if (looking-at (concat outline-regexp
4984 "\\( +\\<" org-comment-string "\\>\\)"))
4985 (replace-match "" t t nil 1)
4986 (if (looking-at outline-regexp)
4987 (progn
4988 (goto-char (match-end 0))
4989 (insert " " org-comment-string))))))
4990
4991 (defvar org-last-todo-state-is-todo nil
4992 "This is non-nil when the last TODO state change led to a TODO state.
4993 If the last change removed the TODO tag or switched to DONE, then
4994 this is nil.")
4995
4996 (defun org-todo (&optional arg)
4997 "Change the TODO state of an item.
4998 The state of an item is given by a keyword at the start of the heading,
4999 like
5000 *** TODO Write paper
5001 *** DONE Call mom
5002
5003 The different keywords are specified in the variable `org-todo-keywords'.
5004 By default the available states are \"TODO\" and \"DONE\".
5005 So for this example: when the item starts with TODO, it is changed to DONE.
5006 When it starts with DONE, the DONE is removed. And when neither TODO nor
5007 DONE are present, add TODO at the beginning of the heading.
5008
5009 With prefix arg, use completion to determine the new state. With numeric
5010 prefix arg, switch to that state."
5011 (interactive "P")
5012 (save-excursion
5013 (org-back-to-heading)
5014 (if (looking-at outline-regexp) (goto-char (match-end 0)))
5015 (or (looking-at (concat " +" org-todo-regexp " *"))
5016 (looking-at " *"))
5017 (let* ((this (match-string 1))
5018 (completion-ignore-case t)
5019 (member (member this org-todo-keywords))
5020 (tail (cdr member))
5021 (state (cond
5022 ((equal arg '(4))
5023 ;; Read a state with completion
5024 (completing-read "State: " (mapcar (lambda(x) (list x))
5025 org-todo-keywords)
5026 nil t))
5027 ((eq arg 'right)
5028 (if this
5029 (if tail (car tail) nil)
5030 (car org-todo-keywords)))
5031 ((eq arg 'left)
5032 (if (equal member org-todo-keywords)
5033 nil
5034 (if this
5035 (nth (- (length org-todo-keywords) (length tail) 2)
5036 org-todo-keywords)
5037 org-done-string)))
5038 (arg
5039 ;; user requests a specific state
5040 (nth (1- (prefix-numeric-value arg))
5041 org-todo-keywords))
5042 ((null member) (car org-todo-keywords))
5043 ((null tail) nil) ;; -> first entry
5044 ((eq org-todo-interpretation 'sequence)
5045 (car tail))
5046 ((memq org-todo-interpretation '(type priority))
5047 (if (eq this-command last-command)
5048 (car tail)
5049 (if (> (length tail) 0) org-done-string nil)))
5050 (t nil)))
5051 (next (if state (concat " " state " ") " ")))
5052 (replace-match next t t)
5053 (setq org-last-todo-state-is-todo
5054 (not (equal state org-done-string)))
5055 (when org-log-done
5056 (if (equal state org-done-string)
5057 (org-add-planning-info 'closed (current-time) 'scheduled)
5058 (if (not this)
5059 (org-add-planning-info nil nil 'closed))))
5060 ;; Fixup tag positioning
5061 (and org-auto-align-tags (org-set-tags nil t))
5062 (run-hooks 'org-after-todo-state-change-hook)))
5063 ;; Fixup cursor location if close to the keyword
5064 (if (and (outline-on-heading-p)
5065 (not (bolp))
5066 (save-excursion (beginning-of-line 1)
5067 (looking-at org-todo-line-regexp))
5068 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5069 (progn
5070 (goto-char (or (match-end 2) (match-end 1)))
5071 (just-one-space))))
5072
5073 (defun org-log-done (&optional undone)
5074 "Add a time stamp logging that a TODO entry has been closed.
5075 When UNDONE is non-nil, remove such a time stamp again."
5076 (interactive)
5077 (let (beg end col)
5078 (save-excursion
5079 (org-back-to-heading t)
5080 (setq beg (point))
5081 (looking-at (concat outline-regexp " *"))
5082 (goto-char (match-end 0))
5083 (setq col (current-column))
5084 (outline-next-heading)
5085 (setq end (point))
5086 (goto-char beg)
5087 (when (re-search-forward (concat
5088 "[\r\n]\\([ \t]*"
5089 (regexp-quote org-closed-string)
5090 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
5091 (delete-region (match-beginning 1) (match-end 1)))
5092 (unless undone
5093 (org-back-to-heading t)
5094 (skip-chars-forward "^\n\r")
5095 (goto-char (min (1+ (point)) (point-max)))
5096 (when (not (member (char-before) '(?\r ?\n)))
5097 (insert "\n"))
5098 (indent-to col)
5099 (insert org-closed-string " "
5100 (format-time-string
5101 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5102 (org-current-time))
5103 "\n")))))
5104
5105 (defun org-show-todo-tree (arg)
5106 "Make a compact tree which shows all headlines marked with TODO.
5107 The tree will show the lines where the regexp matches, and all higher
5108 headlines above the match.
5109 With \\[universal-argument] prefix, also show the DONE entries.
5110 With a numeric prefix N, construct a sparse tree for the Nth element
5111 of `org-todo-keywords'."
5112 (interactive "P")
5113 (let ((case-fold-search nil)
5114 (kwd-re
5115 (cond ((null arg) org-not-done-regexp)
5116 ((equal arg '(4)) org-todo-regexp)
5117 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5118 (regexp-quote (nth (1- (prefix-numeric-value arg))
5119 org-todo-keywords)))
5120 (t (error "Invalid prefix argument: %s" arg)))))
5121 (message "%d TODO entries found"
5122 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5123
5124 (defun org-deadline ()
5125 "Insert the DEADLINE: string to make a deadline.
5126 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5127 to modify it to the correct date."
5128 (interactive)
5129 (org-add-planning-info 'deadline nil 'closed))
5130
5131 (defun org-schedule ()
5132 "Insert the SCHEDULED: string to schedule a TODO item.
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 'scheduled nil 'closed))
5137
5138 (defun org-add-planning-info (what &optional time &rest remove)
5139 "Insert new timestamp with keyword in the line directly after the headline.
5140 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5141 If non is given, the user is prompted for a date.
5142 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5143 be removed."
5144 (interactive)
5145 (when what (setq time (or time (org-read-date nil 'to-time))))
5146 (when (and org-insert-labeled-timestamps-at-point
5147 (member what '(scheduled deadline)))
5148 (insert
5149 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
5150 " "
5151 (format-time-string (car org-time-stamp-formats) time))
5152 (setq what nil))
5153 (save-excursion
5154 (let (col list elt (buffer-invisibility-spec nil) ts)
5155 (org-back-to-heading t)
5156 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5157 (goto-char (match-end 1))
5158 (setq col (current-column))
5159 (goto-char (1+ (match-end 0)))
5160 (if (and (not (looking-at outline-regexp))
5161 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5162 "[^\r\n]*"))
5163 (not (equal (match-string 1) org-clock-string)))
5164 (narrow-to-region (match-beginning 0) (match-end 0))
5165 (insert "\n")
5166 (backward-char 1)
5167 (narrow-to-region (point) (point))
5168 (indent-to-column col))
5169 ;; Check if we have to remove something.
5170 (setq list (cons what remove))
5171 (while list
5172 (setq elt (pop list))
5173 (goto-char (point-min))
5174 (when (or (and (eq elt 'scheduled)
5175 (re-search-forward org-scheduled-time-regexp nil t))
5176 (and (eq elt 'deadline)
5177 (re-search-forward org-deadline-time-regexp nil t))
5178 (and (eq elt 'closed)
5179 (re-search-forward org-closed-time-regexp nil t)))
5180 (replace-match "")
5181 (if (looking-at " +") (replace-match ""))))
5182 (goto-char (point-max))
5183 (when what
5184 (insert
5185 (if (not (equal (char-before) ?\ )) " " "")
5186 (cond ((eq what 'scheduled) org-scheduled-string)
5187 ((eq what 'deadline) org-deadline-string)
5188 ((eq what 'closed) org-closed-string))
5189 " ")
5190 (insert
5191 (setq ts
5192 (format-time-string
5193 (if (eq what 'closed)
5194 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5195 (car org-time-stamp-formats))
5196 time))))
5197 (goto-char (point-min))
5198 (widen)
5199 (if (looking-at "[ \t]+\r?\n")
5200 (replace-match ""))
5201 ts)))
5202
5203 (defun org-occur (regexp &optional callback)
5204 "Make a compact tree which shows all matches of REGEXP.
5205 The tree will show the lines where the regexp matches, and all higher
5206 headlines above the match. It will also show the heading after the match,
5207 to make sure editing the matching entry is easy.
5208 If CALLBACK is non-nil, it is a function which is called to confirm
5209 that the match should indeed be shown."
5210 (interactive "sRegexp: ")
5211 (org-remove-occur-highlights nil nil t)
5212 (let ((cnt 0))
5213 (save-excursion
5214 (goto-char (point-min))
5215 (org-overview)
5216 (while (re-search-forward regexp nil t)
5217 (when (or (not callback)
5218 (save-match-data (funcall callback)))
5219 (setq cnt (1+ cnt))
5220 (org-highlight-new-match (match-beginning 0) (match-end 0))
5221 (org-show-hierarchy-above))))
5222 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5223 nil 'local)
5224 (unless org-sparse-tree-open-archived-trees
5225 (org-hide-archived-subtrees (point-min) (point-max)))
5226 (run-hooks 'org-occur-hook)
5227 (if (interactive-p)
5228 (message "%d match(es) for regexp %s" cnt regexp))
5229 cnt))
5230
5231 (defun org-show-hierarchy-above ()
5232 "Make sure point and the headings hierarchy above is visible."
5233 (catch 'exit
5234 (if (org-on-heading-p t)
5235 (org-flag-heading nil) ; only show the heading
5236 (and (or (org-invisible-p) (org-invisible-p2))
5237 (org-show-hidden-entry))) ; show entire entry
5238 (save-excursion
5239 (and org-show-following-heading
5240 (outline-next-heading)
5241 (org-flag-heading nil))) ; show the next heading
5242 (when org-show-hierarchy-above
5243 (save-excursion ; show all higher headings
5244 (while (and (condition-case nil
5245 (progn (org-up-heading-all 1) t)
5246 (error nil))
5247 (not (bobp)))
5248 (org-flag-heading nil))))))
5249
5250 ;; Overlay compatibility functions
5251 (defun org-make-overlay (beg end &optional buffer)
5252 (if (featurep 'xemacs)
5253 (make-extent beg end buffer)
5254 (make-overlay beg end buffer)))
5255 (defun org-delete-overlay (ovl)
5256 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5257 (defun org-detatch-overlay (ovl)
5258 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5259 (defun org-move-overlay (ovl beg end &optional buffer)
5260 (if (featurep 'xemacs)
5261 (set-extent-endpoints ovl beg end buffer)
5262 (move-overlay ovl beg end buffer)))
5263 (defun org-overlay-put (ovl prop value)
5264 (if (featurep 'xemacs)
5265 (set-extent-property ovl prop value)
5266 (overlay-put ovl prop value)))
5267 (defun org-overlays-at (pos)
5268 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5269 (defun org-overlay-start (o)
5270 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5271 (defun org-overlay-end (o)
5272 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5273
5274 (defvar org-occur-highlights nil)
5275 (make-variable-buffer-local 'org-occur-highlights)
5276 (defun org-highlight-new-match (beg end)
5277 "Highlight from BEG to END and mark the highlight is an occur headline."
5278 (let ((ov (org-make-overlay beg end)))
5279 (org-overlay-put ov 'face 'secondary-selection)
5280 (push ov org-occur-highlights)))
5281
5282 (defvar org-inhibit-highlight-removal nil)
5283 (defun org-remove-occur-highlights (&optional beg end noremove)
5284 "Remove the occur highlights from the buffer.
5285 BEG and END are ignored. If NOREMOVE is nil, remove this function
5286 from the `before-change-functions' in the current buffer."
5287 (interactive)
5288 (unless org-inhibit-highlight-removal
5289 (mapc 'org-delete-overlay org-occur-highlights)
5290 (setq org-occur-highlights nil)
5291 (unless noremove
5292 (remove-hook 'before-change-functions
5293 'org-remove-occur-highlights 'local))))
5294
5295 ;;; Priorities
5296
5297 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5298 "Regular expression matching the priority indicator.")
5299
5300 (defvar org-remove-priority-next-time nil)
5301
5302 (defun org-priority-up ()
5303 "Increase the priority of the current item."
5304 (interactive)
5305 (org-priority 'up))
5306
5307 (defun org-priority-down ()
5308 "Decrease the priority of the current item."
5309 (interactive)
5310 (org-priority 'down))
5311
5312 (defun org-priority (&optional action)
5313 "Change the priority of an item by ARG.
5314 ACTION can be set, up, or down."
5315 (interactive)
5316 (setq action (or action 'set))
5317 (let (current new news have remove)
5318 (save-excursion
5319 (org-back-to-heading)
5320 (if (looking-at org-priority-regexp)
5321 (setq current (string-to-char (match-string 2))
5322 have t)
5323 (setq current org-default-priority))
5324 (cond
5325 ((eq action 'set)
5326 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5327 (setq new (read-char-exclusive))
5328 (cond ((equal new ?\ ) (setq remove t))
5329 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5330 (error "Priority must be between `%c' and `%c'"
5331 ?A org-lowest-priority))))
5332 ((eq action 'up)
5333 (setq new (1- current)))
5334 ((eq action 'down)
5335 (setq new (1+ current)))
5336 (t (error "Invalid action")))
5337 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5338 (setq news (format "%c" new))
5339 (if have
5340 (if remove
5341 (replace-match "" t t nil 1)
5342 (replace-match news t t nil 2))
5343 (if remove
5344 (error "No priority cookie found in line")
5345 (looking-at org-todo-line-regexp)
5346 (if (match-end 2)
5347 (progn
5348 (goto-char (match-end 2))
5349 (insert " [#" news "]"))
5350 (goto-char (match-beginning 3))
5351 (insert "[#" news "] ")))))
5352 (if remove
5353 (message "Priority removed")
5354 (message "Priority of current item set to %s" news))))
5355
5356
5357 (defun org-get-priority (s)
5358 "Find priority cookie and return priority."
5359 (save-match-data
5360 (if (not (string-match org-priority-regexp s))
5361 (* 1000 (- org-lowest-priority org-default-priority))
5362 (* 1000 (- org-lowest-priority
5363 (string-to-char (match-string 2 s)))))))
5364
5365 ;;; Timestamps
5366
5367 (defvar org-last-changed-timestamp nil)
5368
5369 (defun org-time-stamp (arg)
5370 "Prompt for a date/time and insert a time stamp.
5371 If the user specifies a time like HH:MM, or if this command is called
5372 with a prefix argument, the time stamp will contain date and time.
5373 Otherwise, only the date will be included. All parts of a date not
5374 specified by the user will be filled in from the current date/time.
5375 So if you press just return without typing anything, the time stamp
5376 will represent the current date/time. If there is already a timestamp
5377 at the cursor, it will be modified."
5378 (interactive "P")
5379 (let ((fmt (if arg (cdr org-time-stamp-formats)
5380 (car org-time-stamp-formats)))
5381 (org-time-was-given nil)
5382 time)
5383 (cond
5384 ((and (org-at-timestamp-p)
5385 (eq last-command 'org-time-stamp)
5386 (eq this-command 'org-time-stamp))
5387 (insert "--")
5388 (setq time (let ((this-command this-command))
5389 (org-read-date arg 'totime)))
5390 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5391 (insert (format-time-string fmt time)))
5392 ((org-at-timestamp-p)
5393 (setq time (let ((this-command this-command))
5394 (org-read-date arg 'totime)))
5395 (and (org-at-timestamp-p) (replace-match
5396 (setq org-last-changed-timestamp
5397 (format-time-string fmt time))
5398 t t))
5399 (message "Timestamp updated"))
5400 (t
5401 (setq time (let ((this-command this-command))
5402 (org-read-date arg 'totime)))
5403 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5404 (insert (format-time-string fmt time))))))
5405
5406 (defun org-time-stamp-inactive (&optional arg)
5407 "Insert an inactive time stamp.
5408 An inactive time stamp is enclosed in square brackets instead of angle
5409 brackets. It is inactive in the sense that it does not trigger agenda entries,
5410 does not link to the calendar and cannot be changed with the S-cursor keys.
5411 So these are more for recording a certain time/date."
5412 (interactive "P")
5413 (let ((fmt (if arg (cdr org-time-stamp-formats)
5414 (car org-time-stamp-formats)))
5415 (org-time-was-given nil)
5416 time)
5417 (setq time (org-read-date arg 'totime))
5418 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5419 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
5420 (insert (format-time-string fmt time))))
5421
5422 (defvar org-date-ovl (org-make-overlay 1 1))
5423 (org-overlay-put org-date-ovl 'face 'org-warning)
5424 (org-detatch-overlay org-date-ovl)
5425
5426 (defun org-read-date (&optional with-time to-time)
5427 "Read a date and make things smooth for the user.
5428 The prompt will suggest to enter an ISO date, but you can also enter anything
5429 which will at least partially be understood by `parse-time-string'.
5430 Unrecognized parts of the date will default to the current day, month, year,
5431 hour and minute. For example,
5432 3-2-5 --> 2003-02-05
5433 feb 15 --> currentyear-02-15
5434 sep 12 9 --> 2009-09-12
5435 12:45 --> today 12:45
5436 22 sept 0:34 --> currentyear-09-22 0:34
5437 12 --> currentyear-currentmonth-12
5438 Fri --> nearest Friday (today or later)
5439 etc.
5440 The function understands only English month and weekday abbreviations,
5441 but this can be configured with the variables `parse-time-months' and
5442 `parse-time-weekdays'.
5443
5444 While prompting, a calendar is popped up - you can also select the
5445 date with the mouse (button 1). The calendar shows a period of three
5446 months. To scroll it to other months, use the keys `>' and `<'.
5447 If you don't like the calendar, turn it off with
5448 \(setq org-popup-calendar-for-date-prompt nil)
5449
5450 With optional argument TO-TIME, the date will immediately be converted
5451 to an internal time.
5452 With an optional argument WITH-TIME, the prompt will suggest to also
5453 insert a time. Note that when WITH-TIME is not set, you can still
5454 enter a time, and this function will inform the calling routine about
5455 this change. The calling routine may then choose to change the format
5456 used to insert the time stamp into the buffer to include the time."
5457 (require 'parse-time)
5458 (let* ((org-time-stamp-rounding-minutes
5459 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5460 (ct (org-current-time))
5461 (default-time
5462 ;; Default time is either today, or, when entering a range,
5463 ;; the range start.
5464 (if (save-excursion
5465 (re-search-backward
5466 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5467 (- (point) 20) t))
5468 (apply
5469 'encode-time
5470 (mapcar (lambda(x) (or x 0))
5471 (parse-time-string (match-string 1))))
5472 ct))
5473 (calendar-move-hook nil)
5474 (view-diary-entries-initially nil)
5475 (view-calendar-holidays-initially nil)
5476 (timestr (format-time-string
5477 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5478 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5479 ans ans1 ans2
5480 second minute hour day month year tl wday wday1)
5481
5482 (if org-popup-calendar-for-date-prompt
5483 (save-excursion
5484 (save-window-excursion
5485 (calendar)
5486 (calendar-forward-day (- (time-to-days default-time)
5487 (calendar-absolute-from-gregorian
5488 (calendar-current-date))))
5489 (org-eval-in-calendar nil)
5490 (let* ((old-map (current-local-map))
5491 (map (copy-keymap calendar-mode-map))
5492 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5493 (define-key map (kbd "RET") 'org-calendar-select)
5494 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5495 'org-calendar-select-mouse)
5496 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5497 'org-calendar-select-mouse)
5498 (define-key minibuffer-local-map [(meta shift left)]
5499 (lambda () (interactive)
5500 (org-eval-in-calendar '(calendar-backward-month 1))))
5501 (define-key minibuffer-local-map [(meta shift right)]
5502 (lambda () (interactive)
5503 (org-eval-in-calendar '(calendar-forward-month 1))))
5504 (define-key minibuffer-local-map [(shift up)]
5505 (lambda () (interactive)
5506 (org-eval-in-calendar '(calendar-backward-week 1))))
5507 (define-key minibuffer-local-map [(shift down)]
5508 (lambda () (interactive)
5509 (org-eval-in-calendar '(calendar-forward-week 1))))
5510 (define-key minibuffer-local-map [(shift left)]
5511 (lambda () (interactive)
5512 (org-eval-in-calendar '(calendar-backward-day 1))))
5513 (define-key minibuffer-local-map [(shift right)]
5514 (lambda () (interactive)
5515 (org-eval-in-calendar '(calendar-forward-day 1))))
5516 (define-key minibuffer-local-map ">"
5517 (lambda () (interactive)
5518 (org-eval-in-calendar '(scroll-calendar-left 1))))
5519 (define-key minibuffer-local-map "<"
5520 (lambda () (interactive)
5521 (org-eval-in-calendar '(scroll-calendar-right 1))))
5522 (unwind-protect
5523 (progn
5524 (use-local-map map)
5525 (setq ans (read-string prompt "" nil nil))
5526 (if (not (string-match "\\S-" ans)) (setq ans nil))
5527 (setq ans (or ans1 ans ans2)))
5528 (use-local-map old-map)))))
5529 ;; Naked prompt only
5530 (setq ans (read-string prompt "" nil timestr)))
5531 (org-detatch-overlay org-date-ovl)
5532
5533 (if (string-match
5534 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5535 (progn
5536 (setq year (if (match-end 2)
5537 (string-to-number (match-string 2 ans))
5538 (string-to-number (format-time-string "%Y")))
5539 month (string-to-number (match-string 3 ans))
5540 day (string-to-number (match-string 4 ans)))
5541 (if (< year 100) (setq year (+ 2000 year)))
5542 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5543 t nil ans))))
5544 (setq tl (parse-time-string ans)
5545 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5546 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5547 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5548 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5549 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5550 second (or (nth 0 tl) 0)
5551 wday (nth 6 tl))
5552 (when (and wday (not (nth 3 tl)))
5553 ;; Weekday was given, but no day, so pick that day in the week
5554 ;; on or after the derived date.
5555 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5556 (unless (equal wday wday1)
5557 (setq day (+ day (% (- wday wday1 -7) 7)))))
5558 (if (and (boundp 'org-time-was-given)
5559 (nth 2 tl))
5560 (setq org-time-was-given t))
5561 (if (< year 100) (setq year (+ 2000 year)))
5562 (if to-time
5563 (encode-time second minute hour day month year)
5564 (if (or (nth 1 tl) (nth 2 tl))
5565 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5566 (format "%04d-%02d-%02d" year month day)))))
5567
5568 (defun org-eval-in-calendar (form)
5569 "Eval FORM in the calendar window and return to current window.
5570 Also, store the cursor date in variable ans2."
5571 (let ((sw (selected-window)))
5572 (select-window (get-buffer-window "*Calendar*"))
5573 (eval form)
5574 (when (calendar-cursor-to-date)
5575 (let* ((date (calendar-cursor-to-date))
5576 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5577 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5578 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5579 (select-window sw)))
5580
5581 (defun org-calendar-select ()
5582 "Return to `org-read-date' with the date currently selected.
5583 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5584 (interactive)
5585 (when (calendar-cursor-to-date)
5586 (let* ((date (calendar-cursor-to-date))
5587 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5588 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5589 (if (active-minibuffer-window) (exit-minibuffer))))
5590
5591 (defun org-calendar-select-mouse (ev)
5592 "Return to `org-read-date' with the date currently selected.
5593 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5594 (interactive "e")
5595 (mouse-set-point ev)
5596 (when (calendar-cursor-to-date)
5597 (let* ((date (calendar-cursor-to-date))
5598 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5599 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5600 (if (active-minibuffer-window) (exit-minibuffer))))
5601
5602 (defun org-check-deadlines (ndays)
5603 "Check if there are any deadlines due or past due.
5604 A deadline is considered due if it happens within `org-deadline-warning-days'
5605 days from today's date. If the deadline appears in an entry marked DONE,
5606 it is not shown. The prefix arg NDAYS can be used to test that many
5607 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
5608 (interactive "P")
5609 (let* ((org-warn-days
5610 (cond
5611 ((equal ndays '(4)) 100000)
5612 (ndays (prefix-numeric-value ndays))
5613 (t org-deadline-warning-days)))
5614 (case-fold-search nil)
5615 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5616 (callback
5617 (lambda ()
5618 (and (let ((d1 (time-to-days (current-time)))
5619 (d2 (time-to-days
5620 (org-time-string-to-time (match-string 1)))))
5621 (< (- d2 d1) org-warn-days))
5622 (not (org-entry-is-done-p))))))
5623 (message "%d deadlines past-due or due within %d days"
5624 (org-occur regexp callback)
5625 org-warn-days)))
5626
5627 (defun org-evaluate-time-range (&optional to-buffer)
5628 "Evaluate a time range by computing the difference between start and end.
5629 Normally the result is just printed in the echo area, but with prefix arg
5630 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5631 If the time range is actually in a table, the result is inserted into the
5632 next column.
5633 For time difference computation, a year is assumed to be exactly 365
5634 days in order to avoid rounding problems."
5635 (interactive "P")
5636 (or
5637 (org-clock-update-time-maybe)
5638 (save-excursion
5639 (unless (org-at-date-range-p)
5640 (goto-char (point-at-bol))
5641 (re-search-forward org-tr-regexp (point-at-eol) t))
5642 (if (not (org-at-date-range-p))
5643 (error "Not at a time-stamp range, and none found in current line")))
5644 (let* ((ts1 (match-string 1))
5645 (ts2 (match-string 2))
5646 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5647 (match-end (match-end 0))
5648 (time1 (org-time-string-to-time ts1))
5649 (time2 (org-time-string-to-time ts2))
5650 (t1 (time-to-seconds time1))
5651 (t2 (time-to-seconds time2))
5652 (diff (abs (- t2 t1)))
5653 (negative (< (- t2 t1) 0))
5654 ;; (ys (floor (* 365 24 60 60)))
5655 (ds (* 24 60 60))
5656 (hs (* 60 60))
5657 (fy "%dy %dd %02d:%02d")
5658 (fy1 "%dy %dd")
5659 (fd "%dd %02d:%02d")
5660 (fd1 "%dd")
5661 (fh "%02d:%02d")
5662 y d h m align)
5663 (if havetime
5664 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5665 y 0
5666 d (floor (/ diff ds)) diff (mod diff ds)
5667 h (floor (/ diff hs)) diff (mod diff hs)
5668 m (floor (/ diff 60)))
5669 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5670 y 0
5671 d (floor (+ (/ diff ds) 0.5))
5672 h 0 m 0))
5673 (if (not to-buffer)
5674 (message (org-make-tdiff-string y d h m))
5675 (when (org-at-table-p)
5676 (goto-char match-end)
5677 (setq align t)
5678 (and (looking-at " *|") (goto-char (match-end 0))))
5679 (if (looking-at
5680 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5681 (replace-match ""))
5682 (if negative (insert " -"))
5683 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5684 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5685 (insert " " (format fh h m))))
5686 (if align (org-table-align))
5687 (message "Time difference inserted")))))
5688
5689 (defun org-make-tdiff-string (y d h m)
5690 (let ((fmt "")
5691 (l nil))
5692 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5693 l (push y l)))
5694 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5695 l (push d l)))
5696 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5697 l (push h l)))
5698 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5699 l (push m l)))
5700 (apply 'format fmt (nreverse l))))
5701
5702 (defun org-time-string-to-time (s)
5703 (apply 'encode-time (org-parse-time-string s)))
5704
5705 (defun org-parse-time-string (s &optional nodefault)
5706 "Parse the standard Org-mode time string.
5707 This should be a lot faster than the normal `parse-time-string'.
5708 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5709 hour and minute fields will be nil if not given."
5710 (if (string-match org-ts-regexp1 s)
5711 (list 0
5712 (if (or (match-beginning 8) (not nodefault))
5713 (string-to-number (or (match-string 8 s) "0")))
5714 (if (or (match-beginning 7) (not nodefault))
5715 (string-to-number (or (match-string 7 s) "0")))
5716 (string-to-number (match-string 4 s))
5717 (string-to-number (match-string 3 s))
5718 (string-to-number (match-string 2 s))
5719 nil nil nil)
5720 (make-list 9 0)))
5721
5722 (defun org-timestamp-up (&optional arg)
5723 "Increase the date item at the cursor by one.
5724 If the cursor is on the year, change the year. If it is on the month or
5725 the day, change that.
5726 With prefix ARG, change by that many units."
5727 (interactive "p")
5728 (org-timestamp-change (prefix-numeric-value arg)))
5729
5730 (defun org-timestamp-down (&optional arg)
5731 "Decrease the date item at the cursor by one.
5732 If the cursor is on the year, change the year. If it is on the month or
5733 the day, change that.
5734 With prefix ARG, change by that many units."
5735 (interactive "p")
5736 (org-timestamp-change (- (prefix-numeric-value arg))))
5737
5738 (defun org-timestamp-up-day (&optional arg)
5739 "Increase the date in the time stamp by one day.
5740 With prefix ARG, change that many days."
5741 (interactive "p")
5742 (if (and (not (org-at-timestamp-p t))
5743 (org-on-heading-p))
5744 (org-todo 'up)
5745 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5746
5747 (defun org-timestamp-down-day (&optional arg)
5748 "Decrease the date in the time stamp by one day.
5749 With prefix ARG, change that many days."
5750 (interactive "p")
5751 (if (and (not (org-at-timestamp-p t))
5752 (org-on-heading-p))
5753 (org-todo 'down)
5754 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5755
5756 (defsubst org-pos-in-match-range (pos n)
5757 (and (match-beginning n)
5758 (<= (match-beginning n) pos)
5759 (>= (match-end n) pos)))
5760
5761 (defun org-at-timestamp-p (&optional also-inactive)
5762 "Determine if the cursor is in or at a timestamp."
5763 (interactive)
5764 (let* ((tsr (if also-inactive org-ts-regexp3 org-ts-regexp2))
5765 (pos (point))
5766 (ans (or (looking-at tsr)
5767 (save-excursion
5768 (skip-chars-backward "^[<\n\r\t")
5769 (if (> (point) 1) (backward-char 1))
5770 (and (looking-at tsr)
5771 (> (- (match-end 0) pos) -1))))))
5772 (and (boundp 'org-ts-what)
5773 (setq org-ts-what
5774 (cond
5775 ((org-pos-in-match-range pos 2) 'year)
5776 ((org-pos-in-match-range pos 3) 'month)
5777 ((org-pos-in-match-range pos 7) 'hour)
5778 ((org-pos-in-match-range pos 8) 'minute)
5779 ((or (org-pos-in-match-range pos 4)
5780 (org-pos-in-match-range pos 5)) 'day)
5781 (t 'day))))
5782 ans))
5783
5784 (defun org-timestamp-change (n &optional what)
5785 "Change the date in the time stamp at point.
5786 The date will be changed by N times WHAT. WHAT can be `day', `month',
5787 `year', `minute', `second'. If WHAT is not given, the cursor position
5788 in the timestamp determines what will be changed."
5789 (let ((fmt (car org-time-stamp-formats))
5790 org-ts-what
5791 (pos (point))
5792 ts time time0)
5793 (if (not (org-at-timestamp-p t))
5794 (error "Not at a timestamp"))
5795 (setq org-ts-what (or what org-ts-what))
5796 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5797 (- (match-end 0) (match-beginning 0))))
5798 1)
5799 (cdr org-time-stamp-formats)
5800 (car org-time-stamp-formats)))
5801 (if (= (char-after (match-beginning 0)) ?\[)
5802 (setq fmt (concat "[" (substring fmt 1 -1) "]")))
5803 (setq ts (match-string 0))
5804 (replace-match "")
5805 (setq time0 (org-parse-time-string ts))
5806 (setq time
5807 (apply 'encode-time
5808 (append
5809 (list (or (car time0) 0))
5810 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5811 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5812 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5813 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5814 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5815 (nthcdr 6 time0))))
5816 (if (eq what 'calendar)
5817 (let ((cal-date
5818 (save-excursion
5819 (save-match-data
5820 (set-buffer "*Calendar*")
5821 (calendar-cursor-to-date)))))
5822 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5823 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5824 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5825 (setcar time0 (or (car time0) 0))
5826 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5827 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5828 (setq time (apply 'encode-time time0))))
5829 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5830 (org-clock-update-time-maybe)
5831 (goto-char pos)
5832 ;; Try to recenter the calendar window, if any
5833 (if (and org-calendar-follow-timestamp-change
5834 (get-buffer-window "*Calendar*" t)
5835 (memq org-ts-what '(day month year)))
5836 (org-recenter-calendar (time-to-days time)))))
5837
5838 (defun org-recenter-calendar (date)
5839 "If the calendar is visible, recenter it to DATE."
5840 (let* ((win (selected-window))
5841 (cwin (get-buffer-window "*Calendar*" t))
5842 (calendar-move-hook nil))
5843 (when cwin
5844 (select-window cwin)
5845 (calendar-goto-date (if (listp date) date
5846 (calendar-gregorian-from-absolute date)))
5847 (select-window win))))
5848
5849 (defun org-goto-calendar (&optional arg)
5850 "Go to the Emacs calendar at the current date.
5851 If there is a time stamp in the current line, go to that date.
5852 A prefix ARG can be used to force the current date."
5853 (interactive "P")
5854 (let ((tsr org-ts-regexp) diff
5855 (calendar-move-hook nil)
5856 (view-calendar-holidays-initially nil)
5857 (view-diary-entries-initially nil))
5858 (if (or (org-at-timestamp-p)
5859 (save-excursion
5860 (beginning-of-line 1)
5861 (looking-at (concat ".*" tsr))))
5862 (let ((d1 (time-to-days (current-time)))
5863 (d2 (time-to-days
5864 (org-time-string-to-time (match-string 1)))))
5865 (setq diff (- d2 d1))))
5866 (calendar)
5867 (calendar-goto-today)
5868 (if (and diff (not arg)) (calendar-forward-day diff))))
5869
5870 (defun org-date-from-calendar ()
5871 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5872 If there is already a time stamp at the cursor position, update it."
5873 (interactive)
5874 (org-timestamp-change 0 'calendar))
5875
5876 ;;; The clock for measuring work time.
5877
5878 (defvar org-clock-marker (make-marker)
5879 "Marker recording the last clock-in.")
5880
5881 (defun org-clock-in ()
5882 "Start the clock on the current item.
5883 If necessary, clock-out of the currently active clock."
5884 (interactive)
5885 (org-clock-out t)
5886 (let (ts)
5887 (save-excursion
5888 (org-back-to-heading t)
5889 (beginning-of-line 2)
5890 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5891 (not (equal (match-string 1) org-clock-string)))
5892 (beginning-of-line 1))
5893 (insert "\n") (backward-char 1)
5894 (indent-relative)
5895 (insert org-clock-string " "
5896 (setq ts (concat "[" (format-time-string
5897 (substring
5898 (cdr org-time-stamp-formats) 1 -1)
5899 (current-time))
5900 "]")))
5901 (move-marker org-clock-marker (point))
5902 (message "Clock started at %s" ts))))
5903
5904 (defun org-clock-out (&optional fail-quietly)
5905 "Stop the currently running clock.
5906 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
5907 (interactive)
5908 (catch 'exit
5909 (if (not (marker-buffer org-clock-marker))
5910 (if fail-quietly (throw 'exit t) (error "No active clock")))
5911 (let (ts te s h m)
5912 (save-excursion
5913 (set-buffer (marker-buffer org-clock-marker))
5914 (goto-char org-clock-marker)
5915 (beginning-of-line 1)
5916 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5917 (equal (match-string 1) org-clock-string))
5918 (setq ts (match-string 2))
5919 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
5920 (goto-char org-clock-marker)
5921 (setq te (concat "[" (format-time-string
5922 (substring
5923 (cdr org-time-stamp-formats) 1 -1)
5924 (current-time))
5925 "]"))
5926 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
5927 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
5928 h (floor (/ s 3600))
5929 s (- s (* 3600 h))
5930 m (floor (/ s 60))
5931 s (- s (* 60 s)))
5932 (insert "--" te " => " (format "%2d:%02d" h m))
5933 (move-marker org-clock-marker nil)
5934 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
5935
5936 (defun org-clock-cancel ()
5937 "Cancel the running clock be removing the start timestamp."
5938 (interactive)
5939 (if (not (marker-buffer org-clock-marker))
5940 (error "No active clock"))
5941 (save-excursion
5942 (set-buffer (marker-buffer org-clock-marker))
5943 (goto-char org-clock-marker)
5944 (delete-region (1- (point-at-bol)) (point-at-eol)))
5945 (message "Clock canceled"))
5946
5947 (defvar org-clock-file-total-minutes nil
5948 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
5949 (make-variable-buffer-local 'org-clock-file-total-minutes)
5950
5951 (defun org-clock-sum (&optional tstart tend)
5952 "Sum the times for each subtree.
5953 Puts the resulting times in minutes as a text property on each headline."
5954 (interactive)
5955 (let* ((bmp (buffer-modified-p))
5956 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
5957 org-clock-string
5958 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
5959 (lmax 30)
5960 (ltimes (make-vector lmax 0))
5961 (t1 0)
5962 (level 0)
5963 ts te dt
5964 time)
5965 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
5966 (save-excursion
5967 (goto-char (point-max))
5968 (while (re-search-backward re nil t)
5969 (if (match-end 2)
5970 ;; A time
5971 (setq ts (match-string 2)
5972 te (match-string 3)
5973 ts (time-to-seconds
5974 (apply 'encode-time (org-parse-time-string ts)))
5975 te (time-to-seconds
5976 (apply 'encode-time (org-parse-time-string te)))
5977 ts (if tstart (max ts tstart) ts)
5978 te (if tend (min te tend) te)
5979 dt (- te ts)
5980 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
5981 ;; A headline
5982 (setq level (- (match-end 1) (match-beginning 1)))
5983 (when (or (> t1 0) (> (aref ltimes level) 0))
5984 (loop for l from 0 to level do
5985 (aset ltimes l (+ (aref ltimes l) t1)))
5986 (setq t1 0 time (aref ltimes level))
5987 (loop for l from level to (1- lmax) do
5988 (aset ltimes l 0))
5989 (goto-char (match-beginning 0))
5990 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
5991 (setq org-clock-file-total-minutes (aref ltimes 0)))
5992 (set-buffer-modified-p bmp)))
5993
5994 (defun org-clock-display (&optional total-only)
5995 "Show subtree times in the entire buffer.
5996 If TOTAL-ONLY is non-nil, only show the total time for the entire file
5997 in the echo area."
5998 (interactive)
5999 (org-remove-clock-overlays)
6000 (let (time h m p)
6001 (org-clock-sum)
6002 (unless total-only
6003 (save-excursion
6004 (goto-char (point-min))
6005 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6006 (goto-char p)
6007 (when (setq time (get-text-property p :org-clock-minutes))
6008 (org-put-clock-overlay time (funcall outline-level))))
6009 (setq h (/ org-clock-file-total-minutes 60)
6010 m (- org-clock-file-total-minutes (* 60 h)))
6011 ;; Arrange to remove the overlays upon next change.
6012 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
6013 nil 'local)))
6014 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
6015
6016 (defvar org-clock-overlays nil)
6017 (make-variable-buffer-local 'org-clock-overlays)
6018
6019 (defun org-put-clock-overlay (time &optional level)
6020 "Put an overlays on the current line, displaying TIME.
6021 If LEVEL is given, prefix time with a corresponding number of stars.
6022 This creates a new overlay and stores it in `org-clock-overlays', so that it
6023 will be easy to remove."
6024 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
6025 (l (if level (org-get-legal-level level 0) 0))
6026 (off 0)
6027 ov tx)
6028 (move-to-column c)
6029 (unless (eolp) (skip-chars-backward "^ \t"))
6030 (skip-chars-backward " \t")
6031 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6032 tx (concat (buffer-substring (1- (point)) (point))
6033 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6034 (org-add-props (format "%s %2d:%02d%s"
6035 (make-string l ?*) h m
6036 (make-string (- 10 l) ?\ ))
6037 '(face secondary-selection))
6038 ""))
6039 (org-overlay-put ov 'display tx)
6040 (push ov org-clock-overlays)))
6041
6042 (defun org-remove-clock-overlays (&optional beg end noremove)
6043 "Remove the occur highlights from the buffer.
6044 BEG and END are ignored. If NOREMOVE is nil, remove this function
6045 from the `before-change-functions' in the current buffer."
6046 (interactive)
6047 (unless org-inhibit-highlight-removal
6048 (mapc 'org-delete-overlay org-clock-overlays)
6049 (setq org-clock-overlays nil)
6050 (unless noremove
6051 (remove-hook 'before-change-functions
6052 'org-remove-clock-overlays 'local))))
6053
6054 (defun org-clock-out-if-current ()
6055 "Clock out if the current entry contains the running clock.
6056 This is used to stop the clock after a TODO entry is marked DONE."
6057 (when (and (equal state org-done-string)
6058 (equal (marker-buffer org-clock-marker) (current-buffer))
6059 (< (point) org-clock-marker)
6060 (> (save-excursion (outline-next-heading) (point))
6061 org-clock-marker))
6062 (org-clock-out)))
6063
6064 (add-hook 'org-after-todo-state-change-hook
6065 'org-clock-out-if-current)
6066
6067 (defun org-check-running-clock ()
6068 "Check if the current buffer contains the running clock.
6069 If yes, offer to stop it and to save the buffer with the changes."
6070 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6071 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6072 (buffer-name))))
6073 (org-clock-out)
6074 (when (y-or-n-p "Save changed buffer?")
6075 (save-buffer))))
6076
6077 (defun org-clock-report ()
6078 "Create a table containing a report about clocked time.
6079 If the buffer contains lines
6080 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6081
6082 #+END: clocktable
6083 then the table will be inserted between these lines, replacing whatever
6084 is was there before. If these lines are not in the buffer, the table
6085 is inserted at point, surrounded by the special lines.
6086 The BEGIN line can contain parameters. Allowed are:
6087 :maxlevel The maximum level to be included in the table. Default is 3.
6088 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6089 (interactive)
6090 (org-remove-clock-overlays)
6091 (unless (org-find-dblock "clocktable")
6092 (org-create-dblock (list :name "clocktable"
6093 :maxlevel 2 :emphasize nil)))
6094 (org-update-dblock))
6095
6096 (defun org-clock-update-time-maybe ()
6097 "If this is a CLOCK line, update it and return t.
6098 Otherwise, return nil."
6099 (interactive)
6100 (save-excursion
6101 (beginning-of-line 1)
6102 (skip-chars-forward " \t")
6103 (when (looking-at org-clock-string)
6104 (let ((re (concat "[ \t]*" org-clock-string
6105 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
6106 "\\([ \t]*=>.*\\)?"))
6107 ts te h m s)
6108 (if (not (looking-at re))
6109 nil
6110 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
6111 (end-of-line 1)
6112 (setq ts (match-string 1)
6113 te (match-string 2))
6114 (setq s (- (time-to-seconds
6115 (apply 'encode-time (org-parse-time-string te)))
6116 (time-to-seconds
6117 (apply 'encode-time (org-parse-time-string ts))))
6118 h (floor (/ s 3600))
6119 s (- s (* 3600 h))
6120 m (floor (/ s 60))
6121 s (- s (* 60 s)))
6122 (insert " => " (format "%2d:%02d" h m))
6123 t)))))
6124
6125 (defun org-clock-special-range (key &optional time as-strings)
6126 "Return two times bordering a special time range.
6127 Key is a symbol specifying the range and can be one of `today', `yesterday',
6128 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
6129 A week starts Monday 0:00 and ends Sunday 24:00.
6130 The range is determined relative to TIME. TIME defaults to the current time.
6131 The return value is a cons cell with two internal times like the ones
6132 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
6133 the returned times will be formatted strings."
6134 (let* ((tm (decode-time (or time (current-time))))
6135 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
6136 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
6137 (dow (nth 6 tm))
6138 s1 m1 h1 d1 month1 y1 diff ts te fm)
6139 (cond
6140 ((eq key 'today)
6141 (setq h 0 m 0 h1 24 m1 0))
6142 ((eq key 'yesterday)
6143 (setq d (1- d) h 0 m 0 h1 24 m1 0))
6144 ((eq key 'thisweek)
6145 (setq diff (if (= dow 0) 6 (1- dow))
6146 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6147 ((eq key 'lastweek)
6148 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
6149 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6150 ((eq key 'thismonth)
6151 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
6152 ((eq key 'lastmonth)
6153 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
6154 ((eq key 'thisyear)
6155 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
6156 ((eq key 'lastyear)
6157 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
6158 (t (error "No such time block %s" key)))
6159 (setq ts (encode-time s m h d month y)
6160 te (encode-time (or s1 s) (or m1 m) (or h1 h)
6161 (or d1 d) (or month1 month) (or y1 y)))
6162 (setq fm (cdr org-time-stamp-formats))
6163 (if as-strings
6164 (cons (format-time-string fm ts) (format-time-string fm te))
6165 (cons ts te))))
6166
6167 (defun org-dblock-write:clocktable (params)
6168 "Write the standard clocktable."
6169 (let ((hlchars '((1 . "*") (2 . ?/)))
6170 (emph nil)
6171 (ins (make-marker))
6172 ipos time h m p level hlc hdl maxlevel
6173 ts te cc block)
6174 (setq maxlevel (or (plist-get params :maxlevel) 3)
6175 emph (plist-get params :emphasize)
6176 ts (plist-get params :tstart)
6177 te (plist-get params :tend)
6178 block (plist-get params :block))
6179 (when block
6180 (setq cc (org-clock-special-range block nil t)
6181 ts (car cc) te (cdr cc)))
6182 (if ts (setq ts (time-to-seconds
6183 (apply 'encode-time (org-parse-time-string ts)))))
6184 (if te (setq te (time-to-seconds
6185 (apply 'encode-time (org-parse-time-string te)))))
6186 (move-marker ins (point))
6187 (setq ipos (point))
6188 (insert-before-markers "Clock summary at ["
6189 (substring
6190 (format-time-string (cdr org-time-stamp-formats))
6191 1 -1)
6192 "]."
6193 (if block
6194 (format " Considered range is /%s/." block)
6195 "")
6196 "\n\n|L|Headline|Time|\n")
6197 (org-clock-sum ts te)
6198 (setq h (/ org-clock-file-total-minutes 60)
6199 m (- org-clock-file-total-minutes (* 60 h)))
6200 (insert-before-markers "|-\n|0|" "*Total file time*| "
6201 (format "*%d:%02d*" h m)
6202 "|\n")
6203 (goto-char (point-min))
6204 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6205 (goto-char p)
6206 (when (setq time (get-text-property p :org-clock-minutes))
6207 (save-excursion
6208 (beginning-of-line 1)
6209 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6210 (setq level (- (match-end 1) (match-beginning 1)))
6211 (<= level maxlevel))
6212 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6213 hdl (match-string 2)
6214 h (/ time 60)
6215 m (- time (* 60 h)))
6216 (goto-char ins)
6217 (if (= level 1) (insert-before-markers "|-\n"))
6218 (insert-before-markers
6219 "| " (int-to-string level) "|" hlc hdl hlc " |"
6220 (make-string (1- level) ?|)
6221 hlc
6222 (format "%d:%02d" h m)
6223 hlc
6224 " |\n")))))
6225 (goto-char ins)
6226 (backward-delete-char 1)
6227 (goto-char ipos)
6228 (skip-chars-forward "^|")
6229 (org-table-align)))
6230
6231 (defun org-collect-clock-time-entries ()
6232 "Return an internal list with clocking information.
6233 This list has one entry for each CLOCK interval.
6234 FIXME: describe the elements."
6235 (interactive)
6236 (let ((re (concat "^[ \t]*" org-clock-string
6237 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6238 rtn beg end next cont level title total closedp leafp
6239 clockpos titlepos h m donep)
6240 (save-excursion
6241 (org-clock-sum)
6242 (goto-char (point-min))
6243 (while (re-search-forward re nil t)
6244 (setq clockpos (match-beginning 0)
6245 beg (match-string 1) end (match-string 2)
6246 cont (match-end 0))
6247 (setq beg (apply 'encode-time (org-parse-time-string beg))
6248 end (apply 'encode-time (org-parse-time-string end)))
6249 (org-back-to-heading t)
6250 (setq donep (org-entry-is-done-p))
6251 (setq titlepos (point)
6252 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6253 h (/ total 60) m (- total (* 60 h))
6254 total (cons h m))
6255 (looking-at "\\(\\*+\\) +\\(.*\\)")
6256 (setq level (- (match-end 1) (match-beginning 1))
6257 title (org-match-string-no-properties 2))
6258 (save-excursion (outline-next-heading) (setq next (point)))
6259 (setq closedp (re-search-forward org-closed-time-regexp next t))
6260 (goto-char next)
6261 (setq leafp (and (looking-at "^\\*+ ")
6262 (<= (- (match-end 0) (point)) level)))
6263 (push (list beg end clockpos closedp donep
6264 total title titlepos level leafp)
6265 rtn)
6266 (goto-char cont)))
6267 (nreverse rtn)))
6268
6269 ;;; Agenda, and Diary Integration
6270
6271 ;;; Define the mode
6272
6273 (defvar org-agenda-mode-map (make-sparse-keymap)
6274 "Keymap for `org-agenda-mode'.")
6275
6276 (defvar org-agenda-menu) ; defined later in this file.
6277 (defvar org-agenda-follow-mode nil)
6278 (defvar org-agenda-show-log nil)
6279 (defvar org-agenda-buffer-name "*Org Agenda*")
6280 (defvar org-agenda-redo-command nil)
6281 (defvar org-agenda-mode-hook nil)
6282 (defvar org-agenda-type nil)
6283 (defvar org-agenda-force-single-file nil)
6284
6285 (defun org-agenda-mode ()
6286 "Mode for time-sorted view on action items in Org-mode files.
6287
6288 The following commands are available:
6289
6290 \\{org-agenda-mode-map}"
6291 (interactive)
6292 (kill-all-local-variables)
6293 (setq major-mode 'org-agenda-mode)
6294 (setq mode-name "Org-Agenda")
6295 (use-local-map org-agenda-mode-map)
6296 (easy-menu-add org-agenda-menu)
6297 (if org-startup-truncated (setq truncate-lines t))
6298 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6299 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6300 (unless org-agenda-keep-modes
6301 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6302 org-agenda-show-log nil))
6303 (easy-menu-change
6304 '("Agenda") "Agenda Files"
6305 (append
6306 (list
6307 (vector
6308 (if (get 'org-agenda-files 'org-restrict)
6309 "Restricted to single file"
6310 "Edit File List")
6311 '(org-edit-agenda-file-list)
6312 (not (get 'org-agenda-files 'org-restrict)))
6313 "--")
6314 (mapcar 'org-file-menu-entry (org-agenda-files))))
6315 (org-agenda-set-mode-name)
6316 (apply
6317 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6318 (list 'org-agenda-mode-hook)))
6319
6320 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6321 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6322 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6323 (define-key org-agenda-mode-map " " 'org-agenda-show)
6324 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6325 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6326 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6327 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6328 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6329 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6330 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6331 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6332 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6333 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6334 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6335 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6336 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6337
6338 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6339 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6340 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6341 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6342 (while l (define-key org-agenda-mode-map
6343 (int-to-string (pop l)) 'digit-argument)))
6344
6345 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6346 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6347 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6348 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6349 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6350 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6351 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6352 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
6353 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6354 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6355 (define-key org-agenda-mode-map "n" 'next-line)
6356 (define-key org-agenda-mode-map "p" 'previous-line)
6357 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6358 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6359 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6360 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6361 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6362 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6363 (eval-after-load "calendar"
6364 '(define-key calendar-mode-map org-calendar-to-agenda-key
6365 'org-calendar-goto-agenda))
6366 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6367 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6368 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6369 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6370 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6371 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6372 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6373 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6374 (define-key org-agenda-mode-map "O" 'org-clock-out)
6375 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6376 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6377 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6378 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6379 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6380 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6381 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6382 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6383 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6384 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6385 "Local keymap for agenda entries from Org-mode.")
6386
6387 (define-key org-agenda-keymap
6388 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6389 (define-key org-agenda-keymap
6390 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6391 (when org-agenda-mouse-1-follows-link
6392 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6393 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6394 '("Agenda"
6395 ("Agenda Files")
6396 "--"
6397 ["Show" org-agenda-show t]
6398 ["Go To (other window)" org-agenda-goto t]
6399 ["Go To (one window)" org-agenda-switch-to t]
6400 ["Follow Mode" org-agenda-follow-mode
6401 :style toggle :selected org-agenda-follow-mode :active t]
6402 "--"
6403 ["Cycle TODO" org-agenda-todo t]
6404 ("Tags"
6405 ["Show all Tags" org-agenda-show-tags t]
6406 ["Set Tags" org-agenda-set-tags t])
6407 ("Schedule"
6408 ["Schedule" org-agenda-schedule t]
6409 ["Set Deadline" org-agenda-deadline t]
6410 "--"
6411 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6412 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6413 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6414 ("Priority"
6415 ["Set Priority" org-agenda-priority t]
6416 ["Increase Priority" org-agenda-priority-up t]
6417 ["Decrease Priority" org-agenda-priority-down t]
6418 ["Show Priority" org-agenda-show-priority t])
6419 "--"
6420 ;; ["New agenda command" org-agenda t]
6421 ["Rebuild buffer" org-agenda-redo t]
6422 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
6423 "--"
6424 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6425 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6426 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6427 "--"
6428 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6429 :style radio :selected (equal org-agenda-ndays 1)]
6430 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6431 :style radio :selected (equal org-agenda-ndays 7)]
6432 "--"
6433 ["Show Logbook entries" org-agenda-log-mode
6434 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6435 ["Include Diary" org-agenda-toggle-diary
6436 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6437 ["Use Time Grid" org-agenda-toggle-time-grid
6438 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6439 "--"
6440 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6441 ("Calendar Commands"
6442 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6443 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6444 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6445 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6446 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6447 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6448 "--"
6449 ["Quit" org-agenda-quit t]
6450 ["Exit and Release Buffers" org-agenda-exit t]
6451 ))
6452
6453 ;;;###autoload
6454 (defun org-agenda (arg)
6455 "Dispatch agenda commands to collect entries to the agenda buffer.
6456 Prompts for a character to select a command. Any prefix arg will be passed
6457 on to the selected command. The default selections are:
6458
6459 a Call `org-agenda' to display the agenda for the current day or week.
6460 t Call `org-todo-list' to display the global todo list.
6461 T Call `org-todo-list' to display the global todo list, select only
6462 entries with a specific TODO keyword (the user gets a prompt).
6463 m Call `org-tags-view' to display headlines with tags matching
6464 a condition (the user is prompted for the condition).
6465 M Like `m', but select only TODO entries, no ordinary headlines.
6466
6467 More commands can be added by configuring the variable
6468 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
6469 searches can be pre-defined in this way.
6470
6471 If the current buffer is in Org-mode and visiting a file, you can also
6472 first press `1' to indicate that the agenda should be temporarily (until the
6473 next use of \\[org-agenda]) restricted to the current file."
6474 (interactive "P")
6475 (catch 'exit
6476 (let ((restrict-ok (and buffer-file-name (org-mode-p)))
6477 (bfn buffer-file-name)
6478 (custom org-agenda-custom-commands)
6479 c entry key type string)
6480 (put 'org-agenda-files 'org-restrict nil)
6481 (save-window-excursion
6482 (delete-other-windows)
6483 (switch-to-buffer-other-window " *Agenda Commands*")
6484 (erase-buffer)
6485 (insert
6486 "Press key for an agenda command:
6487 --------------------------------
6488 a Agenda for current week or day
6489 t List of all TODO entries T Entries with special TODO kwd
6490 m Match a TAGS query M Like m, but only TODO entries
6491 C Configure your own agenda commands")
6492 (while (setq entry (pop custom))
6493 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
6494 (insert (format "\n%-4s%-14s: %s"
6495 key
6496 (cond
6497 ((eq type 'tags) "Tags query")
6498 ((eq type 'todo) "TODO keyword")
6499 ((eq type 'tags-tree) "Tags tree")
6500 ((eq type 'todo-tree) "TODO kwd tree")
6501 ((eq type 'occur-tree) "Occur tree")
6502 (t "???"))
6503 (org-add-props string nil 'face 'org-warning))))
6504 (goto-char (point-min))
6505 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
6506 (message "Press key for agenda command%s"
6507 (if restrict-ok ", or [1] to restrict to current file" ""))
6508 (setq c (read-char-exclusive))
6509 (message "")
6510 (when (equal c ?1)
6511 (if restrict-ok
6512 (put 'org-agenda-files 'org-restrict (list bfn))
6513 (error "Cannot restrict agenda to current buffer"))
6514 (message "Press key for agenda command%s"
6515 (if restrict-ok " (restricted to current file)" ""))
6516 (setq c (read-char-exclusive))
6517 (message "")))
6518 (require 'calendar) ; FIXME: can we avoid this for some commands?
6519 ;; For example the todo list should not need it (but does...)
6520 (cond
6521 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
6522 ((equal c ?a) (call-interactively 'org-agenda-list))
6523 ((equal c ?t) (call-interactively 'org-todo-list))
6524 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
6525 ((equal c ?m) (call-interactively 'org-tags-view))
6526 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
6527 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
6528 (setq type (nth 1 entry) string (nth 2 entry))
6529 (cond
6530 ((eq type 'tags)
6531 (org-tags-view current-prefix-arg string))
6532 ((eq type 'tags-todo)
6533 (org-tags-view '(4) string))
6534 ((eq type 'todo)
6535 (org-todo-list string))
6536 ((eq type 'tags-tree)
6537 (org-check-for-org-mode)
6538 (org-tags-sparse-tree current-prefix-arg string))
6539 ((eq type 'todo-tree)
6540 (org-check-for-org-mode)
6541 (org-occur (concat "^" outline-regexp "[ \t]*"
6542 (regexp-quote string) "\\>")))
6543 ((eq type 'occur-tree)
6544 (org-check-for-org-mode)
6545 (org-occur string))
6546 (t (error "Invalid custom agenda command type %s" type))))
6547 (t (error "Invalid key"))))))
6548
6549 (defun org-check-for-org-mode ()
6550 "Make sure current buffer is in org-mode. Error if not."
6551 (or (org-mode-p)
6552 (error "Cannot execute org-mode agenda command on buffer in %s."
6553 major-mode)))
6554
6555 (defun org-fit-agenda-window ()
6556 "Fit the window to the buffer size."
6557 (and org-fit-agenda-window
6558 (fboundp 'fit-window-to-buffer)
6559 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
6560 (/ (frame-height) 2))))
6561
6562 (defun org-agenda-files (&optional unrestricted)
6563 "Get the list of agenda files.
6564 Optional UNRESTRICTED means return the full list even if a restriction
6565 is currently in place."
6566 (cond
6567 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
6568 ((stringp org-agenda-files) (org-read-agenda-file-list))
6569 ((listp org-agenda-files) org-agenda-files)
6570 (t (error "Invalid value of `org-agenda-files'"))))
6571
6572 (defvar org-window-configuration)
6573
6574 (defun org-edit-agenda-file-list ()
6575 "Edit the list of agenda files.
6576 Depending on setup, this either uses customize to edit the variable
6577 `org-agenda-files', or it visits the file that is holding the list. In the
6578 latter case, the buffer is set up in a way that saving it automatically kills
6579 the buffer and restores the previous window configuration."
6580 (interactive)
6581 (if (stringp org-agenda-files)
6582 (let ((cw (current-window-configuration)))
6583 (find-file org-agenda-files)
6584 (org-set-local 'org-window-configuration cw)
6585 (org-add-hook 'after-save-hook
6586 (lambda ()
6587 (set-window-configuration
6588 (prog1 org-window-configuration
6589 (kill-buffer (current-buffer))))
6590 (org-install-agenda-files-menu)
6591 (message "New agenda file list installed"))
6592 nil 'local)
6593 (message (substitute-command-keys
6594 "Edit list and finish with \\[save-buffer]")))
6595 (customize-variable 'org-agenda-files)))
6596
6597 (defun org-store-new-agenda-file-list (list)
6598 "Set new value for the agenda file list and save it correcly."
6599 (if (stringp org-agenda-files)
6600 (let ((f org-agenda-files) b)
6601 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
6602 (with-temp-file f
6603 (insert (mapconcat 'identity list "\n") "\n")))
6604 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
6605 (setq org-agenda-files list)
6606 (customize-save-variable 'org-agenda-files org-agenda-files))))
6607
6608 (defun org-read-agenda-file-list ()
6609 "Read the list of agenda files from a file."
6610 (when (stringp org-agenda-files)
6611 (with-temp-buffer
6612 (insert-file-contents org-agenda-files)
6613 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
6614
6615 (defvar org-agenda-markers nil
6616 "List of all currently active markers created by `org-agenda'.")
6617 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
6618 "Creation time of the last agenda marker.")
6619
6620 (defun org-agenda-new-marker (&optional pos)
6621 "Return a new agenda marker.
6622 Org-mode keeps a list of these markers and resets them when they are
6623 no longer in use."
6624 (let ((m (copy-marker (or pos (point)))))
6625 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
6626 (push m org-agenda-markers)
6627 m))
6628
6629 (defun org-agenda-maybe-reset-markers (&optional force)
6630 "Reset markers created by `org-agenda'. But only if they are old enough."
6631 (if (or force
6632 (> (- (time-to-seconds (current-time))
6633 org-agenda-last-marker-time)
6634 5))
6635 (while org-agenda-markers
6636 (move-marker (pop org-agenda-markers) nil))))
6637
6638 (defvar org-agenda-new-buffers nil
6639 "Buffers created to visit agenda files.")
6640
6641 (defun org-get-agenda-file-buffer (file)
6642 "Get a buffer visiting FILE. If the buffer needs to be created, add
6643 it to the list of buffers which might be released later."
6644 (let ((buf (find-buffer-visiting file)))
6645 (if buf
6646 buf ; just return it
6647 ;; Make a new buffer and remember it
6648 (setq buf (find-file-noselect file))
6649 (if buf (push buf org-agenda-new-buffers))
6650 buf)))
6651
6652 (defun org-release-buffers (blist)
6653 "Release all buffers in list, asking the user for confirmation when needed.
6654 When a buffer is unmodified, it is just killed. When modified, it is saved
6655 \(if the user agrees) and then killed."
6656 (let (buf file)
6657 (while (setq buf (pop blist))
6658 (setq file (buffer-file-name buf))
6659 (when (and (buffer-modified-p buf)
6660 file
6661 (y-or-n-p (format "Save file %s? " file)))
6662 (with-current-buffer buf (save-buffer)))
6663 (kill-buffer buf))))
6664
6665 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
6666
6667 (defun org-timeline (&optional include-all keep-modes)
6668 "Show a time-sorted view of the entries in the current org file.
6669 Only entries with a time stamp of today or later will be listed. With
6670 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
6671 under the current date.
6672 If the buffer contains an active region, only check the region for
6673 dates."
6674 (interactive "P")
6675 (require 'calendar)
6676 (org-agenda-maybe-reset-markers 'force)
6677 (org-compile-prefix-format org-timeline-prefix-format)
6678 (let* ((dopast t)
6679 (dotodo include-all)
6680 (doclosed org-agenda-show-log)
6681 (org-agenda-keep-modes keep-modes)
6682 (entry buffer-file-name)
6683 (org-agenda-files (list buffer-file-name))
6684 (date (calendar-current-date))
6685 (win (selected-window))
6686 (pos1 (point))
6687 (beg (if (org-region-active-p) (region-beginning) (point-min)))
6688 (end (if (org-region-active-p) (region-end) (point-max)))
6689 (day-numbers (org-get-all-dates beg end 'no-ranges
6690 t doclosed ; always include today
6691 org-timeline-show-empty-dates))
6692 (today (time-to-days (current-time)))
6693 (org-respect-restriction t)
6694 (past t)
6695 args
6696 s e rtn d emptyp)
6697 (org-prepare-agenda-buffers org-agenda-files)
6698 (setq org-agenda-redo-command
6699 (list 'progn
6700 (list 'switch-to-buffer-other-window (current-buffer))
6701 (list 'org-timeline (list 'quote include-all) t)))
6702 (if (not dopast)
6703 ;; Remove past dates from the list of dates.
6704 (setq day-numbers (delq nil (mapcar (lambda(x)
6705 (if (>= x today) x nil))
6706 day-numbers))))
6707 (switch-to-buffer-other-window
6708 (get-buffer-create org-agenda-buffer-name))
6709 (setq buffer-read-only nil)
6710 (erase-buffer)
6711 (org-agenda-mode) (setq buffer-read-only nil)
6712 (org-set-local 'org-agenda-type 'timeline)
6713 (if doclosed (push :closed args))
6714 (push :timestamp args)
6715 (if dotodo (push :todo args))
6716 (while (setq d (pop day-numbers))
6717 (if (and (listp d) (eq (car d) :omitted))
6718 (progn
6719 (setq s (point))
6720 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
6721 (put-text-property s (1- (point)) 'face 'org-level-3))
6722 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
6723 (if (and (>= d today)
6724 dopast
6725 past)
6726 (progn
6727 (setq past nil)
6728 (insert (make-string 79 ?-) "\n")))
6729 (setq date (calendar-gregorian-from-absolute d))
6730 (setq s (point))
6731 (setq rtn (and (not emptyp)
6732 (apply 'org-agenda-get-day-entries
6733 entry date args)))
6734 (if (or rtn (equal d today) org-timeline-show-empty-dates)
6735 (progn
6736 (insert (calendar-day-name date) " "
6737 (number-to-string (extract-calendar-day date)) " "
6738 (calendar-month-name (extract-calendar-month date)) " "
6739 (number-to-string (extract-calendar-year date)) "\n")
6740 (put-text-property s (1- (point)) 'face
6741 'org-level-3)
6742 (if (equal d today)
6743 (put-text-property s (1- (point)) 'org-today t))
6744 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
6745 (put-text-property s (1- (point)) 'day d)))))
6746 (goto-char (point-min))
6747 (setq buffer-read-only t)
6748 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6749 (point-min)))
6750 (when (not org-select-timeline-window)
6751 (select-window win)
6752 (goto-char pos1))))
6753
6754 ;;;###autoload
6755 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
6756 "Produce a weekly view from all files in variable `org-agenda-files'.
6757 The view will be for the current week, but from the overview buffer you
6758 will be able to go to other weeks.
6759 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
6760 also be shown, under the current date.
6761 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
6762 on the days are also shown. See the variable `org-log-done' for how
6763 to turn on logging.
6764 START-DAY defaults to TODAY, or to the most recent match for the weekday
6765 given in `org-agenda-start-on-weekday'.
6766 NDAYS defaults to `org-agenda-ndays'."
6767 (interactive "P")
6768 (org-agenda-maybe-reset-markers 'force)
6769 (org-compile-prefix-format org-agenda-prefix-format)
6770 (require 'calendar)
6771 (let* ((org-agenda-start-on-weekday
6772 (if (or (equal ndays 1)
6773 (and (null ndays) (equal 1 org-agenda-ndays)))
6774 nil org-agenda-start-on-weekday))
6775 (org-agenda-keep-modes keep-modes)
6776 (thefiles (org-agenda-files))
6777 (files thefiles)
6778 (win (selected-window))
6779 (today (time-to-days (current-time)))
6780 (sd (or start-day today))
6781 (start (if (or (null org-agenda-start-on-weekday)
6782 (< org-agenda-ndays 7))
6783 sd
6784 (let* ((nt (calendar-day-of-week
6785 (calendar-gregorian-from-absolute sd)))
6786 (n1 org-agenda-start-on-weekday)
6787 (d (- nt n1)))
6788 (- sd (+ (if (< d 0) 7 0) d)))))
6789 (day-numbers (list start))
6790 (inhibit-redisplay t)
6791 s e rtn rtnall file date d start-pos end-pos todayp nd)
6792 (org-prepare-agenda-buffers files)
6793 (setq org-agenda-redo-command
6794 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
6795 ;; Make the list of days
6796 (setq ndays (or ndays org-agenda-ndays)
6797 nd ndays)
6798 (while (> ndays 1)
6799 (push (1+ (car day-numbers)) day-numbers)
6800 (setq ndays (1- ndays)))
6801 (setq day-numbers (nreverse day-numbers))
6802 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6803 (progn
6804 (delete-other-windows)
6805 (switch-to-buffer-other-window
6806 (get-buffer-create org-agenda-buffer-name))))
6807 (setq buffer-read-only nil)
6808 (erase-buffer)
6809 (org-agenda-mode) (setq buffer-read-only nil)
6810 (org-set-local 'org-agenda-type 'agenda)
6811 (org-set-local 'starting-day (car day-numbers))
6812 (org-set-local 'include-all-loc include-all)
6813 (when (and (or include-all org-agenda-include-all-todo)
6814 (member today day-numbers))
6815 (setq files thefiles
6816 rtnall nil)
6817 (while (setq file (pop files))
6818 (catch 'nextfile
6819 (org-check-agenda-file file)
6820 (setq date (calendar-gregorian-from-absolute today)
6821 rtn (org-agenda-get-day-entries
6822 file date :todo))
6823 (setq rtnall (append rtnall rtn))))
6824 (when rtnall
6825 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
6826 (add-text-properties (point-min) (1- (point))
6827 (list 'face 'org-level-3))
6828 (insert (org-finalize-agenda-entries rtnall) "\n")))
6829 (while (setq d (pop day-numbers))
6830 (setq date (calendar-gregorian-from-absolute d)
6831 s (point))
6832 (if (or (setq todayp (= d today))
6833 (and (not start-pos) (= d sd)))
6834 (setq start-pos (point))
6835 (if (and start-pos (not end-pos))
6836 (setq end-pos (point))))
6837 (setq files thefiles
6838 rtnall nil)
6839 (while (setq file (pop files))
6840 (catch 'nextfile
6841 (org-check-agenda-file file)
6842 (if org-agenda-show-log
6843 (setq rtn (org-agenda-get-day-entries
6844 file date
6845 :deadline :scheduled :timestamp :closed))
6846 (setq rtn (org-agenda-get-day-entries
6847 file date
6848 :deadline :scheduled :timestamp)))
6849 (setq rtnall (append rtnall rtn))))
6850 (if org-agenda-include-diary
6851 (progn
6852 (require 'diary-lib)
6853 (setq rtn (org-get-entries-from-diary date))
6854 (setq rtnall (append rtnall rtn))))
6855 (if (or rtnall org-agenda-show-all-dates)
6856 (progn
6857 (insert (format "%-9s %2d %s %4d\n"
6858 (calendar-day-name date)
6859 (extract-calendar-day date)
6860 (calendar-month-name (extract-calendar-month date))
6861 (extract-calendar-year date)))
6862 (put-text-property s (1- (point)) 'face
6863 'org-level-3)
6864 (if rtnall (insert
6865 (org-finalize-agenda-entries
6866 (org-agenda-add-time-grid-maybe
6867 rtnall nd todayp))
6868 "\n"))
6869 (put-text-property s (1- (point)) 'day d))))
6870 (goto-char (point-min))
6871 (setq buffer-read-only t)
6872 (org-fit-agenda-window)
6873 (unless (and (pos-visible-in-window-p (point-min))
6874 (pos-visible-in-window-p (point-max)))
6875 (goto-char (1- (point-max)))
6876 (recenter -1)
6877 (if (not (pos-visible-in-window-p (or start-pos 1)))
6878 (progn
6879 (goto-char (or start-pos 1))
6880 (recenter 1))))
6881 (goto-char (or start-pos 1))
6882 (if (not org-select-agenda-window) (select-window win))
6883 (message "")))
6884
6885 (defvar org-select-this-todo-keyword nil)
6886
6887 ;;;###autoload
6888 (defun org-todo-list (arg &optional keep-modes)
6889 "Show all TODO entries from all agenda file in a single list.
6890 The prefix arg can be used to select a specific TODO keyword and limit
6891 the list to these. When using \\[universal-argument], you will be prompted
6892 for a keyword. A numeric prefix directly selects the Nth keyword in
6893 `org-todo-keywords'."
6894 (interactive "P")
6895 (org-agenda-maybe-reset-markers 'force)
6896 (org-compile-prefix-format org-agenda-prefix-format)
6897 (let* ((org-agenda-keep-modes keep-modes)
6898 (today (time-to-days (current-time)))
6899 (date (calendar-gregorian-from-absolute today))
6900 (win (selected-window))
6901 (kwds org-todo-keywords)
6902 (completion-ignore-case t)
6903 (org-select-this-todo-keyword
6904 (if (stringp arg) arg
6905 (and arg (integerp arg) (> arg 0)
6906 (nth (1- arg) org-todo-keywords))))
6907 rtn rtnall files file pos)
6908 (when (equal arg '(4))
6909 (setq org-select-this-todo-keyword
6910 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
6911 nil t)))
6912 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
6913 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6914 (progn
6915 (delete-other-windows)
6916 (switch-to-buffer-other-window
6917 (get-buffer-create org-agenda-buffer-name))))
6918 (setq buffer-read-only nil)
6919 (erase-buffer)
6920 (org-agenda-mode) (setq buffer-read-only nil)
6921 (org-set-local 'org-agenda-type 'todo)
6922 (org-set-local 'last-arg arg)
6923 (org-set-local 'org-todo-keywords kwds)
6924 (org-set-local 'org-agenda-redo-command
6925 '(org-todo-list (or current-prefix-arg last-arg) t))
6926 (setq files (org-agenda-files)
6927 rtnall nil)
6928 (org-prepare-agenda-buffers files)
6929 (while (setq file (pop files))
6930 (catch 'nextfile
6931 (org-check-agenda-file file)
6932 (setq rtn (org-agenda-get-day-entries file date :todo))
6933 (setq rtnall (append rtnall rtn))))
6934 (insert "Global list of TODO items of type: ")
6935 (add-text-properties (point-min) (1- (point))
6936 (list 'face 'org-level-3))
6937 (setq pos (point))
6938 (insert (or org-select-this-todo-keyword "ALL") "\n")
6939 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6940 (setq pos (point))
6941 (insert
6942 "Available with `N r': (0)ALL "
6943 (let ((n 0))
6944 (mapconcat (lambda (x)
6945 (format "(%d)%s" (setq n (1+ n)) x))
6946 org-todo-keywords " "))
6947 "\n")
6948 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
6949 (when rtnall
6950 (insert (org-finalize-agenda-entries rtnall) "\n"))
6951 (goto-char (point-min))
6952 (setq buffer-read-only t)
6953 (org-fit-agenda-window)
6954 (if (not org-select-agenda-window) (select-window win))))
6955
6956 (defun org-check-agenda-file (file)
6957 "Make sure FILE exists. If not, ask user what to do."
6958 (when (not (file-exists-p file))
6959 (message "non-existent file %s. [R]emove from list or [A]bort?"
6960 (abbreviate-file-name file))
6961 (let ((r (downcase (read-char-exclusive))))
6962 (cond
6963 ((equal r ?r)
6964 (org-remove-file file)
6965 (throw 'nextfile t))
6966 (t (error "Abort"))))))
6967
6968 (defun org-agenda-check-type (error &rest types)
6969 "Check if agenda buffer is of allowed type.
6970 If ERROR is non-nil, throw an error, otherwise just return nil."
6971 (if (memq org-agenda-type types)
6972 t
6973 (if error
6974 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
6975 nil)))
6976
6977 (defun org-agenda-quit ()
6978 "Exit agenda by removing the window or the buffer."
6979 (interactive)
6980 (let ((buf (current-buffer)))
6981 (if (not (one-window-p)) (delete-window))
6982 (kill-buffer buf)
6983 (org-agenda-maybe-reset-markers 'force)))
6984
6985 (defun org-agenda-exit ()
6986 "Exit agenda by removing the window or the buffer.
6987 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
6988 Org-mode buffers visited directly by the user will not be touched."
6989 (interactive)
6990 (org-release-buffers org-agenda-new-buffers)
6991 (setq org-agenda-new-buffers nil)
6992 (org-agenda-quit))
6993
6994 ;; FIXME: move this function.
6995 (defun org-save-all-org-buffers ()
6996 "Save all Org-mode buffers without user confirmation."
6997 (interactive)
6998 (message "Saving all Org-mode buffers...")
6999 (save-some-buffers t 'org-mode-p)
7000 (message "Saving all Org-mode buffers... done"))
7001
7002 (defun org-agenda-redo ()
7003 "Rebuild Agenda.
7004 When this is the global TODO list, a prefix argument will be interpreted."
7005 (interactive)
7006 (message "Rebuilding agenda buffer...")
7007 (eval org-agenda-redo-command)
7008 (message "Rebuilding agenda buffer...done"))
7009
7010 (defun org-agenda-goto-today ()
7011 "Go to today."
7012 (interactive)
7013 (org-agenda-check-type t 'timeline 'agenda)
7014 (if (boundp 'starting-day)
7015 (let ((cmd (car org-agenda-redo-command))
7016 (iall (nth 1 org-agenda-redo-command))
7017 (nday (nth 3 org-agenda-redo-command))
7018 (keep (nth 4 org-agenda-redo-command)))
7019 (eval (list cmd iall nil nday keep)))
7020 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
7021 (point-min)))))
7022
7023 (defun org-agenda-later (arg)
7024 "Go forward in time by `org-agenda-ndays' days.
7025 With prefix ARG, go forward that many times `org-agenda-ndays'."
7026 (interactive "p")
7027 (org-agenda-check-type t 'agenda)
7028 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
7029 (+ starting-day (* arg org-agenda-ndays)) nil t))
7030
7031 (defun org-agenda-earlier (arg)
7032 "Go back in time by `org-agenda-ndays' days.
7033 With prefix ARG, go back that many times `org-agenda-ndays'."
7034 (interactive "p")
7035 (org-agenda-check-type t 'agenda)
7036 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
7037 (- starting-day (* arg org-agenda-ndays)) nil t))
7038
7039 (defun org-agenda-week-view ()
7040 "Switch to weekly view for agenda."
7041 (interactive)
7042 (org-agenda-check-type t 'agenda)
7043 (setq org-agenda-ndays 7)
7044 (org-agenda-list include-all-loc
7045 (or (get-text-property (point) 'day)
7046 starting-day)
7047 nil t)
7048 (org-agenda-set-mode-name)
7049 (message "Switched to week view"))
7050
7051 (defun org-agenda-day-view ()
7052 "Switch to daily view for agenda."
7053 (interactive)
7054 (org-agenda-check-type t 'agenda)
7055 (setq org-agenda-ndays 1)
7056 (org-agenda-list include-all-loc
7057 (or (get-text-property (point) 'day)
7058 starting-day)
7059 nil t)
7060 (org-agenda-set-mode-name)
7061 (message "Switched to day view"))
7062
7063 (defun org-agenda-next-date-line (&optional arg)
7064 "Jump to the next line indicating a date in agenda buffer."
7065 (interactive "p")
7066 (org-agenda-check-type t 'agenda 'timeline)
7067 (beginning-of-line 1)
7068 (if (looking-at "^\\S-") (forward-char 1))
7069 (if (not (re-search-forward "^\\S-" nil t arg))
7070 (progn
7071 (backward-char 1)
7072 (error "No next date after this line in this buffer")))
7073 (goto-char (match-beginning 0)))
7074
7075 (defun org-agenda-previous-date-line (&optional arg)
7076 "Jump to the previous line indicating a date in agenda buffer."
7077 (interactive "p")
7078 (org-agenda-check-type t 'agenda 'timeline)
7079 (beginning-of-line 1)
7080 (if (not (re-search-backward "^\\S-" nil t arg))
7081 (error "No previous date before this line in this buffer")))
7082
7083 ;; Initialize the highlight
7084 (defvar org-hl (org-make-overlay 1 1))
7085 (org-overlay-put org-hl 'face 'highlight)
7086
7087 (defun org-highlight (begin end &optional buffer)
7088 "Highlight a region with overlay."
7089 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
7090 org-hl begin end (or buffer (current-buffer))))
7091
7092 (defun org-unhighlight ()
7093 "Detach overlay INDEX."
7094 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
7095
7096
7097 (defun org-agenda-follow-mode ()
7098 "Toggle follow mode in an agenda buffer."
7099 (interactive)
7100 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
7101 (org-agenda-set-mode-name)
7102 (message "Follow mode is %s"
7103 (if org-agenda-follow-mode "on" "off")))
7104
7105 (defun org-agenda-log-mode ()
7106 "Toggle log mode in an agenda buffer."
7107 (interactive)
7108 (org-agenda-check-type t 'agenda 'timeline)
7109 (setq org-agenda-show-log (not org-agenda-show-log))
7110 (org-agenda-set-mode-name)
7111 (org-agenda-redo)
7112 (message "Log mode is %s"
7113 (if org-agenda-show-log "on" "off")))
7114
7115 (defun org-agenda-toggle-diary ()
7116 "Toggle diary inclusion in an agenda buffer."
7117 (interactive)
7118 (org-agenda-check-type t 'agenda)
7119 (setq org-agenda-include-diary (not org-agenda-include-diary))
7120 (org-agenda-redo)
7121 (org-agenda-set-mode-name)
7122 (message "Diary inclusion turned %s"
7123 (if org-agenda-include-diary "on" "off")))
7124
7125 (defun org-agenda-toggle-time-grid ()
7126 "Toggle time grid in an agenda buffer."
7127 (interactive)
7128 (org-agenda-check-type t 'agenda)
7129 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
7130 (org-agenda-redo)
7131 (org-agenda-set-mode-name)
7132 (message "Time-grid turned %s"
7133 (if org-agenda-use-time-grid "on" "off")))
7134
7135 (defun org-agenda-set-mode-name ()
7136 "Set the mode name to indicate all the small mode settings."
7137 (setq mode-name
7138 (concat "Org-Agenda"
7139 (if (equal org-agenda-ndays 1) " Day" "")
7140 (if (equal org-agenda-ndays 7) " Week" "")
7141 (if org-agenda-follow-mode " Follow" "")
7142 (if org-agenda-include-diary " Diary" "")
7143 (if org-agenda-use-time-grid " Grid" "")
7144 (if org-agenda-show-log " Log" "")))
7145 (force-mode-line-update))
7146
7147 (defun org-agenda-post-command-hook ()
7148 (and (eolp) (not (bolp)) (backward-char 1))
7149 (if (and org-agenda-follow-mode
7150 (get-text-property (point) 'org-marker))
7151 (org-agenda-show)))
7152
7153 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
7154
7155 (defun org-get-entries-from-diary (date)
7156 "Get the (Emacs Calendar) diary entries for DATE."
7157 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
7158 (diary-display-hook '(fancy-diary-display))
7159 (list-diary-entries-hook
7160 (cons 'org-diary-default-entry list-diary-entries-hook))
7161 (diary-file-name-prefix-function nil) ; turn this feature off
7162 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7163 entries
7164 (org-disable-agenda-to-diary t))
7165 (save-excursion
7166 (save-window-excursion
7167 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7168 (if (not (get-buffer fancy-diary-buffer))
7169 (setq entries nil)
7170 (with-current-buffer fancy-diary-buffer
7171 (setq buffer-read-only nil)
7172 (if (= (point-max) 1)
7173 ;; No entries
7174 (setq entries nil)
7175 ;; Omit the date and other unnecessary stuff
7176 (org-agenda-cleanup-fancy-diary)
7177 ;; Add prefix to each line and extend the text properties
7178 (if (= (point-max) 1)
7179 (setq entries nil)
7180 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7181 (set-buffer-modified-p nil)
7182 (kill-buffer fancy-diary-buffer)))
7183 (when entries
7184 (setq entries (org-split-string entries "\n"))
7185 (setq entries
7186 (mapcar
7187 (lambda (x)
7188 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7189 ;; Extend the text properties to the beginning of the line
7190 (org-add-props x (text-properties-at (1- (length x)) x)))
7191 entries)))))
7192
7193 (defun org-agenda-cleanup-fancy-diary ()
7194 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7195 This gets rid of the date, the underline under the date, and
7196 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7197 date. It also removes lines that contain only whitespace."
7198 (goto-char (point-min))
7199 (if (looking-at ".*?:[ \t]*")
7200 (progn
7201 (replace-match "")
7202 (re-search-forward "\n=+$" nil t)
7203 (replace-match "")
7204 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7205 (re-search-forward "\n=+$" nil t)
7206 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7207 (goto-char (point-min))
7208 (while (re-search-forward "^ +\n" nil t)
7209 (replace-match ""))
7210 (goto-char (point-min))
7211 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7212 (replace-match "")))
7213
7214 ;; Make sure entries from the diary have the right text properties.
7215 (eval-after-load "diary-lib"
7216 '(if (boundp 'diary-modify-entry-list-string-function)
7217 ;; We can rely on the hook, nothing to do
7218 nil
7219 ;; Hook not avaiable, must use advice to make this work
7220 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7221 "Make the position visible."
7222 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7223 (stringp string)
7224 buffer-file-name)
7225 (setq string (org-modify-diary-entry-string string))))))
7226
7227 (defun org-modify-diary-entry-string (string)
7228 "Add text properties to string, allowing org-mode to act on it."
7229 (org-add-props string nil
7230 'mouse-face 'highlight
7231 'keymap org-agenda-keymap
7232 'help-echo (format "mouse-2 or RET jump to diary file %s"
7233 (abbreviate-file-name buffer-file-name))
7234 'org-agenda-diary-link t
7235 'org-marker (org-agenda-new-marker (point-at-bol))))
7236
7237 (defun org-diary-default-entry ()
7238 "Add a dummy entry to the diary.
7239 Needed to avoid empty dates which mess up holiday display."
7240 ;; Catch the error if dealing with the new add-to-diary-alist
7241 (when org-disable-agenda-to-diary
7242 (condition-case nil
7243 (add-to-diary-list original-date "Org-mode dummy" "")
7244 (error
7245 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7246
7247 (defun org-cycle-agenda-files ()
7248 "Cycle through the files in `org-agenda-files'.
7249 If the current buffer visits an agenda file, find the next one in the list.
7250 If the current buffer does not, find the first agenda file."
7251 (interactive)
7252 (let* ((fs (org-agenda-files t))
7253 (files (append fs (list (car fs))))
7254 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7255 file)
7256 (unless files (error "No agenda files"))
7257 (catch 'exit
7258 (while (setq file (pop files))
7259 (if (equal (file-truename file) tcf)
7260 (when (car files)
7261 (find-file (car files))
7262 (throw 'exit t))))
7263 (find-file (car fs)))))
7264
7265 (defun org-agenda-file-to-end ()
7266 "Move/add the current file to the end of the agenda file list.
7267 If the file is not present in the list, it is appended to the list. If it is
7268 present, it is moved there."
7269 (interactive)
7270 (org-agenda-file-to-front 'to-end))
7271
7272 (defun org-agenda-file-to-front (&optional to-end)
7273 "Move/add the current file to the top of the agenda file list.
7274 If the file is not present in the list, it is added to the front. If it is
7275 present, it is moved there. With optional argument TO-END, add/move to the
7276 end of the list."
7277 (interactive "P")
7278 (let ((file-alist (mapcar (lambda (x)
7279 (cons (file-truename x) x))
7280 (org-agenda-files t)))
7281 (ctf (file-truename buffer-file-name))
7282 x had)
7283 (setq x (assoc ctf file-alist) had x)
7284
7285 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7286 (if to-end
7287 (setq file-alist (append (delq x file-alist) (list x)))
7288 (setq file-alist (cons x (delq x file-alist))))
7289 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7290 (org-install-agenda-files-menu)
7291 (message "File %s to %s of agenda file list"
7292 (if had "moved" "added") (if to-end "end" "front"))))
7293
7294 (defun org-remove-file (&optional file)
7295 "Remove current file from the list of files in variable `org-agenda-files'.
7296 These are the files which are being checked for agenda entries.
7297 Optional argument FILE means, use this file instead of the current."
7298 (interactive)
7299 (let* ((file (or file buffer-file-name))
7300 (true-file (file-truename file))
7301 (afile (abbreviate-file-name file))
7302 (files (delq nil (mapcar
7303 (lambda (x)
7304 (if (equal true-file
7305 (file-truename x))
7306 nil x))
7307 (org-agenda-files t)))))
7308 (if (not (= (length files) (length (org-agenda-files t))))
7309 (progn
7310 (org-store-new-agenda-file-list files)
7311 (org-install-agenda-files-menu)
7312 (message "Removed file: %s" afile))
7313 (message "File was not in list: %s" afile))))
7314
7315 (defun org-file-menu-entry (file)
7316 (vector file (list 'find-file file) t))
7317
7318 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7319 "Return a list of all relevant day numbers from BEG to END buffer positions.
7320 If NO-RANGES is non-nil, include only the start and end dates of a range,
7321 not every single day in the range. If FORCE-TODAY is non-nil, make
7322 sure that TODAY is included in the list. If INACTIVE is non-nil, also
7323 inactive time stamps (those in square brackets) are included.
7324 When EMPTY is non-nil, also include days without any entries."
7325 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
7326 dates dates1 date day day1 day2 ts1 ts2)
7327 (if force-today
7328 (setq dates (list (time-to-days (current-time)))))
7329 (save-excursion
7330 (goto-char beg)
7331 (while (re-search-forward re end t)
7332 (setq day (time-to-days (org-time-string-to-time
7333 (substring (match-string 1) 0 10))))
7334 (or (memq day dates) (push day dates)))
7335 (unless no-ranges
7336 (goto-char beg)
7337 (while (re-search-forward org-tr-regexp end t)
7338 (setq ts1 (substring (match-string 1) 0 10)
7339 ts2 (substring (match-string 2) 0 10)
7340 day1 (time-to-days (org-time-string-to-time ts1))
7341 day2 (time-to-days (org-time-string-to-time ts2)))
7342 (while (< (setq day1 (1+ day1)) day2)
7343 (or (memq day1 dates) (push day1 dates)))))
7344 (setq dates (sort dates '<))
7345 (when empty
7346 (while (setq day (pop dates))
7347 (setq day2 (car dates))
7348 (push day dates1)
7349 (when (and day2 empty)
7350 (if (or (eq empty t)
7351 (and (numberp empty) (<= (- day2 day) empty)))
7352 (while (< (setq day (1+ day)) day2)
7353 (push (list day) dates1))
7354 (push (cons :omitted (- day2 day)) dates1))))
7355 (setq dates (nreverse dates1)))
7356 dates)))
7357
7358 ;;;###autoload
7359 (defun org-diary (&rest args)
7360 "Return diary information from org-files.
7361 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
7362 It accesses org files and extracts information from those files to be
7363 listed in the diary. The function accepts arguments specifying what
7364 items should be listed. The following arguments are allowed:
7365
7366 :timestamp List the headlines of items containing a date stamp or
7367 date range matching the selected date. Deadlines will
7368 also be listed, on the expiration day.
7369
7370 :deadline List any deadlines past due, or due within
7371 `org-deadline-warning-days'. The listing occurs only
7372 in the diary for *today*, not at any other date. If
7373 an entry is marked DONE, it is no longer listed.
7374
7375 :scheduled List all items which are scheduled for the given date.
7376 The diary for *today* also contains items which were
7377 scheduled earlier and are not yet marked DONE.
7378
7379 :todo List all TODO items from the org-file. This may be a
7380 long list - so this is not turned on by default.
7381 Like deadlines, these entries only show up in the
7382 diary for *today*, not at any other date.
7383
7384 The call in the diary file should look like this:
7385
7386 &%%(org-diary) ~/path/to/some/orgfile.org
7387
7388 Use a separate line for each org file to check. Or, if you omit the file name,
7389 all files listed in `org-agenda-files' will be checked automatically:
7390
7391 &%%(org-diary)
7392
7393 If you don't give any arguments (as in the example above), the default
7394 arguments (:deadline :scheduled :timestamp) are used. So the example above may
7395 also be written as
7396
7397 &%%(org-diary :deadline :timestamp :scheduled)
7398
7399 The function expects the lisp variables `entry' and `date' to be provided
7400 by the caller, because this is how the calendar works. Don't use this
7401 function from a program - use `org-agenda-get-day-entries' instead."
7402 (org-agenda-maybe-reset-markers)
7403 (org-compile-prefix-format org-agenda-prefix-format)
7404 (setq args (or args '(:deadline :scheduled :timestamp)))
7405 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
7406 (list entry)
7407 (org-agenda-files t)))
7408 file rtn results)
7409 ;; If this is called during org-agenda, don't return any entries to
7410 ;; the calendar. Org Agenda will list these entries itself.
7411 (if org-disable-agenda-to-diary (setq files nil))
7412 (while (setq file (pop files))
7413 (setq rtn (apply 'org-agenda-get-day-entries file date args))
7414 (setq results (append results rtn)))
7415 (if results
7416 (concat (org-finalize-agenda-entries results) "\n"))))
7417 (defvar org-category-table nil)
7418 (defun org-get-category-table ()
7419 "Get the table of categories and positions in current buffer."
7420 (let (tbl)
7421 (save-excursion
7422 (goto-char (point-min))
7423 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
7424 (push (cons (point) (org-trim (match-string 2))) tbl)))
7425 tbl))
7426 (defun org-get-category (&optional pos)
7427 "Get the category applying to position POS."
7428 (if (not org-category-table)
7429 (cond
7430 ((null org-category)
7431 (setq org-category
7432 (if buffer-file-name
7433 (file-name-sans-extension
7434 (file-name-nondirectory buffer-file-name))
7435 "???")))
7436 ((symbolp org-category) (symbol-name org-category))
7437 (t org-category))
7438 (let ((tbl org-category-table)
7439 (pos (or pos (point))))
7440 (while (and tbl (> (caar tbl) pos))
7441 (pop tbl))
7442 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
7443 org-category-table))))))
7444
7445 (defun org-agenda-get-day-entries (file date &rest args)
7446 "Does the work for `org-diary' and `org-agenda'.
7447 FILE is the path to a file to be checked for entries. DATE is date like
7448 the one returned by `calendar-current-date'. ARGS are symbols indicating
7449 which kind of entries should be extracted. For details about these, see
7450 the documentation of `org-diary'."
7451 (setq args (or args '(:deadline :scheduled :timestamp)))
7452 (let* ((org-startup-with-deadline-check nil)
7453 (org-startup-folded nil)
7454 (org-startup-align-all-tables nil)
7455 (buffer (if (file-exists-p file)
7456 (org-get-agenda-file-buffer file)
7457 (error "No such file %s" file)))
7458 arg results rtn)
7459 (if (not buffer)
7460 ;; If file does not exist, make sure an error message ends up in diary
7461 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7462 (with-current-buffer buffer
7463 (unless (org-mode-p)
7464 (error "Agenda file %s is not in `org-mode'" file))
7465 (setq org-category-table (org-get-category-table))
7466 (let ((case-fold-search nil))
7467 (save-excursion
7468 (save-restriction
7469 (if org-respect-restriction
7470 (if (org-region-active-p)
7471 ;; Respect a region to restrict search
7472 (narrow-to-region (region-beginning) (region-end)))
7473 ;; If we work for the calendar or many files,
7474 ;; get rid of any restriction
7475 (widen))
7476 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
7477 (while (setq arg (pop args))
7478 (cond
7479 ((and (eq arg :todo)
7480 (equal date (calendar-current-date)))
7481 (setq rtn (org-agenda-get-todos))
7482 (setq results (append results rtn)))
7483 ((eq arg :timestamp)
7484 (setq rtn (org-agenda-get-blocks))
7485 (setq results (append results rtn))
7486 (setq rtn (org-agenda-get-timestamps))
7487 (setq results (append results rtn)))
7488 ((eq arg :scheduled)
7489 (setq rtn (org-agenda-get-scheduled))
7490 (setq results (append results rtn)))
7491 ((eq arg :closed)
7492 (setq rtn (org-agenda-get-closed))
7493 (setq results (append results rtn)))
7494 ((and (eq arg :deadline)
7495 (equal date (calendar-current-date)))
7496 (setq rtn (org-agenda-get-deadlines))
7497 (setq results (append results rtn))))))))
7498 results))))
7499
7500 (defun org-entry-is-done-p ()
7501 "Is the current entry marked DONE?"
7502 (save-excursion
7503 (and (re-search-backward "[\r\n]\\*" nil t)
7504 (looking-at org-nl-done-regexp))))
7505
7506 (defun org-at-date-range-p ()
7507 "Is the cursor inside a date range?"
7508 (interactive)
7509 (save-excursion
7510 (catch 'exit
7511 (let ((pos (point)))
7512 (skip-chars-backward "^<\r\n")
7513 (skip-chars-backward "<")
7514 (and (looking-at org-tr-regexp)
7515 (>= (match-end 0) pos)
7516 (throw 'exit t))
7517 (skip-chars-backward "^<\r\n")
7518 (skip-chars-backward "<")
7519 (and (looking-at org-tr-regexp)
7520 (>= (match-end 0) pos)
7521 (throw 'exit t)))
7522 nil)))
7523
7524 (defun org-agenda-get-todos ()
7525 "Return the TODO information for agenda display."
7526 (let* ((props (list 'face nil
7527 'done-face 'org-done
7528 'org-not-done-regexp org-not-done-regexp
7529 'mouse-face 'highlight
7530 'keymap org-agenda-keymap
7531 'help-echo
7532 (format "mouse-2 or RET jump to org file %s"
7533 (abbreviate-file-name buffer-file-name))))
7534 (regexp (concat "[\n\r]\\*+ *\\("
7535 (if org-select-this-todo-keyword
7536 (concat "\\<\\(" org-select-this-todo-keyword
7537 "\\)\\>")
7538 org-not-done-regexp)
7539 "[^\n\r]*\\)"))
7540 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
7541 marker priority category tags
7542 ee txt)
7543 (goto-char (point-min))
7544 (while (re-search-forward regexp nil t)
7545 (catch :skip
7546 (when (and org-agenda-todo-ignore-scheduled
7547 (looking-at sched-re))
7548 ;; FIXME: the following test also happens below, but we need it here
7549 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
7550 (throw :skip nil))
7551 (org-agenda-skip)
7552 (goto-char (match-beginning 1))
7553 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
7554 category (org-get-category)
7555 tags (org-get-tags-at (point))
7556 txt (org-format-agenda-item "" (match-string 1) category tags)
7557 priority
7558 (+ (org-get-priority txt)
7559 (if org-todo-kwd-priority-p
7560 (- org-todo-kwd-max-priority -2
7561 (length
7562 (member (match-string 2) org-todo-keywords)))
7563 1)))
7564 (org-add-props txt props
7565 'org-marker marker 'org-hd-marker marker
7566 'priority priority 'category category)
7567 (push txt ee)
7568 (if org-agenda-todo-list-sublevels
7569 (goto-char (match-end 1))
7570 (org-end-of-subtree 'invisible))))
7571 (nreverse ee)))
7572
7573 (defconst org-agenda-no-heading-message
7574 "No heading for this item in buffer or region.")
7575
7576 (defun org-agenda-get-timestamps ()
7577 "Return the date stamp information for agenda display."
7578 (let* ((props (list 'face nil
7579 'org-not-done-regexp org-not-done-regexp
7580 'mouse-face 'highlight
7581 'keymap org-agenda-keymap
7582 'help-echo
7583 (format "mouse-2 or RET jump to org file %s"
7584 (abbreviate-file-name buffer-file-name))))
7585 (regexp (regexp-quote
7586 (substring
7587 (format-time-string
7588 (car org-time-stamp-formats)
7589 (apply 'encode-time ; DATE bound by calendar
7590 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7591 0 11)))
7592 marker hdmarker deadlinep scheduledp donep tmp priority category
7593 ee txt timestr tags)
7594 (goto-char (point-min))
7595 (while (re-search-forward regexp nil t)
7596 (catch :skip
7597 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
7598 (org-agenda-skip)
7599 (setq marker (org-agenda-new-marker (match-beginning 0))
7600 category (org-get-category (match-beginning 0))
7601 tmp (buffer-substring (max (point-min)
7602 (- (match-beginning 0)
7603 org-ds-keyword-length))
7604 (match-beginning 0))
7605 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7606 deadlinep (string-match org-deadline-regexp tmp)
7607 scheduledp (string-match org-scheduled-regexp tmp)
7608 donep (org-entry-is-done-p))
7609 (if (string-match ">" timestr)
7610 ;; substring should only run to end of time stamp
7611 (setq timestr (substring timestr 0 (match-end 0))))
7612 (save-excursion
7613 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7614 (progn
7615 (goto-char (match-end 1))
7616 (setq hdmarker (org-agenda-new-marker)
7617 tags (org-get-tags-at))
7618 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7619 (setq txt (org-format-agenda-item
7620 (format "%s%s"
7621 (if deadlinep "Deadline: " "")
7622 (if scheduledp "Scheduled: " ""))
7623 (match-string 1) category tags timestr)))
7624 (setq txt org-agenda-no-heading-message))
7625 (setq priority (org-get-priority txt))
7626 (org-add-props txt props
7627 'org-marker marker 'org-hd-marker hdmarker)
7628 (if deadlinep
7629 (org-add-props txt nil
7630 'face (if donep 'org-done 'org-warning)
7631 'undone-face 'org-warning 'done-face 'org-done
7632 'category category 'priority (+ 100 priority))
7633 (if scheduledp
7634 (org-add-props txt nil
7635 'face 'org-scheduled-today
7636 'undone-face 'org-scheduled-today 'done-face 'org-done
7637 'category category 'priority (+ 99 priority))
7638 (org-add-props txt nil 'priority priority 'category category)))
7639 (push txt ee))
7640 (outline-next-heading)))
7641 (nreverse ee)))
7642
7643 (defun org-agenda-get-closed ()
7644 "Return the logged TODO entries for agenda display."
7645 (let* ((props (list 'mouse-face 'highlight
7646 'org-not-done-regexp org-not-done-regexp
7647 'keymap org-agenda-keymap
7648 'help-echo
7649 (format "mouse-2 or RET jump to org file %s"
7650 (abbreviate-file-name buffer-file-name))))
7651 (regexp (concat
7652 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
7653 (regexp-quote
7654 (substring
7655 (format-time-string
7656 (car org-time-stamp-formats)
7657 (apply 'encode-time ; DATE bound by calendar
7658 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7659 1 11))))
7660 marker hdmarker priority category tags closedp
7661 ee txt timestr)
7662 (goto-char (point-min))
7663 (while (re-search-forward regexp nil t)
7664 (catch :skip
7665 (org-agenda-skip)
7666 (setq marker (org-agenda-new-marker (match-beginning 0))
7667 closedp (equal (match-string 1) org-closed-string)
7668 category (org-get-category (match-beginning 0))
7669 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7670 ;; donep (org-entry-is-done-p)
7671 )
7672 (if (string-match "\\]" timestr)
7673 ;; substring should only run to end of time stamp
7674 (setq timestr (substring timestr 0 (match-end 0))))
7675 (save-excursion
7676 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7677 (progn
7678 (goto-char (match-end 1))
7679 (setq hdmarker (org-agenda-new-marker)
7680 tags (org-get-tags-at))
7681 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7682 (setq txt (org-format-agenda-item
7683 (if closedp "Closed: " "Clocked: ")
7684 (match-string 1) category tags timestr)))
7685 (setq txt org-agenda-no-heading-message))
7686 (setq priority 100000)
7687 (org-add-props txt props
7688 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
7689 'priority priority 'category category
7690 'undone-face 'org-warning 'done-face 'org-done)
7691 (push txt ee))
7692 (outline-next-heading)))
7693 (nreverse ee)))
7694
7695 (defun org-agenda-get-deadlines ()
7696 "Return the deadline information for agenda display."
7697 (let* ((wdays org-deadline-warning-days)
7698 (props (list 'mouse-face 'highlight
7699 'org-not-done-regexp org-not-done-regexp
7700 'keymap org-agenda-keymap
7701 'help-echo
7702 (format "mouse-2 or RET jump to org file %s"
7703 (abbreviate-file-name buffer-file-name))))
7704 (regexp org-deadline-time-regexp)
7705 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7706 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7707 d2 diff pos pos1 category tags
7708 ee txt head face)
7709 (goto-char (point-min))
7710 (while (re-search-forward regexp nil t)
7711 (catch :skip
7712 (org-agenda-skip)
7713 (setq pos (1- (match-beginning 1))
7714 d2 (time-to-days
7715 (org-time-string-to-time (match-string 1)))
7716 diff (- d2 d1))
7717 ;; When to show a deadline in the calendar:
7718 ;; If the expiration is within wdays warning time.
7719 ;; Past-due deadlines are only shown on the current date
7720 (if (and (< diff wdays) todayp (not (= diff 0)))
7721 (save-excursion
7722 (setq category (org-get-category))
7723 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7724 (progn
7725 (goto-char (match-end 0))
7726 (setq pos1 (match-end 1))
7727 (setq tags (org-get-tags-at pos1))
7728 (setq head (buffer-substring-no-properties
7729 (point)
7730 (progn (skip-chars-forward "^\r\n")
7731 (point))))
7732 (if (string-match org-looking-at-done-regexp head)
7733 (setq txt nil)
7734 (setq txt (org-format-agenda-item
7735 (format "In %3d d.: " diff) head category tags))))
7736 (setq txt org-agenda-no-heading-message))
7737 (when txt
7738 (setq face (cond ((<= diff 0) 'org-warning)
7739 ((<= diff 5) 'org-upcoming-deadline)
7740 (t nil)))
7741 (org-add-props txt props
7742 'org-marker (org-agenda-new-marker pos)
7743 'org-hd-marker (org-agenda-new-marker pos1)
7744 'priority (+ (- 10 diff) (org-get-priority txt))
7745 'category category
7746 'face face 'undone-face face 'done-face 'org-done)
7747 (push txt ee))))))
7748 ee))
7749
7750 (defun org-agenda-get-scheduled ()
7751 "Return the scheduled information for agenda display."
7752 (let* ((props (list 'face 'org-scheduled-previously
7753 'org-not-done-regexp org-not-done-regexp
7754 'undone-face 'org-scheduled-previously
7755 'done-face 'org-done
7756 'mouse-face 'highlight
7757 'keymap org-agenda-keymap
7758 'help-echo
7759 (format "mouse-2 or RET jump to org file %s"
7760 (abbreviate-file-name buffer-file-name))))
7761 (regexp org-scheduled-time-regexp)
7762 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7763 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7764 d2 diff pos pos1 category tags
7765 ee txt head)
7766 (goto-char (point-min))
7767 (while (re-search-forward regexp nil t)
7768 (catch :skip
7769 (org-agenda-skip)
7770 (setq pos (1- (match-beginning 1))
7771 d2 (time-to-days
7772 (org-time-string-to-time (match-string 1)))
7773 diff (- d2 d1))
7774 ;; When to show a scheduled item in the calendar:
7775 ;; If it is on or past the date.
7776 (if (and (< diff 0) todayp)
7777 (save-excursion
7778 (setq category (org-get-category))
7779 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7780 (progn
7781 (goto-char (match-end 0))
7782 (setq pos1 (match-end 1))
7783 (setq tags (org-get-tags-at))
7784 (setq head (buffer-substring-no-properties
7785 (point)
7786 (progn (skip-chars-forward "^\r\n") (point))))
7787 (if (string-match org-looking-at-done-regexp head)
7788 (setq txt nil)
7789 (setq txt (org-format-agenda-item
7790 (format "Sched.%2dx: " (- 1 diff)) head
7791 category tags))))
7792 (setq txt org-agenda-no-heading-message))
7793 (when txt
7794 (org-add-props txt props
7795 'org-marker (org-agenda-new-marker pos)
7796 'org-hd-marker (org-agenda-new-marker pos1)
7797 'priority (+ (- 5 diff) (org-get-priority txt))
7798 'category category)
7799 (push txt ee))))))
7800 ee))
7801
7802 (defun org-agenda-get-blocks ()
7803 "Return the date-range information for agenda display."
7804 (let* ((props (list 'face nil
7805 'org-not-done-regexp org-not-done-regexp
7806 'mouse-face 'highlight
7807 'keymap org-agenda-keymap
7808 'help-echo
7809 (format "mouse-2 or RET jump to org file %s"
7810 (abbreviate-file-name buffer-file-name))))
7811 (regexp org-tr-regexp)
7812 (d0 (calendar-absolute-from-gregorian date))
7813 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
7814 (goto-char (point-min))
7815 (while (re-search-forward regexp nil t)
7816 (catch :skip
7817 (org-agenda-skip)
7818 (setq pos (point))
7819 (setq timestr (match-string 0)
7820 s1 (match-string 1)
7821 s2 (match-string 2)
7822 d1 (time-to-days (org-time-string-to-time s1))
7823 d2 (time-to-days (org-time-string-to-time s2)))
7824 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
7825 ;; Only allow days between the limits, because the normal
7826 ;; date stamps will catch the limits.
7827 (save-excursion
7828 (setq marker (org-agenda-new-marker (point)))
7829 (setq category (org-get-category))
7830 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7831 (progn
7832 (setq hdmarker (org-agenda-new-marker (match-end 1)))
7833 (goto-char (match-end 1))
7834 (setq tags (org-get-tags-at))
7835 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7836 (setq txt (org-format-agenda-item
7837 (format (if (= d1 d2) "" "(%d/%d): ")
7838 (1+ (- d0 d1)) (1+ (- d2 d1)))
7839 (match-string 1) category tags
7840 (if (= d0 d1) timestr))))
7841 (setq txt org-agenda-no-heading-message))
7842 (org-add-props txt props
7843 'org-marker marker 'org-hd-marker hdmarker
7844 'priority (org-get-priority txt) 'category category)
7845 (push txt ee)))
7846 (goto-char pos)))
7847 ; (outline-next-heading))) ;FIXME: correct to be removed??????
7848 ;; Sort the entries by expiration date.
7849 (nreverse ee)))
7850
7851 (defconst org-plain-time-of-day-regexp
7852 (concat
7853 "\\(\\<[012]?[0-9]"
7854 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7855 "\\(--?"
7856 "\\(\\<[012]?[0-9]"
7857 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7858 "\\)?")
7859 "Regular expression to match a plain time or time range.
7860 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
7861 groups carry important information:
7862 0 the full match
7863 1 the first time, range or not
7864 8 the second time, if it is a range.")
7865
7866 (defconst org-stamp-time-of-day-regexp
7867 (concat
7868 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
7869 "\\([012][0-9]:[0-5][0-9]\\)>"
7870 "\\(--?"
7871 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
7872 "Regular expression to match a timestamp time or time range.
7873 After a match, the following groups carry important information:
7874 0 the full match
7875 1 date plus weekday, for backreferencing to make sure both times on same day
7876 2 the first time, range or not
7877 4 the second time, if it is a range.")
7878
7879 (defvar org-prefix-has-time nil
7880 "A flag, set by `org-compile-prefix-format'.
7881 The flag is set if the currently compiled format contains a `%t'.")
7882 (defvar org-prefix-has-tag nil
7883 "A flag, set by `org-compile-prefix-format'.
7884 The flag is set if the currently compiled format contains a `%T'.")
7885
7886 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
7887 "Format TXT to be inserted into the agenda buffer.
7888 In particular, it adds the prefix and corresponding text properties. EXTRA
7889 must be a string and replaces the `%s' specifier in the prefix format.
7890 CATEGORY (string, symbol or nil) may be used to overrule the default
7891 category taken from local variable or file name. It will replace the `%c'
7892 specifier in the format. DOTIME, when non-nil, indicates that a
7893 time-of-day should be extracted from TXT for sorting of this entry, and for
7894 the `%t' specifier in the format. When DOTIME is a string, this string is
7895 searched for a time before TXT is. NOPREFIX is a flag and indicates that
7896 only the correctly processes TXT should be returned - this is used by
7897 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
7898 (save-match-data
7899 ;; Diary entries sometimes have extra whitespace at the beginning
7900 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
7901 (let* ((category (or category
7902 org-category
7903 (if buffer-file-name
7904 (file-name-sans-extension
7905 (file-name-nondirectory buffer-file-name))
7906 "")))
7907 (tag (if tags (nth (1- (length tags)) tags) ""))
7908 time ;; needed for the eval of the prefix format
7909 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
7910 (time-of-day (and dotime (org-get-time-of-day ts)))
7911 stamp plain s0 s1 s2 rtn)
7912 (when (and dotime time-of-day org-prefix-has-time)
7913 ;; Extract starting and ending time and move them to prefix
7914 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
7915 (setq plain (string-match org-plain-time-of-day-regexp ts)))
7916 (setq s0 (match-string 0 ts)
7917 s1 (match-string (if plain 1 2) ts)
7918 s2 (match-string (if plain 8 4) ts))
7919
7920 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
7921 ;; them, we might want to remove them there to avoid duplication.
7922 ;; The user can turn this off with a variable.
7923 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
7924 (string-match (concat (regexp-quote s0) " *") txt)
7925 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
7926 (= (match-beginning 0) 0)
7927 t))
7928 (setq txt (replace-match "" nil nil txt))))
7929 ;; Normalize the time(s) to 24 hour
7930 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
7931 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
7932
7933 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
7934 ;; Tags are in the string
7935 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
7936 (and org-agenda-remove-tags-when-in-prefix
7937 org-prefix-has-tag))
7938 (setq txt (replace-match "" t t txt))
7939 (setq txt (replace-match
7940 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
7941 (match-string 2 txt))
7942 t t txt))))
7943
7944 ;; Create the final string
7945 (if noprefix
7946 (setq rtn txt)
7947 ;; Prepare the variables needed in the eval of the compiled format
7948 (setq time (cond (s2 (concat s1 "-" s2))
7949 (s1 (concat s1 "......"))
7950 (t ""))
7951 extra (or extra "")
7952 category (if (symbolp category) (symbol-name category) category))
7953 ;; Evaluate the compiled format
7954 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
7955
7956 ;; And finally add the text properties
7957 (org-add-props rtn nil
7958 'category (downcase category) 'tags tags
7959 'prefix-length (- (length rtn) (length txt))
7960 'time-of-day time-of-day
7961 'dotime dotime))))
7962
7963 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
7964 (catch 'exit
7965 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
7966 ((and todayp (member 'today (car org-agenda-time-grid))))
7967 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
7968 ((member 'weekly (car org-agenda-time-grid)))
7969 (t (throw 'exit list)))
7970 (let* ((have (delq nil (mapcar
7971 (lambda (x) (get-text-property 1 'time-of-day x))
7972 list)))
7973 (string (nth 1 org-agenda-time-grid))
7974 (gridtimes (nth 2 org-agenda-time-grid))
7975 (req (car org-agenda-time-grid))
7976 (remove (member 'remove-match req))
7977 new time)
7978 (if (and (member 'require-timed req) (not have))
7979 ;; don't show empty grid
7980 (throw 'exit list))
7981 (while (setq time (pop gridtimes))
7982 (unless (and remove (member time have))
7983 (setq time (int-to-string time))
7984 (push (org-format-agenda-item
7985 nil string "" nil
7986 (concat (substring time 0 -2) ":" (substring time -2)))
7987 new)
7988 (put-text-property
7989 1 (length (car new)) 'face 'org-time-grid (car new))))
7990 (if (member 'time-up org-agenda-sorting-strategy)
7991 (append new list)
7992 (append list new)))))
7993
7994 (defun org-compile-prefix-format (format)
7995 "Compile the prefix format into a Lisp form that can be evaluated.
7996 The resulting form is returned and stored in the variable
7997 `org-prefix-format-compiled'."
7998 (setq org-prefix-has-time nil org-prefix-has-tag nil)
7999 (let ((start 0) varform vars var (s format)e c f opt)
8000 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
8001 s start)
8002 (setq var (cdr (assoc (match-string 4 s)
8003 '(("c" . category) ("t" . time) ("s" . extra)
8004 ("T" . tag))))
8005 c (or (match-string 3 s) "")
8006 opt (match-beginning 1)
8007 start (1+ (match-beginning 0)))
8008 (if (equal var 'time) (setq org-prefix-has-time t))
8009 (if (equal var 'tag) (setq org-prefix-has-tag t))
8010 (setq f (concat "%" (match-string 2 s) "s"))
8011 (if opt
8012 (setq varform
8013 `(if (equal "" ,var)
8014 ""
8015 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
8016 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
8017 (setq s (replace-match "%s" t nil s))
8018 (push varform vars))
8019 (setq vars (nreverse vars))
8020 (setq org-prefix-format-compiled `(format ,s ,@vars))))
8021
8022 (defun org-get-time-of-day (s &optional string mod24)
8023 "Check string S for a time of day.
8024 If found, return it as a military time number between 0 and 2400.
8025 If not found, return nil.
8026 The optional STRING argument forces conversion into a 5 character wide string
8027 HH:MM."
8028 (save-match-data
8029 (when
8030 (or
8031 (string-match
8032 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
8033 (string-match
8034 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
8035 (let* ((h (string-to-number (match-string 1 s)))
8036 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
8037 (ampm (if (match-end 4) (downcase (match-string 4 s))))
8038 (am-p (equal ampm "am"))
8039 (h1 (cond ((not ampm) h)
8040 ((= h 12) (if am-p 0 12))
8041 (t (+ h (if am-p 0 12)))))
8042 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
8043 (mod h1 24) h1))
8044 (t0 (+ (* 100 h2) m))
8045 (t1 (concat (if (>= h1 24) "+" " ")
8046 (if (< t0 100) "0" "")
8047 (if (< t0 10) "0" "")
8048 (int-to-string t0))))
8049 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
8050
8051 (defun org-finalize-agenda-entries (list)
8052 "Sort and concatenate the agenda items."
8053 (setq list (mapcar 'org-agenda-highlight-todo list))
8054 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
8055
8056 (defun org-agenda-highlight-todo (x)
8057 (let (re pl)
8058 (if (eq x 'line)
8059 (save-excursion
8060 (beginning-of-line 1)
8061 (setq re (get-text-property (point) 'org-not-done-regexp))
8062 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
8063 (and (looking-at (concat "[ \t]*" re))
8064 (add-text-properties (match-beginning 0) (match-end 0)
8065 '(face org-todo))))
8066 (setq re (get-text-property 0 'org-not-done-regexp x)
8067 pl (get-text-property 0 'prefix-length x))
8068 (and re (equal (string-match re x pl) pl)
8069 (add-text-properties (match-beginning 0) (match-end 0)
8070 '(face org-todo) x))
8071 x)))
8072
8073 (defsubst org-cmp-priority (a b)
8074 "Compare the priorities of string A and B."
8075 (let ((pa (or (get-text-property 1 'priority a) 0))
8076 (pb (or (get-text-property 1 'priority b) 0)))
8077 (cond ((> pa pb) +1)
8078 ((< pa pb) -1)
8079 (t nil))))
8080
8081 (defsubst org-cmp-category (a b)
8082 "Compare the string values of categories of strings A and B."
8083 (let ((ca (or (get-text-property 1 'category a) ""))
8084 (cb (or (get-text-property 1 'category b) "")))
8085 (cond ((string-lessp ca cb) -1)
8086 ((string-lessp cb ca) +1)
8087 (t nil))))
8088
8089 (defsubst org-cmp-time (a b)
8090 "Compare the time-of-day values of strings A and B."
8091 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
8092 (ta (or (get-text-property 1 'time-of-day a) def))
8093 (tb (or (get-text-property 1 'time-of-day b) def)))
8094 (cond ((< ta tb) -1)
8095 ((< tb ta) +1)
8096 (t nil))))
8097
8098 (defun org-entries-lessp (a b)
8099 "Predicate for sorting agenda entries."
8100 ;; The following variables will be used when the form is evaluated.
8101 (let* ((time-up (org-cmp-time a b))
8102 (time-down (if time-up (- time-up) nil))
8103 (priority-up (org-cmp-priority a b))
8104 (priority-down (if priority-up (- priority-up) nil))
8105 (category-up (org-cmp-category a b))
8106 (category-down (if category-up (- category-up) nil))
8107 (category-keep (if category-up +1 nil)))
8108 (cdr (assoc
8109 (eval (cons 'or org-agenda-sorting-strategy))
8110 '((-1 . t) (1 . nil) (nil . nil))))))
8111
8112 (defun org-agenda-show-priority ()
8113 "Show the priority of the current item.
8114 This priority is composed of the main priority given with the [#A] cookies,
8115 and by additional input from the age of a schedules or deadline entry."
8116 (interactive)
8117 (let* ((pri (get-text-property (point-at-bol) 'priority)))
8118 (message "Priority is %d" (if pri pri -1000))))
8119
8120 (defun org-agenda-show-tags ()
8121 "Show the tags applicable to the current item."
8122 (interactive)
8123 (let* ((tags (get-text-property (point-at-bol) 'tags)))
8124 (if tags
8125 (message "Tags are :%s:"
8126 (org-no-properties (mapconcat 'identity tags ":")))
8127 (message "No tags associated with this line"))))
8128
8129 (defun org-agenda-goto (&optional highlight)
8130 "Go to the Org-mode file which contains the item at point."
8131 (interactive)
8132 (let* ((marker (or (get-text-property (point) 'org-marker)
8133 (org-agenda-error)))
8134 (buffer (marker-buffer marker))
8135 (pos (marker-position marker)))
8136 (switch-to-buffer-other-window buffer)
8137 (widen)
8138 (goto-char pos)
8139 (when (org-mode-p)
8140 (org-show-hidden-entry)
8141 (save-excursion
8142 (and (outline-next-heading)
8143 (org-flag-heading nil)))) ; show the next heading
8144 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
8145
8146 (defun org-agenda-switch-to ()
8147 "Go to the Org-mode file which contains the item at point."
8148 (interactive)
8149 (let* ((marker (or (get-text-property (point) 'org-marker)
8150 (org-agenda-error)))
8151 (buffer (marker-buffer marker))
8152 (pos (marker-position marker)))
8153 (switch-to-buffer buffer)
8154 (delete-other-windows)
8155 (widen)
8156 (goto-char pos)
8157 (when (org-mode-p)
8158 (org-show-hidden-entry)
8159 (save-excursion
8160 (and (outline-next-heading)
8161 (org-flag-heading nil)))))) ; show the next heading
8162
8163 (defun org-agenda-goto-mouse (ev)
8164 "Go to the Org-mode file which contains the item at the mouse click."
8165 (interactive "e")
8166 (mouse-set-point ev)
8167 (org-agenda-goto))
8168
8169 (defun org-agenda-show ()
8170 "Display the Org-mode file which contains the item at point."
8171 (interactive)
8172 (let ((win (selected-window)))
8173 (org-agenda-goto t)
8174 (select-window win)))
8175
8176 (defun org-agenda-recenter (arg)
8177 "Display the Org-mode file which contains the item at point and recenter."
8178 (interactive "P")
8179 (let ((win (selected-window)))
8180 (org-agenda-goto t)
8181 (recenter arg)
8182 (select-window win)))
8183
8184 (defun org-agenda-show-mouse (ev)
8185 "Display the Org-mode file which contains the item at the mouse click."
8186 (interactive "e")
8187 (mouse-set-point ev)
8188 (org-agenda-show))
8189
8190 (defun org-agenda-check-no-diary ()
8191 "Check if the entry is a diary link and abort if yes."
8192 (if (get-text-property (point) 'org-agenda-diary-link)
8193 (org-agenda-error)))
8194
8195 (defun org-agenda-error ()
8196 (error "Command not allowed in this line"))
8197
8198 (defvar org-last-heading-marker (make-marker)
8199 "Marker pointing to the headline that last changed its TODO state
8200 by a remote command from the agenda.")
8201
8202 (defun org-agenda-todo (&optional arg)
8203 "Cycle TODO state of line at point, also in Org-mode file.
8204 This changes the line at point, all other lines in the agenda referring to
8205 the same tree node, and the headline of the tree node in the Org-mode file."
8206 (interactive "P")
8207 (org-agenda-check-no-diary)
8208 (let* ((col (current-column))
8209 (marker (or (get-text-property (point) 'org-marker)
8210 (org-agenda-error)))
8211 (buffer (marker-buffer marker))
8212 (pos (marker-position marker))
8213 (hdmarker (get-text-property (point) 'org-hd-marker))
8214 (buffer-read-only nil)
8215 newhead)
8216 (with-current-buffer buffer
8217 (widen)
8218 (goto-char pos)
8219 (org-show-hidden-entry)
8220 (save-excursion
8221 (and (outline-next-heading)
8222 (org-flag-heading nil))) ; show the next heading
8223 (org-todo arg)
8224 (and (bolp) (forward-char 1))
8225 (setq newhead (org-get-heading))
8226 (save-excursion
8227 (org-back-to-heading)
8228 (move-marker org-last-heading-marker (point))))
8229 (beginning-of-line 1)
8230 (save-excursion
8231 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8232 (move-to-column col)))
8233
8234 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8235 "Change all lines in the agenda buffer which match HDMARKER.
8236 The new content of the line will be NEWHEAD (as modified by
8237 `org-format-agenda-item'). HDMARKER is checked with
8238 `equal' against all `org-hd-marker' text properties in the file.
8239 If FIXFACE is non-nil, the face of each item is modified acording to
8240 the new TODO state."
8241 (let* (props m pl undone-face done-face finish new dotime cat tags)
8242 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
8243 (save-excursion
8244 (goto-char (point-max))
8245 (beginning-of-line 1)
8246 (while (not finish)
8247 (setq finish (bobp))
8248 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8249 (equal m hdmarker))
8250 (setq props (text-properties-at (point))
8251 dotime (get-text-property (point) 'dotime)
8252 cat (get-text-property (point) 'category)
8253 tags (get-text-property (point) 'tags)
8254 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
8255 pl (get-text-property (point) 'prefix-length)
8256 undone-face (get-text-property (point) 'undone-face)
8257 done-face (get-text-property (point) 'done-face))
8258 (move-to-column pl)
8259 (if (looking-at ".*")
8260 (progn
8261 (replace-match new t t)
8262 (beginning-of-line 1)
8263 (add-text-properties (point-at-bol) (point-at-eol) props)
8264 (when fixface
8265 (add-text-properties
8266 (point-at-bol) (point-at-eol)
8267 (list 'face
8268 (if org-last-todo-state-is-todo
8269 undone-face done-face)))
8270 (org-agenda-highlight-todo 'line))
8271 (beginning-of-line 1))
8272 (error "Line update did not work")))
8273 (beginning-of-line 0)))))
8274
8275 (defun org-agenda-priority-up ()
8276 "Increase the priority of line at point, also in Org-mode file."
8277 (interactive)
8278 (org-agenda-priority 'up))
8279
8280 (defun org-agenda-priority-down ()
8281 "Decrease the priority of line at point, also in Org-mode file."
8282 (interactive)
8283 (org-agenda-priority 'down))
8284
8285 (defun org-agenda-priority (&optional force-direction)
8286 "Set the priority of line at point, also in Org-mode file.
8287 This changes the line at point, all other lines in the agenda referring to
8288 the same tree node, and the headline of the tree node in the Org-mode file."
8289 (interactive)
8290 (org-agenda-check-no-diary)
8291 (let* ((marker (or (get-text-property (point) 'org-marker)
8292 (org-agenda-error)))
8293 (buffer (marker-buffer marker))
8294 (pos (marker-position marker))
8295 (hdmarker (get-text-property (point) 'org-hd-marker))
8296 (buffer-read-only nil)
8297 newhead)
8298 (with-current-buffer buffer
8299 (widen)
8300 (goto-char pos)
8301 (org-show-hidden-entry)
8302 (save-excursion
8303 (and (outline-next-heading)
8304 (org-flag-heading nil))) ; show the next heading
8305 (funcall 'org-priority force-direction)
8306 (end-of-line 1)
8307 (setq newhead (org-get-heading)))
8308 (org-agenda-change-all-lines newhead hdmarker)
8309 (beginning-of-line 1)))
8310
8311 (defun org-get-tags-at (&optional pos)
8312 "Get a list of all headline tags applicable at POS.
8313 POS defaults to point. If tags are inherited, the list contains
8314 the targets in the same sequence as the headlines appear, i.e.
8315 the tags of the current headline come last."
8316 (interactive)
8317 (let (tags)
8318 (save-excursion
8319 (goto-char (or pos (point)))
8320 (save-match-data
8321 (org-back-to-heading t)
8322 (condition-case nil
8323 (while t
8324 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
8325 (setq tags (append (org-split-string
8326 (org-match-string-no-properties 1) ":")
8327 tags)))
8328 (or org-use-tag-inheritance (error ""))
8329 (org-up-heading-all 1))
8330 (error nil))))
8331 (message "%s" tags)
8332 tags))
8333
8334 (defun org-agenda-set-tags ()
8335 "Set tags for the current headline."
8336 (interactive)
8337 (org-agenda-check-no-diary)
8338 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
8339 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
8340 (org-agenda-error)))
8341 (buffer (marker-buffer hdmarker))
8342 (pos (marker-position hdmarker))
8343 (buffer-read-only nil)
8344 newhead)
8345 (with-current-buffer buffer
8346 (widen)
8347 (goto-char pos)
8348 (org-show-hidden-entry)
8349 (save-excursion
8350 (and (outline-next-heading)
8351 (org-flag-heading nil))) ; show the next heading
8352 (call-interactively 'org-set-tags)
8353 (end-of-line 1)
8354 (setq newhead (org-get-heading)))
8355 (org-agenda-change-all-lines newhead hdmarker)
8356 (beginning-of-line 1)))
8357
8358 (defun org-agenda-date-later (arg &optional what)
8359 "Change the date of this item to one day later."
8360 (interactive "p")
8361 (org-agenda-check-type t 'agenda 'timeline)
8362 (org-agenda-check-no-diary)
8363 (let* ((marker (or (get-text-property (point) 'org-marker)
8364 (org-agenda-error)))
8365 (buffer (marker-buffer marker))
8366 (pos (marker-position marker)))
8367 (with-current-buffer buffer
8368 (widen)
8369 (goto-char pos)
8370 (if (not (org-at-timestamp-p))
8371 (error "Cannot find time stamp"))
8372 (org-timestamp-change arg (or what 'day))
8373 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8374
8375 (defun org-agenda-date-earlier (arg &optional what)
8376 "Change the date of this item to one day earlier."
8377 (interactive "p")
8378 (org-agenda-date-later (- arg) what))
8379
8380 (defun org-agenda-date-prompt (arg)
8381 "Change the date of this item. Date is prompted for, with default today.
8382 The prefix ARG is passed to the `org-time-stamp' command and can therefore
8383 be used to request time specification in the time stamp."
8384 (interactive "P")
8385 (org-agenda-check-type t 'agenda 'timeline)
8386 (org-agenda-check-no-diary)
8387 (let* ((marker (or (get-text-property (point) 'org-marker)
8388 (org-agenda-error)))
8389 (buffer (marker-buffer marker))
8390 (pos (marker-position marker)))
8391 (with-current-buffer buffer
8392 (widen)
8393 (goto-char pos)
8394 (if (not (org-at-timestamp-p))
8395 (error "Cannot find time stamp"))
8396 (org-time-stamp arg)
8397 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8398
8399 (defun org-agenda-schedule (arg)
8400 "Schedule the item at point."
8401 (interactive "P")
8402 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8403 (org-agenda-check-no-diary)
8404 (let* ((marker (or (get-text-property (point) 'org-marker)
8405 (org-agenda-error)))
8406 (buffer (marker-buffer marker))
8407 (pos (marker-position marker))
8408 (org-insert-labeled-timestamps-at-point nil)
8409 ts)
8410 (with-current-buffer buffer
8411 (widen)
8412 (goto-char pos)
8413 (setq ts (org-schedule))
8414 (message "Item scheduled for %s" ts))))
8415
8416 (defun org-agenda-deadline (arg)
8417 "Schedule the item at point."
8418 (interactive "P")
8419 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8420 (org-agenda-check-no-diary)
8421 (let* ((marker (or (get-text-property (point) 'org-marker)
8422 (org-agenda-error)))
8423 (buffer (marker-buffer marker))
8424 (pos (marker-position marker))
8425 (org-insert-labeled-timestamps-at-point nil)
8426 ts)
8427 (with-current-buffer buffer
8428 (widen)
8429 (goto-char pos)
8430 (setq ts (org-deadline))
8431 (message "Deadline for this item set to %s" ts))))
8432
8433 (defun org-get-heading ()
8434 "Return the heading of the current entry, without the stars."
8435 (save-excursion
8436 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
8437 (if (and (re-search-backward "[\r\n]\\*" nil t)
8438 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
8439 (match-string 1)
8440 "")))
8441
8442 (defun org-agenda-clock-in (&optional arg)
8443 "Start the clock on the currently selected item."
8444 (interactive "P")
8445 (org-agenda-check-no-diary)
8446 (let* ((marker (or (get-text-property (point) 'org-marker)
8447 (org-agenda-error)))
8448 (pos (marker-position marker)))
8449 (with-current-buffer (marker-buffer marker)
8450 (widen)
8451 (goto-char pos)
8452 (org-clock-in))))
8453
8454 (defun org-agenda-diary-entry ()
8455 "Make a diary entry, like the `i' command from the calendar.
8456 All the standard commands work: block, weekly etc."
8457 (interactive)
8458 (org-agenda-check-type t 'agenda 'timeline)
8459 (require 'diary-lib)
8460 (let* ((char (progn
8461 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
8462 (read-char-exclusive)))
8463 (cmd (cdr (assoc char
8464 '((?d . insert-diary-entry)
8465 (?w . insert-weekly-diary-entry)
8466 (?m . insert-monthly-diary-entry)
8467 (?y . insert-yearly-diary-entry)
8468 (?a . insert-anniversary-diary-entry)
8469 (?b . insert-block-diary-entry)
8470 (?c . insert-cyclic-diary-entry)))))
8471 (oldf (symbol-function 'calendar-cursor-to-date))
8472 (point (point))
8473 (mark (or (mark t) (point))))
8474 (unless cmd
8475 (error "No command associated with <%c>" char))
8476 (unless (and (get-text-property point 'day)
8477 (or (not (equal ?b char))
8478 (get-text-property mark 'day)))
8479 (error "Don't know which date to use for diary entry"))
8480 ;; We implement this by hacking the `calendar-cursor-to-date' function
8481 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
8482 (let ((calendar-mark-ring
8483 (list (calendar-gregorian-from-absolute
8484 (or (get-text-property mark 'day)
8485 (get-text-property point 'day))))))
8486 (unwind-protect
8487 (progn
8488 (fset 'calendar-cursor-to-date
8489 (lambda (&optional error)
8490 (calendar-gregorian-from-absolute
8491 (get-text-property point 'day))))
8492 (call-interactively cmd))
8493 (fset 'calendar-cursor-to-date oldf)))))
8494
8495
8496 (defun org-agenda-execute-calendar-command (cmd)
8497 "Execute a calendar command from the agenda, with the date associated to
8498 the cursor position."
8499 (org-agenda-check-type t 'agenda 'timeline)
8500 (require 'diary-lib)
8501 (unless (get-text-property (point) 'day)
8502 (error "Don't know which date to use for calendar command"))
8503 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
8504 (point (point))
8505 (date (calendar-gregorian-from-absolute
8506 (get-text-property point 'day)))
8507 (displayed-day (extract-calendar-day date))
8508 (displayed-month (extract-calendar-month date))
8509 (displayed-year (extract-calendar-year date)))
8510 (unwind-protect
8511 (progn
8512 (fset 'calendar-cursor-to-date
8513 (lambda (&optional error)
8514 (calendar-gregorian-from-absolute
8515 (get-text-property point 'day))))
8516 (call-interactively cmd))
8517 (fset 'calendar-cursor-to-date oldf))))
8518
8519 (defun org-agenda-phases-of-moon ()
8520 "Display the phases of the moon for the 3 months around the cursor date."
8521 (interactive)
8522 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
8523
8524 (defun org-agenda-holidays ()
8525 "Display the holidays for the 3 months around the cursor date."
8526 (interactive)
8527 (org-agenda-execute-calendar-command 'list-calendar-holidays))
8528
8529 (defun org-agenda-sunrise-sunset (arg)
8530 "Display sunrise and sunset for the cursor date.
8531 Latitude and longitude can be specified with the variables
8532 `calendar-latitude' and `calendar-longitude'. When called with prefix
8533 argument, latitude and longitude will be prompted for."
8534 (interactive "P")
8535 (let ((calendar-longitude (if arg nil calendar-longitude))
8536 (calendar-latitude (if arg nil calendar-latitude))
8537 (calendar-location-name
8538 (if arg "the given coordinates" calendar-location-name)))
8539 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
8540
8541 (defun org-agenda-goto-calendar ()
8542 "Open the Emacs calendar with the date at the cursor."
8543 (interactive)
8544 (org-agenda-check-type t 'agenda 'timeline)
8545 (let* ((day (or (get-text-property (point) 'day)
8546 (error "Don't know which date to open in calendar")))
8547 (date (calendar-gregorian-from-absolute day))
8548 (calendar-move-hook nil)
8549 (view-calendar-holidays-initially nil)
8550 (view-diary-entries-initially nil))
8551 (calendar)
8552 (calendar-goto-date date)))
8553
8554 (defun org-calendar-goto-agenda ()
8555 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
8556 This is a command that has to be installed in `calendar-mode-map'."
8557 (interactive)
8558 (org-agenda-list nil (calendar-absolute-from-gregorian
8559 (calendar-cursor-to-date))
8560 nil t))
8561
8562 (defun org-agenda-convert-date ()
8563 (interactive)
8564 (org-agenda-check-type t 'agenda 'timeline)
8565 (let ((day (get-text-property (point) 'day))
8566 date s)
8567 (unless day
8568 (error "Don't know which date to convert"))
8569 (setq date (calendar-gregorian-from-absolute day))
8570 (setq s (concat
8571 "Gregorian: " (calendar-date-string date) "\n"
8572 "ISO: " (calendar-iso-date-string date) "\n"
8573 "Day of Yr: " (calendar-day-of-year-string date) "\n"
8574 "Julian: " (calendar-julian-date-string date) "\n"
8575 "Astron. JD: " (calendar-astro-date-string date)
8576 " (Julian date number at noon UTC)\n"
8577 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
8578 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
8579 "French: " (calendar-french-date-string date) "\n"
8580 "Mayan: " (calendar-mayan-date-string date) "\n"
8581 "Coptic: " (calendar-coptic-date-string date) "\n"
8582 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
8583 "Persian: " (calendar-persian-date-string date) "\n"
8584 "Chinese: " (calendar-chinese-date-string date) "\n"))
8585 (with-output-to-temp-buffer "*Dates*"
8586 (princ s))
8587 (if (fboundp 'fit-window-to-buffer)
8588 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
8589
8590 ;;; Tags
8591
8592 (defun org-scan-tags (action matcher &optional todo-only)
8593 "Scan headline tags with inheritance and produce output ACTION.
8594 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8595 evaluated, testing if a given set of tags qualifies a headline for
8596 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8597 are included in the output."
8598 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8599 (mapconcat 'regexp-quote
8600 (nreverse (cdr (reverse org-todo-keywords)))
8601 "\\|")
8602 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
8603 (props (list 'face nil
8604 'done-face 'org-done
8605 'undone-face nil
8606 'mouse-face 'highlight
8607 'keymap org-agenda-keymap
8608 'help-echo
8609 (format "mouse-2 or RET jump to org file %s"
8610 (abbreviate-file-name buffer-file-name))))
8611 lspos
8612 tags tags-list tags-alist (llast 0) rtn level category i txt
8613 todo marker)
8614 (save-excursion
8615 (goto-char (point-min))
8616 (when (eq action 'sparse-tree) (org-overview))
8617 (while (re-search-forward re nil t)
8618 (catch :skip
8619 (and (eq action 'agenda) (org-agenda-skip))
8620 (setq todo (if (match-end 1) (match-string 2))
8621 tags (if (match-end 4) (match-string 4)))
8622 (goto-char (setq lspos (1+ (match-beginning 0))))
8623 (setq level (funcall outline-level)
8624 category (org-get-category))
8625 (setq i llast llast level)
8626 ;; remove tag lists from same and sublevels
8627 (while (>= i level)
8628 (when (setq entry (assoc i tags-alist))
8629 (setq tags-alist (delete entry tags-alist)))
8630 (setq i (1- i)))
8631 ;; add the nex tags
8632 (when tags
8633 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8634 tags-alist
8635 (cons (cons level tags) tags-alist)))
8636 ;; compile tags for current headline
8637 (setq tags-list
8638 (if org-use-tag-inheritance
8639 (apply 'append (mapcar 'cdr tags-alist))
8640 tags))
8641 (when (and (or (not todo-only) todo)
8642 (eval matcher)
8643 (or (not org-agenda-skip-archived-trees)
8644 (not (member org-archive-tag tags-list))))
8645 ;; list this headline
8646 (if (eq action 'sparse-tree)
8647 (progn
8648 (org-show-hierarchy-above))
8649 (setq txt (org-format-agenda-item
8650 ""
8651 (concat
8652 (if org-tags-match-list-sublevels
8653 (make-string (1- level) ?.) "")
8654 (org-get-heading))
8655 category tags-list))
8656 (goto-char lspos)
8657 (setq marker (org-agenda-new-marker))
8658 (org-add-props txt props
8659 'org-marker marker 'org-hd-marker marker 'category category)
8660 (push txt rtn))
8661 ;; if we are to skip sublevels, jump to end of subtree
8662 (point)
8663 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8664 (when (and (eq action 'sparse-tree)
8665 (not org-sparse-tree-open-archived-trees))
8666 (org-hide-archived-subtrees (point-min) (point-max)))
8667 (nreverse rtn)))
8668
8669 (defun org-tags-sparse-tree (&optional arg match)
8670 "Create a sparse tree according to tags search string MATCH.
8671 MATCH can contain positive and negative selection of tags, like
8672 \"+WORK+URGENT-WITHBOSS\"."
8673 (interactive "P")
8674 (let ((org-show-following-heading nil)
8675 (org-show-hierarchy-above nil))
8676 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
8677
8678 (defun org-make-tags-matcher (match)
8679 "Create the TAGS matcher form for the tags-selecting string MATCH."
8680 (unless match
8681 ;; Get a new match request, with completion
8682 (setq org-last-tags-completion-table
8683 (or (org-get-buffer-tags)
8684 org-last-tags-completion-table))
8685 (setq match (completing-read
8686 "Tags: " 'org-tags-completion-function nil nil nil
8687 'org-tags-history)))
8688 ;; parse the string and create a lisp form
8689 (let ((match0 match) minus tag mm matcher orterms term orlist)
8690 (setq orterms (org-split-string match "|"))
8691 (while (setq term (pop orterms))
8692 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
8693 (setq minus (and (match-end 1)
8694 (equal (match-string 1 term) "-"))
8695 tag (match-string 2 term)
8696 term (substring term (match-end 0))
8697 mm (list 'member (downcase tag) 'tags-list)
8698 mm (if minus (list 'not mm) mm))
8699 (push mm matcher))
8700 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
8701 orlist)
8702 (setq matcher nil))
8703 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8704 ;; Return the string and lisp forms of the matcher
8705 (cons match0 matcher)))
8706
8707 ;;;###autoload
8708 (defun org-tags-view (&optional todo-only match keep-modes)
8709 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
8710 The prefix arg TODO-ONLY limits the search to TODO entries."
8711 (interactive "P")
8712 (org-agenda-maybe-reset-markers 'force)
8713 (org-compile-prefix-format org-agenda-prefix-format)
8714 (let* ((org-agenda-keep-modes keep-modes)
8715 (org-tags-match-list-sublevels
8716 (if todo-only t org-tags-match-list-sublevels))
8717 (win (selected-window))
8718 (completion-ignore-case t)
8719 rtn rtnall files file pos matcher
8720 buffer)
8721 (setq matcher (org-make-tags-matcher match)
8722 match (car matcher) matcher (cdr matcher))
8723 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
8724 (progn
8725 (delete-other-windows)
8726 (switch-to-buffer-other-window
8727 (get-buffer-create org-agenda-buffer-name))))
8728 (setq buffer-read-only nil)
8729 (erase-buffer)
8730 (org-agenda-mode) (setq buffer-read-only nil)
8731 (org-set-local 'org-agenda-type 'tags)
8732 (org-set-local 'org-agenda-redo-command
8733 (list 'org-tags-view (list 'quote todo-only)
8734 (list 'if 'current-prefix-arg nil match) t))
8735 (setq files (org-agenda-files)
8736 rtnall nil)
8737 (org-prepare-agenda-buffers files)
8738 (while (setq file (pop files))
8739 (catch 'nextfile
8740 (org-check-agenda-file file)
8741 (setq buffer (if (file-exists-p file)
8742 (org-get-agenda-file-buffer file)
8743 (error "No such file %s" file)))
8744 (if (not buffer)
8745 ;; If file does not exist, merror message to agenda
8746 (setq rtn (list
8747 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8748 rtnall (append rtnall rtn))
8749 (with-current-buffer buffer
8750 (unless (org-mode-p)
8751 (error "Agenda file %s is not in `org-mode'" file))
8752 (setq org-category-table (org-get-category-table))
8753 (save-excursion
8754 (save-restriction
8755 (if org-respect-restriction
8756 (if (org-region-active-p)
8757 ;; Respect a region to restrict search
8758 (narrow-to-region (region-beginning) (region-end)))
8759 ;; If we work for the calendar or many files,
8760 ;; get rid of any restriction
8761 (widen))
8762 (setq rtn (org-scan-tags 'agenda matcher todo-only))
8763 (setq rtnall (append rtnall rtn))))))))
8764 (insert "Headlines with TAGS match: ")
8765 (add-text-properties (point-min) (1- (point))
8766 (list 'face 'org-level-3))
8767 (setq pos (point))
8768 (insert match "\n")
8769 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
8770 (setq pos (point))
8771 (insert "Press `C-u r' to search again with new search string\n")
8772 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
8773 (when rtnall
8774 (insert (mapconcat 'identity rtnall "\n")))
8775 (goto-char (point-min))
8776 (setq buffer-read-only t)
8777 (org-fit-agenda-window)
8778 (if (not org-select-agenda-window) (select-window win))))
8779
8780 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8781 (defun org-set-tags (&optional arg just-align)
8782 "Set the tags for the current headline.
8783 With prefix ARG, realign all tags in headings in the current buffer."
8784 (interactive "P")
8785 (let* ((re (concat "^" outline-regexp))
8786 (col (current-column))
8787 (current (org-get-tags))
8788 table current-tags inherited-tags ; computed below when needed
8789 tags hd empty invis)
8790 (if arg
8791 (save-excursion
8792 (goto-char (point-min))
8793 (while (re-search-forward re nil t)
8794 (org-set-tags nil t))
8795 (message "All tags realigned to column %d" org-tags-column))
8796 (if just-align
8797 (setq tags current)
8798 (setq table (or org-tag-alist (org-get-buffer-tags))
8799 org-last-tags-completion-table table
8800 current-tags (org-split-string current ":")
8801 inherited-tags (nreverse
8802 (nthcdr (length current-tags)
8803 (nreverse (org-get-tags-at))))
8804 tags
8805 (if (or (eq t org-use-fast-tag-selection)
8806 (and org-use-fast-tag-selection
8807 (delq nil (mapcar 'cdr table))))
8808 (org-fast-tag-selection current-tags inherited-tags table)
8809 (let ((org-add-colon-after-tag-completion t))
8810 (completing-read "Tags: " 'org-tags-completion-function
8811 nil nil current 'org-tags-history))))
8812 (while (string-match "[-+&]+" tags)
8813 (setq tags (replace-match ":" t t tags))))
8814
8815 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
8816 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8817 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8818 (if (equal current "")
8819 (progn
8820 (end-of-line 1)
8821 (or empty (insert-before-markers " ")))
8822 (beginning-of-line 1)
8823 (setq invis (org-invisible-p))
8824 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
8825 (setq hd (match-string 1))
8826 (delete-region (match-beginning 0) (match-end 0))
8827 (insert-before-markers (org-trim hd) (if empty "" " ")))
8828 (if (equal tags "")
8829 (save-excursion
8830 (beginning-of-line 1)
8831 (skip-chars-forward "*")
8832 (if (= (char-after) ?\ ) (forward-char 1))
8833 (and (re-search-forward "[ \t]+$" (point-at-eol) t)
8834 (replace-match "")))
8835 (move-to-column (max (current-column)
8836 (if (> org-tags-column 0)
8837 org-tags-column
8838 (- (- org-tags-column) (length tags))))
8839 t)
8840 (insert-before-markers tags)
8841 (if (and (not invis) (org-invisible-p))
8842 (outline-flag-region (point-at-bol) (point) nil)))
8843 (move-to-column col))))
8844
8845 (defun org-tags-completion-function (string predicate &optional flag)
8846 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8847 (confirm (lambda (x) (stringp (car x)))))
8848 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8849 (setq s1 (match-string 1 string)
8850 s2 (match-string 2 string))
8851 (setq s1 "" s2 string))
8852 (cond
8853 ((eq flag nil)
8854 ;; try completion
8855 (setq rtn (try-completion s2 ctable confirm))
8856 (if (stringp rtn)
8857 (concat s1 s2 (substring rtn (length s2))
8858 (if (and org-add-colon-after-tag-completion
8859 (assoc rtn ctable))
8860 ":" "")))
8861 )
8862 ((eq flag t)
8863 ;; all-completions
8864 (all-completions s2 ctable confirm)
8865 )
8866 ((eq flag 'lambda)
8867 ;; exact match?
8868 (assoc s2 ctable)))
8869 ))
8870
8871 (defun org-fast-tag-insert (kwd tags face &optional end)
8872 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
8873 (insert (format "%-12s" (concat kwd ":"))
8874 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
8875 (or end "")))
8876
8877 (defun org-fast-tag-selection (current inherited table)
8878 "Fast tag selection with single keys.
8879 CURRENT is the current list of tags in the headline, INHERITED is the
8880 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
8881 possibly with grouping information.
8882 If the keys are nil, a-z are automatically assigned.
8883 Returns the new tags string, or nil to not change the current settings."
8884 (let* ((maxlen (apply 'max (mapcar
8885 (lambda (x)
8886 (if (stringp (car x)) (string-width (car x)) 0))
8887 table)))
8888 (fwidth (+ maxlen 3 1 3))
8889 (ncol (/ (- (window-width) 4) fwidth))
8890 (i-face 'org-done)
8891 (c-face 'org-tag)
8892 tg cnt e c char c1 c2 ntable tbl rtn
8893 groups ingroup)
8894 (save-window-excursion
8895 (delete-other-windows)
8896 (split-window-vertically)
8897 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
8898 (erase-buffer)
8899 (org-fast-tag-insert "Inherited" inherited i-face "\n")
8900 (org-fast-tag-insert "Current" current c-face "\n\n")
8901 (setq tbl table char ?a cnt 0)
8902 (while (setq e (pop tbl))
8903 (cond
8904 ((equal e '(:startgroup))
8905 (push '() groups) (setq ingroup t)
8906 (when (not (= cnt 0))
8907 (setq cnt 0)
8908 (insert "\n"))
8909 (insert "{ "))
8910 ((equal e '(:endgroup))
8911 (setq ingroup nil cnt 0)
8912 (insert "}\n"))
8913 (t
8914 (setq tg (car e) c2 nil)
8915 (if (cdr e)
8916 (setq c (cdr e))
8917 ;; automatically assign a character.
8918 (setq c1 (string-to-char
8919 (downcase (substring
8920 tg (if (= (string-to-char tg) ?@) 1 0)))))
8921 (if (or (rassoc c1 ntable) (rassoc c1 table))
8922 (while (or (rassoc char ntable) (rassoc char table))
8923 (setq char (1+ char)))
8924 (setq c2 c1))
8925 (setq c (or c2 char)))
8926 (if ingroup (push tg (car groups)))
8927 (setq tg (org-add-props tg nil 'face
8928 (cond
8929 ((member tg current) c-face)
8930 ((member tg inherited) i-face)
8931 (t nil))))
8932 (if (and (= cnt 0) (not ingroup)) (insert " "))
8933 (insert "[" c "] " tg (make-string
8934 (- fwidth 4 (length tg)) ?\ ))
8935 (push (cons tg c) ntable)
8936 (when (= (setq cnt (1+ cnt)) ncol)
8937 (insert "\n")
8938 (if ingroup (insert " "))
8939 (setq cnt 0)))))
8940 (setq ntable (nreverse ntable))
8941 (insert "\n")
8942 (goto-char (point-min))
8943 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
8944 (setq rtn
8945 (catch 'exit
8946 (while t
8947 (message "[key]:Toggle SPC: clear current RET accept%s"
8948 (if groups " [!] ignore goups" ""))
8949 (setq c (read-char-exclusive))
8950 (cond
8951 ((= c ?\r) (throw 'exit t))
8952 ((= c ?!)
8953 (setq groups nil)
8954 (goto-char (point-min))
8955 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
8956 ((or (= c ?\C-g)
8957 (and (= c ?q) (not (rassoc c ntable))))
8958 (setq quit-flag t))
8959 ((= c ?\ ) (setq current nil))
8960 ((setq e (rassoc c ntable) tg (car e))
8961 (if (member tg current)
8962 (setq current (delete tg current))
8963 (loop for g in groups do
8964 (if (member tg g)
8965 (mapcar (lambda (x)
8966 (setq current (delete x current)))
8967 g)))
8968 (setq current (cons tg current)))))
8969 ;; Create a sorted list
8970 (setq current
8971 (sort current
8972 (lambda (a b)
8973 (assoc b (cdr (memq (assoc a ntable) ntable))))))
8974 (goto-char (point-min))
8975 (beginning-of-line 2)
8976 (delete-region (point) (point-at-eol))
8977 (org-fast-tag-insert "Current" current c-face)
8978 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
8979 (setq tg (match-string 1))
8980 (add-text-properties (match-beginning 1) (match-end 1)
8981 (list 'face
8982 (cond
8983 ((member tg current) c-face)
8984 ((member tg inherited) i-face)
8985 (t nil)))))
8986 (goto-char (point-min)))))
8987 (if rtn
8988 (mapconcat 'identity current ":")
8989 nil))))
8990
8991 (defun org-get-tags ()
8992 "Get the TAGS string in the current headline."
8993 (unless (org-on-heading-p)
8994 (error "Not on a heading"))
8995 (save-excursion
8996 (beginning-of-line 1)
8997 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
8998 (org-match-string-no-properties 1)
8999 "")))
9000
9001 (defun org-get-buffer-tags ()
9002 "Get a table of all tags used in the buffer, for completion."
9003 (let (tags)
9004 (save-excursion
9005 (goto-char (point-min))
9006 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
9007 (mapc (lambda (x) (add-to-list 'tags x))
9008 (org-split-string (org-match-string-no-properties 1) ":"))))
9009 (mapcar 'list tags)))
9010
9011 ;;; Link Stuff
9012
9013 (defvar org-create-file-search-functions nil
9014 "List of functions to construct the right search string for a file link.
9015 These functions are called in turn with point at the location to
9016 which the link should point.
9017
9018 A function in the hook should first test if it would like to
9019 handle this file type, for example by checking the major-mode or
9020 the file extension. If it decides not to handle this file, it
9021 should just return nil to give other functions a chance. If it
9022 does handle the file, it must return the search string to be used
9023 when following the link. The search string will be part of the
9024 file link, given after a double colon, and `org-open-at-point'
9025 will automatically search for it. If special measures must be
9026 taken to make the search successful, another function should be
9027 added to the companion hook `org-execute-file-search-functions',
9028 which see.
9029
9030 A function in this hook may also use `setq' to set the variable
9031 `description' to provide a suggestion for the descriptive text to
9032 be used for this link when it gets inserted into an Org-mode
9033 buffer with \\[org-insert-link].")
9034
9035 (defvar org-execute-file-search-functions nil
9036 "List of functions to execute a file search triggered by a link.
9037
9038 Functions added to this hook must accept a single argument, the
9039 search string that was part of the file link, the part after the
9040 double colon. The function must first check if it would like to
9041 handle this search, for example by checking the major-mode or the
9042 file extension. If it decides not to handle this search, it
9043 should just return nil to give other functions a chance. If it
9044 does handle the search, it must return a non-nil value to keep
9045 other functions from trying.
9046
9047 Each function can access the current prefix argument through the
9048 variable `current-prefix-argument'. Note that a single prefix is
9049 used to force opening a link in Emacs, so it may be good to only
9050 use a numeric or double prefix to guide the search function.
9051
9052 In case this is needed, a function in this hook can also restore
9053 the window configuration before `org-open-at-point' was called using:
9054
9055 (set-window-configuration org-window-config-before-follow-link)")
9056
9057 (defun org-find-file-at-mouse (ev)
9058 "Open file link or URL at mouse."
9059 (interactive "e")
9060 (mouse-set-point ev)
9061 (org-open-at-point 'in-emacs))
9062
9063 (defun org-open-at-mouse (ev)
9064 "Open file link or URL at mouse."
9065 (interactive "e")
9066 (mouse-set-point ev)
9067 (org-open-at-point))
9068
9069 (defvar org-window-config-before-follow-link nil
9070 "The window configuration before following a link.
9071 This is saved in case the need arises to restore it.")
9072
9073 (defun org-open-at-point (&optional in-emacs)
9074 "Open link at or after point.
9075 If there is no link at point, this function will search forward up to
9076 the end of the current subtree.
9077 Normally, files will be opened by an appropriate application. If the
9078 optional argument IN-EMACS is non-nil, Emacs will visit the file."
9079 (interactive "P")
9080 (setq org-window-config-before-follow-link (current-window-configuration))
9081 (org-remove-occur-highlights nil nil t)
9082 (if (org-at-timestamp-p)
9083 (org-agenda-list nil (time-to-days (org-time-string-to-time
9084 (substring (match-string 1) 0 10)))
9085 1)
9086 (let (type path link line search (pos (point)))
9087 (catch 'match
9088 (save-excursion
9089 (skip-chars-forward "^]\n\r")
9090 (when (and (re-search-backward "\\[\\[" nil t)
9091 (looking-at org-bracket-link-regexp)
9092 (<= (match-beginning 0) pos)
9093 (>= (match-end 0) pos))
9094 (setq link (org-link-unescape (org-match-string-no-properties 1)))
9095 (while (string-match " *\n *" link)
9096 (setq link (replace-match " " t t link)))
9097 (if (string-match org-link-re-with-space2 link)
9098 (setq type (match-string 1 link)
9099 path (match-string 2 link))
9100 (setq type "thisfile"
9101 path link))
9102 (throw 'match t)))
9103
9104 (when (get-text-property (point) 'org-linked-text)
9105 (setq type "thisfile"
9106 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9107 (1+ (point)) (point))
9108 path (buffer-substring
9109 (previous-single-property-change pos 'org-linked-text)
9110 (next-single-property-change pos 'org-linked-text)))
9111 (throw 'match t))
9112
9113 (save-excursion
9114 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
9115 (if (equal (char-before) ?<) (backward-char 1))
9116 (when (or (looking-at org-angle-link-re)
9117 (looking-at org-plain-link-re)
9118 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
9119 (re-search-forward org-plain-link-re (point-at-eol) t))
9120 (<= (match-beginning 0) pos)
9121 (>= (match-end 0) pos)))
9122 (setq type (match-string 1)
9123 path (match-string 2))
9124 (throw 'match t)))
9125 (save-excursion
9126 (skip-chars-backward "^ \t\n\r")
9127 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9128 (setq type "tags"
9129 path (match-string 1))
9130 (while (string-match ":" path)
9131 (setq path (replace-match "+" t t path)))
9132 (throw 'match t)))
9133 (save-excursion
9134 (skip-chars-backward "a-zA-Z_")
9135 (when (and (memq 'camel org-activate-links)
9136 (looking-at org-camel-regexp))
9137 (setq type "camel" path (match-string 0))
9138 (if (equal (char-before) ?*)
9139 (setq path (concat "*" path))))
9140 (throw 'match t)))
9141 (unless path
9142 (error "No link found"))
9143 ;; Remove any trailing spaces in path
9144 (if (string-match " +\\'" path)
9145 (setq path (replace-match "" t t path)))
9146
9147 (cond
9148
9149 ((member type '("http" "https" "ftp" "mailto" "news"))
9150 (browse-url (concat type ":" path)))
9151
9152 ((string= type "tags")
9153 (org-tags-view in-emacs path))
9154 ((or (string= type "camel")
9155 (string= type "thisfile"))
9156 (org-mark-ring-push)
9157 (org-link-search
9158 path
9159 (cond ((equal in-emacs '(4)) 'occur)
9160 ((equal in-emacs '(16)) 'org-occur)
9161 (t nil))))
9162
9163 ((string= type "file")
9164 (if (string-match "::\\([0-9]+\\)\\'" path)
9165 (setq line (string-to-number (match-string 1 path))
9166 path (substring path 0 (match-beginning 0)))
9167 (if (string-match "::\\(.+\\)\\'" path)
9168 (setq search (match-string 1 path)
9169 path (substring path 0 (match-beginning 0)))))
9170 (org-open-file path in-emacs line search))
9171
9172 ((string= type "news")
9173 (org-follow-gnus-link path))
9174
9175 ((string= type "bbdb")
9176 (org-follow-bbdb-link path))
9177
9178 ((string= type "info")
9179 (org-follow-info-link path))
9180
9181 ((string= type "gnus")
9182 (let (group article)
9183 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9184 (error "Error in Gnus link"))
9185 (setq group (match-string 1 path)
9186 article (match-string 3 path))
9187 (org-follow-gnus-link group article)))
9188
9189 ((string= type "vm")
9190 (let (folder article)
9191 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9192 (error "Error in VM link"))
9193 (setq folder (match-string 1 path)
9194 article (match-string 3 path))
9195 ;; in-emacs is the prefix arg, will be interpreted as read-only
9196 (org-follow-vm-link folder article in-emacs)))
9197
9198 ((string= type "wl")
9199 (let (folder article)
9200 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9201 (error "Error in Wanderlust link"))
9202 (setq folder (match-string 1 path)
9203 article (match-string 3 path))
9204 (org-follow-wl-link folder article)))
9205
9206 ((string= type "mhe")
9207 (let (folder article)
9208 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9209 (error "Error in MHE link"))
9210 (setq folder (match-string 1 path)
9211 article (match-string 3 path))
9212 (org-follow-mhe-link folder article)))
9213
9214 ((string= type "rmail")
9215 (let (folder article)
9216 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9217 (error "Error in RMAIL link"))
9218 (setq folder (match-string 1 path)
9219 article (match-string 3 path))
9220 (org-follow-rmail-link folder article)))
9221
9222 ((string= type "shell")
9223 (let ((cmd path))
9224 (while (string-match "@{" cmd)
9225 (setq cmd (replace-match "<" t t cmd)))
9226 (while (string-match "@}" cmd)
9227 (setq cmd (replace-match ">" t t cmd)))
9228 (if (or (not org-confirm-shell-link-function)
9229 (funcall org-confirm-shell-link-function
9230 (format "Execute \"%s\" in shell? "
9231 (org-add-props cmd nil
9232 'face 'org-warning))))
9233 (progn
9234 (message "Executing %s" cmd)
9235 (shell-command cmd))
9236 (error "Abort"))))
9237
9238 ((string= type "elisp")
9239 (let ((cmd path))
9240 (if (or (not org-confirm-elisp-link-function)
9241 (funcall org-confirm-elisp-link-function
9242 (format "Execute \"%s\" as elisp? "
9243 (org-add-props cmd nil
9244 'face 'org-warning))))
9245 (message "%s => %s" cmd (eval (read cmd)))
9246 (error "Abort"))))
9247
9248 (t
9249 (browse-url-at-point))))))
9250
9251 (defun org-link-search (s &optional type)
9252 "Search for a link search option.
9253 When S is a CamelCaseWord, search for a target, or for a sentence containing
9254 the words. If S is surrounded by forward slashes, it is interpreted as a
9255 regular expression. In org-mode files, this will create an `org-occur'
9256 sparse tree. In ordinary files, `occur' will be used to list matches.
9257 If the current buffer is in `dired-mode', grep will be used to search
9258 in all files."
9259 (let ((case-fold-search t)
9260 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9261 (pos (point))
9262 (pre "") (post "")
9263 words re0 re1 re2 re3 re4 re5 re2a reall camel)
9264 (cond
9265 ;; First check if there are any special
9266 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9267 ;; Now try the builtin stuff
9268 ((save-excursion
9269 (goto-char (point-min))
9270 (and
9271 (re-search-forward
9272 (concat "<<" (regexp-quote s0) ">>") nil t)
9273 (setq pos (match-beginning 0))))
9274 ;; There is an exact target for this
9275 (goto-char pos))
9276 ((string-match "^/\\(.*\\)/$" s)
9277 ;; A regular expression
9278 (cond
9279 ((org-mode-p)
9280 (org-occur (match-string 1 s)))
9281 ;;((eq major-mode 'dired-mode)
9282 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9283 (t (org-do-occur (match-string 1 s)))))
9284 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
9285 t)
9286 ;; A camel or a normal search string
9287 (when (equal (string-to-char s) ?*)
9288 ;; Anchor on headlines, post may include tags.
9289 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9290 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9291 s (substring s 1)))
9292 (remove-text-properties
9293 0 (length s)
9294 '(face nil mouse-face nil keymap nil fontified nil) s)
9295 ;; Make a series of regular expressions to find a match
9296 (setq words
9297 (if camel
9298 (org-camel-to-words s)
9299 (org-split-string s "[ \n\r\t]+"))
9300 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9301 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9302 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9303 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9304 re1 (concat pre re2 post)
9305 re3 (concat pre re4 post)
9306 re5 (concat pre ".*" re4)
9307 re2 (concat pre re2)
9308 re2a (concat pre re2a)
9309 re4 (concat pre re4)
9310 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9311 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9312 re5 "\\)"
9313 ))
9314 (cond
9315 ((eq type 'org-occur) (org-occur reall))
9316 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9317 (t (goto-char (point-min))
9318 (if (or (org-search-not-link re0 nil t)
9319 (org-search-not-link re1 nil t)
9320 (org-search-not-link re2 nil t)
9321 (org-search-not-link re2a nil t)
9322 (org-search-not-link re3 nil t)
9323 (org-search-not-link re4 nil t)
9324 (org-search-not-link re5 nil t)
9325 )
9326 (goto-char (match-beginning 1))
9327 (goto-char pos)
9328 (error "No match")))))
9329 (t
9330 ;; Normal string-search
9331 (goto-char (point-min))
9332 (if (search-forward s nil t)
9333 (goto-char (match-beginning 0))
9334 (error "No match"))))
9335 (and (org-mode-p) (org-show-hierarchy-above))))
9336
9337 (defun org-search-not-link (&rest args)
9338 "Execute `re-search-forward', but only accept matches that are not a link."
9339 (catch 'exit
9340 (let (p1)
9341 (while (apply 're-search-forward args)
9342 (setq p1 (point))
9343 (if (not (save-match-data
9344 (and (re-search-backward "\\[\\[" nil t)
9345 (looking-at org-bracket-link-regexp)
9346 (<= (match-beginning 0) p1)
9347 (>= (match-end 0) p1))))
9348 (progn (goto-char (match-end 0))
9349 (throw 'exit (point)))
9350 (goto-char (match-end 0)))))))
9351
9352 (defun org-do-occur (regexp &optional cleanup)
9353 "Call the Emacs command `occur'.
9354 If CLEANUP is non-nil, remove the printout of the regular expression
9355 in the *Occur* buffer. This is useful if the regex is long and not useful
9356 to read."
9357 (occur regexp)
9358 (when cleanup
9359 (let ((cwin (selected-window)) win beg end)
9360 (when (setq win (get-buffer-window "*Occur*"))
9361 (select-window win))
9362 (goto-char (point-min))
9363 (when (re-search-forward "match[a-z]+" nil t)
9364 (setq beg (match-end 0))
9365 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9366 (setq end (1- (match-beginning 0)))))
9367 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9368 (goto-char (point-min))
9369 (select-window cwin))))
9370
9371 (defvar org-mark-ring nil
9372 "Mark ring for positions before jumps in Org-mode.")
9373 (defvar org-mark-ring-last-goto nil
9374 "Last position in the mark ring used to go back.")
9375 ;; Fill and close the ring
9376 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9377 (loop for i from 1 to org-mark-ring-length do
9378 (push (make-marker) org-mark-ring))
9379 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9380 org-mark-ring)
9381
9382 (defun org-mark-ring-push (&optional pos buffer)
9383 "Put the current position or POS into the mark ring and rotate it."
9384 (interactive)
9385 (setq pos (or pos (point)))
9386 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9387 (move-marker (car org-mark-ring)
9388 (or pos (point))
9389 (or buffer (current-buffer)))
9390 (message
9391 (substitute-command-keys
9392 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9393
9394 (defun org-mark-ring-goto (&optional n)
9395 "Jump to the previous position in the mark ring.
9396 With prefix arg N, jump back that many stored positions. When
9397 called several times in succession, walk through the entire ring.
9398 Org-mode commands jumping to a different position in the current file,
9399 or to another Org-mode file, automatically push the old position
9400 onto the ring."
9401 (interactive "p")
9402 (let (p m)
9403 (if (eq last-command this-command)
9404 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9405 (setq p org-mark-ring))
9406 (setq org-mark-ring-last-goto p)
9407 (setq m (car p))
9408 (switch-to-buffer (marker-buffer m))
9409 (goto-char m)
9410 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
9411
9412 (defun org-camel-to-words (s)
9413 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
9414 (let ((case-fold-search nil)
9415 words)
9416 (while (string-match "[a-z][A-Z]" s)
9417 (push (substring s 0 (1+ (match-beginning 0))) words)
9418 (setq s (substring s (1+ (match-beginning 0)))))
9419 (nreverse (cons s words))))
9420
9421 (defun org-remove-angle-brackets (s)
9422 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9423 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9424 s)
9425 (defun org-add-angle-brackets (s)
9426 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9427 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9428 s)
9429
9430 (defun org-follow-bbdb-link (name)
9431 "Follow a BBDB link to NAME."
9432 (require 'bbdb)
9433 (let ((inhibit-redisplay t)
9434 (bbdb-electric-p nil))
9435 (catch 'exit
9436 ;; Exact match on name
9437 (bbdb-name (concat "\\`" name "\\'") nil)
9438 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9439 ;; Exact match on name
9440 (bbdb-company (concat "\\`" name "\\'") nil)
9441 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9442 ;; Partial match on name
9443 (bbdb-name name nil)
9444 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9445 ;; Partial match on company
9446 (bbdb-company name nil)
9447 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9448 ;; General match including network address and notes
9449 (bbdb name nil)
9450 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9451 (delete-window (get-buffer-window "*BBDB*"))
9452 (error "No matching BBDB record")))))
9453
9454
9455 (defun org-follow-info-link (name)
9456 "Follow an info file & node link to NAME."
9457 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9458 (string-match "\\(.*\\)" name))
9459 (progn
9460 (require 'info)
9461 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9462 (Info-find-node (match-string 1 name) (match-string 2 name))
9463 (Info-find-node (match-string 1 name) "Top")))
9464 (message (concat "Could not open: " name))))
9465
9466 (defun org-follow-gnus-link (&optional group article)
9467 "Follow a Gnus link to GROUP and ARTICLE."
9468 (require 'gnus)
9469 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9470 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
9471 (if group (gnus-fetch-group group))
9472 (if article
9473 (or (gnus-summary-goto-article article nil 'force)
9474 (if (fboundp 'gnus-summary-insert-cached-articles)
9475 (progn
9476 (gnus-summary-insert-cached-articles)
9477 (gnus-summary-goto-article article nil 'force))
9478 (message "Message could not be found.")))))
9479
9480 (defun org-follow-vm-link (&optional folder article readonly)
9481 "Follow a VM link to FOLDER and ARTICLE."
9482 (require 'vm)
9483 (setq article (org-add-angle-brackets article))
9484 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9485 ;; ange-ftp or efs or tramp access
9486 (let ((user (or (match-string 1 folder) (user-login-name)))
9487 (host (match-string 2 folder))
9488 (file (match-string 3 folder)))
9489 (cond
9490 ((featurep 'tramp)
9491 ;; use tramp to access the file
9492 (if (featurep 'xemacs)
9493 (setq folder (format "[%s@%s]%s" user host file))
9494 (setq folder (format "/%s@%s:%s" user host file))))
9495 (t
9496 ;; use ange-ftp or efs
9497 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9498 (setq folder (format "/%s@%s:%s" user host file))))))
9499 (when folder
9500 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9501 (sit-for 0.1)
9502 (when article
9503 (vm-select-folder-buffer)
9504 (widen)
9505 (let ((case-fold-search t))
9506 (goto-char (point-min))
9507 (if (not (re-search-forward
9508 (concat "^" "message-id: *" (regexp-quote article))))
9509 (error "Could not find the specified message in this folder"))
9510 (vm-isearch-update)
9511 (vm-isearch-narrow)
9512 (vm-beginning-of-message)
9513 (vm-summarize)))))
9514
9515 (defun org-follow-wl-link (folder article)
9516 "Follow a Wanderlust link to FOLDER and ARTICLE."
9517 (setq article (org-add-angle-brackets article))
9518 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
9519 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
9520 (wl-summary-redisplay))
9521
9522 (defun org-follow-rmail-link (folder article)
9523 "Follow an RMAIL link to FOLDER and ARTICLE."
9524 (setq article (org-add-angle-brackets article))
9525 (let (message-number)
9526 (save-excursion
9527 (save-window-excursion
9528 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9529 (setq message-number
9530 (save-restriction
9531 (widen)
9532 (goto-char (point-max))
9533 (if (re-search-backward
9534 (concat "^Message-ID:\\s-+" (regexp-quote
9535 (or article "")))
9536 nil t)
9537 (rmail-what-message))))))
9538 (if message-number
9539 (progn
9540 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9541 (rmail-show-message message-number)
9542 message-number)
9543 (error "Message not found"))))
9544
9545 ;; mh-e integration based on planner-mode
9546 (defun org-mhe-get-message-real-folder ()
9547 "Return the name of the current message real folder, so if you use
9548 sequences, it will now work."
9549 (save-excursion
9550 (let* ((folder
9551 (if (equal major-mode 'mh-folder-mode)
9552 mh-current-folder
9553 ;; Refer to the show buffer
9554 mh-show-folder-buffer))
9555 (end-index
9556 (if (boundp 'mh-index-folder)
9557 (min (length mh-index-folder) (length folder))))
9558 )
9559 ;; a simple test on mh-index-data does not work, because
9560 ;; mh-index-data is always nil in a show buffer.
9561 (if (and (boundp 'mh-index-folder)
9562 (string= mh-index-folder (substring folder 0 end-index)))
9563 (if (equal major-mode 'mh-show-mode)
9564 (save-window-excursion
9565 (when (buffer-live-p (get-buffer folder))
9566 (progn
9567 (pop-to-buffer folder)
9568 (org-mhe-get-message-folder-from-index)
9569 )
9570 ))
9571 (org-mhe-get-message-folder-from-index)
9572 )
9573 folder
9574 )
9575 )))
9576
9577 (defun org-mhe-get-message-folder-from-index ()
9578 "Returns the name of the message folder in a index folder buffer."
9579 (save-excursion
9580 (mh-index-previous-folder)
9581 (re-search-forward "^\\(+.*\\)$" nil t)
9582 (message (match-string 1))))
9583
9584 (defun org-mhe-get-message-folder ()
9585 "Return the name of the current message folder. Be careful if you
9586 use sequences."
9587 (save-excursion
9588 (if (equal major-mode 'mh-folder-mode)
9589 mh-current-folder
9590 ;; Refer to the show buffer
9591 mh-show-folder-buffer)))
9592
9593 (defun org-mhe-get-message-num ()
9594 "Return the number of the current message. Be careful if you
9595 use sequences."
9596 (save-excursion
9597 (if (equal major-mode 'mh-folder-mode)
9598 (mh-get-msg-num nil)
9599 ;; Refer to the show buffer
9600 (mh-show-buffer-message-number))))
9601
9602 (defun org-mhe-get-header (header)
9603 "Return a header of the message in folder mode. This will create a
9604 show buffer for the corresponding message. If you have a more clever
9605 idea..."
9606 (let* ((folder (org-mhe-get-message-folder))
9607 (num (org-mhe-get-message-num))
9608 (buffer (get-buffer-create (concat "show-" folder)))
9609 (header-field))
9610 (with-current-buffer buffer
9611 (mh-display-msg num folder)
9612 (if (equal major-mode 'mh-folder-mode)
9613 (mh-header-display)
9614 (mh-show-header-display))
9615 (set-buffer buffer)
9616 (setq header-field (mh-get-header-field header))
9617 (if (equal major-mode 'mh-folder-mode)
9618 (mh-show)
9619 (mh-show-show))
9620 header-field)))
9621
9622 (defun org-follow-mhe-link (folder article)
9623 "Follow an MHE link to FOLDER and ARTICLE.
9624 If ARTICLE is nil FOLDER is shown. If the configuration variable
9625 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9626 ARTICLE is searched in all folders. Indexed searches (swish++,
9627 namazu, and others supported by MH-E) will always search in all
9628 folders."
9629 (require 'mh-e)
9630 (require 'mh-search)
9631 (require 'mh-utils)
9632 (mh-find-path)
9633 (if (not article)
9634 (mh-visit-folder (mh-normalize-folder-name folder))
9635 (setq article (org-add-angle-brackets article))
9636 (mh-search-choose)
9637 (if (equal mh-searcher 'pick)
9638 (progn
9639 (mh-search folder (list "--message-id" article))
9640 (when (and org-mhe-search-all-folders
9641 (not (org-mhe-get-message-real-folder)))
9642 (kill-this-buffer)
9643 (mh-search "+" (list "--message-id" article))))
9644 (mh-search "+" article))
9645 (if (org-mhe-get-message-real-folder)
9646 (mh-show-msg 1)
9647 (kill-this-buffer)
9648 (error "Message not found"))))
9649
9650 ;; BibTeX links
9651
9652 ;; Use the custom search meachnism to construct and use search strings for
9653 ;; file links to BibTeX database entries.
9654
9655 (defun org-create-file-search-in-bibtex ()
9656 "Create the search string and description for a BibTeX database entry."
9657 (when (eq major-mode 'bibtex-mode)
9658 ;; yes, we want to construct this search string.
9659 ;; Make a good description for this entry, using names, year and the title
9660 ;; Put it into the `description' variable which is dynamically scoped.
9661 (let ((bibtex-autokey-names 1)
9662 (bibtex-autokey-names-stretch 1)
9663 (bibtex-autokey-name-case-convert-function 'identity)
9664 (bibtex-autokey-name-separator " & ")
9665 (bibtex-autokey-additional-names " et al.")
9666 (bibtex-autokey-year-length 4)
9667 (bibtex-autokey-name-year-separator " ")
9668 (bibtex-autokey-titlewords 3)
9669 (bibtex-autokey-titleword-separator " ")
9670 (bibtex-autokey-titleword-case-convert-function 'identity)
9671 (bibtex-autokey-titleword-length 'infty)
9672 (bibtex-autokey-year-title-separator ": "))
9673 (setq description (bibtex-generate-autokey)))
9674 ;; Now parse the entry, get the key and return it.
9675 (save-excursion
9676 (bibtex-beginning-of-entry)
9677 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9678
9679 (defun org-execute-file-search-in-bibtex (s)
9680 "Find the link search string S as a key for a database entry."
9681 (when (eq major-mode 'bibtex-mode)
9682 ;; Yes, we want to do the search in this file.
9683 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9684 (goto-char (point-min))
9685 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9686 (regexp-quote s) "[ \t\n]*,") nil t)
9687 (goto-char (match-beginning 0)))
9688 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9689 ;; Use double prefix to indicate that any web link should be browsed
9690 (let ((b (current-buffer)) (p (point)))
9691 ;; Restore the window configuration because we just use the web link
9692 (set-window-configuration org-window-config-before-follow-link)
9693 (save-excursion (set-buffer b) (goto-char p)
9694 (bibtex-url)))
9695 (recenter 0)) ; Move entry start to beginning of window
9696 ;; return t to indicate that the search is done.
9697 t))
9698
9699 ;; Finally add the functions to the right hooks.
9700 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9701 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9702
9703 ;; end of Bibtex link setup
9704
9705 (defun org-upgrade-old-links (&optional query-description)
9706 "Transfer old <...> style links to new [[...]] style links.
9707 With arg query-description, ask at each match for a description text to use
9708 for this link."
9709 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
9710 (save-excursion
9711 (goto-char (point-min))
9712 (let ((re (concat "\\([^[]\\)<\\("
9713 "\\(" (mapconcat 'identity org-link-types "\\|")
9714 "\\):"
9715 "[^" org-non-link-chars "]+\\)>"))
9716 l1 l2 (cnt 0))
9717 (while (re-search-forward re nil t)
9718 (setq cnt (1+ cnt)
9719 l1 (org-match-string-no-properties 2)
9720 l2 (save-match-data (org-link-escape l1)))
9721 (when query-description (setq l1 (read-string "Desc: " l1)))
9722 (if (equal l1 l2)
9723 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
9724 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
9725 (message "%d matches have beed treated" cnt))))
9726
9727 (defun org-open-file (path &optional in-emacs line search)
9728 "Open the file at PATH.
9729 First, this expands any special file name abbreviations. Then the
9730 configuration variable `org-file-apps' is checked if it contains an
9731 entry for this file type, and if yes, the corresponding command is launched.
9732 If no application is found, Emacs simply visits the file.
9733 With optional argument IN-EMACS, Emacs will visit the file.
9734 Optional LINE specifies a line to go to, optional SEARCH a string to
9735 search for. If LINE or SEARCH is given, the file will always be
9736 opened in Emacs.
9737 If the file does not exist, an error is thrown."
9738 (setq in-emacs (or in-emacs line search))
9739 (let* ((file (if (equal path "")
9740 buffer-file-name
9741 path))
9742 (apps (append org-file-apps (org-default-apps)))
9743 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9744 (dirp (if remp nil (file-directory-p file)))
9745 (dfile (downcase file))
9746 (old-buffer (current-buffer))
9747 (old-pos (point))
9748 (old-mode major-mode)
9749 ext cmd)
9750 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9751 (setq ext (match-string 1 dfile))
9752 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9753 (setq ext (match-string 1 dfile))))
9754 (if in-emacs
9755 (setq cmd 'emacs)
9756 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9757 (and dirp (cdr (assoc 'directory apps)))
9758 (cdr (assoc ext apps))
9759 (cdr (assoc t apps)))))
9760 (when (eq cmd 'mailcap)
9761 (require 'mailcap)
9762 (mailcap-parse-mailcaps)
9763 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9764 (command (mailcap-mime-info mime-type)))
9765 (if (stringp command)
9766 (setq cmd command)
9767 (setq cmd 'emacs))))
9768 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
9769 (not (file-exists-p file))
9770 (not org-open-non-existing-files))
9771 (error "No such file: %s" file))
9772 (cond
9773 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9774 ;; Normalize use of quote, this can vary.
9775 (if (string-match "['\"]%s['\"]" cmd)
9776 (setq cmd (replace-match "'%s'" t t cmd)))
9777 (setq cmd (format cmd file))
9778 (save-window-excursion
9779 (shell-command (concat cmd " &"))))
9780 ((or (stringp cmd)
9781 (eq cmd 'emacs))
9782 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
9783 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
9784 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9785 (if line (goto-line line)
9786 (if search (org-link-search search))))
9787 ((consp cmd)
9788 (eval cmd))
9789 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9790 (and (org-mode-p) (eq old-mode 'org-mode)
9791 (or (not (equal old-buffer (current-buffer)))
9792 (not (equal old-pos (point))))
9793 (org-mark-ring-push old-pos old-buffer))))
9794
9795 (defun org-default-apps ()
9796 "Return the default applications for this operating system."
9797 (cond
9798 ((eq system-type 'darwin)
9799 org-file-apps-defaults-macosx)
9800 ((eq system-type 'windows-nt)
9801 org-file-apps-defaults-windowsnt)
9802 (t org-file-apps-defaults-gnu)))
9803
9804 (defun org-expand-file-name (path)
9805 "Replace special path abbreviations and expand the file name."
9806 (expand-file-name path))
9807
9808 (defun org-file-remote-p (file)
9809 "Test whether FILE specifies a location on a remote system.
9810 Return non-nil if the location is indeed remote.
9811
9812 For example, the filename \"/user@host:/foo\" specifies a location
9813 on the system \"/user@host:\"."
9814 (cond ((fboundp 'file-remote-p)
9815 (file-remote-p file))
9816 ((fboundp 'tramp-handle-file-remote-p)
9817 (tramp-handle-file-remote-p file))
9818 ((and (boundp 'ange-ftp-name-format)
9819 (string-match (car ange-ftp-name-format) file))
9820 t)
9821 (t nil)))
9822
9823 (defvar org-insert-link-history nil
9824 "Minibuffer history for links inserted with `org-insert-link'.")
9825
9826 (defvar org-stored-links nil
9827 "Contains the links stored with `org-store-link'.")
9828
9829 ;;;###autoload
9830 (defun org-store-link (arg)
9831 "\\<org-mode-map>Store an org-link to the current location.
9832 This link can later be inserted into an org-buffer with
9833 \\[org-insert-link].
9834 For some link types, a prefix arg is interpreted:
9835 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9836 For file links, arg negates `org-context-in-file-links'."
9837 (interactive "P")
9838 (let (link cpltxt desc description search txt (pos (point)))
9839 (cond
9840
9841 ((eq major-mode 'bbdb-mode)
9842 (setq cpltxt (concat
9843 "bbdb:"
9844 (or (bbdb-record-name (bbdb-current-record))
9845 (bbdb-record-company (bbdb-current-record))))
9846 link (org-make-link cpltxt)))
9847
9848 ((eq major-mode 'Info-mode)
9849 (setq link (org-make-link "info:"
9850 (file-name-nondirectory Info-current-file)
9851 ":" Info-current-node))
9852 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9853 ":" Info-current-node)))
9854
9855 ((eq major-mode 'calendar-mode)
9856 (let ((cd (calendar-cursor-to-date)))
9857 (setq link
9858 (format-time-string
9859 (car org-time-stamp-formats)
9860 (apply 'encode-time
9861 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9862 nil nil nil))))))
9863
9864 ((or (eq major-mode 'vm-summary-mode)
9865 (eq major-mode 'vm-presentation-mode))
9866 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9867 (vm-follow-summary-cursor)
9868 (save-excursion
9869 (vm-select-folder-buffer)
9870 (let* ((message (car vm-message-pointer))
9871 (folder buffer-file-name)
9872 (subject (vm-su-subject message))
9873 (author (vm-su-full-name message))
9874 (message-id (vm-su-message-id message)))
9875 (setq message-id (org-remove-angle-brackets message-id))
9876 (setq folder (abbreviate-file-name folder))
9877 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9878 folder)
9879 (setq folder (replace-match "" t t folder)))
9880 (setq cpltxt (concat author " on: " subject))
9881 (setq link (org-make-link "vm:" folder "#" message-id)))))
9882
9883 ((eq major-mode 'wl-summary-mode)
9884 (let* ((msgnum (wl-summary-message-number))
9885 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9886 msgnum 'message-id))
9887 (wl-message-entity (elmo-msgdb-overview-get-entity
9888 msgnum (wl-summary-buffer-msgdb)))
9889 (author (wl-summary-line-from)) ; FIXME: correct?
9890 (subject "???")) ; FIXME:
9891 (setq message-id (org-remove-angle-brackets message-id))
9892 (setq cpltxt (concat author " on: " subject))
9893 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9894 "#" message-id))))
9895
9896 ((or (equal major-mode 'mh-folder-mode)
9897 (equal major-mode 'mh-show-mode))
9898 (let ((from-header (org-mhe-get-header "From:"))
9899 (to-header (org-mhe-get-header "To:"))
9900 (subject (org-mhe-get-header "Subject:")))
9901 (setq cpltxt (concat from-header " on: " subject))
9902 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9903 (org-remove-angle-brackets
9904 (org-mhe-get-header "Message-Id:"))))))
9905
9906 ((eq major-mode 'rmail-mode)
9907 (save-excursion
9908 (save-restriction
9909 (rmail-narrow-to-non-pruned-header)
9910 (let ((folder buffer-file-name)
9911 (message-id (mail-fetch-field "message-id"))
9912 (author (mail-fetch-field "from"))
9913 (subject (mail-fetch-field "subject")))
9914 (setq message-id (org-remove-angle-brackets message-id))
9915 (setq cpltxt (concat author " on: " subject))
9916 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9917
9918 ((eq major-mode 'gnus-group-mode)
9919 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9920 (gnus-group-group-name)) ; version
9921 ((fboundp 'gnus-group-name)
9922 (gnus-group-name))
9923 (t "???"))))
9924 (setq cpltxt (concat
9925 (if (org-xor arg org-usenet-links-prefer-google)
9926 "http://groups.google.com/groups?group="
9927 "gnus:")
9928 group)
9929 link (org-make-link cpltxt))))
9930
9931 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9932 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9933 (gnus-summary-beginning-of-article)
9934 (let* ((group (car gnus-article-current))
9935 (article (cdr gnus-article-current))
9936 (header (gnus-summary-article-header article))
9937 (author (mail-header-from header))
9938 (message-id (mail-header-id header))
9939 (date (mail-header-date header))
9940 (subject (gnus-summary-subject-string)))
9941 (setq cpltxt (concat author " on: " subject))
9942 (if (org-xor arg org-usenet-links-prefer-google)
9943 (setq link
9944 (concat
9945 cpltxt "\n "
9946 (format "http://groups.google.com/groups?as_umsgid=%s"
9947 (org-fixup-message-id-for-http message-id))))
9948 (setq link (org-make-link "gnus:" group
9949 "#" (number-to-string article))))))
9950
9951 ((eq major-mode 'w3-mode)
9952 (setq cpltxt (url-view-url t)
9953 link (org-make-link cpltxt)))
9954 ((eq major-mode 'w3m-mode)
9955 (setq cpltxt (or w3m-current-title w3m-current-url)
9956 link (org-make-link w3m-current-url)))
9957
9958 ((setq search (run-hook-with-args-until-success
9959 'org-create-file-search-functions))
9960 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9961 "::" search))
9962 (setq cpltxt (or description link)))
9963
9964 ((eq major-mode 'image-mode)
9965 (setq cpltxt (concat "file:"
9966 (abbreviate-file-name buffer-file-name))
9967 link (org-make-link cpltxt)))
9968
9969 ((org-mode-p)
9970 ;; Just link to current headline
9971 (setq cpltxt (concat "file:"
9972 (abbreviate-file-name buffer-file-name)))
9973 ;; Add a context search string
9974 (when (org-xor org-context-in-file-links arg)
9975 ;; Check if we are on a target
9976 (if (save-excursion
9977 (skip-chars-forward "^>\n\r")
9978 (and (re-search-backward "<<" nil t)
9979 (looking-at "<<\\(.*?\\)>>")
9980 (<= (match-beginning 0) pos)
9981 (>= (match-end 0) pos)))
9982 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9983 (setq txt (cond
9984 ((org-on-heading-p) nil)
9985 ((org-region-active-p)
9986 (buffer-substring (region-beginning) (region-end)))
9987 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9988 (when (or (null txt) (string-match "\\S-" txt))
9989 (setq cpltxt
9990 (concat cpltxt "::"
9991 (if org-file-link-context-use-camel-case
9992 (org-make-org-heading-camel txt)
9993 (org-make-org-heading-search-string txt)))
9994 desc "NONE"))))
9995 (if (string-match "::\\'" cpltxt)
9996 (setq cpltxt (substring cpltxt 0 -2)))
9997 (setq link (org-make-link cpltxt)))
9998
9999 (buffer-file-name
10000 ;; Just link to this file here.
10001 (setq cpltxt (concat "file:"
10002 (abbreviate-file-name buffer-file-name)))
10003 ;; Add a context string
10004 (when (org-xor org-context-in-file-links arg)
10005 (setq txt (if (org-region-active-p)
10006 (buffer-substring (region-beginning) (region-end))
10007 (buffer-substring (point-at-bol) (point-at-eol))))
10008 ;; Only use search option if there is some text.
10009 (when (string-match "\\S-" txt)
10010 (setq cpltxt
10011 (concat cpltxt "::"
10012 (if org-file-link-context-use-camel-case
10013 (org-make-org-heading-camel txt)
10014 (org-make-org-heading-search-string txt)))
10015 desc "NONE")))
10016 (setq link (org-make-link cpltxt)))
10017
10018 ((interactive-p)
10019 (error "Cannot link to a buffer which is not visiting a file"))
10020
10021 (t (setq link nil)))
10022
10023 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10024 (setq link (or link cpltxt)
10025 desc (or desc cpltxt))
10026 (if (equal desc "NONE") (setq desc nil))
10027
10028 (if (and (interactive-p) link)
10029 (progn
10030 (setq org-stored-links
10031 (cons (list cpltxt link desc) org-stored-links))
10032 (message "Stored: %s" (or cpltxt link)))
10033 (org-make-link-string link desc))))
10034
10035 (defun org-make-org-heading-search-string (&optional string heading)
10036 "Make search string for STRING or current headline."
10037 (interactive)
10038 (let ((s (or string (org-get-heading))))
10039 (unless (and string (not heading))
10040 ;; We are using a headline, clean up garbage in there.
10041 (if (string-match org-todo-regexp s)
10042 (setq s (replace-match "" t t s)))
10043 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10044 (setq s (replace-match "" t t s)))
10045 (setq s (org-trim s))
10046 (if (string-match (concat "^\\(" org-quote-string "\\|"
10047 org-comment-string "\\)") s)
10048 (setq s (replace-match "" t t s)))
10049 (while (string-match org-ts-regexp s)
10050 (setq s (replace-match "" t t s))))
10051 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10052 (setq s (replace-match " " t t s)))
10053 (or string (setq s (concat "*" s))) ; Add * for headlines
10054 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10055
10056 (defun org-make-org-heading-camel (&optional string heading)
10057 "Make a CamelCase string for STRING or the current headline."
10058 (interactive)
10059 (let ((s (or string (org-get-heading))))
10060 (unless (and string (not heading))
10061 ;; We are using a headline, clean up garbage in there.
10062 (if (string-match org-todo-regexp s)
10063 (setq s (replace-match "" t t s)))
10064 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10065 (setq s (replace-match "" t t s)))
10066 (setq s (org-trim s))
10067 (if (string-match (concat "^\\(" org-quote-string "\\|"
10068 org-comment-string "\\)") s)
10069 (setq s (replace-match "" t t s)))
10070 (while (string-match org-ts-regexp s)
10071 (setq s (replace-match "" t t s))))
10072 (while (string-match "[^a-zA-Z_ \t]+" s)
10073 (setq s (replace-match " " t t s)))
10074 (or string (setq s (concat "*" s))) ; Add * for headlines
10075 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
10076
10077 (defun org-make-link (&rest strings)
10078 "Concatenate STRINGS, format resulting string with `org-link-format'."
10079 (format org-link-format (apply 'concat strings)))
10080
10081 (defun org-make-link-string (link &optional description)
10082 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10083 (if (eq org-link-style 'plain)
10084 (if (equal description link)
10085 link
10086 (concat description "\n" link))
10087 (when (stringp description)
10088 ;; Remove brackets from the description, they are fatal.
10089 (while (string-match "\\[\\|\\]" description)
10090 (setq description (replace-match "" t t description))))
10091 (when (equal (org-link-escape link) description)
10092 ;; No description needed, it is identical
10093 (setq description nil))
10094 (when (and (not description)
10095 (not (equal link (org-link-escape link))))
10096 (setq description link))
10097 (concat "[[" (org-link-escape link) "]"
10098 (if description (concat "[" description "]") "")
10099 "]")))
10100
10101 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
10102 "Association list of escapes for some characters problematic in links.")
10103
10104 (defun org-link-escape (text)
10105 "Escape charaters in TEXT that are problematic for links."
10106 (when text
10107 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10108 org-link-escape-chars "\\|")))
10109 (while (string-match re text)
10110 (setq text
10111 (replace-match
10112 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10113 t t text)))
10114 text)))
10115
10116 (defun org-link-unescape (text)
10117 "Reverse the action of `org-link-escape'."
10118 (when text
10119 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10120 org-link-escape-chars "\\|")))
10121 (while (string-match re text)
10122 (setq text
10123 (replace-match
10124 (car (rassoc (match-string 0 text) org-link-escape-chars))
10125 t t text)))
10126 text)))
10127
10128 (defun org-xor (a b)
10129 "Exclusive or."
10130 (if a (not b) b))
10131
10132 (defun org-get-header (header)
10133 "Find a header field in the current buffer."
10134 (save-excursion
10135 (goto-char (point-min))
10136 (let ((case-fold-search t) s)
10137 (cond
10138 ((eq header 'from)
10139 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10140 (setq s (match-string 1)))
10141 (while (string-match "\"" s)
10142 (setq s (replace-match "" t t s)))
10143 (if (string-match "[<(].*" s)
10144 (setq s (replace-match "" t t s))))
10145 ((eq header 'message-id)
10146 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10147 (setq s (match-string 1))))
10148 ((eq header 'subject)
10149 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10150 (setq s (match-string 1)))))
10151 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10152 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10153 s)))
10154
10155
10156 (defun org-fixup-message-id-for-http (s)
10157 "Replace special characters in a message id, so it can be used in an http query."
10158 (while (string-match "<" s)
10159 (setq s (replace-match "%3C" t t s)))
10160 (while (string-match ">" s)
10161 (setq s (replace-match "%3E" t t s)))
10162 (while (string-match "@" s)
10163 (setq s (replace-match "%40" t t s)))
10164 s)
10165
10166 (defun org-insert-link (&optional complete-file)
10167 "Insert a link. At the prompt, enter the link.
10168
10169 Completion can be used to select a link previously stored with
10170 `org-store-link'. When the empty string is entered (i.e. if you just
10171 press RET at the prompt), the link defaults to the most recently
10172 stored link. As SPC triggers completion in the minibuffer, you need to
10173 use M-SPC or C-q SPC to force the insertion of a space character.
10174
10175 You will also be prompted for a description, and if one is given, it will
10176 be displayed in the buffer instead of the link.
10177
10178 If there is already a link at point, this command will allow you to edit link
10179 and description parts.
10180
10181 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10182 selected using completion. The path to the file will be relative to
10183 the current directory if the file is in the current directory or a
10184 subdirectory. Otherwise, the link will be the absolute path as
10185 completed in the minibuffer (i.e. normally ~/path/to/file).
10186
10187 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10188 is in the current directory or below.
10189 With three \\[universal-argument] prefixes, negate the meaning of
10190 `org-keep-stored-link-after-insertion'."
10191 (interactive "P")
10192 (let (link desc entry remove file (pos (point)))
10193 (cond
10194 ((save-excursion
10195 (skip-chars-forward "^]\n\r")
10196 (and (re-search-backward "\\[\\[" nil t)
10197 (looking-at org-bracket-link-regexp)
10198 (<= (match-beginning 0) pos)
10199 (>= (match-end 0) pos)))
10200 ;; We do have a link at point, and we are going to edit it.
10201 (setq remove (list (match-beginning 0) (match-end 0)))
10202 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10203 (setq link (read-string "Link: "
10204 (org-link-unescape
10205 (org-match-string-no-properties 1)))))
10206 ((equal complete-file '(4))
10207 ;; Completing read for file names.
10208 (setq file (read-file-name "File: "))
10209 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10210 (pwd1 (file-name-as-directory (abbreviate-file-name
10211 (expand-file-name ".")))))
10212 (cond
10213 ((equal complete-file '(16))
10214 (setq link (org-make-link
10215 "file:"
10216 (abbreviate-file-name (expand-file-name file)))))
10217 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10218 (setq link (org-make-link "file:" (match-string 1 file))))
10219 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10220 (expand-file-name file))
10221 (setq link (org-make-link
10222 "file:" (match-string 1 (expand-file-name file)))))
10223 (t (setq link (org-make-link "file:" file))))))
10224 (t
10225 ;; Read link, with completion for stored links.
10226 (setq link (org-completing-read
10227 "Link: " org-stored-links nil nil nil
10228 org-insert-link-history
10229 (or (car (car org-stored-links)))))
10230 (setq entry (assoc link org-stored-links))
10231 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10232 (not org-keep-stored-link-after-insertion))
10233 (setq org-stored-links (delq (assoc link org-stored-links)
10234 org-stored-links)))
10235 (setq link (if entry (nth 1 entry) link)
10236 desc (or desc (nth 2 entry)))))
10237
10238 (if (string-match org-plain-link-re link)
10239 ;; URL-like link, normalize the use of angular brackets.
10240 (setq link (org-make-link (org-remove-angle-brackets link))))
10241
10242 ;; Check if we are linking to the current file with a search option
10243 ;; If yes, simplify the link by using only the search option.
10244 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
10245 (let* ((path (match-string 1 link))
10246 (case-fold-search nil)
10247 (search (match-string 2 link)))
10248 (save-match-data
10249 (if (equal (file-truename buffer-file-name) (file-truename path))
10250 ;; We are linking to this same file, with a search option
10251 (setq link search)))))
10252
10253 ;; Check if we can/should use a relative path. If yes, simplify the link
10254 (when (string-match "\\<file:\\(.*\\)" link)
10255 (let* ((path (match-string 1 link))
10256 (case-fold-search nil))
10257 (cond
10258 ((eq org-link-file-path-type 'absolute)
10259 (setq path (abbreviate-file-name (expand-file-name path))))
10260 ((eq org-link-file-path-type 'noabbrev)
10261 (setq path (expand-file-name path)))
10262 ((eq org-link-file-path-type 'relative)
10263 (setq path (file-relative-name path)))
10264 (t
10265 (save-match-data
10266 (if (string-match (concat "^" (regexp-quote
10267 (file-name-as-directory
10268 (expand-file-name "."))))
10269 (expand-file-name path))
10270 ;; We are linking a file with relative path name.
10271 (setq path (substring (expand-file-name path)
10272 (match-end 0)))))))
10273 (setq link (concat "file:" path))))
10274
10275 (setq desc (read-string "Description: " desc))
10276 (unless (string-match "\\S-" desc) (setq desc nil))
10277 (if remove (apply 'delete-region remove))
10278 (insert (org-make-link-string link desc))))
10279
10280 (defun org-completing-read (&rest args)
10281 (let ((minibuffer-local-completion-map
10282 (copy-keymap minibuffer-local-completion-map)))
10283 (define-key minibuffer-local-completion-map " " 'self-insert-command)
10284 (apply 'completing-read args)))
10285
10286 ;;; Hooks for remember.el
10287
10288 (defvar org-finish-function nil)
10289
10290 ;;;###autoload
10291 (defun org-remember-annotation ()
10292 "Return a link to the current location as an annotation for remember.el.
10293 If you are using Org-mode files as target for data storage with
10294 remember.el, then the annotations should include a link compatible with the
10295 conventions in Org-mode. This function returns such a link."
10296 (org-store-link nil))
10297
10298 (defconst org-remember-help
10299 "Select a destination location for the note.
10300 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10301 RET at beg-of-buf -> Append to file as level 2 headline
10302 RET on headline -> Store as sublevel entry to current headline
10303 <left>/<right> -> before/after current headline, same headings level")
10304
10305 ;;;###autoload
10306 (defun org-remember-apply-template ()
10307 "Initialize *remember* buffer with template, invoke `org-mode'.
10308 This function should be placed into `remember-mode-hook' and in fact requires
10309 to be run from that hook to fucntion properly."
10310 (if org-remember-templates
10311
10312 (let* ((entry (if (= (length org-remember-templates) 1)
10313 (cdar org-remember-templates)
10314 (message "Select template: %s"
10315 (mapconcat
10316 (lambda (x) (char-to-string (car x)))
10317 org-remember-templates " "))
10318 (cdr (assoc (read-char-exclusive) org-remember-templates))))
10319 (tpl (car entry))
10320 (file (if (consp (cdr entry)) (nth 1 entry)))
10321 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10322 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10323 (v-u (concat "[" (substring v-t 1 -1) "]"))
10324 (v-U (concat "[" (substring v-T 1 -1) "]"))
10325 (v-a annotation) ; defined in `remember-mode'
10326 (v-i initial) ; defined in `remember-mode'
10327 (v-n user-full-name)
10328 )
10329 (unless tpl (setq tpl "") (message "No template") (ding))
10330 (insert tpl) (goto-char (point-min))
10331 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
10332 (when (and initial (equal (match-string 0) "%i"))
10333 (save-match-data
10334 (let* ((lead (buffer-substring
10335 (point-at-bol) (match-beginning 0))))
10336 (setq v-i (mapconcat 'identity
10337 (org-split-string initial "\n")
10338 (concat "\n" lead))))))
10339 (replace-match
10340 (or (eval (intern (concat "v-" (match-string 1)))) "")
10341 t t))
10342 (let ((org-startup-folded nil)
10343 (org-startup-with-deadline-check nil))
10344 (org-mode))
10345 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10346 (org-set-local 'org-default-notes-file file))
10347 (goto-char (point-min))
10348 (if (re-search-forward "%\\?" nil t) (replace-match "")))
10349 (let ((org-startup-folded nil)
10350 (org-startup-with-deadline-check nil))
10351 (org-mode)))
10352 (org-set-local 'org-finish-function 'remember-buffer))
10353
10354 ;;;###autoload
10355 (defun org-remember-handler ()
10356 "Store stuff from remember.el into an org file.
10357 First prompts for an org file. If the user just presses return, the value
10358 of `org-default-notes-file' is used.
10359 Then the command offers the headings tree of the selected file in order to
10360 file the text at a specific location.
10361 You can either immediately press RET to get the note appended to the
10362 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10363 find a better place. Then press RET or <left> or <right> in insert the note.
10364
10365 Key Cursor position Note gets inserted
10366 -----------------------------------------------------------------------------
10367 RET buffer-start as level 2 heading at end of file
10368 RET on headline as sublevel of the heading at cursor
10369 RET no heading at cursor position, level taken from context.
10370 Or use prefix arg to specify level manually.
10371 <left> on headline as same level, before current heading
10372 <right> on headline as same level, after current heading
10373
10374 So the fastest way to store the note is to press RET RET to append it to
10375 the default file. This way your current train of thought is not
10376 interrupted, in accordance with the principles of remember.el. But with
10377 little extra effort, you can push it directly to the correct location.
10378
10379 Before being stored away, the function ensures that the text has a
10380 headline, i.e. a first line that starts with a \"*\". If not, a headline
10381 is constructed from the current date and some additional data.
10382
10383 If the variable `org-adapt-indentation' is non-nil, the entire text is
10384 also indented so that it starts in the same column as the headline
10385 \(i.e. after the stars).
10386
10387 See also the variable `org-reverse-note-order'."
10388 (catch 'quit
10389 (let* ((txt (buffer-substring (point-min) (point-max)))
10390 (fastp current-prefix-arg)
10391 (file (if fastp org-default-notes-file (org-get-org-file)))
10392 (visiting (find-buffer-visiting file))
10393 (org-startup-with-deadline-check nil)
10394 (org-startup-folded nil)
10395 (org-startup-align-all-tables nil)
10396 spos level indent reversed)
10397 ;; Modify text so that it becomes a nice subtree which can be inserted
10398 ;; into an org tree.
10399 (let* ((lines (split-string txt "\n"))
10400 first)
10401 ;; remove empty lines at the beginning
10402 (while (and lines (string-match "^[ \t]*\n" (car lines)))
10403 (setq lines (cdr lines)))
10404 (setq first (car lines) lines (cdr lines))
10405 (if (string-match "^\\*+" first)
10406 ;; Is already a headline
10407 (setq indent nil)
10408 ;; We need to add a headline: Use time and first buffer line
10409 (setq lines (cons first lines)
10410 first (concat "* " (current-time-string)
10411 " (" (remember-buffer-desc) ")")
10412 indent " "))
10413 (if (and org-adapt-indentation indent)
10414 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10415 (setq txt (concat first "\n"
10416 (mapconcat 'identity lines "\n"))))
10417 ;; Find the file
10418 (if (not visiting)
10419 (find-file-noselect file))
10420 (with-current-buffer (get-file-buffer file)
10421 (save-excursion (and (goto-char (point-min))
10422 (not (re-search-forward "^\\* " nil t))
10423 (insert "\n* Notes\n")))
10424 (setq reversed (org-notes-order-reversed-p))
10425 (save-excursion
10426 (save-restriction
10427 (widen)
10428 ;; Ask the User for a location
10429 (setq spos (if fastp 1 (org-get-location
10430 (current-buffer)
10431 org-remember-help)))
10432 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10433 ; not handle this note
10434 (goto-char spos)
10435 (cond ((bobp)
10436 ;; Put it at the start or end, as level 2
10437 (save-restriction
10438 (widen)
10439 (goto-char (if reversed (point-min) (point-max)))
10440 (if (not (bolp)) (newline))
10441 (org-paste-subtree 2 txt)))
10442 ((and (org-on-heading-p nil) (not current-prefix-arg))
10443 ;; Put it below this entry, at the beg/end of the subtree
10444 (org-back-to-heading)
10445 (setq level (funcall outline-level))
10446 (if reversed
10447 (outline-end-of-heading)
10448 (outline-end-of-subtree))
10449 (if (not (bolp)) (newline))
10450 (beginning-of-line 1)
10451 (org-paste-subtree (1+ level) txt))
10452 (t
10453 ;; Put it right there, with automatic level determined by
10454 ;; org-paste-subtree or from prefix arg
10455 (org-paste-subtree current-prefix-arg txt)))
10456 (when remember-save-after-remembering
10457 (save-buffer)
10458 (if (not visiting) (kill-buffer (current-buffer)))))))))
10459 t) ;; return t to indicate that we took care of this note.
10460
10461 (defun org-get-org-file ()
10462 "Read a filename, with default directory `org-directory'."
10463 (let ((default (or org-default-notes-file remember-data-file)))
10464 (read-file-name (format "File name [%s]: " default)
10465 (file-name-as-directory org-directory)
10466 default)))
10467
10468 (defun org-notes-order-reversed-p ()
10469 "Check if the current file should receive notes in reversed order."
10470 (cond
10471 ((not org-reverse-note-order) nil)
10472 ((eq t org-reverse-note-order) t)
10473 ((not (listp org-reverse-note-order)) nil)
10474 (t (catch 'exit
10475 (let ((all org-reverse-note-order)
10476 entry)
10477 (while (setq entry (pop all))
10478 (if (string-match (car entry) buffer-file-name)
10479 (throw 'exit (cdr entry))))
10480 nil)))))
10481
10482 ;;; Tables
10483
10484 ;; Watch out: Here we are talking about two different kind of tables.
10485 ;; Most of the code is for the tables created with the Org-mode table editor.
10486 ;; Sometimes, we talk about tables created and edited with the table.el
10487 ;; Emacs package. We call the former org-type tables, and the latter
10488 ;; table.el-type tables.
10489
10490
10491 (defun org-before-change-function (beg end)
10492 "Every change indicates that a table might need an update."
10493 (setq org-table-may-need-update t))
10494
10495 (defconst org-table-line-regexp "^[ \t]*|"
10496 "Detects an org-type table line.")
10497 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
10498 "Detects an org-type table line.")
10499 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
10500 "Detects a table line marked for automatic recalculation.")
10501 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
10502 "Detects a table line marked for automatic recalculation.")
10503 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
10504 "Detects a table line marked for automatic recalculation.")
10505 (defconst org-table-hline-regexp "^[ \t]*|-"
10506 "Detects an org-type table hline.")
10507 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
10508 "Detects a table-type table hline.")
10509 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
10510 "Detects an org-type or table-type table.")
10511 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
10512 "Searching from within a table (any type) this finds the first line
10513 outside the table.")
10514 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
10515 "Searching from within a table (any type) this finds the first line
10516 outside the table.")
10517
10518 (defun org-table-create-with-table.el ()
10519 "Use the table.el package to insert a new table.
10520 If there is already a table at point, convert between Org-mode tables
10521 and table.el tables."
10522 (interactive)
10523 (require 'table)
10524 (cond
10525 ((org-at-table.el-p)
10526 (if (y-or-n-p "Convert table to Org-mode table? ")
10527 (org-table-convert)))
10528 ((org-at-table-p)
10529 (if (y-or-n-p "Convert table to table.el table? ")
10530 (org-table-convert)))
10531 (t (call-interactively 'table-insert))))
10532
10533 (defun org-table-create-or-convert-from-region (arg)
10534 "Convert region to table, or create an empty table.
10535 If there is an active region, convert it to a table. If there is no such
10536 region, create an empty table."
10537 (interactive "P")
10538 (if (org-region-active-p)
10539 (org-table-convert-region (region-beginning) (region-end) arg)
10540 (org-table-create arg)))
10541
10542 (defun org-table-create (&optional size)
10543 "Query for a size and insert a table skeleton.
10544 SIZE is a string Columns x Rows like for example \"3x2\"."
10545 (interactive "P")
10546 (unless size
10547 (setq size (read-string
10548 (concat "Table size Columns x Rows [e.g. "
10549 org-table-default-size "]: ")
10550 "" nil org-table-default-size)))
10551
10552 (let* ((pos (point))
10553 (indent (make-string (current-column) ?\ ))
10554 (split (org-split-string size " *x *"))
10555 (rows (string-to-number (nth 1 split)))
10556 (columns (string-to-number (car split)))
10557 (line (concat (apply 'concat indent "|" (make-list columns " |"))
10558 "\n")))
10559 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
10560 (point-at-bol) (point)))
10561 (beginning-of-line 1)
10562 (newline))
10563 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
10564 (dotimes (i rows) (insert line))
10565 (goto-char pos)
10566 (if (> rows 1)
10567 ;; Insert a hline after the first row.
10568 (progn
10569 (end-of-line 1)
10570 (insert "\n|-")
10571 (goto-char pos)))
10572 (org-table-align)))
10573
10574 (defun org-table-convert-region (beg0 end0 &optional nspace)
10575 "Convert region to a table.
10576 The region goes from BEG0 to END0, but these borders will be moved
10577 slightly, to make sure a beginning of line in the first line is included.
10578 When NSPACE is non-nil, it indicates the minimum number of spaces that
10579 separate columns (default: just one space)."
10580 (interactive "rP")
10581 (let* ((beg (min beg0 end0))
10582 (end (max beg0 end0))
10583 (tabsep t)
10584 re)
10585 (goto-char beg)
10586 (beginning-of-line 1)
10587 (setq beg (move-marker (make-marker) (point)))
10588 (goto-char end)
10589 (if (bolp) (backward-char 1) (end-of-line 1))
10590 (setq end (move-marker (make-marker) (point)))
10591 ;; Lets see if this is tab-separated material. If every nonempty line
10592 ;; contains a tab, we will assume that it is tab-separated material
10593 (if nspace
10594 (setq tabsep nil)
10595 (goto-char beg)
10596 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
10597 (if nspace (setq tabsep nil))
10598 (if tabsep
10599 (setq re "^\\|\t")
10600 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
10601 (max 1 (prefix-numeric-value nspace)))))
10602 (goto-char beg)
10603 (while (re-search-forward re end t)
10604 (replace-match "|" t t))
10605 (goto-char beg)
10606 (insert " ")
10607 (org-table-align)))
10608
10609 (defun org-table-import (file arg)
10610 "Import FILE as a table.
10611 The file is assumed to be tab-separated. Such files can be produced by most
10612 spreadsheet and database applications. If no tabs (at least one per line)
10613 are found, lines will be split on whitespace into fields."
10614 (interactive "f\nP")
10615 (or (bolp) (newline))
10616 (let ((beg (point))
10617 (pm (point-max)))
10618 (insert-file-contents file)
10619 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
10620
10621 (defun org-table-export ()
10622 "Export table as a tab-separated file.
10623 Such a file can be imported into a spreadsheet program like Excel."
10624 (interactive)
10625 (let* ((beg (org-table-begin))
10626 (end (org-table-end))
10627 (table (buffer-substring beg end))
10628 (file (read-file-name "Export table to: "))
10629 buf)
10630 (unless (or (not (file-exists-p file))
10631 (y-or-n-p (format "Overwrite file %s? " file)))
10632 (error "Abort"))
10633 (with-current-buffer (find-file-noselect file)
10634 (setq buf (current-buffer))
10635 (erase-buffer)
10636 (fundamental-mode)
10637 (insert table)
10638 (goto-char (point-min))
10639 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
10640 (replace-match "" t t)
10641 (end-of-line 1))
10642 (goto-char (point-min))
10643 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
10644 (replace-match "" t t)
10645 (goto-char (min (1+ (point)) (point-max))))
10646 (goto-char (point-min))
10647 (while (re-search-forward "^-[-+]*$" nil t)
10648 (replace-match "")
10649 (if (looking-at "\n")
10650 (delete-char 1)))
10651 (goto-char (point-min))
10652 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
10653 (replace-match "\t" t t))
10654 (save-buffer))
10655 (kill-buffer buf)))
10656
10657 (defvar org-table-aligned-begin-marker (make-marker)
10658 "Marker at the beginning of the table last aligned.
10659 Used to check if cursor still is in that table, to minimize realignment.")
10660 (defvar org-table-aligned-end-marker (make-marker)
10661 "Marker at the end of the table last aligned.
10662 Used to check if cursor still is in that table, to minimize realignment.")
10663 (defvar org-table-last-alignment nil
10664 "List of flags for flushright alignment, from the last re-alignment.
10665 This is being used to correctly align a single field after TAB or RET.")
10666 (defvar org-table-last-column-widths nil
10667 "List of max width of fields in each column.
10668 This is being used to correctly align a single field after TAB or RET.")
10669
10670 (defvar org-last-recalc-line nil)
10671 (defconst org-narrow-column-arrow "=>"
10672 "Used as display property in narrowed table columns.")
10673
10674 (defun org-table-align ()
10675 "Align the table at point by aligning all vertical bars."
10676 (interactive)
10677 (let* (
10678 ;; Limits of table
10679 (beg (org-table-begin))
10680 (end (org-table-end))
10681 ;; Current cursor position
10682 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10683 (colpos (org-table-current-column))
10684 (winstart (window-start))
10685 lines (new "") lengths l typenums ty fields maxfields i
10686 column
10687 (indent "") cnt frac
10688 rfmt hfmt
10689 (spaces '(1 . 1))
10690 (sp1 (car spaces))
10691 (sp2 (cdr spaces))
10692 (rfmt1 (concat
10693 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
10694 (hfmt1 (concat
10695 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
10696 emptystrings links narrow fmax f1 len c e)
10697 (untabify beg end)
10698 (remove-text-properties beg end '(org-cwidth t display t))
10699 ;; Check if we have links
10700 (goto-char beg)
10701 (setq links (re-search-forward org-bracket-link-regexp end t))
10702 ;; Make sure the link properties are right
10703 (when links (goto-char beg) (while (org-activate-bracket-links end)))
10704 ;; Check if we are narrowing any columns
10705 (goto-char beg)
10706 (setq narrow (and org-format-transports-properties-p
10707 (re-search-forward "<[0-9]+>" end t)))
10708 ;; Get the rows
10709 (setq lines (org-split-string
10710 (buffer-substring beg end) "\n"))
10711 ;; Store the indentation of the first line
10712 (if (string-match "^ *" (car lines))
10713 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
10714 ;; Mark the hlines by setting the corresponding element to nil
10715 ;; At the same time, we remove trailing space.
10716 (setq lines (mapcar (lambda (l)
10717 (if (string-match "^ *|-" l)
10718 nil
10719 (if (string-match "[ \t]+$" l)
10720 (substring l 0 (match-beginning 0))
10721 l)))
10722 lines))
10723 ;; Get the data fields by splitting the lines.
10724 (setq fields (mapcar
10725 (lambda (l)
10726 (org-split-string l " *| *"))
10727 (delq nil (copy-sequence lines))))
10728 ;; How many fields in the longest line?
10729 (condition-case nil
10730 (setq maxfields (apply 'max (mapcar 'length fields)))
10731 (error
10732 (kill-region beg end)
10733 (org-table-create org-table-default-size)
10734 (error "Empty table - created default table")))
10735 ;; A list of empty string to fill any short rows on output
10736 (setq emptystrings (make-list maxfields ""))
10737 ;; Check for special formatting.
10738 (setq i -1)
10739 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
10740 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
10741 ;; Check if there is an explicit width specified
10742 (when (and org-table-limit-column-width narrow)
10743 (setq c column fmax nil)
10744 (while c
10745 (setq e (pop c))
10746 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
10747 (setq fmax (string-to-number (match-string 1 e)) c nil)))
10748 ;; Find fields that are wider than fmax, and shorten them
10749 (when fmax
10750 (loop for xx in column do
10751 (when (and (stringp xx)
10752 (> (org-string-width xx) fmax))
10753 (org-add-props xx nil
10754 'help-echo
10755 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
10756 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
10757 (unless (> f1 1)
10758 (error "Cannot narrow field starting with wide link \"%s\""
10759 (match-string 0 xx)))
10760 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
10761 (add-text-properties (- f1 2) f1
10762 (list 'display org-narrow-column-arrow)
10763 xx)))))
10764 ;; Get the maximum width for each column
10765 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
10766 ;; Get the fraction of numbers, to decide about alignment of the column
10767 (setq cnt 0 frac 0.0)
10768 (loop for x in column do
10769 (if (equal x "")
10770 nil
10771 (setq frac ( / (+ (* frac cnt)
10772 (if (string-match org-table-number-regexp x) 1 0))
10773 (setq cnt (1+ cnt))))))
10774 (push (>= frac org-table-number-fraction) typenums))
10775 (setq lengths (nreverse lengths) typenums (nreverse typenums))
10776
10777 ;; Store the alignment of this table, for later editing of single fields
10778 (setq org-table-last-alignment typenums
10779 org-table-last-column-widths lengths)
10780
10781 ;; With invisible characters, `format' does not get the field width right
10782 ;; So we need to make these fields wide by hand.
10783 (when links
10784 (loop for i from 0 upto (1- maxfields) do
10785 (setq len (nth i lengths))
10786 (loop for j from 0 upto (1- (length fields)) do
10787 (setq c (nthcdr i (car (nthcdr j fields))))
10788 (if (and (stringp (car c))
10789 (string-match org-bracket-link-regexp (car c))
10790 (< (org-string-width (car c)) len))
10791 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
10792
10793 ;; Compute the formats needed for output of the table
10794 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
10795 (while (setq l (pop lengths))
10796 (setq ty (if (pop typenums) "" "-")) ; number types flushright
10797 (setq rfmt (concat rfmt (format rfmt1 ty l))
10798 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
10799 (setq rfmt (concat rfmt "\n")
10800 hfmt (concat (substring hfmt 0 -1) "|\n"))
10801
10802 (setq new (mapconcat
10803 (lambda (l)
10804 (if l (apply 'format rfmt
10805 (append (pop fields) emptystrings))
10806 hfmt))
10807 lines ""))
10808 ;; Replace the old one
10809 (delete-region beg end)
10810 (move-marker end nil)
10811 (move-marker org-table-aligned-begin-marker (point))
10812 (insert new)
10813 (move-marker org-table-aligned-end-marker (point))
10814 (when (and orgtbl-mode (not (org-mode-p)))
10815 (goto-char org-table-aligned-begin-marker)
10816 (while (org-hide-wide-columns org-table-aligned-end-marker)))
10817 ;; Try to move to the old location (approximately)
10818 (goto-line linepos)
10819 (set-window-start (selected-window) winstart 'noforce)
10820 (org-table-goto-column colpos)
10821 (setq org-table-may-need-update nil)
10822 ))
10823
10824 (defun org-string-width (s)
10825 "Compute width of string, ignoring invisible characters.
10826 This ignores character with invisibility property `org-link', and also
10827 characters with property `org-cwidth', because these will become invisible
10828 upon the next fontification round."
10829 (let (b)
10830 (when (or (eq t buffer-invisibility-spec)
10831 (assq 'org-link buffer-invisibility-spec))
10832 (while (setq b (text-property-any 0 (length s)
10833 'invisible 'org-link s))
10834 (setq s (concat (substring s 0 b)
10835 (substring s (or (next-single-property-change
10836 b 'invisible s) (length s)))))))
10837 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
10838 (setq s (concat (substring s 0 b)
10839 (substring s (or (next-single-property-change
10840 b 'org-cwidth s) (length s))))))
10841 (string-width s)))
10842
10843 (defun org-table-begin (&optional table-type)
10844 "Find the beginning of the table and return its position.
10845 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
10846 (save-excursion
10847 (if (not (re-search-backward
10848 (if table-type org-table-any-border-regexp
10849 org-table-border-regexp)
10850 nil t))
10851 (progn (goto-char (point-min)) (point))
10852 (goto-char (match-beginning 0))
10853 (beginning-of-line 2)
10854 (point))))
10855
10856 (defun org-table-end (&optional table-type)
10857 "Find the end of the table and return its position.
10858 With argument TABLE-TYPE, go to the end of a table.el-type table."
10859 (save-excursion
10860 (if (not (re-search-forward
10861 (if table-type org-table-any-border-regexp
10862 org-table-border-regexp)
10863 nil t))
10864 (goto-char (point-max))
10865 (goto-char (match-beginning 0)))
10866 (point-marker)))
10867
10868 (defun org-table-justify-field-maybe (&optional new)
10869 "Justify the current field, text to left, number to right.
10870 Optional argument NEW may specify text to replace the current field content."
10871 (cond
10872 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
10873 ((org-at-table-hline-p))
10874 ((and (not new)
10875 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
10876 (current-buffer)))
10877 (< (point) org-table-aligned-begin-marker)
10878 (>= (point) org-table-aligned-end-marker)))
10879 ;; This is not the same table, force a full re-align
10880 (setq org-table-may-need-update t))
10881 (t ;; realign the current field, based on previous full realign
10882 (let* ((pos (point)) s
10883 (col (org-table-current-column))
10884 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
10885 l f n o e)
10886 (when (> col 0)
10887 (skip-chars-backward "^|\n")
10888 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
10889 (progn
10890 (setq s (match-string 1)
10891 o (match-string 0)
10892 l (max 1 (- (match-end 0) (match-beginning 0) 3))
10893 e (not (= (match-beginning 2) (match-end 2))))
10894 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
10895 l (if e "|" (setq org-table-may-need-update t) ""))
10896 n (format f s))
10897 (if new
10898 (if (<= (length new) l) ;; FIXME: length -> str-width?
10899 (setq n (format f new))
10900 (setq n (concat new "|") org-table-may-need-update t)))
10901 (or (equal n o)
10902 (let (org-table-may-need-update)
10903 (replace-match n))))
10904 (setq org-table-may-need-update t))
10905 (goto-char pos))))))
10906
10907 (defun org-table-next-field ()
10908 "Go to the next field in the current table, creating new lines as needed.
10909 Before doing so, re-align the table if necessary."
10910 (interactive)
10911 (org-table-maybe-eval-formula)
10912 (org-table-maybe-recalculate-line)
10913 (if (and org-table-automatic-realign
10914 org-table-may-need-update)
10915 (org-table-align))
10916 (let ((end (org-table-end)))
10917 (if (org-at-table-hline-p)
10918 (end-of-line 1))
10919 (condition-case nil
10920 (progn
10921 (re-search-forward "|" end)
10922 (if (looking-at "[ \t]*$")
10923 (re-search-forward "|" end))
10924 (if (and (looking-at "-")
10925 org-table-tab-jumps-over-hlines
10926 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
10927 (goto-char (match-beginning 1)))
10928 (if (looking-at "-")
10929 (progn
10930 (beginning-of-line 0)
10931 (org-table-insert-row 'below))
10932 (if (looking-at " ") (forward-char 1))))
10933 (error
10934 (org-table-insert-row 'below)))))
10935
10936 (defun org-table-previous-field ()
10937 "Go to the previous field in the table.
10938 Before doing so, re-align the table if necessary."
10939 (interactive)
10940 (org-table-justify-field-maybe)
10941 (org-table-maybe-recalculate-line)
10942 (if (and org-table-automatic-realign
10943 org-table-may-need-update)
10944 (org-table-align))
10945 (if (org-at-table-hline-p)
10946 (end-of-line 1))
10947 (re-search-backward "|" (org-table-begin))
10948 (re-search-backward "|" (org-table-begin))
10949 (while (looking-at "|\\(-\\|[ \t]*$\\)")
10950 (re-search-backward "|" (org-table-begin)))
10951 (if (looking-at "| ?")
10952 (goto-char (match-end 0))))
10953
10954 (defun org-table-next-row ()
10955 "Go to the next row (same column) in the current table.
10956 Before doing so, re-align the table if necessary."
10957 (interactive)
10958 (org-table-maybe-eval-formula)
10959 (org-table-maybe-recalculate-line)
10960 (if (or (looking-at "[ \t]*$")
10961 (save-excursion (skip-chars-backward " \t") (bolp)))
10962 (newline)
10963 (if (and org-table-automatic-realign
10964 org-table-may-need-update)
10965 (org-table-align))
10966 (let ((col (org-table-current-column)))
10967 (beginning-of-line 2)
10968 (if (or (not (org-at-table-p))
10969 (org-at-table-hline-p))
10970 (progn
10971 (beginning-of-line 0)
10972 (org-table-insert-row 'below)))
10973 (org-table-goto-column col)
10974 (skip-chars-backward "^|\n\r")
10975 (if (looking-at " ") (forward-char 1)))))
10976
10977 (defun org-table-copy-down (n)
10978 "Copy a field down in the current column.
10979 If the field at the cursor is empty, copy into it the content of the nearest
10980 non-empty field above. With argument N, use the Nth non-empty field.
10981 If the current field is not empty, it is copied down to the next row, and
10982 the cursor is moved with it. Therefore, repeating this command causes the
10983 column to be filled row-by-row.
10984 If the variable `org-table-copy-increment' is non-nil and the field is an
10985 integer, it will be incremented while copying."
10986 (interactive "p")
10987 (let* ((colpos (org-table-current-column))
10988 (field (org-table-get-field))
10989 (non-empty (string-match "[^ \t]" field))
10990 (beg (org-table-begin))
10991 txt)
10992 (org-table-check-inside-data-field)
10993 (if non-empty
10994 (progn
10995 (setq txt (org-trim field))
10996 (org-table-next-row)
10997 (org-table-blank-field))
10998 (save-excursion
10999 (setq txt
11000 (catch 'exit
11001 (while (progn (beginning-of-line 1)
11002 (re-search-backward org-table-dataline-regexp
11003 beg t))
11004 (org-table-goto-column colpos t)
11005 (if (and (looking-at
11006 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
11007 (= (setq n (1- n)) 0))
11008 (throw 'exit (match-string 1))))))))
11009 (if txt
11010 (progn
11011 (if (and org-table-copy-increment
11012 (string-match "^[0-9]+$" txt))
11013 (setq txt (format "%d" (+ (string-to-number txt) 1))))
11014 (insert txt)
11015 (org-table-maybe-recalculate-line)
11016 (org-table-align))
11017 (error "No non-empty field found"))))
11018
11019 (defun org-table-check-inside-data-field ()
11020 "Is point inside a table data field?
11021 I.e. not on a hline or before the first or after the last column?
11022 This actually throws an error, so it aborts the current command."
11023 (if (or (not (org-at-table-p))
11024 (= (org-table-current-column) 0)
11025 (org-at-table-hline-p)
11026 (looking-at "[ \t]*$"))
11027 (error "Not in table data field")))
11028
11029 (defvar org-table-clip nil
11030 "Clipboard for table regions.")
11031
11032 (defun org-table-blank-field ()
11033 "Blank the current table field or active region."
11034 (interactive)
11035 (org-table-check-inside-data-field)
11036 (if (and (interactive-p) (org-region-active-p))
11037 (let (org-table-clip)
11038 (org-table-cut-region (region-beginning) (region-end)))
11039 (skip-chars-backward "^|")
11040 (backward-char 1)
11041 (if (looking-at "|[^|\n]+")
11042 (let* ((pos (match-beginning 0))
11043 (match (match-string 0))
11044 (len (org-string-width match)))
11045 (replace-match (concat "|" (make-string (1- len) ?\ )))
11046 (goto-char (+ 2 pos))
11047 (substring match 1)))))
11048
11049 (defun org-table-get-field (&optional n replace)
11050 "Return the value of the field in column N of current row.
11051 N defaults to current field.
11052 If REPLACE is a string, replace field with this value. The return value
11053 is always the old value."
11054 (and n (org-table-goto-column n))
11055 (skip-chars-backward "^|\n")
11056 (backward-char 1)
11057 (if (looking-at "|[^|\r\n]*")
11058 (let* ((pos (match-beginning 0))
11059 (val (buffer-substring (1+ pos) (match-end 0))))
11060 (if replace
11061 (replace-match (concat "|" replace)))
11062 (goto-char (min (point-at-eol) (+ 2 pos)))
11063 val)
11064 (forward-char 1) ""))
11065
11066 (defun org-table-current-column ()
11067 "Find out which column we are in.
11068 When called interactively, column is also displayed in echo area."
11069 (interactive)
11070 (if (interactive-p) (org-table-check-inside-data-field))
11071 (save-excursion
11072 (let ((cnt 0) (pos (point)))
11073 (beginning-of-line 1)
11074 (while (search-forward "|" pos t)
11075 (setq cnt (1+ cnt)))
11076 (if (interactive-p) (message "This is table column %d" cnt))
11077 cnt)))
11078
11079 (defun org-table-goto-column (n &optional on-delim force)
11080 "Move the cursor to the Nth column in the current table line.
11081 With optional argument ON-DELIM, stop with point before the left delimiter
11082 of the field.
11083 If there are less than N fields, just go to after the last delimiter.
11084 However, when FORCE is non-nil, create new columns if necessary."
11085 (interactive "p")
11086 (let ((pos (point-at-eol)))
11087 (beginning-of-line 1)
11088 (when (> n 0)
11089 (while (and (> (setq n (1- n)) -1)
11090 (or (search-forward "|" pos t)
11091 (and force
11092 (progn (end-of-line 1)
11093 (skip-chars-backward "^|")
11094 (insert " | "))))))
11095 ; (backward-char 2) t)))))
11096 (when (and force (not (looking-at ".*|")))
11097 (save-excursion (end-of-line 1) (insert " | ")))
11098 (if on-delim
11099 (backward-char 1)
11100 (if (looking-at " ") (forward-char 1))))))
11101
11102 (defun org-at-table-p (&optional table-type)
11103 "Return t if the cursor is inside an org-type table.
11104 If TABLE-TYPE is non-nil, also check for table.el-type tables."
11105 (if org-enable-table-editor
11106 (save-excursion
11107 (beginning-of-line 1)
11108 (looking-at (if table-type org-table-any-line-regexp
11109 org-table-line-regexp)))
11110 nil))
11111
11112 (defun org-at-table.el-p ()
11113 "Return t if and only if we are at a table.el table."
11114 (and (org-at-table-p 'any)
11115 (save-excursion
11116 (goto-char (org-table-begin 'any))
11117 (looking-at org-table1-hline-regexp))))
11118
11119 (defun org-table-recognize-table.el ()
11120 "If there is a table.el table nearby, recognize it and move into it."
11121 (if org-table-tab-recognizes-table.el
11122 (if (org-at-table.el-p)
11123 (progn
11124 (beginning-of-line 1)
11125 (if (looking-at org-table-dataline-regexp)
11126 nil
11127 (if (looking-at org-table1-hline-regexp)
11128 (progn
11129 (beginning-of-line 2)
11130 (if (looking-at org-table-any-border-regexp)
11131 (beginning-of-line -1)))))
11132 (if (re-search-forward "|" (org-table-end t) t)
11133 (progn
11134 (require 'table)
11135 (if (table--at-cell-p (point))
11136 t
11137 (message "recognizing table.el table...")
11138 (table-recognize-table)
11139 (message "recognizing table.el table...done")))
11140 (error "This should not happen..."))
11141 t)
11142 nil)
11143 nil))
11144
11145 (defun org-at-table-hline-p ()
11146 "Return t if the cursor is inside a hline in a table."
11147 (if org-enable-table-editor
11148 (save-excursion
11149 (beginning-of-line 1)
11150 (looking-at org-table-hline-regexp))
11151 nil))
11152
11153 (defun org-table-insert-column ()
11154 "Insert a new column into the table."
11155 (interactive)
11156 (if (not (org-at-table-p))
11157 (error "Not at a table"))
11158 (org-table-find-dataline)
11159 (let* ((col (max 1 (org-table-current-column)))
11160 (beg (org-table-begin))
11161 (end (org-table-end))
11162 ;; Current cursor position
11163 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11164 (colpos col))
11165 (goto-char beg)
11166 (while (< (point) end)
11167 (if (org-at-table-hline-p)
11168 nil
11169 (org-table-goto-column col t)
11170 (insert "| "))
11171 (beginning-of-line 2))
11172 (move-marker end nil)
11173 (goto-line linepos)
11174 (org-table-goto-column colpos)
11175 (org-table-align)
11176 (org-table-modify-formulas 'insert col)))
11177
11178 (defun org-table-find-dataline ()
11179 "Find a dataline in the current table, which is needed for column commands."
11180 (if (and (org-at-table-p)
11181 (not (org-at-table-hline-p)))
11182 t
11183 (let ((col (current-column))
11184 (end (org-table-end)))
11185 (move-to-column col)
11186 (while (and (< (point) end)
11187 (or (not (= (current-column) col))
11188 (org-at-table-hline-p)))
11189 (beginning-of-line 2)
11190 (move-to-column col))
11191 (if (and (org-at-table-p)
11192 (not (org-at-table-hline-p)))
11193 t
11194 (error
11195 "Please position cursor in a data line for column operations")))))
11196
11197 (defun org-table-delete-column ()
11198 "Delete a column from the table."
11199 (interactive)
11200 (if (not (org-at-table-p))
11201 (error "Not at a table"))
11202 (org-table-find-dataline)
11203 (org-table-check-inside-data-field)
11204 (let* ((col (org-table-current-column))
11205 (beg (org-table-begin))
11206 (end (org-table-end))
11207 ;; Current cursor position
11208 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11209 (colpos col))
11210 (goto-char beg)
11211 (while (< (point) end)
11212 (if (org-at-table-hline-p)
11213 nil
11214 (org-table-goto-column col t)
11215 (and (looking-at "|[^|\n]+|")
11216 (replace-match "|")))
11217 (beginning-of-line 2))
11218 (move-marker end nil)
11219 (goto-line linepos)
11220 (org-table-goto-column colpos)
11221 (org-table-align)
11222 (org-table-modify-formulas 'remove col)))
11223
11224 (defun org-table-move-column-right ()
11225 "Move column to the right."
11226 (interactive)
11227 (org-table-move-column nil))
11228 (defun org-table-move-column-left ()
11229 "Move column to the left."
11230 (interactive)
11231 (org-table-move-column 'left))
11232
11233 (defun org-table-move-column (&optional left)
11234 "Move the current column to the right. With arg LEFT, move to the left."
11235 (interactive "P")
11236 (if (not (org-at-table-p))
11237 (error "Not at a table"))
11238 (org-table-find-dataline)
11239 (org-table-check-inside-data-field)
11240 (let* ((col (org-table-current-column))
11241 (col1 (if left (1- col) col))
11242 (beg (org-table-begin))
11243 (end (org-table-end))
11244 ;; Current cursor position
11245 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11246 (colpos (if left (1- col) (1+ col))))
11247 (if (and left (= col 1))
11248 (error "Cannot move column further left"))
11249 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
11250 (error "Cannot move column further right"))
11251 (goto-char beg)
11252 (while (< (point) end)
11253 (if (org-at-table-hline-p)
11254 nil
11255 (org-table-goto-column col1 t)
11256 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
11257 (replace-match "|\\2|\\1|")))
11258 (beginning-of-line 2))
11259 (move-marker end nil)
11260 (goto-line linepos)
11261 (org-table-goto-column colpos)
11262 (org-table-align)
11263 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
11264
11265 (defun org-table-move-row-down ()
11266 "Move table row down."
11267 (interactive)
11268 (org-table-move-row nil))
11269 (defun org-table-move-row-up ()
11270 "Move table row up."
11271 (interactive)
11272 (org-table-move-row 'up))
11273
11274 (defun org-table-move-row (&optional up)
11275 "Move the current table line down. With arg UP, move it up."
11276 (interactive "P")
11277 (let ((col (current-column))
11278 (pos (point))
11279 (tonew (if up 0 2))
11280 txt)
11281 (beginning-of-line tonew)
11282 (if (not (org-at-table-p))
11283 (progn
11284 (goto-char pos)
11285 (error "Cannot move row further")))
11286 (goto-char pos)
11287 (beginning-of-line 1)
11288 (setq pos (point))
11289 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
11290 (delete-region (point) (1+ (point-at-eol)))
11291 (beginning-of-line tonew)
11292 (insert txt)
11293 (beginning-of-line 0)
11294 (move-to-column col)))
11295
11296 (defun org-table-insert-row (&optional arg)
11297 "Insert a new row above the current line into the table.
11298 With prefix ARG, insert below the current line."
11299 (interactive "P")
11300 (if (not (org-at-table-p))
11301 (error "Not at a table"))
11302 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
11303 (new (org-table-clean-line line)))
11304 ;; Fix the first field if necessary
11305 (if (string-match "^[ \t]*| *[#$] *|" line)
11306 (setq new (replace-match (match-string 0 line) t t new)))
11307 (beginning-of-line (if arg 2 1))
11308 (let (org-table-may-need-update) (insert-before-markers new "\n"))
11309 (beginning-of-line 0)
11310 (re-search-forward "| ?" (point-at-eol) t)
11311 (and org-table-may-need-update (org-table-align))))
11312
11313 (defun org-table-insert-hline (&optional arg)
11314 "Insert a horizontal-line below the current line into the table.
11315 With prefix ARG, insert above the current line."
11316 (interactive "P")
11317 (if (not (org-at-table-p))
11318 (error "Not at a table"))
11319 (let ((line (org-table-clean-line
11320 (buffer-substring (point-at-bol) (point-at-eol))))
11321 (col (current-column)))
11322 (while (string-match "|\\( +\\)|" line)
11323 (setq line (replace-match
11324 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
11325 ?-) "|") t t line)))
11326 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
11327 (beginning-of-line (if arg 1 2))
11328 (insert line "\n")
11329 (beginning-of-line (if arg 1 -1))
11330 (move-to-column col)))
11331
11332 (defun org-table-clean-line (s)
11333 "Convert a table line S into a string with only \"|\" and space.
11334 In particular, this does handle wide and invisible characters."
11335 (if (string-match "^[ \t]*|-" s)
11336 ;; It's a hline, just map the characters
11337 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
11338 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
11339 (setq s (replace-match
11340 (concat "|" (make-string (org-string-width (match-string 1 s))
11341 ?\ ) "|")
11342 t t s)))
11343 s))
11344
11345 (defun org-table-kill-row ()
11346 "Delete the current row or horizontal line from the table."
11347 (interactive)
11348 (if (not (org-at-table-p))
11349 (error "Not at a table"))
11350 (let ((col (current-column)))
11351 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
11352 (if (not (org-at-table-p)) (beginning-of-line 0))
11353 (move-to-column col)))
11354
11355 (defun org-table-sort-lines (beg end numericp)
11356 "Sort table lines in region.
11357 Point and mark define the first and last line to include. Both point and
11358 mark should be in the column that is used for sorting. For example, to
11359 sort according to column 3, put the mark in the first line to sort, in
11360 table column 3. Put point into the last line to be included in the sorting,
11361 also in table column 3. The command will prompt for the sorting method
11362 \(n for numerical, a for alphanumeric)."
11363 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
11364 (setq numericp (string-match "[nN]" numericp))
11365 (org-table-align) ;; Just to be safe
11366 (let* (bcol ecol cmp column lns)
11367 (goto-char beg)
11368 (org-table-check-inside-data-field)
11369 (setq column (org-table-current-column)
11370 beg (move-marker (make-marker) (point-at-bol)))
11371 (goto-char end)
11372 (org-table-check-inside-data-field)
11373 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
11374 (untabify beg end)
11375 (goto-char beg)
11376 (org-table-goto-column column)
11377 (skip-chars-backward "^|")
11378 (setq bcol (current-column))
11379 (org-table-goto-column (1+ column))
11380 (skip-chars-backward "^|")
11381 (setq ecol (1- (current-column)))
11382 (setq cmp (if numericp
11383 (lambda (a b) (< (car a) (car b)))
11384 (lambda (a b) (string< (car a) (car b)))))
11385 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
11386 (org-split-string (buffer-substring beg end) "\n")))
11387 (if numericp
11388 (setq lns (mapcar (lambda(x)
11389 (cons (string-to-number (car x)) (cdr x)))
11390 lns)))
11391 (delete-region beg end)
11392 (move-marker beg nil)
11393 (move-marker end nil)
11394 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
11395 (message "%d lines sorted %s based on column %d"
11396 (length lns)
11397 (if numericp "numerically" "alphabetically") column)))
11398
11399 (defun org-table-cut-region (beg end)
11400 "Copy region in table to the clipboard and blank all relevant fields."
11401 (interactive "r")
11402 (org-table-copy-region beg end 'cut))
11403
11404 (defun org-table-copy-region (beg end &optional cut)
11405 "Copy rectangular region in table to clipboard.
11406 A special clipboard is used which can only be accessed
11407 with `org-table-paste-rectangle'."
11408 (interactive "rP")
11409 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
11410 region cols
11411 (rpl (if cut " " nil)))
11412 (goto-char beg)
11413 (org-table-check-inside-data-field)
11414 (setq l01 (count-lines (point-min) (point))
11415 c01 (org-table-current-column))
11416 (goto-char end)
11417 (org-table-check-inside-data-field)
11418 (setq l02 (count-lines (point-min) (point))
11419 c02 (org-table-current-column))
11420 (setq l1 (min l01 l02) l2 (max l01 l02)
11421 c1 (min c01 c02) c2 (max c01 c02))
11422 (catch 'exit
11423 (while t
11424 (catch 'nextline
11425 (if (> l1 l2) (throw 'exit t))
11426 (goto-line l1)
11427 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
11428 (setq cols nil ic1 c1 ic2 c2)
11429 (while (< ic1 (1+ ic2))
11430 (push (org-table-get-field ic1 rpl) cols)
11431 (setq ic1 (1+ ic1)))
11432 (push (nreverse cols) region)
11433 (setq l1 (1+ l1)))))
11434 (setq org-table-clip (nreverse region))
11435 (if cut (org-table-align))
11436 org-table-clip))
11437
11438 (defun org-table-paste-rectangle ()
11439 "Paste a rectangular region into a table.
11440 The upper right corner ends up in the current field. All involved fields
11441 will be overwritten. If the rectangle does not fit into the present table,
11442 the table is enlarged as needed. The process ignores horizontal separator
11443 lines."
11444 (interactive)
11445 (unless (and org-table-clip (listp org-table-clip))
11446 (error "First cut/copy a region to paste!"))
11447 (org-table-check-inside-data-field)
11448 (let* ((clip org-table-clip)
11449 (line (count-lines (point-min) (point)))
11450 (col (org-table-current-column))
11451 (org-enable-table-editor t)
11452 (org-table-automatic-realign nil)
11453 c cols field)
11454 (while (setq cols (pop clip))
11455 (while (org-at-table-hline-p) (beginning-of-line 2))
11456 (if (not (org-at-table-p))
11457 (progn (end-of-line 0) (org-table-next-field)))
11458 (setq c col)
11459 (while (setq field (pop cols))
11460 (org-table-goto-column c nil 'force)
11461 (org-table-get-field nil field)
11462 (setq c (1+ c)))
11463 (beginning-of-line 2))
11464 (goto-line line)
11465 (org-table-goto-column col)
11466 (org-table-align)))
11467
11468 (defun org-table-convert ()
11469 "Convert from `org-mode' table to table.el and back.
11470 Obviously, this only works within limits. When an Org-mode table is
11471 converted to table.el, all horizontal separator lines get lost, because
11472 table.el uses these as cell boundaries and has no notion of horizontal lines.
11473 A table.el table can be converted to an Org-mode table only if it does not
11474 do row or column spanning. Multiline cells will become multiple cells.
11475 Beware, Org-mode does not test if the table can be successfully converted - it
11476 blindly applies a recipe that works for simple tables."
11477 (interactive)
11478 (require 'table)
11479 (if (org-at-table.el-p)
11480 ;; convert to Org-mode table
11481 (let ((beg (move-marker (make-marker) (org-table-begin t)))
11482 (end (move-marker (make-marker) (org-table-end t))))
11483 (table-unrecognize-region beg end)
11484 (goto-char beg)
11485 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
11486 (replace-match ""))
11487 (goto-char beg))
11488 (if (org-at-table-p)
11489 ;; convert to table.el table
11490 (let ((beg (move-marker (make-marker) (org-table-begin)))
11491 (end (move-marker (make-marker) (org-table-end))))
11492 ;; first, get rid of all horizontal lines
11493 (goto-char beg)
11494 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
11495 (replace-match ""))
11496 ;; insert a hline before first
11497 (goto-char beg)
11498 (org-table-insert-hline 'above)
11499 (beginning-of-line -1)
11500 ;; insert a hline after each line
11501 (while (progn (beginning-of-line 3) (< (point) end))
11502 (org-table-insert-hline))
11503 (goto-char beg)
11504 (setq end (move-marker end (org-table-end)))
11505 ;; replace "+" at beginning and ending of hlines
11506 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
11507 (replace-match "\\1+-"))
11508 (goto-char beg)
11509 (while (re-search-forward "-|[ \t]*$" end t)
11510 (replace-match "-+"))
11511 (goto-char beg)))))
11512
11513 (defun org-table-wrap-region (arg)
11514 "Wrap several fields in a column like a paragraph.
11515 This is useful if you'd like to spread the contents of a field over several
11516 lines, in order to keep the table compact.
11517
11518 If there is an active region, and both point and mark are in the same column,
11519 the text in the column is wrapped to minimum width for the given number of
11520 lines. Generally, this makes the table more compact. A prefix ARG may be
11521 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
11522 formats the selected text to two lines. If the region was longer than two
11523 lines, the remaining lines remain empty. A negative prefix argument reduces
11524 the current number of lines by that amount. The wrapped text is pasted back
11525 into the table. If you formatted it to more lines than it was before, fields
11526 further down in the table get overwritten - so you might need to make space in
11527 the table first.
11528
11529 If there is no region, the current field is split at the cursor position and
11530 the text fragment to the right of the cursor is prepended to the field one
11531 line down.
11532
11533 If there is no region, but you specify a prefix ARG, the current field gets
11534 blank, and the content is appended to the field above."
11535 (interactive "P")
11536 (org-table-check-inside-data-field)
11537 (if (org-region-active-p)
11538 ;; There is a region: fill as a paragraph
11539 (let ((beg (region-beginning))
11540 nlines)
11541 (org-table-cut-region (region-beginning) (region-end))
11542 (if (> (length (car org-table-clip)) 1)
11543 (error "Region must be limited to single column"))
11544 (setq nlines (if arg
11545 (if (< arg 1)
11546 (+ (length org-table-clip) arg)
11547 arg)
11548 (length org-table-clip)))
11549 (setq org-table-clip
11550 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
11551 nil nlines)))
11552 (goto-char beg)
11553 (org-table-paste-rectangle))
11554 ;; No region, split the current field at point
11555 (if arg
11556 ;; combine with field above
11557 (let ((s (org-table-blank-field))
11558 (col (org-table-current-column)))
11559 (beginning-of-line 0)
11560 (while (org-at-table-hline-p) (beginning-of-line 0))
11561 (org-table-goto-column col)
11562 (skip-chars-forward "^|")
11563 (skip-chars-backward " ")
11564 (insert " " (org-trim s))
11565 (org-table-align))
11566 ;; split field
11567 (when (looking-at "\\([^|]+\\)+|")
11568 (let ((s (match-string 1)))
11569 (replace-match " |")
11570 (goto-char (match-beginning 0))
11571 (org-table-next-row)
11572 (insert (org-trim s) " ")
11573 (org-table-align))))))
11574
11575 (defvar org-field-marker nil)
11576
11577 (defun org-table-edit-field (arg)
11578 "Edit table field in a different window.
11579 This is mainly useful for fields that contain hidden parts.
11580 When called with a \\[universal-argument] prefix, just make the full field visible so that
11581 it can be edited in place."
11582 (interactive "P")
11583 (if arg
11584 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
11585 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
11586 (remove-text-properties b e '(org-cwidth t invisible t
11587 display t intangible t))
11588 (if (and (boundp 'font-lock-mode) font-lock-mode)
11589 (font-lock-fontify-block)))
11590 (let ((pos (move-marker (make-marker) (point)))
11591 (field (org-table-get-field))
11592 (cw (current-window-configuration))
11593 p)
11594 (switch-to-buffer-other-window "*Org tmp*")
11595 (erase-buffer)
11596 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
11597 (org-mode)
11598 (goto-char (setq p (point-max)))
11599 (insert (org-trim field))
11600 (remove-text-properties p (point-max)
11601 '(invisible t org-cwidth t display t
11602 intangible t))
11603 (goto-char p)
11604 (org-set-local 'org-finish-function
11605 'org-table-finish-edit-field)
11606 (org-set-local 'org-window-configuration cw)
11607 (org-set-local 'org-field-marker pos)
11608 (message "Edit and finish with C-c C-c"))))
11609
11610 (defun org-table-finish-edit-field ()
11611 "Finish editing a table data field.
11612 Remove all newline characters, insert the result into the table, realign
11613 the table and kill the editing buffer."
11614 (let ((pos org-field-marker)
11615 (cw org-window-configuration)
11616 (cb (current-buffer))
11617 text)
11618 (goto-char (point-min))
11619 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
11620 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
11621 (replace-match " "))
11622 (setq text (org-trim (buffer-string)))
11623 (set-window-configuration cw)
11624 (kill-buffer cb)
11625 (select-window (get-buffer-window (marker-buffer pos)))
11626 (goto-char pos)
11627 (move-marker pos nil)
11628 (org-table-check-inside-data-field)
11629 (org-table-get-field nil text)
11630 (org-table-align)
11631 (message "New field value inserted")))
11632
11633 (defun org-trim (s)
11634 "Remove whitespace at beginning and end of string."
11635 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
11636 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
11637 s)
11638
11639 (defun org-wrap (string &optional width lines)
11640 "Wrap string to either a number of lines, or a width in characters.
11641 If WIDTH is non-nil, the string is wrapped to that width, however many lines
11642 that costs. If there is a word longer than WIDTH, the text is actually
11643 wrapped to the length of that word.
11644 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
11645 many lines, whatever width that takes.
11646 The return value is a list of lines, without newlines at the end."
11647 (let* ((words (org-split-string string "[ \t\n]+"))
11648 (maxword (apply 'max (mapcar 'org-string-width words)))
11649 w ll)
11650 (cond (width
11651 (org-do-wrap words (max maxword width)))
11652 (lines
11653 (setq w maxword)
11654 (setq ll (org-do-wrap words maxword))
11655 (if (<= (length ll) lines)
11656 ll
11657 (setq ll words)
11658 (while (> (length ll) lines)
11659 (setq w (1+ w))
11660 (setq ll (org-do-wrap words w)))
11661 ll))
11662 (t (error "Cannot wrap this")))))
11663
11664
11665 (defun org-do-wrap (words width)
11666 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
11667 (let (lines line)
11668 (while words
11669 (setq line (pop words))
11670 (while (and words (< (+ (length line) (length (car words))) width))
11671 (setq line (concat line " " (pop words))))
11672 (setq lines (push line lines)))
11673 (nreverse lines)))
11674
11675 (defun org-split-string (string &optional separators)
11676 "Splits STRING into substrings at SEPARATORS.
11677 No empty strings are returned if there are matches at the beginning
11678 and end of string."
11679 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
11680 (start 0)
11681 notfirst
11682 (list nil))
11683 (while (and (string-match rexp string
11684 (if (and notfirst
11685 (= start (match-beginning 0))
11686 (< start (length string)))
11687 (1+ start) start))
11688 (< (match-beginning 0) (length string)))
11689 (setq notfirst t)
11690 (or (eq (match-beginning 0) 0)
11691 (and (eq (match-beginning 0) (match-end 0))
11692 (eq (match-beginning 0) start))
11693 (setq list
11694 (cons (substring string start (match-beginning 0))
11695 list)))
11696 (setq start (match-end 0)))
11697 (or (eq start (length string))
11698 (setq list
11699 (cons (substring string start)
11700 list)))
11701 (nreverse list)))
11702
11703 (defun org-table-map-tables (function)
11704 "Apply FUNCTION to the start of all tables in the buffer."
11705 (save-excursion
11706 (save-restriction
11707 (widen)
11708 (goto-char (point-min))
11709 (while (re-search-forward org-table-any-line-regexp nil t)
11710 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
11711 (beginning-of-line 1)
11712 (if (looking-at org-table-line-regexp)
11713 (save-excursion (funcall function)))
11714 (re-search-forward org-table-any-border-regexp nil 1))))
11715 (message "Mapping tables: done"))
11716
11717 (defun org-table-sum (&optional beg end nlast)
11718 "Sum numbers in region of current table column.
11719 The result will be displayed in the echo area, and will be available
11720 as kill to be inserted with \\[yank].
11721
11722 If there is an active region, it is interpreted as a rectangle and all
11723 numbers in that rectangle will be summed. If there is no active
11724 region and point is located in a table column, sum all numbers in that
11725 column.
11726
11727 If at least one number looks like a time HH:MM or HH:MM:SS, all other
11728 numbers are assumed to be times as well (in decimal hours) and the
11729 numbers are added as such.
11730
11731 If NLAST is a number, only the NLAST fields will actually be summed."
11732 (interactive)
11733 (save-excursion
11734 (let (col (timecnt 0) diff h m s org-table-clip)
11735 (cond
11736 ((and beg end)) ; beg and end given explicitly
11737 ((org-region-active-p)
11738 (setq beg (region-beginning) end (region-end)))
11739 (t
11740 (setq col (org-table-current-column))
11741 (goto-char (org-table-begin))
11742 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
11743 (error "No table data"))
11744 (org-table-goto-column col)
11745 ;not needed? (skip-chars-backward "^|")
11746 (setq beg (point))
11747 (goto-char (org-table-end))
11748 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
11749 (error "No table data"))
11750 (org-table-goto-column col)
11751 ;not needed? (skip-chars-forward "^|")
11752 (setq end (point))))
11753 (let* ((items (apply 'append (org-table-copy-region beg end)))
11754 (items1 (cond ((not nlast) items)
11755 ((>= nlast (length items)) items)
11756 (t (setq items (reverse items))
11757 (setcdr (nthcdr (1- nlast) items) nil)
11758 (nreverse items))))
11759 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
11760 items1)))
11761 (res (apply '+ numbers))
11762 (sres (if (= timecnt 0)
11763 (format "%g" res)
11764 (setq diff (* 3600 res)
11765 h (floor (/ diff 3600)) diff (mod diff 3600)
11766 m (floor (/ diff 60)) diff (mod diff 60)
11767 s diff)
11768 (format "%d:%02d:%02d" h m s))))
11769 (kill-new sres)
11770 (if (interactive-p)
11771 (message "%s"
11772 (substitute-command-keys
11773 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
11774 (length numbers) sres))))
11775 sres))))
11776
11777 (defun org-table-get-number-for-summing (s)
11778 (let (n)
11779 (if (string-match "^ *|? *" s)
11780 (setq s (replace-match "" nil nil s)))
11781 (if (string-match " *|? *$" s)
11782 (setq s (replace-match "" nil nil s)))
11783 (setq n (string-to-number s))
11784 (cond
11785 ((and (string-match "0" s)
11786 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
11787 ((string-match "\\`[ \t]+\\'" s) nil)
11788 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
11789 (let ((h (string-to-number (or (match-string 1 s) "0")))
11790 (m (string-to-number (or (match-string 2 s) "0")))
11791 (s (string-to-number (or (match-string 4 s) "0"))))
11792 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
11793 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
11794 ((equal n 0) nil)
11795 (t n))))
11796
11797 (defun org-table-get-vertical-vector (desc &optional tbeg col)
11798 "Get a calc vector from a column, accorting to descriptor DESC.
11799 Optional arguments TBEG and COL can give the beginning of the table and
11800 the current column, to avoid unnecessary parsing."
11801 (save-excursion
11802 (or tbeg (setq tbeg (org-table-begin)))
11803 (or col (setq col (org-table-current-column)))
11804 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
11805 (cond
11806 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
11807 (setq n1 (- (match-end 1) (match-beginning 1)))
11808 (if (match-beginning 3)
11809 (setq n2 (- (match-end 2) (match-beginning 3))))
11810 (setq n (if n2 (max n1 n2) n1))
11811 (setq n1 (if n2 (min n1 n2)))
11812 (setq nn n)
11813 (while (and (> nn 0)
11814 (re-search-backward org-table-hline-regexp tbeg t))
11815 (push (org-current-line) hline-list)
11816 (setq nn (1- nn)))
11817 (setq hline-list (nreverse hline-list))
11818 (goto-line (nth (1- n) hline-list))
11819 (when (re-search-forward org-table-dataline-regexp)
11820 (org-table-goto-column col)
11821 (setq beg (point)))
11822 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
11823 (when (re-search-backward org-table-dataline-regexp)
11824 (org-table-goto-column col)
11825 (setq end (point)))
11826 (setq l (apply 'append (org-table-copy-region beg end)))
11827 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
11828 (if (equal x "") "0" x))
11829 l ",") "]"))
11830 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
11831 (setq n1 (string-to-number (match-string 1 desc))
11832 n2 (string-to-number (match-string 2 desc)))
11833 (beginning-of-line 1)
11834 (save-excursion
11835 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
11836 (org-table-goto-column col)
11837 (setq beg (point))))
11838 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
11839 (org-table-goto-column col)
11840 (setq end (point)))
11841 (setq l (apply 'append (org-table-copy-region beg end)))
11842 (concat "[" (mapconcat
11843 (lambda (x) (setq x (org-trim x))
11844 (if (equal x "") "0" x))
11845 l ",") "]"))
11846 ((string-match "\\([0-9]+\\)" desc)
11847 (beginning-of-line 1)
11848 (when (re-search-backward org-table-dataline-regexp tbeg t
11849 (string-to-number (match-string 0 desc)))
11850 (org-table-goto-column col)
11851 (org-trim (org-table-get-field))))))))
11852
11853 (defvar org-table-formula-history nil)
11854
11855 (defvar org-table-column-names nil
11856 "Alist with column names, derived from the `!' line.")
11857 (defvar org-table-column-name-regexp nil
11858 "Regular expression matching the current column names.")
11859 (defvar org-table-local-parameters nil
11860 "Alist with parameter names, derived from the `$' line.")
11861 (defvar org-table-named-field-locations nil
11862 "Alist with locations of named fields.")
11863
11864 (defun org-table-get-formula (&optional equation named)
11865 "Read a formula from the minibuffer, offer stored formula as default."
11866 (let* ((name (car (rassoc (list (org-current-line)
11867 (org-table-current-column))
11868 org-table-named-field-locations)))
11869 (scol (if named
11870 (if name name
11871 (error "Not in a named field"))
11872 (int-to-string (org-table-current-column))))
11873 (dummy (and name (not named)
11874 (not (y-or-n-p "Replace named-field formula with column equation? " ))
11875 (error "Abort")))
11876 (org-table-may-need-update nil)
11877 (stored-list (org-table-get-stored-formulas))
11878 (stored (cdr (assoc scol stored-list)))
11879 (eq (cond
11880 ((and stored equation (string-match "^ *=? *$" equation))
11881 stored)
11882 ((stringp equation)
11883 equation)
11884 (t (read-string
11885 (format "%s formula $%s=" (if named "Field" "Column") scol)
11886 (or stored "") 'org-table-formula-history
11887 ;stored
11888 ))))
11889 mustsave)
11890 (when (not (string-match "\\S-" eq))
11891 ;; remove formula
11892 (setq stored-list (delq (assoc scol stored-list) stored-list))
11893 (org-table-store-formulas stored-list)
11894 (error "Formula removed"))
11895 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
11896 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
11897 (if (and name (not named))
11898 ;; We set the column equation, delete the named one.
11899 (setq stored-list (delq (assoc name stored-list) stored-list)
11900 mustsave t))
11901 (if stored
11902 (setcdr (assoc scol stored-list) eq)
11903 (setq stored-list (cons (cons scol eq) stored-list)))
11904 (if (or mustsave (not (equal stored eq)))
11905 (org-table-store-formulas stored-list))
11906 eq))
11907
11908 (defun org-table-store-formulas (alist)
11909 "Store the list of formulas below the current table."
11910 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
11911 (save-excursion
11912 (goto-char (org-table-end))
11913 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
11914 (delete-region (point) (match-end 0)))
11915 (insert "#+TBLFM: "
11916 (mapconcat (lambda (x)
11917 (concat "$" (car x) "=" (cdr x)))
11918 alist "::")
11919 "\n")))
11920
11921 (defun org-table-get-stored-formulas ()
11922 "Return an alist with the stored formulas directly after current table."
11923 (interactive)
11924 (let (scol eq eq-alist strings string seen)
11925 (save-excursion
11926 (goto-char (org-table-end))
11927 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
11928 (setq strings (org-split-string (match-string 2) " *:: *"))
11929 (while (setq string (pop strings))
11930 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
11931 (setq scol (match-string 1 string)
11932 eq (match-string 2 string)
11933 eq-alist (cons (cons scol eq) eq-alist))
11934 (if (member scol seen)
11935 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
11936 (push scol seen))))))
11937 (nreverse eq-alist)))
11938
11939 (defun org-table-modify-formulas (action &rest columns)
11940 "Modify the formulas stored below the current table.
11941 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
11942 expected, for the other actions only a single column number is needed."
11943 (let ((list (org-table-get-stored-formulas))
11944 (nmax (length (org-split-string
11945 (buffer-substring (point-at-bol) (point-at-eol))
11946 "|")))
11947 col col1 col2 scol si sc1 sc2)
11948 (cond
11949 ((null list)) ; No action needed if there are no stored formulas
11950 ((eq action 'remove)
11951 (setq col (car columns)
11952 scol (int-to-string col))
11953 (org-table-replace-in-formulas list scol "INVALID")
11954 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
11955 (loop for i from (1+ col) upto nmax by 1 do
11956 (setq si (int-to-string i))
11957 (org-table-replace-in-formulas list si (int-to-string (1- i)))
11958 (if (assoc si list) (setcar (assoc si list)
11959 (int-to-string (1- i))))))
11960 ((eq action 'insert)
11961 (setq col (car columns))
11962 (loop for i from nmax downto col 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 'swap)
11968 (setq col1 (car columns) col2 (nth 1 columns)
11969 sc1 (int-to-string col1) sc2 (int-to-string col2))
11970 ;; Hopefully, ZqZtZ will never be a name in a table
11971 (org-table-replace-in-formulas list sc1 "ZqZtZ")
11972 (org-table-replace-in-formulas list sc2 sc1)
11973 (org-table-replace-in-formulas list "ZqZtZ" sc2)
11974 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
11975 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
11976 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
11977 (t (error "Invalid action in `org-table-modify-formulas'")))
11978 (if list (org-table-store-formulas list))))
11979
11980 (defun org-table-replace-in-formulas (list s1 s2)
11981 (let (elt re s)
11982 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
11983 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
11984 re (concat (regexp-quote s1) "\\>"))
11985 (while (setq elt (pop list))
11986 (setq s (cdr elt))
11987 (while (string-match re s)
11988 (setq s (replace-match s2 t t s)))
11989 (setcdr elt s))))
11990
11991 (defun org-table-get-specials ()
11992 "Get the column names and local parameters for this table."
11993 (save-excursion
11994 (let ((beg (org-table-begin)) (end (org-table-end))
11995 names name fields fields1 field cnt c v line col)
11996 (setq org-table-column-names nil
11997 org-table-local-parameters nil
11998 org-table-named-field-locations nil)
11999 (goto-char beg)
12000 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
12001 (setq names (org-split-string (match-string 1) " *| *")
12002 cnt 1)
12003 (while (setq name (pop names))
12004 (setq cnt (1+ cnt))
12005 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
12006 (push (cons name (int-to-string cnt)) org-table-column-names))))
12007 (setq org-table-column-names (nreverse org-table-column-names))
12008 (setq org-table-column-name-regexp
12009 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
12010 (goto-char beg)
12011 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
12012 (setq fields (org-split-string (match-string 1) " *| *"))
12013 (while (setq field (pop fields))
12014 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
12015 (push (cons (match-string 1 field) (match-string 2 field))
12016 org-table-local-parameters))))
12017 (goto-char beg)
12018 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
12019 (setq c (match-string 1)
12020 fields (org-split-string (match-string 2) " *| *"))
12021 (save-excursion
12022 (beginning-of-line (if (equal c "_") 2 0))
12023 (setq line (org-current-line) col 1)
12024 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
12025 (setq fields1 (org-split-string (match-string 1) " *| *"))))
12026 (while (and fields1 (setq field (pop fields)))
12027 (setq v (pop fields1) col (1+ col))
12028 (when (and (stringp field) (stringp v)
12029 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
12030 (push (cons field v) org-table-local-parameters)
12031 (push (list field line col) org-table-named-field-locations)))))))
12032
12033 (defun org-this-word ()
12034 ;; Get the current word
12035 (save-excursion
12036 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
12037 (end (progn (skip-chars-forward "^ \t\n") (point))))
12038 (buffer-substring-no-properties beg end))))
12039
12040 (defun org-table-maybe-eval-formula ()
12041 "Check if the current field starts with \"=\" or \":=\".
12042 If yes, store the formula and apply it."
12043 ;; We already know we are in a table. Get field will only return a formula
12044 ;; when appropriate. It might return a separator line, but no problem.
12045 (when org-table-formula-evaluate-inline
12046 (let* ((field (org-trim (or (org-table-get-field) "")))
12047 named eq)
12048 (when (string-match "^:?=\\(.*\\)" field)
12049 (setq named (equal (string-to-char field) ?:)
12050 eq (match-string 1 field))
12051 (if (fboundp 'calc-eval)
12052 (org-table-eval-formula (if named '(4) nil) eq))))))
12053
12054 (defvar org-recalc-commands nil
12055 "List of commands triggering the recalculation of a line.
12056 Will be filled automatically during use.")
12057
12058 (defvar org-recalc-marks
12059 '((" " . "Unmarked: no special line, no automatic recalculation")
12060 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
12061 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
12062 ("!" . "Column name definition line. Reference in formula as $name.")
12063 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
12064 ("_" . "Names for values in row below this one.")
12065 ("^" . "Names for values in row above this one.")))
12066
12067 (defun org-table-rotate-recalc-marks (&optional newchar)
12068 "Rotate the recalculation mark in the first column.
12069 If in any row, the first field is not consistent with a mark,
12070 insert a new column for the markers.
12071 When there is an active region, change all the lines in the region,
12072 after prompting for the marking character.
12073 After each change, a message will be displayed indicating the meaning
12074 of the new mark."
12075 (interactive)
12076 (unless (org-at-table-p) (error "Not at a table"))
12077 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
12078 (beg (org-table-begin))
12079 (end (org-table-end))
12080 (l (org-current-line))
12081 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
12082 (l2 (if (org-region-active-p) (org-current-line (region-end))))
12083 (have-col
12084 (save-excursion
12085 (goto-char beg)
12086 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
12087 (col (org-table-current-column))
12088 (forcenew (car (assoc newchar org-recalc-marks)))
12089 epos new)
12090 (when l1
12091 (message "Change region to what mark? Type # * ! $ or SPC: ")
12092 (setq newchar (char-to-string (read-char-exclusive))
12093 forcenew (car (assoc newchar org-recalc-marks))))
12094 (if (and newchar (not forcenew))
12095 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
12096 newchar))
12097 (if l1 (goto-line l1))
12098 (save-excursion
12099 (beginning-of-line 1)
12100 (unless (looking-at org-table-dataline-regexp)
12101 (error "Not at a table data line")))
12102 (unless have-col
12103 (org-table-goto-column 1)
12104 (org-table-insert-column)
12105 (org-table-goto-column (1+ col)))
12106 (setq epos (point-at-eol))
12107 (save-excursion
12108 (beginning-of-line 1)
12109 (org-table-get-field
12110 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
12111 (concat " "
12112 (setq new (or forcenew
12113 (cadr (member (match-string 1) marks))))
12114 " ")
12115 " # ")))
12116 (if (and l1 l2)
12117 (progn
12118 (goto-line l1)
12119 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
12120 (and (looking-at org-table-dataline-regexp)
12121 (org-table-get-field 1 (concat " " new " "))))
12122 (goto-line l1)))
12123 (if (not (= epos (point-at-eol))) (org-table-align))
12124 (goto-line l)
12125 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
12126
12127 (defun org-table-maybe-recalculate-line ()
12128 "Recompute the current line if marked for it, and if we haven't just done it."
12129 (interactive)
12130 (and org-table-allow-automatic-line-recalculation
12131 (not (and (memq last-command org-recalc-commands)
12132 (equal org-last-recalc-line (org-current-line))))
12133 (save-excursion (beginning-of-line 1)
12134 (looking-at org-table-auto-recalculate-regexp))
12135 (fboundp 'calc-eval)
12136 (org-table-recalculate) t))
12137
12138 (defvar org-table-formula-debug nil
12139 "Non-nil means, debug table formulas.
12140 When nil, simply write \"#ERROR\" in corrupted fields.")
12141
12142 (defvar modes)
12143 (defsubst org-set-calc-mode (var &optional value)
12144 (if (stringp var)
12145 (setq var (assoc var '(("D" calc-angle-mode deg)
12146 ("R" calc-angle-mode rad)
12147 ("F" calc-prefer-frac t)
12148 ("S" calc-symbolic-mode t)))
12149 value (nth 2 var) var (nth 1 var)))
12150 (if (memq var modes)
12151 (setcar (cdr (memq var modes)) value)
12152 (cons var (cons value modes)))
12153 modes)
12154
12155 (defun org-table-eval-formula (&optional arg equation
12156 suppress-align suppress-const
12157 suppress-store)
12158 "Replace the table field value at the cursor by the result of a calculation.
12159
12160 This function makes use of Dave Gillespie's Calc package, in my view the
12161 most exciting program ever written for GNU Emacs. So you need to have Calc
12162 installed in order to use this function.
12163
12164 In a table, this command replaces the value in the current field with the
12165 result of a formula. It also installs the formula as the \"current\" column
12166 formula, by storing it in a special line below the table. When called
12167 with a `C-u' prefix, the current field must ba a named field, and the
12168 formula is installed as valid in only this specific field.
12169
12170 When called, the command first prompts for a formula, which is read in
12171 the minibuffer. Previously entered formulas are available through the
12172 history list, and the last used formula is offered as a default.
12173 These stored formulas are adapted correctly when moving, inserting, or
12174 deleting columns with the corresponding commands.
12175
12176 The formula can be any algebraic expression understood by the Calc package.
12177 For details, see the Org-mode manual.
12178
12179 This function can also be called from Lisp programs and offers
12180 additional arguments: EQUATION can be the formula to apply. If this
12181 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
12182 used to speed-up recursive calls by by-passing unnecessary aligns.
12183 SUPPRESS-CONST suppresses the interpretation of constants in the
12184 formula, assuming that this has been done already outside the function.
12185 SUPPRESS-STORE means the formula should not be stored, either because
12186 it is already stored, or because it is a modified equation that should
12187 not overwrite the stored one."
12188 (interactive "P")
12189 (require 'calc)
12190 (org-table-check-inside-data-field)
12191 (org-table-get-specials)
12192 (let* (fields
12193 (ndown (if (integerp arg) arg 1))
12194 (org-table-automatic-realign nil)
12195 (case-fold-search nil)
12196 (down (> ndown 1))
12197 (formula (if (and equation suppress-store)
12198 equation
12199 (org-table-get-formula equation (equal arg '(4)))))
12200 (n0 (org-table-current-column))
12201 (modes (copy-sequence org-calc-default-modes))
12202 n form fmt x ev orig c lispp)
12203 ;; Parse the format string. Since we have a lot of modes, this is
12204 ;; a lot of work. However, I think calc still uses most of the time.
12205 (if (string-match ";" formula)
12206 (let ((tmp (org-split-string formula ";")))
12207 (setq formula (car tmp)
12208 fmt (concat (cdr (assoc "%" org-table-local-parameters))
12209 (nth 1 tmp)))
12210 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
12211 (setq c (string-to-char (match-string 1 fmt))
12212 n (string-to-number (match-string 2 fmt)))
12213 (if (= c ?p)
12214 (setq modes (org-set-calc-mode 'calc-internal-prec n))
12215 (setq modes (org-set-calc-mode
12216 'calc-float-format
12217 (list (cdr (assoc c '((?n . float) (?f . fix)
12218 (?s . sci) (?e . eng))))
12219 n))))
12220 (setq fmt (replace-match "" t t fmt)))
12221 (while (string-match "[DRFS]" fmt)
12222 (setq modes (org-set-calc-mode (match-string 0 fmt)))
12223 (setq fmt (replace-match "" t t fmt)))
12224 (unless (string-match "\\S-" fmt)
12225 (setq fmt nil))))
12226 (if (and (not suppress-const) org-table-formula-use-constants)
12227 (setq formula (org-table-formula-substitute-names formula)))
12228 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
12229 (while (> ndown 0)
12230 (setq fields (org-split-string
12231 (buffer-substring
12232 (point-at-bol) (point-at-eol)) " *| *"))
12233 (if org-table-formula-numbers-only
12234 (setq fields (mapcar
12235 (lambda (x) (number-to-string (string-to-number x)))
12236 fields)))
12237 (setq ndown (1- ndown))
12238 (setq form (copy-sequence formula)
12239 lispp (equal (substring form 0 2) "'("))
12240 ;; Insert the references to fields in same row
12241 (while (string-match "\\$\\([0-9]+\\)?" form)
12242 (setq n (if (match-beginning 1)
12243 (string-to-number (match-string 1 form))
12244 n0)
12245 x (nth (1- n) fields))
12246 (unless x (error "Invalid field specifier \"%s\""
12247 (match-string 0 form)))
12248 (if (equal x "") (setq x "0"))
12249 (setq form (replace-match
12250 (if lispp x (concat "(" x ")"))
12251 t t form)))
12252 ;; Insert ranges in current column
12253 (while (string-match "\\&[-I0-9]+" form)
12254 (setq form (replace-match
12255 (save-match-data
12256 (org-table-get-vertical-vector (match-string 0 form)
12257 nil n0))
12258 t t form)))
12259 (if lispp
12260 (setq ev (eval (eval (read form)))
12261 ev (if (numberp ev) (number-to-string ev) ev))
12262 (setq ev (calc-eval (cons form modes)
12263 (if org-table-formula-numbers-only 'num))))
12264
12265 (when org-table-formula-debug
12266 (with-output-to-temp-buffer "*Help*"
12267 (princ (format "Substitution history of formula
12268 Orig: %s
12269 $xyz-> %s
12270 $1-> %s\n" orig formula form))
12271 (if (listp ev)
12272 (princ (format " %s^\nError: %s"
12273 (make-string (car ev) ?\-) (nth 1 ev)))
12274 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
12275 ev (or fmt "NONE")
12276 (if fmt (format fmt (string-to-number ev)) ev)))))
12277 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
12278 (unless (and (interactive-p) (not ndown))
12279 (unless (let (inhibit-redisplay)
12280 (y-or-n-p "Debugging Formula. Continue to next? "))
12281 (org-table-align)
12282 (error "Abort"))
12283 (delete-window (get-buffer-window "*Help*"))
12284 (message "")))
12285 (if (listp ev) (setq fmt nil ev "#ERROR"))
12286 (org-table-justify-field-maybe
12287 (if fmt (format fmt (string-to-number ev)) ev))
12288 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
12289 (call-interactively 'org-return)
12290 (setq ndown 0)))
12291 (and down (org-table-maybe-recalculate-line))
12292 (or suppress-align (and org-table-may-need-update
12293 (org-table-align)))))
12294
12295 (defun org-table-recalculate (&optional all noalign)
12296 "Recalculate the current table line by applying all stored formulas.
12297 With prefix arg ALL, do this for all lines in the table."
12298 (interactive "P")
12299 (or (memq this-command org-recalc-commands)
12300 (setq org-recalc-commands (cons this-command org-recalc-commands)))
12301 (unless (org-at-table-p) (error "Not at a table"))
12302 (org-table-get-specials)
12303 (let* ((eqlist (sort (org-table-get-stored-formulas)
12304 (lambda (a b) (string< (car a) (car b)))))
12305 (inhibit-redisplay t)
12306 (line-re org-table-dataline-regexp)
12307 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
12308 (thiscol (org-table-current-column))
12309 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
12310 ;; Insert constants in all formulas
12311 (setq eqlist
12312 (mapcar (lambda (x)
12313 (setcdr x (org-table-formula-substitute-names (cdr x)))
12314 x)
12315 eqlist))
12316 ;; Split the equation list
12317 (while (setq eq (pop eqlist))
12318 (if (<= (string-to-char (car eq)) ?9)
12319 (push eq eqlnum)
12320 (push eq eqlname)))
12321 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
12322 (if all
12323 (progn
12324 (setq end (move-marker (make-marker) (1+ (org-table-end))))
12325 (goto-char (setq beg (org-table-begin)))
12326 (if (re-search-forward org-table-calculate-mark-regexp end t)
12327 ;; This is a table with marked lines, only compute selected lines
12328 (setq line-re org-table-recalculate-regexp)
12329 ;; Move forward to the first non-header line
12330 (if (and (re-search-forward org-table-dataline-regexp end t)
12331 (re-search-forward org-table-hline-regexp end t)
12332 (re-search-forward org-table-dataline-regexp end t))
12333 (setq beg (match-beginning 0))
12334 nil))) ;; just leave beg where it is
12335 (setq beg (point-at-bol)
12336 end (move-marker (make-marker) (1+ (point-at-eol)))))
12337 (goto-char beg)
12338 (and all (message "Re-applying formulas to full table..."))
12339 (while (re-search-forward line-re end t)
12340 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
12341 ;; Unprotected line, recalculate
12342 (and all (message "Re-applying formulas to full table...(line %d)"
12343 (setq cnt (1+ cnt))))
12344 (setq org-last-recalc-line (org-current-line))
12345 (setq eql eqlnum)
12346 (while (setq entry (pop eql))
12347 (goto-line org-last-recalc-line)
12348 (org-table-goto-column (string-to-number (car entry)) nil 'force)
12349 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
12350 (goto-line thisline)
12351 (org-table-goto-column thiscol)
12352 (or noalign (and org-table-may-need-update (org-table-align))
12353 (and all (message "Re-applying formulas to %d lines...done" cnt)))
12354 ;; Now do the names fields
12355 (while (setq eq (pop eqlname))
12356 (setq name (car eq)
12357 a (assoc name org-table-named-field-locations))
12358 (when a
12359 (message "Re-applying formula to named field: %s" name)
12360 (goto-line (nth 1 a))
12361 (org-table-goto-column (nth 2 a))
12362 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
12363 ;; back to initial position
12364 (goto-line thisline)
12365 (org-table-goto-column thiscol)
12366 (or noalign (and org-table-may-need-update (org-table-align))
12367 (and all (message "Re-applying formulas...done")))))
12368
12369 (defun org-table-formula-substitute-names (f)
12370 "Replace $const with values in string F."
12371 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
12372 ;; First, check for column names
12373 (while (setq start (string-match org-table-column-name-regexp f start))
12374 (setq start (1+ start))
12375 (setq a (assoc (match-string 1 f) org-table-column-names))
12376 (setq f (replace-match (concat "$" (cdr a)) t t f)))
12377 ;; Expand ranges to vectors
12378 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
12379 (setq n1 (string-to-number (match-string 1 f))
12380 n2 (string-to-number (match-string 2 f))
12381 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
12382 s (concat "[($" (number-to-string (1- nn1)) ")"))
12383 (loop for i from nn1 upto nn2 do
12384 (setq s (concat s ",($" (int-to-string i) ")")))
12385 (setq s (concat s "]"))
12386 (if (< n2 n1) (setq s (concat "rev(" s ")")))
12387 (setq f (replace-match s t t f)))
12388 ;; Parameters and constants
12389 (setq start 0)
12390 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
12391 (setq start (1+ start))
12392 (if (setq a (save-match-data
12393 (org-table-get-constant (match-string 1 f))))
12394 (setq f (replace-match (concat "(" a ")") t t f))))
12395 (if org-table-formula-debug
12396 (put-text-property 0 (length f) :orig-formula f1 f))
12397 f))
12398
12399 (defun org-table-get-constant (const)
12400 "Find the value for a parameter or constant in a formula.
12401 Parameters get priority."
12402 (or (cdr (assoc const org-table-local-parameters))
12403 (cdr (assoc const org-table-formula-constants))
12404 (and (fboundp 'constants-get) (constants-get const))
12405 "#UNDEFINED_NAME"))
12406
12407 (defvar org-edit-formulas-map (make-sparse-keymap))
12408 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
12409 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
12410 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
12411
12412 (defvar org-pos)
12413
12414 (defun org-table-edit-formulas ()
12415 "Edit the formulas of the current table in a separate buffer."
12416 (interactive)
12417 (unless (org-at-table-p)
12418 (error "Not at a table"))
12419 (org-table-get-specials)
12420 (let ((eql (org-table-get-stored-formulas))
12421 (pos (move-marker (make-marker) (point)))
12422 (wc (current-window-configuration))
12423 entry loc s)
12424 (switch-to-buffer-other-window "*Edit Formulas*")
12425 (erase-buffer)
12426 (fundamental-mode)
12427 (org-set-local 'org-pos pos)
12428 (org-set-local 'org-window-configuration wc)
12429 (use-local-map org-edit-formulas-map)
12430 (setq s "# Edit formulas and finish with `C-c C-c'.
12431 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
12432 # Use `C-c ?' to get information about $name at point.
12433 # To cancel editing, press `C-c C-q'.\n")
12434 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12435 (insert s)
12436 (while (setq entry (pop eql))
12437 (when (setq loc (assoc (car entry) org-table-named-field-locations))
12438 (setq s (format "# Named formula, referring to column %d in line %d\n"
12439 (nth 2 loc) (nth 1 loc)))
12440 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12441 (insert s))
12442 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
12443 (remove-text-properties 0 (length s) '(face nil) s)
12444 (insert s))
12445 (goto-char (point-min))
12446 (message "Edit formulas and finish with `C-c C-c'.")))
12447
12448 (defun org-show-variable ()
12449 "Show the location/value of the $ expression at point."
12450 (interactive)
12451 (let (var (pos org-pos) (win (selected-window)) e)
12452 (save-excursion
12453 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
12454 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
12455 (setq var (match-string 1))
12456 (error "No variable at point")))
12457 (cond
12458 ((setq e (assoc var org-table-named-field-locations))
12459 (switch-to-buffer-other-window (marker-buffer pos))
12460 (goto-line (nth 1 e))
12461 (org-table-goto-column (nth 2 e))
12462 (select-window win)
12463 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
12464 ((setq e (assoc var org-table-column-names))
12465 (switch-to-buffer-other-window (marker-buffer pos))
12466 (goto-char pos)
12467 (goto-char (org-table-begin))
12468 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
12469 (org-table-end) t)
12470 (progn
12471 (goto-char (match-beginning 1))
12472 (message "Named column (column %s)" (cdr e)))
12473 (error "Column name not found"))
12474 (select-window win))
12475 ((string-match "^[0-9]$" var)
12476 ;; column number
12477 (switch-to-buffer-other-window (marker-buffer pos))
12478 (goto-char pos)
12479 (goto-char (org-table-begin))
12480 (recenter 1)
12481 (if (re-search-forward org-table-dataline-regexp
12482 (org-table-end) t)
12483 (progn
12484 (goto-char (match-beginning 0))
12485 (org-table-goto-column (string-to-number var))
12486 (message "Column %s" var))
12487 (error "Column name not found"))
12488 (select-window win))
12489 ((setq e (assoc var org-table-local-parameters))
12490 (switch-to-buffer-other-window (marker-buffer pos))
12491 (goto-char pos)
12492 (goto-char (org-table-begin))
12493 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
12494 (progn
12495 (goto-char (match-beginning 1))
12496 (message "Local parameter."))
12497 (error "Parameter not found"))
12498 (select-window win))
12499 (t
12500 (cond
12501 ((setq e (assoc var org-table-formula-constants))
12502 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
12503 ((setq e (and (fboundp 'constants-get) (constants-get var)))
12504 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
12505 (t (error "Undefined name $%s" var)))))))
12506
12507 (defun org-finish-edit-formulas (&optional arg)
12508 "Parse the buffer for formula definitions and install them.
12509 With prefix ARG, apply the new formulas to the table."
12510 (interactive "P")
12511 (let ((pos org-pos) eql)
12512 (goto-char (point-min))
12513 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
12514 (push (cons (match-string 1) (match-string 2)) eql))
12515 (set-window-configuration org-window-configuration)
12516 (select-window (get-buffer-window (marker-buffer pos)))
12517 (goto-char pos)
12518 (unless (org-at-table-p)
12519 (error "Lost table position - cannot install formulae"))
12520 (org-table-store-formulas eql)
12521 (move-marker pos nil)
12522 (kill-buffer "*Edit Formulas*")
12523 (if arg
12524 (org-table-recalculate 'all)
12525 (message "New formulas installed - press C-u C-c C-c to apply."))))
12526
12527 (defun org-abort-edit-formulas ()
12528 "Abort editing formulas, without installing the changes."
12529 (interactive)
12530 (let ((pos org-pos))
12531 (set-window-configuration org-window-configuration)
12532 (select-window (get-buffer-window (marker-buffer pos)))
12533 (goto-char pos)
12534 (message "Formula editing aborted without installing changes")))
12535
12536 ;;; The orgtbl minor mode
12537
12538 ;; Define a minor mode which can be used in other modes in order to
12539 ;; integrate the org-mode table editor.
12540
12541 ;; This is really a hack, because the org-mode table editor uses several
12542 ;; keys which normally belong to the major mode, for example the TAB and
12543 ;; RET keys. Here is how it works: The minor mode defines all the keys
12544 ;; necessary to operate the table editor, but wraps the commands into a
12545 ;; function which tests if the cursor is currently inside a table. If that
12546 ;; is the case, the table editor command is executed. However, when any of
12547 ;; those keys is used outside a table, the function uses `key-binding' to
12548 ;; look up if the key has an associated command in another currently active
12549 ;; keymap (minor modes, major mode, global), and executes that command.
12550 ;; There might be problems if any of the keys used by the table editor is
12551 ;; otherwise used as a prefix key.
12552
12553 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
12554 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
12555 ;; addresses this by checking explicitly for both bindings.
12556
12557 ;; The optimized version (see variable `orgtbl-optimized') takes over
12558 ;; all keys which are bound to `self-insert-command' in the *global map*.
12559 ;; Some modes bind other commands to simple characters, for example
12560 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
12561 ;; active, this binding is ignored inside tables and replaced with a
12562 ;; modified self-insert.
12563
12564 (defvar orgtbl-mode nil
12565 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
12566 table editor in arbitrary modes.")
12567 (make-variable-buffer-local 'orgtbl-mode)
12568
12569 (defvar orgtbl-mode-map (make-keymap)
12570 "Keymap for `orgtbl-mode'.")
12571
12572 ;;;###autoload
12573 (defun turn-on-orgtbl ()
12574 "Unconditionally turn on `orgtbl-mode'."
12575 (orgtbl-mode 1))
12576
12577 ;;;###autoload
12578 (defun orgtbl-mode (&optional arg)
12579 "The `org-mode' table editor as a minor mode for use in other modes."
12580 (interactive)
12581 (if (org-mode-p)
12582 ;; Exit without error, in case some hook functions calls this
12583 ;; by accident in org-mode.
12584 (message "Orgtbl-mode is not useful in org-mode, command ignored")
12585 (setq orgtbl-mode
12586 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
12587 (if orgtbl-mode
12588 (progn
12589 (and (orgtbl-setup) (defun orgtbl-setup () nil))
12590 ;; Make sure we are first in minor-mode-map-alist
12591 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
12592 (and c (setq minor-mode-map-alist
12593 (cons c (delq c minor-mode-map-alist)))))
12594 (org-set-local (quote org-table-may-need-update) t)
12595 (org-add-hook 'before-change-functions 'org-before-change-function
12596 nil 'local)
12597 (org-set-local 'org-old-auto-fill-inhibit-regexp
12598 auto-fill-inhibit-regexp)
12599 (org-set-local 'auto-fill-inhibit-regexp
12600 (if auto-fill-inhibit-regexp
12601 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
12602 "[ \t]*|"))
12603 (org-add-to-invisibility-spec '(org-cwidth))
12604 (easy-menu-add orgtbl-mode-menu)
12605 (run-hooks 'orgtbl-mode-hook))
12606 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
12607 (org-cleanup-narrow-column-properties)
12608 (org-remove-from-invisibility-spec '(org-cwidth))
12609 (remove-hook 'before-change-functions 'org-before-change-function t)
12610 (easy-menu-remove orgtbl-mode-menu)
12611 (force-mode-line-update 'all))))
12612
12613 (defun org-cleanup-narrow-column-properties ()
12614 "Remove all properties related to narrow-column invisibility."
12615 (let ((s 1))
12616 (while (setq s (text-property-any s (point-max)
12617 'display org-narrow-column-arrow))
12618 (remove-text-properties s (1+ s) '(display t)))
12619 (setq s 1)
12620 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
12621 (remove-text-properties s (1+ s) '(org-cwidth t)))
12622 (setq s 1)
12623 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
12624 (remove-text-properties s (1+ s) '(invisible t)))))
12625
12626 ;; Install it as a minor mode.
12627 (put 'orgtbl-mode :included t)
12628 (put 'orgtbl-mode :menu-tag "Org Table Mode")
12629 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
12630
12631 (defun orgtbl-make-binding (fun n &rest keys)
12632 "Create a function for binding in the table minor mode.
12633 FUN is the command to call inside a table. N is used to create a unique
12634 command name. KEYS are keys that should be checked in for a command
12635 to execute outside of tables."
12636 (eval
12637 (list 'defun
12638 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
12639 '(arg)
12640 (concat "In tables, run `" (symbol-name fun) "'.\n"
12641 "Outside of tables, run the binding of `"
12642 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
12643 "'.")
12644 '(interactive "p")
12645 (list 'if
12646 '(org-at-table-p)
12647 (list 'call-interactively (list 'quote fun))
12648 (list 'let '(orgtbl-mode)
12649 (list 'call-interactively
12650 (append '(or)
12651 (mapcar (lambda (k)
12652 (list 'key-binding k))
12653 keys)
12654 '('orgtbl-error))))))))
12655
12656 (defun orgtbl-error ()
12657 "Error when there is no default binding for a table key."
12658 (interactive)
12659 (error "This key is has no function outside tables"))
12660
12661 (defun orgtbl-setup ()
12662 "Setup orgtbl keymaps."
12663 (let ((nfunc 0)
12664 (bindings
12665 (list
12666 '([(meta shift left)] org-table-delete-column)
12667 '([(meta left)] org-table-move-column-left)
12668 '([(meta right)] org-table-move-column-right)
12669 '([(meta shift right)] org-table-insert-column)
12670 '([(meta shift up)] org-table-kill-row)
12671 '([(meta shift down)] org-table-insert-row)
12672 '([(meta up)] org-table-move-row-up)
12673 '([(meta down)] org-table-move-row-down)
12674 '("\C-c\C-w" org-table-cut-region)
12675 '("\C-c\M-w" org-table-copy-region)
12676 '("\C-c\C-y" org-table-paste-rectangle)
12677 '("\C-c-" org-table-insert-hline)
12678 ; '([(shift tab)] org-table-previous-field)
12679 '("\C-m" org-table-next-row)
12680 (list (org-key 'S-return) 'org-table-copy-down)
12681 '([(meta return)] org-table-wrap-region)
12682 '("\C-c\C-q" org-table-wrap-region)
12683 '("\C-c?" org-table-current-column)
12684 '("\C-c " org-table-blank-field)
12685 '("\C-c+" org-table-sum)
12686 '("\C-c=" org-table-eval-formula)
12687 '("\C-c'" org-table-edit-formulas)
12688 '("\C-c`" org-table-edit-field)
12689 '("\C-c*" org-table-recalculate)
12690 '("\C-c|" org-table-create-or-convert-from-region)
12691 '("\C-c^" org-table-sort-lines)
12692 '([(control ?#)] org-table-rotate-recalc-marks)))
12693 elt key fun cmd)
12694 (while (setq elt (pop bindings))
12695 (setq nfunc (1+ nfunc))
12696 (setq key (car elt)
12697 fun (nth 1 elt)
12698 cmd (orgtbl-make-binding fun nfunc key))
12699 (define-key orgtbl-mode-map key cmd))
12700 ;; Special treatment needed for TAB and RET
12701 (define-key orgtbl-mode-map [(return)]
12702 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
12703 (define-key orgtbl-mode-map "\C-m"
12704 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
12705 (define-key orgtbl-mode-map [(tab)]
12706 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
12707 (define-key orgtbl-mode-map "\C-i"
12708 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
12709 (define-key orgtbl-mode-map "\C-i"
12710 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
12711 (define-key orgtbl-mode-map "\C-c\C-c"
12712 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
12713 (when orgtbl-optimized
12714 ;; If the user wants maximum table support, we need to hijack
12715 ;; some standard editing functions
12716 (org-remap orgtbl-mode-map
12717 'self-insert-command 'orgtbl-self-insert-command
12718 'delete-char 'org-delete-char
12719 'delete-backward-char 'org-delete-backward-char)
12720 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
12721 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
12722 '("OrgTbl"
12723 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
12724 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
12725 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
12726 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
12727 "--"
12728 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
12729 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
12730 ["Copy Field from Above"
12731 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
12732 "--"
12733 ("Column"
12734 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
12735 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
12736 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
12737 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
12738 "--"
12739 ["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])
12740 ("Row"
12741 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
12742 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
12743 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
12744 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
12745 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
12746 "--"
12747 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
12748 ("Rectangle"
12749 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
12750 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
12751 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
12752 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
12753 "--"
12754 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
12755 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12756 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
12757 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
12758 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
12759 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
12760 ["Sum Column/Rectangle" org-table-sum
12761 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
12762 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
12763 ["Debug Formulas"
12764 (setq org-table-formula-debug (not org-table-formula-debug))
12765 :style toggle :selected org-table-formula-debug]
12766 ))
12767 t)
12768
12769 (defun orgtbl-tab (arg)
12770 "Justification and field motion for `orgtbl-mode'."
12771 (interactive "P")
12772 (if arg (org-table-edit-field t)
12773 (org-table-justify-field-maybe)
12774 (org-table-next-field)))
12775
12776 (defun orgtbl-ret ()
12777 "Justification and field motion for `orgtbl-mode'."
12778 (interactive)
12779 (org-table-justify-field-maybe)
12780 (org-table-next-row))
12781
12782 (defun orgtbl-self-insert-command (N)
12783 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12784 If the cursor is in a table looking at whitespace, the whitespace is
12785 overwritten, and the table is not marked as requiring realignment."
12786 (interactive "p")
12787 (if (and (org-at-table-p)
12788 (or
12789 (and org-table-auto-blank-field
12790 (member last-command
12791 '(orgtbl-hijacker-command-100
12792 orgtbl-hijacker-command-101
12793 orgtbl-hijacker-command-102
12794 orgtbl-hijacker-command-103
12795 orgtbl-hijacker-command-104
12796 orgtbl-hijacker-command-105))
12797 (org-table-blank-field))
12798 t)
12799 (eq N 1)
12800 (looking-at "[^|\n]* +|"))
12801 (let (org-table-may-need-update)
12802 (goto-char (1- (match-end 0)))
12803 (delete-backward-char 1)
12804 (goto-char (match-beginning 0))
12805 (self-insert-command N))
12806 (setq org-table-may-need-update t)
12807 (let (orgtbl-mode)
12808 (call-interactively (key-binding (vector last-input-event))))))
12809
12810 (defun org-force-self-insert (N)
12811 "Needed to enforce self-insert under remapping."
12812 (interactive "p")
12813 (self-insert-command N))
12814
12815 ;;; Exporting
12816
12817 (defconst org-level-max 20)
12818
12819 (defvar org-export-html-preamble nil
12820 "Preamble, to be inserted just after <body>. Set by publishing functions.")
12821 (defvar org-export-html-postamble nil
12822 "Preamble, to be inserted just before </body>. Set by publishing functions.")
12823 (defvar org-export-html-auto-preamble t
12824 "Should default preamble be inserted? Set by publishing functions.")
12825 (defvar org-export-html-auto-postamble t
12826 "Should default postamble be inserted? Set by publishing functions.")
12827
12828 (defconst org-export-plist-vars
12829 '((:language . org-export-default-language)
12830 (:headline-levels . org-export-headline-levels)
12831 (:section-numbers . org-export-with-section-numbers)
12832 (:table-of-contents . org-export-with-toc)
12833 (:archived-trees . org-export-with-archived-trees)
12834 (:emphasize . org-export-with-emphasize)
12835 (:sub-superscript . org-export-with-sub-superscripts)
12836 (:TeX-macros . org-export-with-TeX-macros)
12837 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
12838 (:fixed-width . org-export-with-fixed-width)
12839 (:timestamps . org-export-with-timestamps)
12840 (:tables . org-export-with-tables)
12841 (:table-auto-headline . org-export-highlight-first-table-line)
12842 (:style . org-export-html-style)
12843 (:convert-org-links . org-export-html-link-org-files-as-html)
12844 (:inline-images . org-export-html-inline-images)
12845 (:expand-quoted-html . org-export-html-expand)
12846 (:timestamp . org-export-html-with-timestamp)
12847 (:publishing-directory . org-export-publishing-directory)
12848 (:preamble . org-export-html-preamble)
12849 (:postamble . org-export-html-postamble)
12850 (:auto-preamble . org-export-html-auto-preamble)
12851 (:auto-postamble . org-export-html-auto-postamble)
12852 (:author . user-full-name)
12853 (:email . user-mail-address)))
12854
12855 (defun org-default-export-plist ()
12856 "Return the property list with default settings for the export variables."
12857 (let ((l org-export-plist-vars) rtn e)
12858 (while (setq e (pop l))
12859 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
12860 rtn))
12861
12862 (defun org-infile-export-plist ()
12863 "Return the property list with file-local settings for export."
12864 (save-excursion
12865 (goto-char 0)
12866 (let ((re (org-make-options-regexp
12867 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12868 p key val text options)
12869 (while (re-search-forward re nil t)
12870 (setq key (org-match-string-no-properties 1)
12871 val (org-match-string-no-properties 2))
12872 (cond
12873 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
12874 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
12875 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
12876 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
12877 ((string-equal key "TEXT")
12878 (setq text (if text (concat text "\n" val) val)))
12879 ((string-equal key "OPTIONS") (setq options val))))
12880 (setq p (plist-put p :text text))
12881 (when options
12882 (let ((op '(("H" . :headline-levels)
12883 ("num" . :section-numbers)
12884 ("toc" . :table-of-contents)
12885 ("\\n" . :preserve-breaks)
12886 ("@" . :expand-quoted-html)
12887 (":" . :fixed-width)
12888 ("|" . :tables)
12889 ("^" . :sub-superscript)
12890 ("*" . :emphasize)
12891 ("TeX" . :TeX-macros)
12892 ("LaTeX" . :LaTeX-fragments)))
12893 o)
12894 (while (setq o (pop op))
12895 (if (string-match (concat (regexp-quote (car o))
12896 ":\\([^ \t\n\r;,.]*\\)")
12897 options)
12898 (setq p (plist-put p (cdr o)
12899 (car (read-from-string
12900 (match-string 1 options)))))))))
12901 p)))
12902
12903 (defun org-combine-plists (&rest plists)
12904 "Create a single property list from all plists in PLISTS.
12905 The process starts by copying the last list, and then setting properties
12906 from the other lists. Settings in the first list are the most significant
12907 ones and overrule settings in the other lists."
12908 (let ((rtn (copy-sequence (pop plists)))
12909 p v ls)
12910 (while plists
12911 (setq ls (pop plists))
12912 (while ls
12913 (setq p (pop ls) v (pop ls))
12914 (setq rtn (plist-put rtn p v))))
12915 rtn))
12916
12917 (defun org-export-directory (type plist)
12918 (let* ((val (plist-get plist :publishing-directory))
12919 (dir (if (listp val)
12920 (or (cdr (assoc type val)) ".")
12921 val)))
12922 dir))
12923
12924 (defun org-export-find-first-heading-line (list)
12925 "Remove all lines from LIST which are before the first headline."
12926 (let ((orig-list list)
12927 (re (concat "^" outline-regexp)))
12928 (while (and list
12929 (not (string-match re (car list))))
12930 (pop list))
12931 (or list orig-list)))
12932
12933 (defun org-skip-comments (lines)
12934 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
12935 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
12936 (re2 "^\\(\\*+\\)[ \t\n\r]")
12937 rtn line level)
12938 (while (setq line (pop lines))
12939 (cond
12940 ((and (string-match re1 line)
12941 (setq level (- (match-end 1) (match-beginning 1))))
12942 ;; Beginning of a COMMENT subtree. Skip it.
12943 (while (and (setq line (pop lines))
12944 (or (not (string-match re2 line))
12945 (> (- (match-end 1) (match-beginning 1)) level))))
12946 (setq lines (cons line lines)))
12947 ((string-match "^#" line)
12948 ;; an ordinary comment line
12949 )
12950 ((and org-export-table-remove-special-lines
12951 (string-match "^[ \t]*|" line)
12952 (or (string-match "^[ \t]*| *[!_^] *|" line)
12953 (and (string-match "| *<[0-9]+> *|" line)
12954 (not (string-match "| *[^ <|]" line)))))
12955 ;; a special table line that should be removed
12956 )
12957 (t (setq rtn (cons line rtn)))))
12958 (nreverse rtn)))
12959
12960 (defun org-export (&optional arg)
12961 (interactive)
12962 (let ((help "[t] insert the export option template
12963 \[v] limit export to visible part of outline tree
12964
12965 \[a] export as ASCII
12966 \[h] export as HTML
12967 \[b] export as HTML and browse immediately
12968 \[x] export as XOXO
12969
12970 \[i] export current file as iCalendar file
12971 \[I] export all agenda files as iCalendar files
12972 \[c] export agenda files into combined iCalendar file
12973
12974 \[F] publish current file
12975 \[P] publish current project
12976 \[X] publish... (project will be prompted for)
12977 \[A] publish all projects")
12978 (cmds
12979 '((?t . org-insert-export-options-template)
12980 (?v . org-export-visible)
12981 (?a . org-export-as-ascii)
12982 (?h . org-export-as-html)
12983 (?b . org-export-as-html-and-open)
12984 (?x . org-export-as-xoxo)
12985 (?i . org-export-icalendar-this-file)
12986 (?I . org-export-icalendar-all-agenda-files)
12987 (?c . org-export-icalendar-combine-agenda-files)
12988 (?F . org-publish-current-file)
12989 (?P . org-publish-current-project)
12990 (?X . org-publish)
12991 (?A . org-publish-all)))
12992 r1 r2 ass)
12993 (save-window-excursion
12994 (delete-other-windows)
12995 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
12996 (princ help))
12997 (message "Select command: ")
12998 (setq r1 (read-char-exclusive)))
12999 (setq r2 (if (< r1 27) (+ r1 96) r1))
13000 (if (setq ass (assq r2 cmds))
13001 (call-interactively (cdr ass))
13002 (error "No command associated with key %c" r1))))
13003
13004 ;; ASCII
13005
13006 (defconst org-html-entities
13007 '(("nbsp")
13008 ("iexcl")
13009 ("cent")
13010 ("pound")
13011 ("curren")
13012 ("yen")
13013 ("brvbar")
13014 ("sect")
13015 ("uml")
13016 ("copy")
13017 ("ordf")
13018 ("laquo")
13019 ("not")
13020 ("shy")
13021 ("reg")
13022 ("macr")
13023 ("deg")
13024 ("plusmn")
13025 ("sup2")
13026 ("sup3")
13027 ("acute")
13028 ("micro")
13029 ("para")
13030 ("middot")
13031 ("odot"."o")
13032 ("star"."*")
13033 ("cedil")
13034 ("sup1")
13035 ("ordm")
13036 ("raquo")
13037 ("frac14")
13038 ("frac12")
13039 ("frac34")
13040 ("iquest")
13041 ("Agrave")
13042 ("Aacute")
13043 ("Acirc")
13044 ("Atilde")
13045 ("Auml")
13046 ("Aring") ("AA"."&Aring;")
13047 ("AElig")
13048 ("Ccedil")
13049 ("Egrave")
13050 ("Eacute")
13051 ("Ecirc")
13052 ("Euml")
13053 ("Igrave")
13054 ("Iacute")
13055 ("Icirc")
13056 ("Iuml")
13057 ("ETH")
13058 ("Ntilde")
13059 ("Ograve")
13060 ("Oacute")
13061 ("Ocirc")
13062 ("Otilde")
13063 ("Ouml")
13064 ("times")
13065 ("Oslash")
13066 ("Ugrave")
13067 ("Uacute")
13068 ("Ucirc")
13069 ("Uuml")
13070 ("Yacute")
13071 ("THORN")
13072 ("szlig")
13073 ("agrave")
13074 ("aacute")
13075 ("acirc")
13076 ("atilde")
13077 ("auml")
13078 ("aring")
13079 ("aelig")
13080 ("ccedil")
13081 ("egrave")
13082 ("eacute")
13083 ("ecirc")
13084 ("euml")
13085 ("igrave")
13086 ("iacute")
13087 ("icirc")
13088 ("iuml")
13089 ("eth")
13090 ("ntilde")
13091 ("ograve")
13092 ("oacute")
13093 ("ocirc")
13094 ("otilde")
13095 ("ouml")
13096 ("divide")
13097 ("oslash")
13098 ("ugrave")
13099 ("uacute")
13100 ("ucirc")
13101 ("uuml")
13102 ("yacute")
13103 ("thorn")
13104 ("yuml")
13105 ("fnof")
13106 ("Alpha")
13107 ("Beta")
13108 ("Gamma")
13109 ("Delta")
13110 ("Epsilon")
13111 ("Zeta")
13112 ("Eta")
13113 ("Theta")
13114 ("Iota")
13115 ("Kappa")
13116 ("Lambda")
13117 ("Mu")
13118 ("Nu")
13119 ("Xi")
13120 ("Omicron")
13121 ("Pi")
13122 ("Rho")
13123 ("Sigma")
13124 ("Tau")
13125 ("Upsilon")
13126 ("Phi")
13127 ("Chi")
13128 ("Psi")
13129 ("Omega")
13130 ("alpha")
13131 ("beta")
13132 ("gamma")
13133 ("delta")
13134 ("epsilon")
13135 ("varepsilon"."&epsilon;")
13136 ("zeta")
13137 ("eta")
13138 ("theta")
13139 ("iota")
13140 ("kappa")
13141 ("lambda")
13142 ("mu")
13143 ("nu")
13144 ("xi")
13145 ("omicron")
13146 ("pi")
13147 ("rho")
13148 ("sigmaf") ("varsigma"."&sigmaf;")
13149 ("sigma")
13150 ("tau")
13151 ("upsilon")
13152 ("phi")
13153 ("chi")
13154 ("psi")
13155 ("omega")
13156 ("thetasym") ("vartheta"."&thetasym;")
13157 ("upsih")
13158 ("piv")
13159 ("bull") ("bullet"."&bull;")
13160 ("hellip") ("dots"."&hellip;")
13161 ("prime")
13162 ("Prime")
13163 ("oline")
13164 ("frasl")
13165 ("weierp")
13166 ("image")
13167 ("real")
13168 ("trade")
13169 ("alefsym")
13170 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
13171 ("uarr") ("uparrow"."&uarr;")
13172 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
13173 ("darr")("downarrow"."&darr;")
13174 ("harr") ("leftrightarrow"."&harr;")
13175 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
13176 ("lArr") ("Leftarrow"."&lArr;")
13177 ("uArr") ("Uparrow"."&uArr;")
13178 ("rArr") ("Rightarrow"."&rArr;")
13179 ("dArr") ("Downarrow"."&dArr;")
13180 ("hArr") ("Leftrightarrow"."&hArr;")
13181 ("forall")
13182 ("part") ("partial"."&part;")
13183 ("exist") ("exists"."&exist;")
13184 ("empty") ("emptyset"."&empty;")
13185 ("nabla")
13186 ("isin") ("in"."&isin;")
13187 ("notin")
13188 ("ni")
13189 ("prod")
13190 ("sum")
13191 ("minus")
13192 ("lowast") ("ast"."&lowast;")
13193 ("radic")
13194 ("prop") ("proptp"."&prop;")
13195 ("infin") ("infty"."&infin;")
13196 ("ang") ("angle"."&ang;")
13197 ("and") ("vee"."&and;")
13198 ("or") ("wedge"."&or;")
13199 ("cap")
13200 ("cup")
13201 ("int")
13202 ("there4")
13203 ("sim")
13204 ("cong") ("simeq"."&cong;")
13205 ("asymp")("approx"."&asymp;")
13206 ("ne") ("neq"."&ne;")
13207 ("equiv")
13208 ("le")
13209 ("ge")
13210 ("sub") ("subset"."&sub;")
13211 ("sup") ("supset"."&sup;")
13212 ("nsub")
13213 ("sube")
13214 ("supe")
13215 ("oplus")
13216 ("otimes")
13217 ("perp")
13218 ("sdot") ("cdot"."&sdot;")
13219 ("lceil")
13220 ("rceil")
13221 ("lfloor")
13222 ("rfloor")
13223 ("lang")
13224 ("rang")
13225 ("loz") ("Diamond"."&loz;")
13226 ("spades") ("spadesuit"."&spades;")
13227 ("clubs") ("clubsuit"."&clubs;")
13228 ("hearts") ("diamondsuit"."&hearts;")
13229 ("diams") ("diamondsuit"."&diams;")
13230 ("quot")
13231 ("amp")
13232 ("lt")
13233 ("gt")
13234 ("OElig")
13235 ("oelig")
13236 ("Scaron")
13237 ("scaron")
13238 ("Yuml")
13239 ("circ")
13240 ("tilde")
13241 ("ensp")
13242 ("emsp")
13243 ("thinsp")
13244 ("zwnj")
13245 ("zwj")
13246 ("lrm")
13247 ("rlm")
13248 ("ndash")
13249 ("mdash")
13250 ("lsquo")
13251 ("rsquo")
13252 ("sbquo")
13253 ("ldquo")
13254 ("rdquo")
13255 ("bdquo")
13256 ("dagger")
13257 ("Dagger")
13258 ("permil")
13259 ("lsaquo")
13260 ("rsaquo")
13261 ("euro")
13262
13263 ("arccos"."arccos")
13264 ("arcsin"."arcsin")
13265 ("arctan"."arctan")
13266 ("arg"."arg")
13267 ("cos"."cos")
13268 ("cosh"."cosh")
13269 ("cot"."cot")
13270 ("coth"."coth")
13271 ("csc"."csc")
13272 ("deg"."deg")
13273 ("det"."det")
13274 ("dim"."dim")
13275 ("exp"."exp")
13276 ("gcd"."gcd")
13277 ("hom"."hom")
13278 ("inf"."inf")
13279 ("ker"."ker")
13280 ("lg"."lg")
13281 ("lim"."lim")
13282 ("liminf"."liminf")
13283 ("limsup"."limsup")
13284 ("ln"."ln")
13285 ("log"."log")
13286 ("max"."max")
13287 ("min"."min")
13288 ("Pr"."Pr")
13289 ("sec"."sec")
13290 ("sin"."sin")
13291 ("sinh"."sinh")
13292 ("sup"."sup")
13293 ("tan"."tan")
13294 ("tanh"."tanh")
13295 )
13296 "Entities for TeX->HTML translation.
13297 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
13298 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
13299 In that case, \"\\ent\" will be translated to \"&other;\".
13300 The list contains HTML entities for Latin-1, Greek and other symbols.
13301 It is supplemented by a number of commonly used TeX macros with appropriate
13302 translations. There is currently no way for users to extend this.")
13303
13304 (defun org-cleaned-string-for-export (string &rest parameters)
13305 "Cleanup a buffer substring so that links can be created safely."
13306 (interactive)
13307 (let* ((re-radio (and org-target-link-regexp
13308 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
13309 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
13310 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
13311 (re-archive (concat ":" org-archive-tag ":"))
13312 rtn)
13313 (save-excursion
13314 (set-buffer (get-buffer-create " org-mode-tmp"))
13315 (erase-buffer)
13316 (insert string)
13317 (let ((org-inhibit-startup t)) (org-mode))
13318
13319 ;; Get rid of archived trees
13320 (when (not (eq org-export-with-archived-trees t))
13321 (goto-char (point-min))
13322 (while (re-search-forward re-archive nil t)
13323 (if (not (org-on-heading-p))
13324 (org-end-of-subtree t)
13325 (beginning-of-line 1)
13326 (delete-region
13327 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
13328 (org-end-of-subtree)))))
13329
13330 ;; Find targets in comments and move them out of comments,
13331 ;; but mark them as targets that should be invisible
13332 (goto-char (point-min))
13333 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
13334 (replace-match "\\1(INVISIBLE)"))
13335
13336 ;; Find matches for radio targets and turn them into internal links
13337 (goto-char (point-min))
13338 (when re-radio
13339 (while (re-search-forward re-radio nil t)
13340 (replace-match "\\1[[\\2]]")))
13341
13342 ;; Find all links that contain a newline and put them into a single line
13343 (goto-char (point-min))
13344 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
13345 (replace-match "\\1 \\3")
13346 (goto-char (match-beginning 0)))
13347
13348 ;; Convert LaTeX fragments to images
13349 (when (memq :LaTeX-fragments parameters)
13350 (org-format-latex
13351 (concat "ltxpng/" (file-name-sans-extension
13352 (file-name-nondirectory
13353 org-current-export-file)))
13354 org-current-export-dir nil "Creating LaTeX image %s"))
13355 (message "Exporting...")
13356
13357 ;; Normalize links: Convert angle and plain links into bracket links
13358 (goto-char (point-min))
13359 (while (re-search-forward re-plain-link nil t)
13360 (replace-match
13361 (concat
13362 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13363 t t))
13364 (goto-char (point-min))
13365 (while (re-search-forward re-angle-link nil t)
13366 (replace-match
13367 (concat
13368 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13369 t t))
13370
13371 ;; Find multiline emphasis and put them into single line
13372 (when (memq :emph-multiline parameters)
13373 (goto-char (point-min))
13374 (while (re-search-forward org-emph-re nil t)
13375 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
13376 (goto-char (1- (match-end 0)))))
13377
13378 ;; Remove comments
13379 (goto-char (point-min))
13380 (while (re-search-forward "^#.*\n?" nil t)
13381 (replace-match ""))
13382 (setq rtn (buffer-string)))
13383 (kill-buffer " org-mode-tmp")
13384 rtn))
13385
13386 (defun org-solidify-link-text (s &optional alist)
13387 "Take link text and make a safe target out of it."
13388 (save-match-data
13389 (let* ((rtn
13390 (mapconcat
13391 'identity
13392 (org-split-string s "[ \t\r\n]+") "--"))
13393 (a (assoc rtn alist)))
13394 (or (cdr a) rtn))))
13395
13396 (defun org-convert-to-odd-levels ()
13397 "Convert an org-mode file with all levels allowed to one with odd levels.
13398 This will leave level 1 alone, convert level 2 to level 3, level 3 to
13399 level 5 etc."
13400 (interactive)
13401 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
13402 (let ((org-odd-levels-only nil) n)
13403 (save-excursion
13404 (goto-char (point-min))
13405 (while (re-search-forward "^\\*\\*+" nil t)
13406 (setq n (1- (length (match-string 0))))
13407 (while (>= (setq n (1- n)) 0)
13408 (org-demote))
13409 (end-of-line 1))))))
13410
13411
13412 (defun org-convert-to-oddeven-levels ()
13413 "Convert an org-mode file with only odd levels to one with odd and even levels.
13414 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
13415 section with an even level, conversion would destroy the structure of the file. An error
13416 is signaled in this case."
13417 (interactive)
13418 (goto-char (point-min))
13419 ;; First check if there are no even levels
13420 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
13421 (org-show-hierarchy-above)
13422 (error "Not all levels are odd in this file. Conversion not possible."))
13423 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
13424 (let ((org-odd-levels-only nil) n)
13425 (save-excursion
13426 (goto-char (point-min))
13427 (while (re-search-forward "^\\*\\*+" nil t)
13428 (setq n (/ (length (match-string 0)) 2))
13429 (while (>= (setq n (1- n)) 0)
13430 (org-promote))
13431 (end-of-line 1))))))
13432
13433 (defun org-tr-level (n)
13434 "Make N odd if required."
13435 (if org-odd-levels-only (1+ (/ n 2)) n))
13436
13437 (defvar org-last-level nil) ; dynamically scoped variable
13438 (defvar org-ascii-current-indentation nil) ; For communication
13439
13440 (defun org-export-as-ascii (arg)
13441 "Export the outline as a pretty ASCII file.
13442 If there is an active region, export only the region.
13443 The prefix ARG specifies how many levels of the outline should become
13444 underlined headlines. The default is 3."
13445 (interactive "P")
13446 (setq-default org-todo-line-regexp org-todo-line-regexp)
13447 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13448 (org-infile-export-plist)))
13449 (region
13450 (buffer-substring
13451 (if (org-region-active-p) (region-beginning) (point-min))
13452 (if (org-region-active-p) (region-end) (point-max))))
13453 (lines (org-export-find-first-heading-line
13454 (org-skip-comments
13455 (org-split-string
13456 (org-cleaned-string-for-export region)
13457 "[\r\n]"))))
13458 (org-ascii-current-indentation '(0 . 0))
13459 (org-startup-with-deadline-check nil)
13460 (level 0) line txt
13461 (umax nil)
13462 (case-fold-search nil)
13463 (filename (concat (file-name-as-directory
13464 (org-export-directory :ascii opt-plist))
13465 (file-name-sans-extension
13466 (file-name-nondirectory buffer-file-name))
13467 ".txt"))
13468 (buffer (find-file-noselect filename))
13469 (levels-open (make-vector org-level-max nil))
13470 (odd org-odd-levels-only)
13471 (date (format-time-string "%Y/%m/%d" (current-time)))
13472 (time (format-time-string "%X" (org-current-time)))
13473 (author (plist-get opt-plist :author))
13474 (title (or (plist-get opt-plist :title)
13475 (file-name-sans-extension
13476 (file-name-nondirectory buffer-file-name))))
13477 (email (plist-get opt-plist :email))
13478 (language (plist-get opt-plist :language))
13479 (text nil)
13480 (todo nil)
13481 (lang-words nil))
13482
13483 (setq org-last-level 1)
13484 (org-init-section-numbers)
13485
13486 (find-file-noselect filename)
13487
13488 (setq lang-words (or (assoc language org-export-language-setup)
13489 (assoc "en" org-export-language-setup)))
13490 (if org-export-ascii-show-new-buffer
13491 (switch-to-buffer-other-window buffer)
13492 (set-buffer buffer))
13493 (erase-buffer)
13494 (fundamental-mode)
13495 ;; create local variables for all options, to make sure all called
13496 ;; functions get the correct information
13497 (mapcar (lambda (x)
13498 (set (make-local-variable (cdr x))
13499 (plist-get opt-plist (car x))))
13500 org-export-plist-vars)
13501 (org-set-local 'org-odd-levels-only odd)
13502 (setq umax (if arg (prefix-numeric-value arg)
13503 org-export-headline-levels))
13504
13505 ;; File header
13506 (if title (org-insert-centered title ?=))
13507 (insert "\n")
13508 (if (or author email)
13509 (insert (concat (nth 1 lang-words) ": " (or author "")
13510 (if email (concat " <" email ">") "")
13511 "\n")))
13512 (if (and date time)
13513 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
13514 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
13515
13516 (insert "\n\n")
13517
13518 (if org-export-with-toc
13519 (progn
13520 (insert (nth 3 lang-words) "\n"
13521 (make-string (length (nth 3 lang-words)) ?=) "\n")
13522 (mapcar '(lambda (line)
13523 (if (string-match org-todo-line-regexp
13524 line)
13525 ;; This is a headline
13526 (progn
13527 (setq level (- (match-end 1) (match-beginning 1))
13528 level (org-tr-level level)
13529 txt (match-string 3 line)
13530 todo
13531 (or (and org-export-mark-todo-in-toc
13532 (match-beginning 2)
13533 (not (equal (match-string 2 line)
13534 org-done-string)))
13535 ; TODO, not DONE
13536 (and org-export-mark-todo-in-toc
13537 (= level umax)
13538 (org-search-todo-below
13539 line lines level))))
13540 (setq txt (org-html-expand-for-ascii txt))
13541
13542 (if org-export-with-section-numbers
13543 (setq txt (concat (org-section-number level)
13544 " " txt)))
13545 (if (<= level umax)
13546 (progn
13547 (insert
13548 (make-string (* (1- level) 4) ?\ )
13549 (format (if todo "%s (*)\n" "%s\n") txt))
13550 (setq org-last-level level))
13551 ))))
13552 lines)))
13553
13554 (org-init-section-numbers)
13555 (while (setq line (pop lines))
13556 ;; Remove the quoted HTML tags.
13557 (setq line (org-html-expand-for-ascii line))
13558 ;; Remove targets
13559 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
13560 (setq line (replace-match "" t t line)))
13561 ;; Replace internal links
13562 (while (string-match org-bracket-link-regexp line)
13563 (setq line (replace-match
13564 (if (match-end 3) "[\\3]" "[\\1]")
13565 t nil line)))
13566 (cond
13567 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13568 ;; a Headline
13569 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13570 txt (match-string 2 line))
13571 (org-ascii-level-start level txt umax lines))
13572 (t
13573 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
13574 (normal-mode)
13575 (save-buffer)
13576 ;; remove display and invisible chars
13577 (let (beg end)
13578 (goto-char (point-min))
13579 (while (setq beg (next-single-property-change (point) 'display))
13580 (setq end (next-single-property-change beg 'display))
13581 (delete-region beg end)
13582 (goto-char beg)
13583 (insert "=>"))
13584 (goto-char (point-min))
13585 (while (setq beg (next-single-property-change (point) 'org-cwidth))
13586 (setq end (next-single-property-change beg 'org-cwidth))
13587 (delete-region beg end)
13588 (goto-char beg)))
13589 (goto-char (point-min))))
13590
13591 (defun org-search-todo-below (line lines level)
13592 "Search the subtree below LINE for any TODO entries."
13593 (let ((rest (cdr (memq line lines)))
13594 (re org-todo-line-regexp)
13595 line lv todo)
13596 (catch 'exit
13597 (while (setq line (pop rest))
13598 (if (string-match re line)
13599 (progn
13600 (setq lv (- (match-end 1) (match-beginning 1))
13601 todo (and (match-beginning 2)
13602 (not (equal (match-string 2 line)
13603 org-done-string))))
13604 ; TODO, not DONE
13605 (if (<= lv level) (throw 'exit nil))
13606 (if todo (throw 'exit t))))))))
13607
13608 (defun org-html-expand-for-ascii (line)
13609 "Handle quoted HTML for ASCII export."
13610 (if org-export-html-expand
13611 (while (string-match "@<[^<>\n]*>" line)
13612 ;; We just remove the tags for now.
13613 (setq line (replace-match "" nil nil line))))
13614 line)
13615
13616 (defun org-insert-centered (s &optional underline)
13617 "Insert the string S centered and underline it with character UNDERLINE."
13618 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
13619 (insert (make-string ind ?\ ) s "\n")
13620 (if underline
13621 (insert (make-string ind ?\ )
13622 (make-string (string-width s) underline)
13623 "\n"))))
13624
13625 (defun org-ascii-level-start (level title umax &optional lines)
13626 "Insert a new level in ASCII export."
13627 (let (char (n (- level umax 1)) (ind 0))
13628 (if (> level umax)
13629 (progn
13630 (insert (make-string (* 2 n) ?\ )
13631 (char-to-string (nth (% n (length org-export-ascii-bullets))
13632 org-export-ascii-bullets))
13633 " " title "\n")
13634 ;; find the indentation of the next non-empty line
13635 (catch 'stop
13636 (while lines
13637 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
13638 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
13639 (throw 'stop (setq ind (org-get-indentation (car lines)))))
13640 (pop lines)))
13641 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
13642 (if (or (not (equal (char-before) ?\n))
13643 (not (equal (char-before (1- (point))) ?\n)))
13644 (insert "\n"))
13645 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
13646 (if org-export-with-section-numbers
13647 (setq title (concat (org-section-number level) " " title)))
13648 (insert title "\n" (make-string (string-width title) char) "\n")
13649 (setq org-ascii-current-indentation '(0 . 0)))))
13650
13651 (defun org-export-visible (type arg)
13652 "Create a copy of the visible part of the current buffer, and export it.
13653 The copy is created in a temporary buffer and removed after use.
13654 TYPE is the final key (as a string) that also select the export command in
13655 the `C-c C-e' export dispatcher.
13656 As a special case, if the you type SPC at the prompt, the temporary
13657 org-mode file will not be removed but presented to you so that you can
13658 continue to use it. The prefix arg ARG is passed through to the exporting
13659 command."
13660 (interactive
13661 (list (progn
13662 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
13663 (read-char-exclusive))
13664 current-prefix-arg))
13665 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
13666 (error "Invalid export key"))
13667 (let* ((binding (cdr (assoc type
13668 '((?a . org-export-as-ascii)
13669 (?\C-a . org-export-as-ascii)
13670 (?b . org-export-as-html-and-open)
13671 (?\C-b . org-export-as-html-and-open)
13672 (?h . org-export-as-html)
13673 (?x . org-export-as-xoxo)))))
13674 (keepp (equal type ?\ ))
13675 (file buffer-file-name)
13676 (buffer (get-buffer-create "*Org Export Visible*"))
13677 s e)
13678 (with-current-buffer buffer (erase-buffer))
13679 (save-excursion
13680 (setq s (goto-char (point-min)))
13681 (while (not (= (point) (point-max)))
13682 (goto-char (org-find-invisible))
13683 (append-to-buffer buffer s (point))
13684 (setq s (goto-char (org-find-visible))))
13685 (goto-char (point-min))
13686 (unless keepp
13687 ;; Copy all comment lines to the end, to make sure #+ settings are
13688 ;; still available for the second export step. Kind of a hack, but
13689 ;; does do the trick.
13690 (if (looking-at "#[^\r\n]*")
13691 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
13692 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
13693 (append-to-buffer buffer (1+ (match-beginning 0))
13694 (min (point-max) (1+ (match-end 0))))))
13695 (set-buffer buffer)
13696 (let ((buffer-file-name file)
13697 (org-inhibit-startup t))
13698 (org-mode)
13699 (show-all)
13700 (unless keepp (funcall binding arg))))
13701 (if (not keepp)
13702 (kill-buffer buffer)
13703 (switch-to-buffer-other-window buffer)
13704 (goto-char (point-min)))))
13705
13706 (defun org-find-visible ()
13707 (let ((s (point)))
13708 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13709 (get-char-property s 'invisible)))
13710 s))
13711 (defun org-find-invisible ()
13712 (let ((s (point)))
13713 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13714 (not (get-char-property s 'invisible))))
13715 s))
13716
13717 ;; HTML
13718
13719 (defun org-get-current-options ()
13720 "Return a string with current options as keyword options.
13721 Does include HTML export options as well as TODO and CATEGORY stuff."
13722 (format
13723 "#+TITLE: %s
13724 #+AUTHOR: %s
13725 #+EMAIL: %s
13726 #+LANGUAGE: %s
13727 #+TEXT: Some descriptive text to be emitted. Several lines OK.
13728 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
13729 #+CATEGORY: %s
13730 #+SEQ_TODO: %s
13731 #+TYP_TODO: %s
13732 #+STARTUP: %s %s %s %s %s %s
13733 #+TAGS: %s
13734 #+ARCHIVE: %s
13735 "
13736 (buffer-name) (user-full-name) user-mail-address org-export-default-language
13737 org-export-headline-levels
13738 org-export-with-section-numbers
13739 org-export-with-toc
13740 org-export-preserve-breaks
13741 org-export-html-expand
13742 org-export-with-fixed-width
13743 org-export-with-tables
13744 org-export-with-sub-superscripts
13745 org-export-with-emphasize
13746 org-export-with-TeX-macros
13747 org-export-with-LaTeX-fragments
13748 (file-name-nondirectory buffer-file-name)
13749 (if (equal org-todo-interpretation 'sequence)
13750 (mapconcat 'identity org-todo-keywords " ")
13751 "TODO FEEDBACK VERIFY DONE")
13752 (if (equal org-todo-interpretation 'type)
13753 (mapconcat 'identity org-todo-keywords " ")
13754 "Me Jason Marie DONE")
13755 (cdr (assoc org-startup-folded
13756 '((nil . "showall") (t . "overview") (content . "content"))))
13757 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
13758 (if org-odd-levels-only "odd" "oddeven")
13759 (if org-hide-leading-stars "hidestars" "showstars")
13760 (if org-startup-align-all-tables "align" "noalign")
13761 (if org-log-done "logging" "nologging")
13762 (if org-tag-alist (mapconcat 'car org-tag-alist " ") "")
13763 org-archive-location
13764 ))
13765
13766 (defun org-insert-export-options-template ()
13767 "Insert into the buffer a template with information for exporting."
13768 (interactive)
13769 (if (not (bolp)) (newline))
13770 (let ((s (org-get-current-options)))
13771 (and (string-match "#\\+CATEGORY" s)
13772 (setq s (substring s 0 (match-beginning 0))))
13773 (insert s)))
13774
13775 (defun org-toggle-fixed-width-section (arg)
13776 "Toggle the fixed-width export.
13777 If there is no active region, the QUOTE keyword at the current headline is
13778 inserted or removed. When present, it causes the text between this headline
13779 and the next to be exported as fixed-width text, and unmodified.
13780 If there is an active region, this command adds or removes a colon as the
13781 first character of this line. If the first character of a line is a colon,
13782 this line is also exported in fixed-width font."
13783 (interactive "P")
13784 (let* ((cc 0)
13785 (regionp (org-region-active-p))
13786 (beg (if regionp (region-beginning) (point)))
13787 (end (if regionp (region-end)))
13788 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13789 (re "[ \t]*\\(:\\)")
13790 off)
13791 (if regionp
13792 (save-excursion
13793 (goto-char beg)
13794 (setq cc (current-column))
13795 (beginning-of-line 1)
13796 (setq off (looking-at re))
13797 (while (> nlines 0)
13798 (setq nlines (1- nlines))
13799 (beginning-of-line 1)
13800 (cond
13801 (arg
13802 (move-to-column cc t)
13803 (insert ":\n")
13804 (forward-line -1))
13805 ((and off (looking-at re))
13806 (replace-match "" t t nil 1))
13807 ((not off) (move-to-column cc t) (insert ":")))
13808 (forward-line 1)))
13809 (save-excursion
13810 (org-back-to-heading)
13811 (if (looking-at (concat outline-regexp
13812 "\\( +\\<" org-quote-string "\\>\\)"))
13813 (replace-match "" t t nil 1)
13814 (if (looking-at outline-regexp)
13815 (progn
13816 (goto-char (match-end 0))
13817 (insert " " org-quote-string))))))))
13818
13819 (defun org-export-as-html-and-open (arg)
13820 "Export the outline as HTML and immediately open it with a browser.
13821 If there is an active region, export only the region.
13822 The prefix ARG specifies how many levels of the outline should become
13823 headlines. The default is 3. Lower levels will become bulleted lists."
13824 (interactive "P")
13825 (org-export-as-html arg 'hidden)
13826 (org-open-file buffer-file-name))
13827
13828 (defun org-export-as-html-batch ()
13829 "Call `org-export-as-html', may be used in batch processing as
13830 emacs --batch
13831 --load=$HOME/lib/emacs/org.el
13832 --eval \"(setq org-export-headline-levels 2)\"
13833 --visit=MyFile --funcall org-export-as-html-batch"
13834 (org-export-as-html org-export-headline-levels 'hidden))
13835
13836 (defun org-export-as-html (arg &optional hidden ext-plist)
13837 "Export the outline as a pretty HTML file.
13838 If there is an active region, export only the region.
13839 The prefix ARG specifies how many levels of the outline should become
13840 headlines. The default is 3. Lower levels will become bulleted lists.
13841 When HIDDEN is non-nil, don't display the HTML buffer.
13842 EXT-PLIST is a property list with external parameters overriding
13843 org-mode's default settings, but still inferior to file-local settings."
13844 (interactive "P")
13845 (message "Exporting...")
13846 (setq-default org-todo-line-regexp org-todo-line-regexp)
13847 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
13848 (setq-default org-done-string org-done-string)
13849 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13850 ext-plist
13851 (org-infile-export-plist)))
13852
13853 (style (plist-get opt-plist :style))
13854 (link-validate (plist-get opt-plist :link-validation-function))
13855 valid
13856 (odd org-odd-levels-only)
13857 (region-p (org-region-active-p))
13858 (region
13859 (buffer-substring
13860 (if region-p (region-beginning) (point-min))
13861 (if region-p (region-end) (point-max))))
13862 ;; The following two are dynamically scoped into other
13863 ;; routines below.
13864 (org-current-export-dir (org-export-directory :html opt-plist))
13865 (org-current-export-file buffer-file-name)
13866 (all_lines
13867 (org-skip-comments (org-split-string
13868 (org-cleaned-string-for-export
13869 region :emph-multiline
13870 (if (plist-get opt-plist :LaTeX-fragments)
13871 :LaTeX-fragments))
13872 "[\r\n]")))
13873 (lines (org-export-find-first-heading-line all_lines))
13874 (level 0) (line "") (origline "") txt todo
13875 (umax nil)
13876 (filename (concat (file-name-as-directory
13877 (org-export-directory :html opt-plist))
13878 (file-name-sans-extension
13879 (file-name-nondirectory buffer-file-name))
13880 ".html"))
13881 (current-dir (file-name-directory buffer-file-name))
13882 (buffer (find-file-noselect filename))
13883 (levels-open (make-vector org-level-max nil))
13884 (date (format-time-string "%Y/%m/%d" (current-time)))
13885 (time (format-time-string "%X" (org-current-time)))
13886 (author (plist-get opt-plist :author))
13887 (title (or (plist-get opt-plist :title)
13888 (file-name-sans-extension
13889 (file-name-nondirectory buffer-file-name))))
13890 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
13891 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
13892 (inquote nil)
13893 (infixed nil)
13894 (in-local-list nil)
13895 (local-list-num nil)
13896 (local-list-indent nil)
13897 (llt org-plain-list-ordered-item-terminator)
13898 (email (plist-get opt-plist :email))
13899 (language (plist-get opt-plist :language))
13900 (text (plist-get opt-plist :text))
13901 (lang-words nil)
13902 (target-alist nil) tg
13903 (head-count 0) cnt
13904 (start 0)
13905 (coding-system (and (fboundp 'coding-system-get)
13906 (boundp 'buffer-file-coding-system)
13907 buffer-file-coding-system))
13908 (coding-system-for-write (or coding-system coding-system-for-write))
13909 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
13910 (charset (and coding-system
13911 (coding-system-get coding-system 'mime-charset)))
13912 table-open type
13913 table-buffer table-orig-buffer
13914 ind start-is-num starter
13915 rpl path desc descp desc1 desc2 link
13916 )
13917 (message "Exporting...")
13918
13919 (setq org-last-level 1)
13920 (org-init-section-numbers)
13921
13922 ;; Get the language-dependent settings
13923 (setq lang-words (or (assoc language org-export-language-setup)
13924 (assoc "en" org-export-language-setup)))
13925
13926 ;; Switch to the output buffer
13927 (if (or hidden (not org-export-html-show-new-buffer))
13928 (set-buffer buffer)
13929 (switch-to-buffer-other-window buffer))
13930 (erase-buffer)
13931 (fundamental-mode)
13932 (let ((case-fold-search nil)
13933 (org-odd-levels-only odd))
13934 ;; create local variables for all options, to make sure all called
13935 ;; functions get the correct information
13936 (mapcar (lambda (x)
13937 (set (make-local-variable (cdr x))
13938 (plist-get opt-plist (car x))))
13939 org-export-plist-vars)
13940 (setq umax (if arg (prefix-numeric-value arg)
13941 org-export-headline-levels))
13942
13943 ;; File header
13944 (insert (format
13945 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
13946 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
13947 <html xmlns=\"http://www.w3.org/1999/xhtml\"
13948 lang=\"%s\" xml:lang=\"%s\">
13949 <head>
13950 <title>%s</title>
13951 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
13952 <meta name=\"generator\" content=\"Org-mode\"/>
13953 <meta name=\"generated\" content=\"%s %s\"/>
13954 <meta name=\"author\" content=\"%s\"/>
13955 %s
13956 </head><body>
13957 "
13958 language language (org-html-expand title) (or charset "iso-8859-1")
13959 date time author style))
13960
13961
13962 (insert (or (plist-get opt-plist :preamble) ""))
13963
13964 (when (plist-get opt-plist :auto-preamble)
13965 (if title (insert (format org-export-html-title-format
13966 (org-html-expand title))))
13967 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
13968
13969 (if org-export-with-toc
13970 (progn
13971 (insert (format "<h%d>%s</h%d>\n"
13972 org-export-html-toplevel-hlevel
13973 (nth 3 lang-words)
13974 org-export-html-toplevel-hlevel))
13975 (insert "<ul>\n<li>")
13976 (setq lines
13977 (mapcar '(lambda (line)
13978 (if (string-match org-todo-line-regexp line)
13979 ;; This is a headline
13980 (progn
13981 (setq level (- (match-end 1) (match-beginning 1))
13982 level (org-tr-level level)
13983 txt (save-match-data
13984 (org-html-expand
13985 (org-export-cleanup-toc-line
13986 (match-string 3 line))))
13987 todo
13988 (or (and org-export-mark-todo-in-toc
13989 (match-beginning 2)
13990 (not (equal (match-string 2 line)
13991 org-done-string)))
13992 ; TODO, not DONE
13993 (and org-export-mark-todo-in-toc
13994 (= level umax)
13995 (org-search-todo-below
13996 line lines level))))
13997 (if org-export-with-section-numbers
13998 (setq txt (concat (org-section-number level)
13999 " " txt)))
14000 (if (<= level umax)
14001 (progn
14002 (setq head-count (+ head-count 1))
14003 (if (> level org-last-level)
14004 (progn
14005 (setq cnt (- level org-last-level))
14006 (while (>= (setq cnt (1- cnt)) 0)
14007 (insert "\n<ul>\n<li>"))
14008 (insert "\n")))
14009 (if (< level org-last-level)
14010 (progn
14011 (setq cnt (- org-last-level level))
14012 (while (>= (setq cnt (1- cnt)) 0)
14013 (insert "</li>\n</ul>"))
14014 (insert "\n")))
14015 ;; Check for targets
14016 (while (string-match org-target-regexp line)
14017 (setq tg (match-string 1 line)
14018 line (replace-match
14019 (concat "@<span class=\"target\">" tg "@</span> ")
14020 t t line))
14021 (push (cons (org-solidify-link-text tg)
14022 (format "sec-%d" head-count))
14023 target-alist))
14024 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
14025 (setq txt (replace-match "" t t txt)))
14026 (insert
14027 (format
14028 (if todo
14029 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
14030 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
14031 head-count txt))
14032
14033 (setq org-last-level level))
14034 )))
14035 line)
14036 lines))
14037 (while (> org-last-level 0)
14038 (setq org-last-level (1- org-last-level))
14039 (insert "</li>\n</ul>\n"))
14040 ))
14041 (setq head-count 0)
14042 (org-init-section-numbers)
14043
14044 (while (setq line (pop lines) origline line)
14045 (catch 'nextline
14046
14047 ;; end of quote section?
14048 (when (and inquote (string-match "^\\*+" line))
14049 (insert "</pre>\n")
14050 (setq inquote nil))
14051 ;; inside a quote section?
14052 (when inquote
14053 (insert (org-html-protect line) "\n")
14054 (throw 'nextline nil))
14055
14056 ;; verbatim lines
14057 (when (and org-export-with-fixed-width
14058 (string-match "^[ \t]*:\\(.*\\)" line))
14059 (when (not infixed)
14060 (setq infixed t)
14061 (insert "<pre>\n"))
14062 (insert (org-html-protect (match-string 1 line)) "\n")
14063 (when (and lines
14064 (not (string-match "^[ \t]*\\(:.*\\)"
14065 (car lines))))
14066 (setq infixed nil)
14067 (insert "</pre>\n"))
14068 (throw 'nextline nil))
14069
14070
14071 ;; make targets to anchors
14072 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
14073 (cond
14074 ((match-end 2)
14075 (setq line (replace-match
14076 (concat "@<a name=\""
14077 (org-solidify-link-text (match-string 1 line))
14078 "\">\\nbsp@</a>")
14079 t t line)))
14080 ((and org-export-with-toc (equal (string-to-char line) ?*))
14081 (setq line (replace-match
14082 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
14083 ; (concat "@<i>" (match-string 1 line) "@</i> ")
14084 t t line)))
14085 (t
14086 (setq line (replace-match
14087 (concat "@<a name=\""
14088 (org-solidify-link-text (match-string 1 line))
14089 "\" class=\"target\">" (match-string 1 line) "@</a> ")
14090 t t line)))))
14091
14092 (setq line (org-html-handle-time-stamps line))
14093
14094 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
14095 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
14096 ;; Also handle sub_superscripts and checkboxes
14097 (setq line (org-html-expand line))
14098
14099 ;; Format the links
14100 (setq start 0)
14101 (while (string-match org-bracket-link-analytic-regexp line start)
14102 (setq start (match-beginning 0))
14103 (setq type (if (match-end 2) (match-string 2 line) "internal"))
14104 (setq path (match-string 3 line))
14105 (setq desc1 (if (match-end 5) (match-string 5 line))
14106 desc2 (if (match-end 2) (concat type ":" path) path)
14107 descp (and desc1 (not (equal desc1 desc2)))
14108 desc (or desc1 desc2))
14109 ;; FIXME: do we need to unescape here somewhere?
14110 (cond
14111 ((equal type "internal")
14112 (setq rpl
14113 (concat
14114 "<a href=\"#"
14115 (org-solidify-link-text path target-alist)
14116 "\">" desc "</a>")))
14117 ((member type '("http" "https" "ftp" "mailto" "news"))
14118 ;; standard URL
14119 (setq link (concat type ":" path))
14120 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
14121 ((string= type "file")
14122 ;; FILE link
14123 (let* ((filename path)
14124 (abs-p (file-name-absolute-p filename))
14125 thefile file-is-image-p search)
14126 (save-match-data
14127 (if (string-match "::\\(.*\\)" filename)
14128 (setq search (match-string 1 filename)
14129 filename (replace-match "" t nil filename)))
14130 (setq valid
14131 (if (functionp link-validate)
14132 (funcall link-validate filename current-dir)
14133 t))
14134 (setq file-is-image-p
14135 (string-match (org-image-file-name-regexp) filename))
14136 (setq thefile (if abs-p (expand-file-name filename) filename))
14137 (when (and org-export-html-link-org-files-as-html
14138 (string-match "\\.org$" thefile))
14139 (setq thefile (concat (substring thefile 0
14140 (match-beginning 0))
14141 ".html"))
14142 (if (and search
14143 ;; make sure this is can be used as target search
14144 (not (string-match "^[0-9]*$" search))
14145 (not (string-match "^\\*" search))
14146 (not (string-match "^/.*/$" search)))
14147 (setq thefile (concat thefile "#"
14148 (org-solidify-link-text
14149 (org-link-unescape search)))))
14150 (when (string-match "^file:" desc)
14151 (setq desc (replace-match "" t t desc))
14152 (if (string-match "\\.org$" desc)
14153 (setq desc (replace-match "" t t desc))))))
14154 (setq rpl (if (and file-is-image-p
14155 (or (eq t org-export-html-inline-images)
14156 (and org-export-html-inline-images
14157 (not descp))))
14158 (concat "<img src=\"" thefile "\"/>")
14159 (concat "<a href=\"" thefile "\">" desc "</a>")))
14160 (if (not valid) (setq rpl desc))))
14161 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
14162 (setq rpl (concat "<i>&lt;" type ":"
14163 (save-match-data (org-link-unescape path))
14164 "&gt;</i>"))))
14165 (setq line (replace-match rpl t t line)
14166 start (+ start (length rpl))))
14167 ;; TODO items
14168 (if (and (string-match org-todo-line-regexp line)
14169 (match-beginning 2))
14170 (if (equal (match-string 2 line) org-done-string)
14171 (setq line (replace-match
14172 "<span class=\"done\">\\2</span>"
14173 t nil line 2))
14174 (setq line (replace-match "<span class=\"todo\">\\2</span>"
14175 t nil line 2))))
14176
14177 (cond
14178 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14179 ;; This is a headline
14180 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14181 txt (match-string 2 line))
14182 (if (string-match quote-re0 txt)
14183 (setq txt (replace-match "" t t txt)))
14184 (if (<= level umax) (setq head-count (+ head-count 1)))
14185 (when in-local-list
14186 ;; Close any local lists before inserting a new header line
14187 (while local-list-num
14188 (org-close-li)
14189 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14190 (pop local-list-num))
14191 (setq local-list-indent nil
14192 in-local-list nil))
14193 (org-html-level-start level txt umax
14194 (and org-export-with-toc (<= level umax))
14195 head-count)
14196 ;; QUOTES
14197 (when (string-match quote-re line)
14198 (insert "<pre>")
14199 (setq inquote t)))
14200
14201 ((and org-export-with-tables
14202 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
14203 (if (not table-open)
14204 ;; New table starts
14205 (setq table-open t table-buffer nil table-orig-buffer nil))
14206 ;; Accumulate lines
14207 (setq table-buffer (cons line table-buffer)
14208 table-orig-buffer (cons origline table-orig-buffer))
14209 (when (or (not lines)
14210 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
14211 (car lines))))
14212 (setq table-open nil
14213 table-buffer (nreverse table-buffer)
14214 table-orig-buffer (nreverse table-orig-buffer))
14215 (org-close-par-maybe)
14216 (insert (org-format-table-html table-buffer table-orig-buffer))))
14217 (t
14218 ;; Normal lines
14219 (when (string-match
14220 (cond
14221 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14222 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14223 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14224 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
14225 line)
14226 (setq ind (org-get-string-indentation line)
14227 start-is-num (match-beginning 4)
14228 starter (if (match-beginning 2)
14229 (substring (match-string 2 line) 0 -1))
14230 line (substring line (match-beginning 5)))
14231 (unless (string-match "[^ \t]" line)
14232 ;; empty line. Pretend indentation is large.
14233 (setq ind (1+ (or (car local-list-indent) 1))))
14234 (while (and in-local-list
14235 (or (and (= ind (car local-list-indent))
14236 (not starter))
14237 (< ind (car local-list-indent))))
14238 (org-close-li)
14239 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14240 (pop local-list-num) (pop local-list-indent)
14241 (setq in-local-list local-list-indent))
14242 (cond
14243 ((and starter
14244 (or (not in-local-list)
14245 (> ind (car local-list-indent))))
14246 ;; Start new (level of ) list
14247 (org-close-par-maybe)
14248 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
14249 (push start-is-num local-list-num)
14250 (push ind local-list-indent)
14251 (setq in-local-list t))
14252 (starter
14253 ;; continue current list
14254 (org-close-li)
14255 (insert "<li>\n")))
14256 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
14257 (setq line
14258 (replace-match
14259 (if (equal (match-string 1 line) "X")
14260 "<b>[X]</b>"
14261 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
14262 t t line))))
14263
14264 ;; Empty lines start a new paragraph. If hand-formatted lists
14265 ;; are not fully interpreted, lines starting with "-", "+", "*"
14266 ;; also start a new paragraph.
14267 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
14268
14269 ;; Check if the line break needs to be conserved
14270 (cond
14271 ((string-match "\\\\\\\\[ \t]*$" line)
14272 (setq line (replace-match "<br/>" t t line)))
14273 (org-export-preserve-breaks
14274 (setq line (concat line "<br/>"))))
14275
14276 (insert line "\n")))))
14277
14278 ;; Properly close all local lists and other lists
14279 (when inquote (insert "</pre>\n"))
14280 (when in-local-list
14281 ;; Close any local lists before inserting a new header line
14282 (while local-list-num
14283 (org-close-li)
14284 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
14285 (pop local-list-num))
14286 (setq local-list-indent nil
14287 in-local-list nil))
14288 (org-html-level-start 1 nil umax
14289 (and org-export-with-toc (<= level umax))
14290 head-count)
14291
14292 (when (plist-get opt-plist :auto-postamble)
14293 (when author
14294 (insert "<p class=\"author\"> "
14295 (nth 1 lang-words) ": " author "\n")
14296 (when email
14297 (insert "<a href=\"mailto:" email "\">&lt;"
14298 email "&gt;</a>\n"))
14299 (insert "</p>\n"))
14300 (when (and date time)
14301 (insert "<p class=\"date\"> "
14302 (nth 2 lang-words) ": "
14303 date " " time "</p>\n")))
14304
14305 (if org-export-html-with-timestamp
14306 (insert org-export-html-html-helper-timestamp))
14307 (insert (or (plist-get opt-plist :postamble) ""))
14308 (insert "</body>\n</html>\n")
14309 (normal-mode)
14310 ;; remove empty paragraphs and lists
14311 (goto-char (point-min))
14312 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
14313 (replace-match ""))
14314 (goto-char (point-min))
14315 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
14316 (replace-match ""))
14317 (save-buffer)
14318 (goto-char (point-min))
14319 (message "Exporting... done"))))
14320
14321
14322 (defun org-format-table-html (lines olines)
14323 "Find out which HTML converter to use and return the HTML code."
14324 (if (string-match "^[ \t]*|" (car lines))
14325 ;; A normal org table
14326 (org-format-org-table-html lines)
14327 ;; Table made by table.el - test for spanning
14328 (let* ((hlines (delq nil (mapcar
14329 (lambda (x)
14330 (if (string-match "^[ \t]*\\+-" x) x
14331 nil))
14332 lines)))
14333 (first (car hlines))
14334 (ll (and (string-match "\\S-+" first)
14335 (match-string 0 first)))
14336 (re (concat "^[ \t]*" (regexp-quote ll)))
14337 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
14338 hlines))))
14339 (if (and (not spanning)
14340 (not org-export-prefer-native-exporter-for-tables))
14341 ;; We can use my own converter with HTML conversions
14342 (org-format-table-table-html lines)
14343 ;; Need to use the code generator in table.el, with the original text.
14344 (org-format-table-table-html-using-table-generate-source olines)))))
14345
14346 (defun org-format-org-table-html (lines)
14347 "Format a table into HTML."
14348 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14349 (setq lines (nreverse lines))
14350 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14351 (setq lines (nreverse lines))
14352 (when org-export-table-remove-special-lines
14353 ;; Check if the table has a marking column. If yes remove the
14354 ;; column and the special lines
14355 (let* ((special
14356 (not
14357 (memq nil
14358 (mapcar
14359 (lambda (x)
14360 (or (string-match "^[ \t]*|-" x)
14361 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
14362 lines)))))
14363 (if special
14364 (setq lines
14365 (delq nil
14366 (mapcar
14367 (lambda (x)
14368 (if (string-match "^[ \t]*| *[!_^] *|" x)
14369 nil ; ignore this line
14370 (and (or (string-match "^[ \t]*|-+\\+" x)
14371 (string-match "^[ \t]*|[^|]*|" x))
14372 (replace-match "|" t t x))))
14373 lines))))))
14374
14375 (let ((head (and org-export-highlight-first-table-line
14376 (delq nil (mapcar
14377 (lambda (x) (string-match "^[ \t]*|-" x))
14378 (cdr lines)))))
14379 line fields html)
14380 (setq html (concat org-export-html-table-tag "\n"))
14381 (while (setq line (pop lines))
14382 (catch 'next-line
14383 (if (string-match "^[ \t]*|-" line)
14384 (progn
14385 (setq head nil) ;; head ends here, first time around
14386 ;; ignore this line
14387 (throw 'next-line t)))
14388 ;; Break the line into fields
14389 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14390 (setq html (concat
14391 html
14392 "<tr>"
14393 (mapconcat (lambda (x)
14394 (if head
14395 (concat "<th>" x "</th>")
14396 (concat "<td>" x "</td>")))
14397 fields "")
14398 "</tr>\n"))))
14399 (setq html (concat html "</table>\n"))
14400 html))
14401
14402 (defun org-fake-empty-table-line (line)
14403 "Replace everything except \"|\" with spaces."
14404 (let ((i (length line))
14405 (newstr (copy-sequence line)))
14406 (while (> i 0)
14407 (setq i (1- i))
14408 (if (not (eq (aref newstr i) ?|))
14409 (aset newstr i ?\ )))
14410 newstr))
14411
14412 (defun org-format-table-table-html (lines)
14413 "Format a table generated by table.el into HTML.
14414 This conversion does *not* use `table-generate-source' from table.el.
14415 This has the advantage that Org-mode's HTML conversions can be used.
14416 But it has the disadvantage, that no cell- or row-spanning is allowed."
14417 (let (line field-buffer
14418 (head org-export-highlight-first-table-line)
14419 fields html empty)
14420 (setq html (concat org-export-html-table-tag "\n"))
14421 (while (setq line (pop lines))
14422 (setq empty "&nbsp;")
14423 (catch 'next-line
14424 (if (string-match "^[ \t]*\\+-" line)
14425 (progn
14426 (if field-buffer
14427 (progn
14428 (setq html (concat
14429 html
14430 "<tr>"
14431 (mapconcat
14432 (lambda (x)
14433 (if (equal x "") (setq x empty))
14434 (if head
14435 (concat "<th>" x "</th>\n")
14436 (concat "<td>" x "</td>\n")))
14437 field-buffer "\n")
14438 "</tr>\n"))
14439 (setq head nil)
14440 (setq field-buffer nil)))
14441 ;; Ignore this line
14442 (throw 'next-line t)))
14443 ;; Break the line into fields and store the fields
14444 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14445 (if field-buffer
14446 (setq field-buffer (mapcar
14447 (lambda (x)
14448 (concat x "<br/>" (pop fields)))
14449 field-buffer))
14450 (setq field-buffer fields))))
14451 (setq html (concat html "</table>\n"))
14452 html))
14453
14454 (defun org-format-table-table-html-using-table-generate-source (lines)
14455 "Format a table into html, using `table-generate-source' from table.el.
14456 This has the advantage that cell- or row-spanning is allowed.
14457 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
14458 (require 'table)
14459 (with-current-buffer (get-buffer-create " org-tmp1 ")
14460 (erase-buffer)
14461 (insert (mapconcat 'identity lines "\n"))
14462 (goto-char (point-min))
14463 (if (not (re-search-forward "|[^+]" nil t))
14464 (error "Error processing table"))
14465 (table-recognize-table)
14466 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
14467 (table-generate-source 'html " org-tmp2 ")
14468 (set-buffer " org-tmp2 ")
14469 (buffer-substring (point-min) (point-max))))
14470
14471 (defun org-html-handle-time-stamps (s)
14472 "Format time stamps in string S, or remove them."
14473 (catch 'exit
14474 (let (r b)
14475 (while (string-match org-maybe-keyword-time-regexp s)
14476 ;; FIXME: is it good to never export CLOCK, or do we need control?
14477 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
14478 (throw 'exit ""))
14479 (or b (setq b (substring s 0 (match-beginning 0))))
14480 (if (not org-export-with-timestamps)
14481 (setq r (concat r (substring s 0 (match-beginning 0)))
14482 s (substring s (match-end 0)))
14483 (setq r (concat
14484 r (substring s 0 (match-beginning 0))
14485 (if (match-end 1)
14486 (format "@<span class=\"timestamp-kwd\">%s @</span>"
14487 (match-string 1 s)))
14488 (format " @<span class=\"timestamp\">%s@</span>"
14489 (substring (match-string 3 s) 1 -1)))
14490 s (substring s (match-end 0)))))
14491 ;; Line break if line started and ended with time stamp stuff
14492 (if (not r)
14493 s
14494 (setq r (concat r s))
14495 (unless (string-match "\\S-" (concat b s))
14496 (setq r (concat r "@<br/>")))
14497 r))))
14498
14499 (defun org-html-protect (s)
14500 ;; convert & to &amp;, < to &lt; and > to &gt;
14501 (let ((start 0))
14502 (while (string-match "&" s start)
14503 (setq s (replace-match "&amp;" t t s)
14504 start (1+ (match-beginning 0))))
14505 (while (string-match "<" s)
14506 (setq s (replace-match "&lt;" t t s)))
14507 (while (string-match ">" s)
14508 (setq s (replace-match "&gt;" t t s))))
14509 s)
14510
14511 (defun org-export-cleanup-toc-line (s)
14512 "Remove tags and time staps from lines going into the toc."
14513 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
14514 (setq s (replace-match "" t t s)))
14515 (when org-export-remove-timestamps-from-toc
14516 (while (string-match org-maybe-keyword-time-regexp s)
14517 (setq s (replace-match "" t t s))))
14518 s)
14519
14520 (defun org-html-expand (string)
14521 "Prepare STRING for HTML export. Applies all active conversions.
14522 If there are links in the string, don't modify these."
14523 (let* (m s l res)
14524 (while (setq m (string-match org-bracket-link-regexp string))
14525 (setq s (substring string 0 m)
14526 l (match-string 0 string)
14527 string (substring string (match-end 0)))
14528 (push (org-html-do-expand s) res)
14529 (push l res))
14530 (push (org-html-do-expand string) res)
14531 (apply 'concat (nreverse res))))
14532
14533 (defun org-html-do-expand (s)
14534 "Apply all active conversions to translate special ASCII to HTML."
14535 (setq s (org-html-protect s))
14536 (if org-export-html-expand
14537 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
14538 (setq s (replace-match "<\\1>" t nil s))))
14539 (if org-export-with-emphasize
14540 (setq s (org-export-html-convert-emphasize s)))
14541 (if org-export-with-sub-superscripts
14542 (setq s (org-export-html-convert-sub-super s)))
14543 (if org-export-with-TeX-macros
14544 (let ((start 0) wd ass)
14545 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
14546 (setq wd (match-string 1 s))
14547 (if (setq ass (assoc wd org-html-entities))
14548 (setq s (replace-match (or (cdr ass)
14549 (concat "&" (car ass) ";"))
14550 t t s))
14551 (setq start (+ start (length wd)))))))
14552 s)
14553
14554 (defun org-create-multibrace-regexp (left right n)
14555 "Create a regular expression which will match a balanced sexp.
14556 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
14557 as single character strings.
14558 The regexp returned will match the entire expression including the
14559 delimiters. It will also define a single group which contains the
14560 match except for the outermost delimiters. The maximum depth of
14561 stacked delimiters is N. Escaping delimiters is not possible."
14562 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
14563 (or "\\|")
14564 (re nothing)
14565 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
14566 (while (> n 1)
14567 (setq n (1- n)
14568 re (concat re or next)
14569 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
14570 (concat left "\\(" re "\\)" right)))
14571
14572 (defvar org-match-substring-regexp
14573 (concat
14574 "\\([^\\]\\)\\([_^]\\)\\("
14575 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
14576 "\\|"
14577 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
14578 "\\|"
14579 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
14580 "The regular expression matching a sub- or superscript.")
14581
14582 (defun org-export-html-convert-sub-super (string)
14583 "Convert sub- and superscripts in STRING to HTML."
14584 (let (key c)
14585 (while (string-match org-match-substring-regexp string)
14586 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
14587 (setq c (or (match-string 8 string)
14588 (match-string 6 string)
14589 (match-string 5 string)))
14590 (setq string (replace-match
14591 (concat (match-string 1 string)
14592 "<" key ">" c "</" key ">")
14593 t t string)))
14594 (while (string-match "\\\\\\([_^]\\)" string)
14595 (setq string (replace-match (match-string 1 string) t t string))))
14596 string)
14597
14598 (defun org-export-html-convert-emphasize (string)
14599 "Apply emphasis."
14600 (while (string-match org-emph-re string)
14601 (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)))
14602 string)
14603
14604 (defvar org-par-open nil)
14605 (defun org-open-par ()
14606 "Insert <p>, but first close previous paragraph if any."
14607 (org-close-par-maybe)
14608 (insert "\n<p>")
14609 (setq org-par-open t))
14610 (defun org-close-par-maybe ()
14611 "Close paragraph if there is one open."
14612 (when org-par-open
14613 (insert "</p>")
14614 (setq org-par-open nil)))
14615 (defun org-close-li ()
14616 "Close <li> if necessary."
14617 (org-close-par-maybe)
14618 (insert "</li>\n"))
14619 ; (when (save-excursion
14620 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
14621 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
14622 ; (insert "</li>"))))
14623
14624 (defun org-html-level-start (level title umax with-toc head-count)
14625 "Insert a new level in HTML export.
14626 When TITLE is nil, just close all open levels."
14627 (org-close-par-maybe)
14628 (let ((l (1+ (max level umax))))
14629 (while (<= l org-level-max)
14630 (if (aref levels-open (1- l))
14631 (progn
14632 (org-html-level-close l)
14633 (aset levels-open (1- l) nil)))
14634 (setq l (1+ l)))
14635 (when title
14636 ;; If title is nil, this means this function is called to close
14637 ;; all levels, so the rest is done only if title is given
14638 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14639 (setq title (replace-match
14640 (if org-export-with-tags
14641 (save-match-data
14642 (concat
14643 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
14644 (mapconcat 'identity (org-split-string
14645 (match-string 1 title) ":")
14646 "&nbsp;")
14647 "</span>"))
14648 "")
14649 t t title)))
14650 (if (> level umax)
14651 (progn
14652 (if (aref levels-open (1- level))
14653 (progn
14654 (org-close-li)
14655 (insert "<li>" title "<br/>\n"))
14656 (aset levels-open (1- level) t)
14657 (org-close-par-maybe)
14658 (insert "<ul>\n<li>" title "<br/>\n")))
14659 (if org-export-with-section-numbers
14660 (setq title (concat (org-section-number level) " " title)))
14661 (setq level (+ level org-export-html-toplevel-hlevel -1))
14662 (if with-toc
14663 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
14664 level head-count title level))
14665 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
14666 (org-open-par)))))
14667
14668 (defun org-html-level-close (&rest args)
14669 "Terminate one level in HTML export."
14670 (org-close-li)
14671 (insert "</ul>"))
14672
14673 ;; Variable holding the vector with section numbers
14674 (defvar org-section-numbers (make-vector org-level-max 0))
14675
14676 (defun org-init-section-numbers ()
14677 "Initialize the vector for the section numbers."
14678 (let* ((level -1)
14679 (numbers (nreverse (org-split-string "" "\\.")))
14680 (depth (1- (length org-section-numbers)))
14681 (i depth) number-string)
14682 (while (>= i 0)
14683 (if (> i level)
14684 (aset org-section-numbers i 0)
14685 (setq number-string (or (car numbers) "0"))
14686 (if (string-match "\\`[A-Z]\\'" number-string)
14687 (aset org-section-numbers i
14688 (- (string-to-char number-string) ?A -1))
14689 (aset org-section-numbers i (string-to-number number-string)))
14690 (pop numbers))
14691 (setq i (1- i)))))
14692
14693 (defun org-section-number (&optional level)
14694 "Return a string with the current section number.
14695 When LEVEL is non-nil, increase section numbers on that level."
14696 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
14697 (when level
14698 (when (> level -1)
14699 (aset org-section-numbers
14700 level (1+ (aref org-section-numbers level))))
14701 (setq idx (1+ level))
14702 (while (<= idx depth)
14703 (if (not (= idx 1))
14704 (aset org-section-numbers idx 0))
14705 (setq idx (1+ idx))))
14706 (setq idx 0)
14707 (while (<= idx depth)
14708 (setq n (aref org-section-numbers idx))
14709 (setq string (concat string (if (not (string= string "")) "." "")
14710 (int-to-string n)))
14711 (setq idx (1+ idx)))
14712 (save-match-data
14713 (if (string-match "\\`\\([@0]\\.\\)+" string)
14714 (setq string (replace-match "" t nil string)))
14715 (if (string-match "\\(\\.0\\)+\\'" string)
14716 (setq string (replace-match "" t nil string))))
14717 string))
14718
14719
14720 ;;;###autoload
14721 (defun org-export-icalendar-this-file ()
14722 "Export current file as an iCalendar file.
14723 The iCalendar file will be located in the same directory as the Org-mode
14724 file, but with extension `.ics'."
14725 (interactive)
14726 (org-export-icalendar nil buffer-file-name))
14727
14728 (defun org-export-as-xoxo-insert-into (buffer &rest output)
14729 (with-current-buffer buffer
14730 (apply 'insert output)))
14731
14732 (defun org-export-as-xoxo (&optional buffer)
14733 "Export the org buffer as XOXO.
14734 The XOXO buffer is named *xoxo-<source buffer name>*"
14735 (interactive (list (current-buffer)))
14736 ;; A quickie abstraction
14737
14738 ;; Output everything as XOXO
14739 (with-current-buffer (get-buffer buffer)
14740 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
14741 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14742 (org-infile-export-plist)))
14743 (filename (concat (file-name-as-directory
14744 (org-export-directory :xoxo opt-plist))
14745 (file-name-sans-extension
14746 (file-name-nondirectory buffer-file-name))
14747 ".html"))
14748 (out (find-file-noselect filename))
14749 (last-level 1)
14750 (hanging-li nil))
14751 ;; Check the output buffer is empty.
14752 (with-current-buffer out (erase-buffer))
14753 ;; Kick off the output
14754 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
14755 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
14756 (let* ((hd (match-string-no-properties 1))
14757 (level (length hd))
14758 (text (concat
14759 (match-string-no-properties 2)
14760 (save-excursion
14761 (goto-char (match-end 0))
14762 (let ((str ""))
14763 (catch 'loop
14764 (while 't
14765 (forward-line)
14766 (if (looking-at "^[ \t]\\(.*\\)")
14767 (setq str (concat str (match-string-no-properties 1)))
14768 (throw 'loop str)))))))))
14769
14770 ;; Handle level rendering
14771 (cond
14772 ((> level last-level)
14773 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
14774
14775 ((< level last-level)
14776 (dotimes (- (- last-level level) 1)
14777 (if hanging-li
14778 (org-export-as-xoxo-insert-into out "</li>\n"))
14779 (org-export-as-xoxo-insert-into out "</ol>\n"))
14780 (when hanging-li
14781 (org-export-as-xoxo-insert-into out "</li>\n")
14782 (setq hanging-li nil)))
14783
14784 ((equal level last-level)
14785 (if hanging-li
14786 (org-export-as-xoxo-insert-into out "</li>\n")))
14787 )
14788
14789 (setq last-level level)
14790
14791 ;; And output the new li
14792 (setq hanging-li 't)
14793 (if (equal ?+ (elt text 0))
14794 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
14795 (org-export-as-xoxo-insert-into out "<li>" text))))
14796
14797 ;; Finally finish off the ol
14798 (dotimes (- last-level 1)
14799 (if hanging-li
14800 (org-export-as-xoxo-insert-into out "</li>\n"))
14801 (org-export-as-xoxo-insert-into out "</ol>\n"))
14802
14803 ;; Finish the buffer off and clean it up.
14804 (switch-to-buffer-other-window out)
14805 (indent-region (point-min) (point-max) nil)
14806 (save-buffer)
14807 (goto-char (point-min))
14808 )))
14809
14810 ;;;###autoload
14811 (defun org-export-icalendar-all-agenda-files ()
14812 "Export all files in `org-agenda-files' to iCalendar .ics files.
14813 Each iCalendar file will be located in the same directory as the Org-mode
14814 file, but with extension `.ics'."
14815 (interactive)
14816 (apply 'org-export-icalendar nil (org-agenda-files t)))
14817
14818 ;;;###autoload
14819 (defun org-export-icalendar-combine-agenda-files ()
14820 "Export all files in `org-agenda-files' to a single combined iCalendar file.
14821 The file is stored under the name `org-combined-agenda-icalendar-file'."
14822 (interactive)
14823 (apply 'org-export-icalendar t (org-agenda-files t)))
14824
14825 (defun org-export-icalendar (combine &rest files)
14826 "Create iCalendar files for all elements of FILES.
14827 If COMBINE is non-nil, combine all calendar entries into a single large
14828 file and store it under the name `org-combined-agenda-icalendar-file'."
14829 (save-excursion
14830 (let* ((dir (org-export-directory
14831 :ical (list :publishing-directory
14832 org-export-publishing-directory)))
14833 file ical-file ical-buffer category started org-agenda-new-buffers)
14834
14835 (when combine
14836 (setq ical-file
14837 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
14838 org-combined-agenda-icalendar-file
14839 (expand-file-name org-combined-agenda-icalendar-file dir))
14840 ical-buffer (org-get-agenda-file-buffer ical-file))
14841 (set-buffer ical-buffer) (erase-buffer))
14842 (while (setq file (pop files))
14843 (catch 'nextfile
14844 (org-check-agenda-file file)
14845 (set-buffer (org-get-agenda-file-buffer file))
14846 (unless combine
14847 (setq ical-file (concat (file-name-as-directory dir)
14848 (file-name-sans-extension
14849 (file-name-nondirectory buffer-file-name))
14850 ".ics"))
14851 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
14852 (with-current-buffer ical-buffer (erase-buffer)))
14853 (setq category (or org-category
14854 (file-name-sans-extension
14855 (file-name-nondirectory buffer-file-name))))
14856 (if (symbolp category) (setq category (symbol-name category)))
14857 (let ((standard-output ical-buffer))
14858 (if combine
14859 (and (not started) (setq started t)
14860 (org-start-icalendar-file org-icalendar-combined-name))
14861 (org-start-icalendar-file category))
14862 (org-print-icalendar-entries combine category)
14863 (when (or (and combine (not files)) (not combine))
14864 (org-finish-icalendar-file)
14865 (set-buffer ical-buffer)
14866 (save-buffer)
14867 (run-hooks 'org-after-save-iCalendar-file-hook)))))
14868 (org-release-buffers org-agenda-new-buffers))))
14869
14870 (defvar org-after-save-iCalendar-file-hook nil
14871 "Hook run after an iCalendar file has been saved.
14872 The iCalendar buffer is still current when this hook is run.
14873 A good way to use this is to tell a desktop calenndar application to re-read
14874 the iCalendar file.")
14875
14876 (defun org-print-icalendar-entries (&optional combine category)
14877 "Print iCalendar entries for the current Org-mode file to `standard-output'.
14878 When COMBINE is non nil, add the category to each line."
14879 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
14880 (dts (org-ical-ts-to-string
14881 (format-time-string (cdr org-time-stamp-formats) (current-time))
14882 "DTSTART"))
14883 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
14884 (save-excursion
14885 (goto-char (point-min))
14886 (while (re-search-forward org-ts-regexp nil t)
14887 (setq pos (match-beginning 0)
14888 ts (match-string 0)
14889 inc t
14890 hd (org-get-heading))
14891 (if (looking-at re2)
14892 (progn
14893 (goto-char (match-end 0))
14894 (setq ts2 (match-string 1) inc nil))
14895 (setq ts2 ts
14896 tmp (buffer-substring (max (point-min)
14897 (- pos org-ds-keyword-length))
14898 pos)
14899 deadlinep (string-match org-deadline-regexp tmp)
14900 scheduledp (string-match org-scheduled-regexp tmp)
14901 ;; donep (org-entry-is-done-p)
14902 ))
14903 (if (or (string-match org-tr-regexp hd)
14904 (string-match org-ts-regexp hd))
14905 (setq hd (replace-match "" t t hd)))
14906 (if combine
14907 (setq hd (concat hd " (category " category ")")))
14908 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
14909 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
14910 (princ (format "BEGIN:VEVENT
14911 %s
14912 %s
14913 SUMMARY:%s
14914 END:VEVENT\n"
14915 (org-ical-ts-to-string ts "DTSTART")
14916 (org-ical-ts-to-string ts2 "DTEND" inc)
14917 hd)))
14918 (when org-icalendar-include-todo
14919 (goto-char (point-min))
14920 (while (re-search-forward org-todo-line-regexp nil t)
14921 (setq state (match-string 1))
14922 (unless (equal state org-done-string)
14923 (setq hd (match-string 3))
14924 (if (string-match org-priority-regexp hd)
14925 (setq pri (string-to-char (match-string 2 hd))
14926 hd (concat (substring hd 0 (match-beginning 1))
14927 (substring hd (- (match-end 1)))))
14928 (setq pri org-default-priority))
14929 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
14930 (- org-lowest-priority ?A))))))
14931
14932 (princ (format "BEGIN:VTODO
14933 %s
14934 SUMMARY:%s
14935 SEQUENCE:1
14936 PRIORITY:%d
14937 END:VTODO\n"
14938 dts hd pri))))))))
14939
14940 (defun org-start-icalendar-file (name)
14941 "Start an iCalendar file by inserting the header."
14942 (let ((user user-full-name)
14943 (name (or name "unknown"))
14944 (timezone (cadr (current-time-zone))))
14945 (princ
14946 (format "BEGIN:VCALENDAR
14947 VERSION:2.0
14948 X-WR-CALNAME:%s
14949 PRODID:-//%s//Emacs with Org-mode//EN
14950 X-WR-TIMEZONE:%s
14951 CALSCALE:GREGORIAN\n" name user timezone))))
14952
14953 (defun org-finish-icalendar-file ()
14954 "Finish an iCalendar file by inserting the END statement."
14955 (princ "END:VCALENDAR\n"))
14956
14957 (defun org-ical-ts-to-string (s keyword &optional inc)
14958 "Take a time string S and convert it to iCalendar format.
14959 KEYWORD is added in front, to make a complete line like DTSTART....
14960 When INC is non-nil, increase the hour by two (if time string contains
14961 a time), or the day by one (if it does not contain a time)."
14962 (let ((t1 (org-parse-time-string s 'nodefault))
14963 t2 fmt have-time time)
14964 (if (and (car t1) (nth 1 t1) (nth 2 t1))
14965 (setq t2 t1 have-time t)
14966 (setq t2 (org-parse-time-string s)))
14967 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
14968 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
14969 (when inc
14970 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
14971 (setq time (encode-time s mi h d m y)))
14972 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
14973 (concat keyword (format-time-string fmt time))))
14974
14975 ;;; LaTeX stuff
14976
14977 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14978 "Keymap for the minor `org-cdlatex-mode'.")
14979
14980 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14981 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14982 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14983 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14984 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14985
14986 (defvar org-cdlatex-texmathp-advice-is-done nil
14987 "Flag remembering if we have applied the advice to texmathp already.")
14988
14989 (define-minor-mode org-cdlatex-mode
14990 "Toggle the minor `org-cdlatex-mode'.
14991 This mode supports entering LaTeX environment and math in LaTeX fragments
14992 in Org-mode.
14993 \\{org-cdlatex-mode-map}"
14994 nil " OCDL" nil
14995 (when org-cdlatex-mode (require 'cdlatex))
14996 (unless org-cdlatex-texmathp-advice-is-done
14997 (setq org-cdlatex-texmathp-advice-is-done t)
14998 (defadvice texmathp (around org-math-always-on activate)
14999 "Always return t in org-mode buffers.
15000 This is because we want to insert math symbols without dollars even outside
15001 the LaTeX math segments. If Orgmode thinks that point is actually inside
15002 en embedded LaTeX fragement, let texmathp do its job.
15003 \\[org-cdlatex-mode-map]"
15004 (interactive)
15005 (let (p)
15006 (cond
15007 ((not (org-mode-p)) ad-do-it)
15008 ((eq this-command 'cdlatex-math-symbol)
15009 (setq ad-return-value t
15010 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15011 (t
15012 (let ((p (org-inside-LaTeX-fragment-p)))
15013 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15014 (setq ad-return-value t
15015 texmathp-why '("Org-mode embedded math" . 0))
15016 (if p ad-do-it)))))))))
15017
15018 (defun turn-on-org-cdlatex ()
15019 "Unconditionally turn on `org-cdlatex-mode'."
15020 (org-cdlatex-mode 1))
15021
15022 (defun org-inside-LaTeX-fragment-p ()
15023 "Test if point is inside a LaTeX fragment.
15024 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15025 sequence appearing also before point.
15026 Even though the matchers for math are configurable, this function assumes
15027 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15028 delimiters are skipped when they have been removed by customization.
15029 The return value is nil, or a cons cell with the delimiter and
15030 and the position of this delimiter.
15031
15032 This function does a reasonably good job, but can locally be fooled by
15033 for example currency specifications. For example it will assume being in
15034 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15035 fragments that are properly closed, but during editing, we have to live
15036 with the uncertainty caused by missing closing delimiters. This function
15037 looks only before point, not after."
15038 (catch 'exit
15039 (let ((pos (point))
15040 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15041 (lim (progn
15042 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15043 (point)))
15044 dd-on str (start 0) m re)
15045 (goto-char pos)
15046 (when dodollar
15047 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15048 re (nth 1 (assoc "$" org-latex-regexps)))
15049 (while (string-match re str start)
15050 (cond
15051 ((= (match-end 0) (length str))
15052 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
15053 ((= (match-end 0) (- (length str) 5))
15054 (throw 'exit nil))
15055 (t (setq start (match-end 0))))))
15056 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15057 (goto-char pos)
15058 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15059 (and (match-beginning 2) (throw 'exit nil))
15060 ;; count $$
15061 (while (re-search-backward "\\$\\$" lim t)
15062 (setq dd-on (not dd-on)))
15063 (goto-char pos)
15064 (if dd-on (cons "$$" m))))))
15065
15066
15067 (defun org-try-cdlatex-tab ()
15068 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15069 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15070 - inside a LaTeX fragment, or
15071 - after the first word in a line, where an abbreviation expansion could
15072 insert a LaTeX environment."
15073 ;; FIXME: This may still need refinement.
15074 (when org-cdlatex-mode
15075 (cond
15076 ((save-excursion
15077 (skip-chars-backward "a-zA-Z0-9*")
15078 (skip-chars-backward " \t")
15079 (bolp))
15080 (cdlatex-tab) t)
15081 ((org-inside-LaTeX-fragment-p)
15082 (cdlatex-tab) t)
15083 (t nil))))
15084
15085 (defun org-cdlatex-underscore-caret (&optional arg)
15086 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15087 Revert to the normal definition outside of these fragments."
15088 (interactive "P")
15089 (if (org-inside-LaTeX-fragment-p)
15090 (call-interactively 'cdlatex-sub-superscript)
15091 (let (org-cdlatex-mode)
15092 (call-interactively (key-binding (vector last-input-event))))))
15093
15094 (defun org-cdlatex-math-modify (&optional arg)
15095 "Execute `cdlatex-math-modify' in LaTeX fragments.
15096 Revert to the normal definition outside of these fragments."
15097 (interactive "P")
15098 (if (org-inside-LaTeX-fragment-p)
15099 (call-interactively 'cdlatex-math-modify)
15100 (let (org-cdlatex-mode)
15101 (call-interactively (key-binding (vector last-input-event))))))
15102
15103 (defvar org-latex-fragment-image-overlays nil
15104 "List of overlays carrying the images of latex fragments.")
15105 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15106
15107 (defun org-remove-latex-fragment-image-overlays ()
15108 "Remove all overlays with LaTeX fragment images in current buffer."
15109 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15110 (setq org-latex-fragment-image-overlays nil))
15111
15112 (defun org-preview-latex-fragment (&optional subtree)
15113 "Preview the LaTeX fragment at point, or all locally or globally.
15114 If the cursor is in a LaTeX fragment, create the image and overlay
15115 it over the source code. If there is no fragment at point, display
15116 all fragments in the current text, from one headline to the next. With
15117 prefix SUBTREE, display all fragments in the current subtree. With a
15118 double prefix `C-u C-u', or when the cursor is before the first headline,
15119 display all fragments in the buffer.
15120 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15121 (interactive "P")
15122 (org-remove-latex-fragment-image-overlays)
15123 (save-excursion
15124 (save-restriction
15125 (let (beg end at msg)
15126 (cond
15127 ((or (equal subtree '(16))
15128 (not (save-excursion
15129 (re-search-backward (concat "^" outline-regexp) nil t))))
15130 (setq beg (point-min) end (point-max)
15131 msg "Creating images for buffer...%s"))
15132 ((equal subtree '(4))
15133 (org-back-to-heading)
15134 (setq beg (point) end (org-end-of-subtree)
15135 msg "Creating images for subtree...%s"))
15136 (t
15137 (if (setq at (org-inside-LaTeX-fragment-p))
15138 (goto-char (max (point-min) (- (cdr at) 2)))
15139 (org-back-to-heading))
15140 (setq beg (point) end (progn (outline-next-heading) (point))
15141 msg (if at "Creating image...%s"
15142 "Creating images for entry...%s"))))
15143 (message msg "")
15144 (narrow-to-region beg end)
15145 (org-format-latex
15146 (concat "ltxpng/" (file-name-sans-extension
15147 (file-name-nondirectory
15148 buffer-file-name)))
15149 default-directory 'overlays msg at)
15150 (message msg "done. Use `C-c C-c' to remove images.")))))
15151
15152 (defvar org-latex-regexps
15153 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15154 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15155 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15156 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
15157 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15158 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
15159 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
15160 "Regular expressions for matching embedded LaTeX.")
15161
15162 (defun org-format-latex (prefix &optional dir overlays msg at)
15163 "Replace LaTeX fragments with links to an image, and produce images."
15164 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15165 (let* ((prefixnodir (file-name-nondirectory prefix))
15166 (absprefix (expand-file-name prefix dir))
15167 (todir (file-name-directory absprefix))
15168 (opt org-format-latex-options)
15169 (matchers (plist-get opt :matchers))
15170 (re-list org-latex-regexps)
15171 (cnt 0) txt link beg end re e oldfiles
15172 m n block linkfile movefile ov)
15173 ;; Make sure the directory exists
15174 (or (file-directory-p todir) (make-directory todir))
15175 ;; Check if there are old images files with this prefix, and remove them
15176 (setq oldfiles (directory-files
15177 todir 'full
15178 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
15179 (while oldfiles (delete-file (pop oldfiles)))
15180 ;; Check the different regular expressions
15181 (while (setq e (pop re-list))
15182 (setq m (car e) re (nth 1 e) n (nth 2 e)
15183 block (if (nth 3 e) "\n\n" ""))
15184 (when (member m matchers)
15185 (goto-char (point-min))
15186 (while (re-search-forward re nil t)
15187 (when (or (not at) (equal (cdr at) (match-beginning n)))
15188 (setq txt (match-string n)
15189 beg (match-beginning n) end (match-end n)
15190 cnt (1+ cnt)
15191 linkfile (format "%s_%04d.png" prefix cnt)
15192 movefile (format "%s_%04d.png" absprefix cnt)
15193 link (concat block "[[file:" linkfile "]]" block))
15194 (if msg (message msg cnt))
15195 (goto-char beg)
15196 (org-create-formula-image
15197 txt movefile opt)
15198 (if overlays
15199 (progn
15200 (setq ov (org-make-overlay beg end))
15201 (if (featurep 'xemacs)
15202 (progn
15203 (org-overlay-put ov 'invisible t)
15204 (org-overlay-put
15205 ov 'end-glyph
15206 (make-glyph (vector 'png :file movefile))))
15207 (org-overlay-put
15208 ov 'display
15209 (list 'image :type 'png :file movefile :ascent 'center)))
15210 (push ov org-latex-fragment-image-overlays)
15211 (goto-char end))
15212 (delete-region beg end)
15213 (insert link))))))))
15214
15215 ;; This function borrows from Ganesh Swami's latex2png.el
15216 (defun org-create-formula-image (string tofile options)
15217 (let* ((tmpdir (if (featurep 'xemacs)
15218 (temp-directory)
15219 temporary-file-directory))
15220 (texfilebase (make-temp-name
15221 (expand-file-name "orgtex" tmpdir)))
15222
15223 ;(texfilebase (make-temp-file "orgtex"))
15224 ; (dummy (delete-file texfilebase))
15225 (texfile (concat texfilebase ".tex"))
15226 (dvifile (concat texfilebase ".dvi"))
15227 (pngfile (concat texfilebase ".png"))
15228 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15229 (fg (or (plist-get options :foreground) "Black"))
15230 (bg (or (plist-get options :background) "Transparent")))
15231 (with-temp-file texfile
15232 (insert "\\documentclass{article}
15233 \\usepackage{fullpage}
15234 \\usepackage{amssymb}
15235 \\usepackage[usenames]{color}
15236 \\usepackage{amsmath}
15237 \\usepackage{latexsym}
15238 \\usepackage[mathscr]{eucal}
15239 \\pagestyle{empty}
15240 \\begin{document}\n" string "\n\\end{document}\n"))
15241 (let ((dir default-directory))
15242 (condition-case nil
15243 (progn
15244 (cd tmpdir)
15245 (call-process "latex" nil nil nil texfile))
15246 (error nil))
15247 (cd dir))
15248 (if (not (file-exists-p dvifile))
15249 (progn (message "Failed to create dvi file from %s" texfile) nil)
15250 (call-process "dvipng" nil nil nil
15251 "-E" "-fg" fg "-bg" bg
15252 "-x" scale "-y" scale "-T" "tight"
15253 "-o" pngfile
15254 dvifile)
15255 (if (not (file-exists-p pngfile))
15256 (progn (message "Failed to create png file from %s" texfile) nil)
15257 ;; Use the requested file name and clean up
15258 (copy-file pngfile tofile 'replace)
15259 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15260 (delete-file (concat texfilebase e)))
15261 pngfile))))
15262
15263 ;;; Key bindings
15264
15265 ;; - Bindings in Org-mode map are currently
15266 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
15267 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
15268 ;; e (?) useful from outline-mode
15269 ;; i k @ expendable from outline-mode
15270 ;; 0123456789 % & ()_{} " ` free
15271
15272 ;; Make `C-c C-x' a prefix key
15273 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
15274
15275 ;; TAB key with modifiers
15276 (define-key org-mode-map "\C-i" 'org-cycle)
15277 (define-key org-mode-map [(tab)] 'org-cycle)
15278 (define-key org-mode-map [(meta tab)] 'org-complete)
15279 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
15280 ;; The following line is necessary under Suse GNU/Linux
15281 (unless (featurep 'xemacs)
15282 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
15283 (define-key org-mode-map [(shift tab)] 'org-shifttab)
15284
15285 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
15286 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
15287 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15288 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
15289 (define-key org-mode-map [(meta return)] 'org-meta-return)
15290 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
15291 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
15292
15293 ;; Cursor keys with modifiers
15294 (define-key org-mode-map [(meta left)] 'org-metaleft)
15295 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
15296 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
15297 (define-key org-mode-map [(meta right)] 'org-metaright)
15298 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
15299 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
15300 (define-key org-mode-map [(meta up)] 'org-metaup)
15301 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
15302 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
15303 (define-key org-mode-map [(meta down)] 'org-metadown)
15304 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
15305 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
15306
15307 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15308 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
15309 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
15310 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
15311 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
15312 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
15313 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
15314 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
15315 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
15316 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
15317 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
15318 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
15319 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
15320 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
15321 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
15322 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
15323
15324 ;; All the other keys
15325
15326 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15327 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
15328 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
15329 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
15330 (define-key org-mode-map "\C-c\C-j" 'org-goto)
15331 (define-key org-mode-map "\C-c\C-t" 'org-todo)
15332 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
15333 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
15334 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
15335 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15336 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
15337 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
15338 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
15339 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
15340 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
15341 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
15342 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
15343 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
15344 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
15345 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
15346 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15347 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15348 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15349 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15350 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
15351 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
15352 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15353 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
15354 (define-key org-mode-map "\C-c]" 'org-remove-file)
15355 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
15356 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
15357 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
15358 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15359 (define-key org-mode-map "\C-m" 'org-return)
15360 (define-key org-mode-map "\C-c?" 'org-table-current-column)
15361 (define-key org-mode-map "\C-c " 'org-table-blank-field)
15362 (define-key org-mode-map "\C-c+" 'org-table-sum)
15363 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
15364 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
15365 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
15366 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15367 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
15368 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15369 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
15370 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
15371 (define-key org-mode-map "\C-c\C-e" 'org-export)
15372 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15373
15374 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
15375 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15376 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15377 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15378
15379 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15380 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15381 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15382 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15383 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15384 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15385 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15386 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15387
15388 (when (featurep 'xemacs)
15389 (define-key org-mode-map 'button3 'popup-mode-menu))
15390
15391 (defsubst org-table-p () (org-at-table-p))
15392
15393 (defun org-self-insert-command (N)
15394 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15395 If the cursor is in a table looking at whitespace, the whitespace is
15396 overwritten, and the table is not marked as requiring realignment."
15397 (interactive "p")
15398 (if (and (org-table-p)
15399 (progn
15400 ;; check if we blank the field, and if that triggers align
15401 (and org-table-auto-blank-field
15402 (member last-command
15403 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
15404 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15405 ;; got extra space, this field does not determine column width
15406 (let (org-table-may-need-update) (org-table-blank-field))
15407 ;; no extra space, this field may determine column width
15408 (org-table-blank-field)))
15409 t)
15410 (eq N 1)
15411 (looking-at "[^|\n]* |"))
15412 (let (org-table-may-need-update)
15413 (goto-char (1- (match-end 0)))
15414 (delete-backward-char 1)
15415 (goto-char (match-beginning 0))
15416 (self-insert-command N))
15417 (setq org-table-may-need-update t)
15418 (self-insert-command N)))
15419
15420 (defun org-delete-backward-char (N)
15421 "Like `delete-backward-char', insert whitespace at field end in tables.
15422 When deleting backwards, in tables this function will insert whitespace in
15423 front of the next \"|\" separator, to keep the table aligned. The table will
15424 still be marked for re-alignment if the field did fill the entire column,
15425 because, in this case the deletion might narrow the column."
15426 (interactive "p")
15427 (if (and (org-table-p)
15428 (eq N 1)
15429 (string-match "|" (buffer-substring (point-at-bol) (point)))
15430 (looking-at ".*?|"))
15431 (let ((pos (point))
15432 (noalign (looking-at "[^|\n\r]* |"))
15433 (c org-table-may-need-update))
15434 (backward-delete-char N)
15435 (skip-chars-forward "^|")
15436 (insert " ")
15437 (goto-char (1- pos))
15438 ;; noalign: if there were two spaces at the end, this field
15439 ;; does not determine the width of the column.
15440 (if noalign (setq org-table-may-need-update c)))
15441 (backward-delete-char N)))
15442
15443 (defun org-delete-char (N)
15444 "Like `delete-char', but insert whitespace at field end in tables.
15445 When deleting characters, in tables this function will insert whitespace in
15446 front of the next \"|\" separator, to keep the table aligned. The table will
15447 still be marked for re-alignment if the field did fill the entire column,
15448 because, in this case the deletion might narrow the column."
15449 (interactive "p")
15450 (if (and (org-table-p)
15451 (not (bolp))
15452 (not (= (char-after) ?|))
15453 (eq N 1))
15454 (if (looking-at ".*?|")
15455 (let ((pos (point))
15456 (noalign (looking-at "[^|\n\r]* |"))
15457 (c org-table-may-need-update))
15458 (replace-match (concat
15459 (substring (match-string 0) 1 -1)
15460 " |"))
15461 (goto-char pos)
15462 ;; noalign: if there were two spaces at the end, this field
15463 ;; does not determine the width of the column.
15464 (if noalign (setq org-table-may-need-update c)))
15465 (delete-char N))
15466 (delete-char N)))
15467
15468 ;; How to do this: Measure non-white length of current string
15469 ;; If equal to column width, we should realign.
15470
15471 (defun org-remap (map &rest commands)
15472 "In MAP, remap the functions given in COMMANDS.
15473 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15474 (let (new old)
15475 (while commands
15476 (setq old (pop commands) new (pop commands))
15477 (if (fboundp 'command-remapping)
15478 (define-key map (vector 'remap old) new)
15479 (substitute-key-definition old new map global-map)))))
15480
15481 (when (eq org-enable-table-editor 'optimized)
15482 ;; If the user wants maximum table support, we need to hijack
15483 ;; some standard editing functions
15484 (org-remap org-mode-map
15485 'self-insert-command 'org-self-insert-command
15486 'delete-char 'org-delete-char
15487 'delete-backward-char 'org-delete-backward-char)
15488 (define-key org-mode-map "|" 'org-force-self-insert))
15489
15490 (defun org-shiftcursor-error ()
15491 "Throw an error because Shift-Cursor command was applied in wrong context."
15492 (error "This command is active in special context like tables, headlines or timestamps"))
15493
15494 (defun org-shifttab (&optional arg)
15495 "Global visibility cycling or move to previous table field.
15496 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15497 on context.
15498 See the individual commands for more information."
15499 (interactive "P")
15500 (cond
15501 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15502 (t (call-interactively 'org-global-cycle))))
15503
15504 (defun org-shiftmetaleft ()
15505 "Promote subtree or delete table column.
15506 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
15507 See the individual commands for more information."
15508 (interactive)
15509 (cond
15510 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15511 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15512 ((org-at-item-p) (call-interactively 'org-outdent-item))
15513 (t (org-shiftcursor-error))))
15514
15515 (defun org-shiftmetaright ()
15516 "Demote subtree or insert table column.
15517 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
15518 See the individual commands for more information."
15519 (interactive)
15520 (cond
15521 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15522 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15523 ((org-at-item-p) (call-interactively 'org-indent-item))
15524 (t (org-shiftcursor-error))))
15525
15526 (defun org-shiftmetaup (&optional arg)
15527 "Move subtree up or kill table row.
15528 Calls `org-move-subtree-up' or `org-table-kill-row' or
15529 `org-move-item-up' depending on context. See the individual commands
15530 for more information."
15531 (interactive "P")
15532 (cond
15533 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15534 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15535 ((org-at-item-p) (call-interactively 'org-move-item-up))
15536 (t (org-shiftcursor-error))))
15537 (defun org-shiftmetadown (&optional arg)
15538 "Move subtree down or insert table row.
15539 Calls `org-move-subtree-down' or `org-table-insert-row' or
15540 `org-move-item-down', depending on context. See the individual
15541 commands for more information."
15542 (interactive "P")
15543 (cond
15544 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15545 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15546 ((org-at-item-p) (call-interactively 'org-move-item-down))
15547 (t (org-shiftcursor-error))))
15548
15549 (defun org-metaleft (&optional arg)
15550 "Promote heading or move table column to left.
15551 Calls `org-do-promote' or `org-table-move-column', depending on context.
15552 With no specific context, calls the Emacs default `backward-word'.
15553 See the individual commands for more information."
15554 (interactive "P")
15555 (cond
15556 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15557 ((or (org-on-heading-p) (org-region-active-p))
15558 (call-interactively 'org-do-promote))
15559 (t (call-interactively 'backward-word))))
15560
15561 (defun org-metaright (&optional arg)
15562 "Demote subtree or move table column to right.
15563 Calls `org-do-demote' or `org-table-move-column', depending on context.
15564 With no specific context, calls the Emacs default `forward-word'.
15565 See the individual commands for more information."
15566 (interactive "P")
15567 (cond
15568 ((org-at-table-p) (call-interactively 'org-table-move-column))
15569 ((or (org-on-heading-p) (org-region-active-p))
15570 (call-interactively 'org-do-demote))
15571 (t (call-interactively 'forward-word))))
15572
15573 (defun org-metaup (&optional arg)
15574 "Move subtree up or move table row up.
15575 Calls `org-move-subtree-up' or `org-table-move-row' or
15576 `org-move-item-up', depending on context. See the individual commands
15577 for more information."
15578 (interactive "P")
15579 (cond
15580 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15581 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15582 ((org-at-item-p) (call-interactively 'org-move-item-up))
15583 (t (org-shiftcursor-error))))
15584
15585 (defun org-metadown (&optional arg)
15586 "Move subtree down or move table row down.
15587 Calls `org-move-subtree-down' or `org-table-move-row' or
15588 `org-move-item-down', depending on context. See the individual
15589 commands for more information."
15590 (interactive "P")
15591 (cond
15592 ((org-at-table-p) (call-interactively 'org-table-move-row))
15593 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15594 ((org-at-item-p) (call-interactively 'org-move-item-down))
15595 (t (org-shiftcursor-error))))
15596
15597 (defun org-shiftup (&optional arg)
15598 "Increase item in timestamp or increase priority of current headline.
15599 Calls `org-timestamp-up' or `org-priority-up', depending on context.
15600 See the individual commands for more information."
15601 (interactive "P")
15602 (cond
15603 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
15604 ((org-on-heading-p) (call-interactively 'org-priority-up))
15605 ((org-at-item-p) (call-interactively 'org-previous-item))
15606 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
15607
15608 (defun org-shiftdown (&optional arg)
15609 "Decrease item in timestamp or decrease priority of current headline.
15610 Calls `org-timestamp-down' or `org-priority-down', depending on context.
15611 See the individual commands for more information."
15612 (interactive "P")
15613 (cond
15614 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
15615 ((org-on-heading-p) (call-interactively 'org-priority-down))
15616 (t (call-interactively 'org-next-item))))
15617
15618 (defun org-shiftright ()
15619 "Next TODO keyword or timestamp one day later, depending on context."
15620 (interactive)
15621 (cond
15622 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15623 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
15624 (t (org-shiftcursor-error))))
15625
15626 (defun org-shiftleft ()
15627 "Previous TODO keyword or timestamp one day earlier, depending on context."
15628 (interactive)
15629 (cond
15630 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15631 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
15632 (t (org-shiftcursor-error))))
15633
15634 (defun org-copy-special ()
15635 "Copy region in table or copy current subtree.
15636 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15637 See the individual commands for more information."
15638 (interactive)
15639 (call-interactively
15640 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15641
15642 (defun org-cut-special ()
15643 "Cut region in table or cut current subtree.
15644 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15645 See the individual commands for more information."
15646 (interactive)
15647 (call-interactively
15648 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15649
15650 (defun org-paste-special (arg)
15651 "Paste rectangular region into table, or past subtree relative to level.
15652 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15653 See the individual commands for more information."
15654 (interactive "P")
15655 (if (org-at-table-p)
15656 (org-table-paste-rectangle)
15657 (org-paste-subtree arg)))
15658
15659 (defun org-ctrl-c-ctrl-c (&optional arg)
15660 "Set tags in headline, or update according to changed information at point.
15661
15662 This command does many different things, depending on context:
15663
15664 - If the cursor is in a headline, prompt for tags and insert them
15665 into the current line, aligned to `org-tags-column'. When called
15666 with prefix arg, realign all tags in the current buffer.
15667
15668 - If the cursor is in one of the special #+KEYWORD lines, this
15669 triggers scanning the buffer for these lines and updating the
15670 information.
15671
15672 - If the cursor is inside a table, realign the table. This command
15673 works even if the automatic table editor has been turned off.
15674
15675 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15676 the entire table.
15677
15678 - If the cursor is inside a table created by the table.el package,
15679 activate that table.
15680
15681 - If the current buffer is a remember buffer, close note and file it.
15682 with a prefix argument, file it without further interaction to the default
15683 location.
15684
15685 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15686 links in this buffer.
15687
15688 - If the cursor is on a numbered item in a plain list, renumber the
15689 ordered list."
15690 (interactive "P")
15691 (let ((org-enable-table-editor t))
15692 (cond
15693 ((or org-clock-overlays org-occur-highlights
15694 org-latex-fragment-image-overlays)
15695 (org-remove-clock-overlays)
15696 (org-remove-occur-highlights)
15697 (org-remove-latex-fragment-image-overlays)
15698 (message "Temporary highlights/overlays removed from current buffer"))
15699 ((and (local-variable-p 'org-finish-function (current-buffer))
15700 (fboundp org-finish-function))
15701 (funcall org-finish-function))
15702 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15703 ((org-on-heading-p) (call-interactively 'org-set-tags))
15704 ((org-at-table.el-p)
15705 (require 'table)
15706 (beginning-of-line 1)
15707 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15708 (call-interactively 'table-recognize-table))
15709 ((org-at-table-p)
15710 (org-table-maybe-eval-formula)
15711 (if arg
15712 (call-interactively 'org-table-recalculate)
15713 (org-table-maybe-recalculate-line))
15714 (call-interactively 'org-table-align))
15715 ((org-at-item-checkbox-p)
15716 (call-interactively 'org-toggle-checkbox))
15717 ((org-at-item-p)
15718 (call-interactively 'org-renumber-ordered-list))
15719 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
15720 (cond
15721 ((equal (match-string 1) "TBLFM")
15722 ;; Recalculate the table before this line
15723 (save-excursion
15724 (beginning-of-line 1)
15725 (skip-chars-backward " \r\n\t")
15726 (if (org-at-table-p)
15727 (org-call-with-arg 'org-table-recalculate t))))
15728 (t
15729 (call-interactively 'org-mode-restart))))
15730 (t (error "C-c C-c can do nothing useful at this location.")))))
15731
15732 (defun org-mode-restart ()
15733 "Restart Org-mode, to scan again for special lines.
15734 Also updates the keyword regular expressions."
15735 (interactive)
15736 (let ((org-inhibit-startup t)) (org-mode))
15737 (message "Org-mode restarted to refresh keyword and special line setup"))
15738
15739 (defun org-return ()
15740 "Goto next table row or insert a newline.
15741 Calls `org-table-next-row' or `newline', depending on context.
15742 See the individual commands for more information."
15743 (interactive)
15744 (cond
15745 ((org-at-table-p)
15746 (org-table-justify-field-maybe)
15747 (call-interactively 'org-table-next-row))
15748 (t (newline))))
15749
15750 (defun org-meta-return (&optional arg)
15751 "Insert a new heading or wrap a region in a table.
15752 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15753 See the individual commands for more information."
15754 (interactive "P")
15755 (cond
15756 ((org-at-table-p)
15757 (call-interactively 'org-table-wrap-region))
15758 (t (call-interactively 'org-insert-heading))))
15759
15760 ;;; Menu entries
15761
15762 ;; Define the Org-mode menus
15763 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15764 '("Tbl"
15765 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
15766 ["Next Field" org-cycle (org-at-table-p)]
15767 ["Previous Field" org-shifttab (org-at-table-p)]
15768 ["Next Row" org-return (org-at-table-p)]
15769 "--"
15770 ["Blank Field" org-table-blank-field (org-at-table-p)]
15771 ["Edit Field" org-table-edit-field (org-at-table-p)]
15772 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15773 "--"
15774 ("Column"
15775 ["Move Column Left" org-metaleft (org-at-table-p)]
15776 ["Move Column Right" org-metaright (org-at-table-p)]
15777 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15778 ["Insert Column" org-shiftmetaright (org-at-table-p)]
15779 "--"
15780 ["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])
15781 ("Row"
15782 ["Move Row Up" org-metaup (org-at-table-p)]
15783 ["Move Row Down" org-metadown (org-at-table-p)]
15784 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15785 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15786 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15787 "--"
15788 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
15789 ("Rectangle"
15790 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15791 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15792 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15793 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15794 "--"
15795 ("Calculate"
15796 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15797 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15798 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
15799 "--"
15800 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15801 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15802 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15803 "--"
15804 ["Sum Column/Rectangle" org-table-sum
15805 (or (org-at-table-p) (org-region-active-p))]
15806 ["Which Column?" org-table-current-column (org-at-table-p)])
15807 ["Debug Formulas"
15808 (setq org-table-formula-debug (not org-table-formula-debug))
15809 :style toggle :selected org-table-formula-debug]
15810 "--"
15811 ["Create" org-table-create (and (not (org-at-table-p))
15812 org-enable-table-editor)]
15813 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15814 ["Import from File" org-table-import (not (org-at-table-p))]
15815 ["Export to File" org-table-export (org-at-table-p)]
15816 "--"
15817 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15818
15819 (easy-menu-define org-org-menu org-mode-map "Org menu"
15820 '("Org"
15821 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
15822 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
15823 ["Sparse Tree" org-occur t]
15824 ["Show All" show-all t]
15825 "--"
15826 ["New Heading" org-insert-heading t]
15827 ("Navigate Headings"
15828 ["Up" outline-up-heading t]
15829 ["Next" outline-next-visible-heading t]
15830 ["Previous" outline-previous-visible-heading t]
15831 ["Next Same Level" outline-forward-same-level t]
15832 ["Previous Same Level" outline-backward-same-level t]
15833 "--"
15834 ["Jump" org-goto t])
15835 ("Edit Structure"
15836 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15837 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15838 "--"
15839 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15840 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15841 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15842 "--"
15843 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15844 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15845 ["Demote Heading" org-metaright (not (org-at-table-p))]
15846 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15847 "--"
15848 ["Convert to odd levels" org-convert-to-odd-levels t]
15849 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15850 ("Archive"
15851 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15852 ["Check and Tag Children" (org-toggle-archive-tag (4))
15853 :active t :keys "C-u C-c C-x C-a"]
15854 ["Sparse trees open ARCHIVE trees"
15855 (setq org-sparse-tree-open-archived-trees
15856 (not org-sparse-tree-open-archived-trees))
15857 :style toggle :selected org-sparse-tree-open-archived-trees]
15858 ["Cycling opens ARCHIVE trees"
15859 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15860 :style toggle :selected org-cycle-open-archived-trees]
15861 ["Agenda includes ARCHIVE trees"
15862 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
15863 :style toggle :selected (not org-agenda-skip-archived-trees)]
15864 "--"
15865 ["Move Subtree to Archive" org-archive-subtree t]
15866 ["Check and Move Children" (org-archive-subtree '(4))
15867 :active t :keys "C-u C-c $"])
15868 "--"
15869 ("TODO Lists"
15870 ["TODO/DONE/-" org-todo t]
15871 ("Select keyword"
15872 ["Next keyword" org-shiftright (org-on-heading-p)]
15873 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15874 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
15875 ["Show TODO Tree" org-show-todo-tree t]
15876 ["Global TODO list" org-todo-list t]
15877 "--"
15878 ["Set Priority" org-priority t]
15879 ["Priority Up" org-shiftup t]
15880 ["Priority Down" org-shiftdown t])
15881 ("Dates and Scheduling"
15882 ["Timestamp" org-time-stamp t]
15883 ["Timestamp (inactive)" org-time-stamp-inactive t]
15884 ("Change Date"
15885 ["1 Day Later" org-timestamp-up-day t]
15886 ["1 Day Earlier" org-timestamp-down-day t]
15887 ["1 ... Later" org-shiftup t]
15888 ["1 ... Earlier" org-shiftdown t])
15889 ["Compute Time Range" org-evaluate-time-range t]
15890 ["Schedule Item" org-schedule t]
15891 ["Deadline" org-deadline t]
15892 "--"
15893 ["Goto Calendar" org-goto-calendar t]
15894 ["Date from Calendar" org-date-from-calendar t])
15895 ("Logging work"
15896 ["Clock in" org-clock-in t]
15897 ["Clock out" org-clock-out t]
15898 ["Clock cancel" org-clock-cancel t]
15899 ["Display times" org-clock-display t]
15900 ["Create clock table" org-clock-report t]
15901 "--"
15902 ["Record DONE time"
15903 (progn (setq org-log-done (not org-log-done))
15904 (message "Switching to %s will %s record a timestamp"
15905 org-done-string
15906 (if org-log-done "automatically" "not")))
15907 :style toggle :selected org-log-done])
15908 "--"
15909 ["Agenda Command" org-agenda t]
15910 ("File List for Agenda")
15911 ("Special views current file"
15912 ["TODO Tree" org-show-todo-tree t]
15913 ["Check Deadlines" org-check-deadlines t]
15914 ["Timeline" org-timeline t]
15915 ["Tags Tree" org-tags-sparse-tree t])
15916 "--"
15917 ("Hyperlinks"
15918 ["Store Link (Global)" org-store-link t]
15919 ["Insert Link" org-insert-link t]
15920 ["Follow Link" org-open-at-point t]
15921 "--"
15922 ["Descriptive Links"
15923 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15924 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
15925 ["Literal Links"
15926 (progn
15927 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15928 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
15929 "--"
15930 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
15931 (save-excursion (goto-char (point-min))
15932 (re-search-forward "<[a-z]+:" nil t))])
15933 "--"
15934 ["Export/Publish" org-export t]
15935 ("LaTeX"
15936 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15937 :selected org-cdlatex-mode]
15938 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15939 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15940 ["Modify math symbol" org-cdlatex-math-modify
15941 (org-inside-LaTeX-fragment-p)]
15942 ["Export LaTeX fragments as images"
15943 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
15944 :style toggle :selected org-export-with-LaTeX-fragments])
15945 "--"
15946 ("Documentation"
15947 ["Show Version" org-version t]
15948 ["Info Documentation" org-info t])
15949 ("Customize"
15950 ["Browse Org Group" org-customize t]
15951 "--"
15952 ["Expand This Menu" org-create-customize-menu
15953 (fboundp 'customize-menu-create)])
15954 "--"
15955 ["Refresh setup" org-mode-restart t]
15956 ))
15957
15958 (defun org-info (&optional node)
15959 "Read documentation for Org-mode in the info system.
15960 With optional NODE, go directly to that node."
15961 (interactive)
15962 (require 'info)
15963 (Info-goto-node (format "(org)%s" (or node ""))))
15964
15965 (defun org-install-agenda-files-menu ()
15966 (let ((bl (buffer-list)))
15967 (save-excursion
15968 (while bl
15969 (set-buffer (pop bl))
15970 (if (org-mode-p) (setq bl nil)))
15971 (when (org-mode-p)
15972 (easy-menu-change
15973 '("Org") "File List for Agenda"
15974 (append
15975 (list
15976 ["Edit File List" (org-edit-agenda-file-list) t]
15977 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15978 ["Remove Current File from List" org-remove-file t]
15979 ["Cycle through agenda files" org-cycle-agenda-files t]
15980 "--")
15981 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15982
15983 ;;; Documentation
15984
15985 (defun org-customize ()
15986 "Call the customize function with org as argument."
15987 (interactive)
15988 (customize-browse 'org))
15989
15990 (defun org-create-customize-menu ()
15991 "Create a full customization menu for Org-mode, insert it into the menu."
15992 (interactive)
15993 (if (fboundp 'customize-menu-create)
15994 (progn
15995 (easy-menu-change
15996 '("Org") "Customize"
15997 `(["Browse Org group" org-customize t]
15998 "--"
15999 ,(customize-menu-create 'org)
16000 ["Set" Custom-set t]
16001 ["Save" Custom-save t]
16002 ["Reset to Current" Custom-reset-current t]
16003 ["Reset to Saved" Custom-reset-saved t]
16004 ["Reset to Standard Settings" Custom-reset-standard t]))
16005 (message "\"Org\"-menu now contains full customization menu"))
16006 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16007
16008 ;;; Miscellaneous stuff
16009
16010 (defun org-context ()
16011 "Return a list of contexts of the current cursor position.
16012 If several contexts apply, all are returned.
16013 Each context entry is a list with a symbol naming the context, and
16014 two positions indicating start and end of the context. Possible
16015 contexts are:
16016
16017 :headline anywhere in a headline
16018 :headline-stars on the leading stars in a headline
16019 :todo-keyword on a TODO keyword (including DONE) in a headline
16020 :tags on the TAGS in a headline
16021 :priority on the priority cookie in a headline
16022 :item on the first line of a plain list item
16023 :item-bullet on the bullet/number of a plain list item
16024 :checkbox on the checkbox in a plain list item
16025 :table in an org-mode table
16026 :table-special on a special filed in a table
16027 :table-table in a table.el table
16028 :link on a hyperline
16029 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16030 :target on a <<target>>
16031 :radio-target on a <<<radio-target>>>
16032 :latex-fragment on a LaTeX fragment
16033 :latex-preview on a LaTeX fragment with overlayed preview image
16034
16035 This function expects the position to be visible because it uses font-lock
16036 faces as a help to recognize the following contexts: :table-special, :link,
16037 and :keyword."
16038 (let* ((f (get-text-property (point) 'face))
16039 (faces (if (listp f) f (list f)))
16040 (p (point)) clist o)
16041 ;; First the large context
16042 (cond
16043 ((org-on-heading-p)
16044 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16045 (when (progn
16046 (beginning-of-line 1)
16047 (looking-at org-todo-line-tags-regexp))
16048 (push (org-point-in-group p 1 :headline-stars) clist)
16049 (push (org-point-in-group p 2 :todo-keyword) clist)
16050 (push (org-point-in-group p 4 :tags) clist))
16051 (goto-char p)
16052 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
16053 (if (looking-at "\\[#[A-Z]\\]")
16054 (push (org-point-in-group p 0 :priority) clist)))
16055
16056 ((org-at-item-p)
16057 (push (org-point-in-group p 2 :item-bullet) clist)
16058 (push (list :item (point-at-bol)
16059 (save-excursion (org-end-of-item) (point)))
16060 clist)
16061 (and (org-at-item-checkbox-p)
16062 (push (org-point-in-group p 0 :checkbox) clist)))
16063
16064 ((org-at-table-p)
16065 (push (list :table (org-table-begin) (org-table-end)) clist)
16066 (if (memq 'org-formula faces)
16067 (push (list :table-special
16068 (previous-single-property-change p 'face)
16069 (next-single-property-change p 'face)) clist)))
16070 ((org-at-table-p 'any)
16071 (push (list :table-table) clist)))
16072 (goto-char p)
16073
16074 ;; Now the small context
16075 (cond
16076 ((org-at-timestamp-p)
16077 (push (org-point-in-group p 0 :timestamp) clist))
16078 ((memq 'org-link faces)
16079 (push (list :link
16080 (previous-single-property-change p 'face)
16081 (next-single-property-change p 'face)) clist))
16082 ((memq 'org-special-keyword faces)
16083 (push (list :keyword
16084 (previous-single-property-change p 'face)
16085 (next-single-property-change p 'face)) clist))
16086 ((org-on-target-p)
16087 (push (org-point-in-group p 0 :target) clist)
16088 (goto-char (1- (match-beginning 0)))
16089 (if (looking-at org-radio-target-regexp)
16090 (push (org-point-in-group p 0 :radio-target) clist))
16091 (goto-char p))
16092 ((setq o (car (delq nil
16093 (mapcar
16094 (lambda (x)
16095 (if (memq x org-latex-fragment-image-overlays) x))
16096 (org-overlays-at (point))))))
16097 (push (list :latex-fragment
16098 (org-overlay-start o) (org-overlay-end o)) clist)
16099 (push (list :latex-preview
16100 (org-overlay-start o) (org-overlay-end o)) clist))
16101 ((org-inside-LaTeX-fragment-p)
16102 ;; FIXME: positions wring.
16103 (push (list :latex-fragment (point) (point)) clist)))
16104
16105 (setq clist (nreverse (delq nil clist)))
16106 clist))
16107
16108 (defun org-point-in-group (point group &optional context)
16109 "Check if POINT is in match-group GROUP.
16110 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16111 match. If the match group does ot exist or point is not inside it,
16112 return nil."
16113 (and (match-beginning group)
16114 (>= point (match-beginning group))
16115 (<= point (match-end group))
16116 (if context
16117 (list context (match-beginning group) (match-end group))
16118 t)))
16119
16120 (defun org-move-line-down (arg)
16121 "Move the current line down. With prefix argument, move it past ARG lines."
16122 (interactive "p")
16123 (let ((col (current-column))
16124 beg end pos)
16125 (beginning-of-line 1) (setq beg (point))
16126 (beginning-of-line 2) (setq end (point))
16127 (beginning-of-line (+ 1 arg))
16128 (setq pos (move-marker (make-marker) (point)))
16129 (insert (delete-and-extract-region beg end))
16130 (goto-char pos)
16131 (move-to-column col)))
16132
16133 (defun org-move-line-up (arg)
16134 "Move the current line up. With prefix argument, move it past ARG lines."
16135 (interactive "p")
16136 (let ((col (current-column))
16137 beg end pos)
16138 (beginning-of-line 1) (setq beg (point))
16139 (beginning-of-line 2) (setq end (point))
16140 (beginning-of-line (- arg))
16141 (setq pos (move-marker (make-marker) (point)))
16142 (insert (delete-and-extract-region beg end))
16143 (goto-char pos)
16144 (move-to-column col)))
16145
16146 ;; Paragraph filling stuff.
16147 ;; We want this to be just right, so use the full arsenal.
16148
16149 (defun org-set-autofill-regexps ()
16150 (interactive)
16151 ;; In the paragraph separator we include headlines, because filling
16152 ;; text in a line directly attached to a headline would otherwise
16153 ;; fill the headline as well.
16154 (org-set-local 'comment-start-skip "^#+[ \t]*")
16155 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
16156 ;; The paragraph starter includes hand-formatted lists.
16157 (org-set-local 'paragraph-start
16158 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
16159 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16160 ;; But only if the user has not turned off tables or fixed-width regions
16161 (org-set-local
16162 'auto-fill-inhibit-regexp
16163 (concat "\\*\\|#"
16164 "\\|[ \t]*" org-keyword-time-regexp
16165 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16166 (concat
16167 "\\|[ \t]*["
16168 (if org-enable-table-editor "|" "")
16169 (if org-enable-fixed-width-editor ":" "")
16170 "]"))))
16171 ;; We use our own fill-paragraph function, to make sure that tables
16172 ;; and fixed-width regions are not wrapped. That function will pass
16173 ;; through to `fill-paragraph' when appropriate.
16174 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16175 ; Adaptive filling: To get full control, first make sure that
16176 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16177 (org-set-local 'adaptive-fill-regexp "\000")
16178 (org-set-local 'adaptive-fill-function
16179 'org-adaptive-fill-function))
16180
16181 (defun org-fill-paragraph (&optional justify)
16182 "Re-align a table, pass through to fill-paragraph if no table."
16183 (let ((table-p (org-at-table-p))
16184 (table.el-p (org-at-table.el-p)))
16185 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
16186 (table.el-p t) ; skip table.el tables
16187 (table-p (org-table-align) t) ; align org-mode tables
16188 (t nil)))) ; call paragraph-fill
16189
16190 ;; For reference, this is the default value of adaptive-fill-regexp
16191 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16192
16193 (defun org-adaptive-fill-function ()
16194 "Return a fill prefix for org-mode files.
16195 In particular, this makes sure hanging paragraphs for hand-formatted lists
16196 work correctly."
16197 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
16198 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
16199
16200 ;; Functions needed for Emacs/XEmacs region compatibility
16201
16202 (defun org-add-hook (hook function &optional append local)
16203 "Add-hook, compatible with both Emacsen."
16204 (if (and local (featurep 'xemacs))
16205 (add-local-hook hook function append)
16206 (add-hook hook function append local)))
16207
16208 (defun org-region-active-p ()
16209 "Is `transient-mark-mode' on and the region active?
16210 Works on both Emacs and XEmacs."
16211 (if org-ignore-region
16212 nil
16213 (if (featurep 'xemacs)
16214 (and zmacs-regions (region-active-p))
16215 (and transient-mark-mode mark-active))))
16216
16217 (defun org-add-to-invisibility-spec (arg)
16218 "Add elements to `buffer-invisibility-spec'.
16219 See documentation for `buffer-invisibility-spec' for the kind of elements
16220 that can be added."
16221 (cond
16222 ((fboundp 'add-to-invisibility-spec)
16223 (add-to-invisibility-spec arg))
16224 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
16225 (setq buffer-invisibility-spec (list arg)))
16226 (t
16227 (setq buffer-invisibility-spec
16228 (cons arg buffer-invisibility-spec)))))
16229
16230 (defun org-remove-from-invisibility-spec (arg)
16231 "Remove elements from `buffer-invisibility-spec'."
16232 (if (fboundp 'remove-from-invisibility-spec)
16233 (remove-from-invisibility-spec arg)
16234 (if (consp buffer-invisibility-spec)
16235 (setq buffer-invisibility-spec
16236 (delete arg buffer-invisibility-spec)))))
16237
16238 (defun org-in-invisibility-spec-p (arg)
16239 "Is ARG a member of `buffer-invisibility-spec'?"
16240 (if (consp buffer-invisibility-spec)
16241 (member arg buffer-invisibility-spec)
16242 nil))
16243
16244 (defun org-image-file-name-regexp ()
16245 "Return regexp matching the file names of images."
16246 (if (fboundp 'image-file-name-regexp)
16247 (image-file-name-regexp)
16248 (let ((image-file-name-extensions
16249 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16250 "xbm" "xpm" "pbm" "pgm" "ppm")))
16251 (concat "\\."
16252 (regexp-opt (nconc (mapcar 'upcase
16253 image-file-name-extensions)
16254 image-file-name-extensions)
16255 t)
16256 "\\'"))))
16257
16258 ;; Functions extending outline functionality
16259
16260 ;; C-a should go to the beginning of a *visible* line, also in the
16261 ;; new outline.el. I guess this should be patched into Emacs?
16262 (defun org-beginning-of-line ()
16263 "Go to the beginning of the current line. If that is invisible, continue
16264 to a visible line beginning. This makes the function of C-a more intuitive."
16265 (interactive)
16266 (beginning-of-line 1)
16267 (if (bobp)
16268 nil
16269 (backward-char 1)
16270 (if (org-invisible-p)
16271 (while (and (not (bobp)) (org-invisible-p))
16272 (backward-char 1)
16273 (beginning-of-line 1))
16274 (forward-char 1))))
16275
16276 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16277
16278 (defun org-invisible-p ()
16279 "Check if point is at a character currently not visible."
16280 ;; Early versions of noutline don't have `outline-invisible-p'.
16281 (if (fboundp 'outline-invisible-p)
16282 (outline-invisible-p)
16283 (get-char-property (point) 'invisible)))
16284
16285 (defun org-invisible-p2 ()
16286 "Check if point is at a character currently not visible."
16287 (save-excursion
16288 (if (and (eolp) (not (bobp))) (backward-char 1))
16289 ;; Early versions of noutline don't have `outline-invisible-p'.
16290 (if (fboundp 'outline-invisible-p)
16291 (outline-invisible-p)
16292 (get-char-property (point) 'invisible))))
16293
16294 (defalias 'org-back-to-heading 'outline-back-to-heading)
16295 (defalias 'org-on-heading-p 'outline-on-heading-p)
16296
16297 (defun org-on-target-p ()
16298 (let ((pos (point)))
16299 (save-excursion
16300 (skip-chars-forward "<")
16301 (and (re-search-backward "<<" nil t)
16302 (or (looking-at org-radio-target-regexp)
16303 (looking-at org-target-regexp))
16304 (<= (match-beginning 0) pos)
16305 (>= (1+ (match-end 0)) pos)))))
16306
16307 (defun org-up-heading-all (arg)
16308 "Move to the heading line of which the present line is a subheading.
16309 This function considers both visible and invisible heading lines.
16310 With argument, move up ARG levels."
16311 (if (fboundp 'outline-up-heading-all)
16312 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16313 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16314
16315 (defun org-show-hidden-entry ()
16316 "Show an entry where even the heading is hidden."
16317 (save-excursion
16318 (org-show-entry)))
16319
16320 (defun org-flag-heading (flag &optional entry)
16321 "Flag the current heading. FLAG non-nil means make invisible.
16322 When ENTRY is non-nil, show the entire entry."
16323 (save-excursion
16324 (org-back-to-heading t)
16325 ;; Check if we should show the entire entry
16326 (if entry
16327 (progn
16328 (org-show-entry)
16329 (save-excursion
16330 (and (outline-next-heading)
16331 (org-flag-heading nil))))
16332 (outline-flag-region (max 1 (1- (point)))
16333 (save-excursion (outline-end-of-heading) (point))
16334 flag))))
16335
16336 (defun org-end-of-subtree (&optional invisible-OK)
16337 ;; This is an exact copy of the original function, but it uses
16338 ;; `org-back-to-heading', to make it work also in invisible
16339 ;; trees. And is uses an invisible-OK argument.
16340 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16341 (org-back-to-heading invisible-OK)
16342 (let ((first t)
16343 (level (funcall outline-level)))
16344 (while (and (not (eobp))
16345 (or first (> (funcall outline-level) level)))
16346 (setq first nil)
16347 (outline-next-heading))
16348 (if (memq (preceding-char) '(?\n ?\^M))
16349 (progn
16350 ;; Go to end of line before heading
16351 (forward-char -1)
16352 (if (memq (preceding-char) '(?\n ?\^M))
16353 ;; leave blank line before heading
16354 (forward-char -1)))))
16355 (point))
16356
16357 (defun org-show-subtree ()
16358 "Show everything after this heading at deeper levels."
16359 (outline-flag-region
16360 (point)
16361 (save-excursion
16362 (outline-end-of-subtree) (outline-next-heading) (point))
16363 nil))
16364
16365 (defun org-show-entry ()
16366 "Show the body directly following this heading.
16367 Show the heading too, if it is currently invisible."
16368 (interactive)
16369 (save-excursion
16370 (org-back-to-heading t)
16371 (outline-flag-region
16372 (max 1 (1- (point)))
16373 (save-excursion
16374 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
16375 (or (match-beginning 1) (point-max)))
16376 nil)))
16377
16378 (defun org-make-options-regexp (kwds)
16379 "Make a regular expression for keyword lines."
16380 (concat
16381 "^"
16382 "#?[ \t]*\\+\\("
16383 (mapconcat 'regexp-quote kwds "\\|")
16384 "\\):[ \t]*"
16385 "\\(.+\\)"))
16386
16387 ;; Make `bookmark-jump' show the jump location if it was hidden.
16388 (eval-after-load "bookmark"
16389 '(if (boundp 'bookmark-after-jump-hook)
16390 ;; We can use the hook
16391 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16392 ;; Hook not available, use advice
16393 (defadvice bookmark-jump (after org-make-visible activate)
16394 "Make the position visible."
16395 (org-bookmark-jump-unhide))))
16396
16397 (defun org-bookmark-jump-unhide ()
16398 "Unhide the current position, to show the bookmark location."
16399 (and (org-mode-p)
16400 (or (org-invisible-p)
16401 (save-excursion (goto-char (max (point-min) (1- (point))))
16402 (org-invisible-p)))
16403 (org-show-hierarchy-above)))
16404
16405 ;;; Experimental code
16406
16407
16408 ;;; Finish up
16409
16410 (provide 'org)
16411
16412 (run-hooks 'org-load-hook)
16413
16414 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16415 ;;; org.el ends here