Release 4.58
[org-mode.git] / org.el
blob7435b7937c5b2b65260c4d62994343ff6150afae
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.58
9 ;;
10 ;; This file is part of GNU Emacs.
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.
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.
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
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.
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.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://staff.science.uva.nl/~dominik/Tools/org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; Recent changes
63 ;; --------------
64 ;; Version 4.58
65 ;; - Full undo support in the agenda buffer.
66 ;; - Listing stuck GTD projects (projects without any NEXT ACTIONS).
67 ;; Configure `org-stuck-projects' before using it.
68 ;; - C-c C-x b shows the current subtree in an indirect buffer, in
69 ;; another, dedicated frame.
70 ;; - Custom agenda commands take precedence over builtin commands.
71 ;; - auto-fill for comments works on the Emacs side, XEmacs not yet.
73 ;; Version 4.57
74 ;; - Sorting of outline items on same level.
75 ;; - Sorting tables automatically selects line range between hlines.
76 ;; - Changes in Agenda buffer
77 ;; - `C-c C-o' follows a link in the current line.
78 ;; - `C-c $' archives the subtree corresponding to the line.
79 ;; - Changing dates with S-left and S-right show new date in agenda,
80 ;; but still do not move the entry to the new date.
81 ;; - new option `org-agenda-skip-scheduled-if-done'.
82 ;; - Agenda and sparse tree construction using tag matches can now
83 ;; use regular expressions.
84 ;; - When prompted for a date/time, entering "+7" indicates a date
85 ;; 7 days from now - but only this is the only thing you give.
86 ;; - Custom time formats also apply to exported html and ascii.
87 ;; - Bug fixes.
89 ;; Version 4.56
90 ;; - `C-k' in agenda kills current line and corresponding subtree in file.
91 ;; - XEmacs compatibility issues fixed, in particular tag alignment.
92 ;; - M-left/right now in/outdents plain list items, no Shift needed.
93 ;; - Bug fixes.
95 ;; Version 4.55
96 ;; - Bug fixes.
98 ;; Version 4.54
99 ;; - Improvements to fast tag selection
100 ;; + show status also in target line.
101 ;; + option to auto-exit after first change to tags list (see manual).
102 ;; - Tags sparse trees now also respect the settings in
103 ;; `org-show-hierarchy-above' and `org-show-following-heading'.
104 ;; - Bug fixes.
106 ;; Version 4.53
107 ;; - Custom time formats can be overlayed over time stamps.
108 ;; - New option `org-agenda-todo-ignore-deadlines'.
109 ;; - Work-around for flyspell bug (CVS Emacs has this fixed in flyspell.el).
110 ;; - Work-around for session.el problem with circular data structures.
111 ;; - Bug fixes.
113 ;; Version 4.52
114 ;; - TAG matches can also specify conditions on TODO keywords.
115 ;; - The fast tag interface allows setting tags that are not in the
116 ;; predefined list.
117 ;; - Bug fixes.
119 ;; Version 4.51
120 ;; - Link abbreviations (manual section 4.5).
121 ;; - More control over how agenda is displayed. See the new variables
122 ;; `org-agenda-window-setup', `org-agenda-restore-windows-after-quit'.
123 ;; - Bug fixes.
125 ;;; Code:
127 (eval-when-compile
128 (require 'cl)
129 (require 'gnus-sum)
130 (require 'calendar))
131 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
132 ;; the file noutline.el being loaded.
133 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
134 ;; We require noutline, which might be provided in outline.el
135 (require 'outline) (require 'noutline)
136 ;; Other stuff we need.
137 (require 'time-date)
138 (require 'easymenu)
140 ;;;; Customization variables
142 (defvar org-version "4.58"
143 "The version number of the file org.el.")
144 (defun org-version ()
145 (interactive)
146 (message "Org-mode version %s" org-version))
148 ;;; Compatibility constants
149 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
150 (defconst org-format-transports-properties-p
151 (let ((x "a"))
152 (add-text-properties 0 1 '(test t) x)
153 (get-text-property 0 'test (format "%s" x)))
154 "Does format transport text properties?")
156 (defgroup org nil
157 "Outline-based notes management and organizer."
158 :tag "Org"
159 :group 'outlines
160 :group 'hypermedia
161 :group 'calendar)
163 (defgroup org-startup nil
164 "Options concerning startup of Org-mode."
165 :tag "Org Startup"
166 :group 'org)
168 (defcustom org-startup-folded t
169 "Non-nil means, entering Org-mode will switch to OVERVIEW.
170 This can also be configured on a per-file basis by adding one of
171 the following lines anywhere in the buffer:
173 #+STARTUP: fold
174 #+STARTUP: nofold
175 #+STARTUP: content"
176 :group 'org-startup
177 :type '(choice
178 (const :tag "nofold: show all" nil)
179 (const :tag "fold: overview" t)
180 (const :tag "content: all headlines" content)))
182 (defcustom org-startup-truncated t
183 "Non-nil means, entering Org-mode will set `truncate-lines'.
184 This is useful since some lines containing links can be very long and
185 uninteresting. Also tables look terrible when wrapped."
186 :group 'org-startup
187 :type 'boolean)
189 (defcustom org-startup-align-all-tables nil
190 "Non-nil means, align all tables when visiting a file.
191 This is useful when the column width in tables is forced with <N> cookies
192 in table fields. Such tables will look correct only after the first re-align.
193 This can also be configured on a per-file basis by adding one of
194 the following lines anywhere in the buffer:
195 #+STARTUP: align
196 #+STARTUP: noalign"
197 :group 'org-startup
198 :type 'boolean)
200 (defcustom org-startup-with-deadline-check nil
201 "Non-nil means, entering Org-mode will run the deadline check.
202 This means, if you start editing an org file, you will get an
203 immediate reminder of any due deadlines.
204 This can also be configured on a per-file basis by adding one of
205 the following lines anywhere in the buffer:
206 #+STARTUP: dlcheck
207 #+STARTUP: nodlcheck"
208 :group 'org-startup
209 :type 'boolean)
211 (defcustom org-insert-mode-line-in-empty-file nil
212 "Non-nil means insert the first line setting Org-mode in empty files.
213 When the function `org-mode' is called interactively in an empty file, this
214 normally means that the file name does not automatically trigger Org-mode.
215 To ensure that the file will always be in Org-mode in the future, a
216 line enforcing Org-mode will be inserted into the buffer, if this option
217 has been set."
218 :group 'org-startup
219 :type 'boolean)
221 (defcustom org-CUA-compatible nil
222 "Non-nil means use alternative key bindings for S-<cursor movement>.
223 Org-mode used S-<cursor movement> for changing timestamps and priorities.
224 S-<cursor movement> is also used for example by `CUA-mode' to select text.
225 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
226 alternative bindings. Setting this variable to t will replace the following
227 keys both in Org-mode and in the Org-agenda buffer.
229 S-RET -> C-S-RET
230 S-up -> M-p
231 S-down -> M-n
232 S-left -> M--
233 S-right -> M-+
235 If you do not like the alternative keys, take a look at the variable
236 `org-disputed-keys'.
238 This option is only relevant at load-time of Org-mode. Changing it requires
239 a restart of Emacs to become effective."
240 :group 'org-startup
241 :type 'boolean)
243 (defvar org-disputed-keys
244 '((S-up [(shift up)] [(meta ?p)])
245 (S-down [(shift down)] [(meta ?n)])
246 (S-left [(shift left)] [(meta ?-)])
247 (S-right [(shift right)] [(meta ?+)])
248 (S-return [(shift return)] [(control shift return)]))
249 "Keys for which Org-mode and other modes compete.
250 This is an alist, cars are symbols for lookup, 1st element is the default key,
251 second element will be used when `org-CUA-compatible' is t.")
253 (defun org-key (key)
254 "Select a key according to `org-CUA-compatible'."
255 (nth (if org-CUA-compatible 2 1)
256 (or (assq key org-disputed-keys)
257 (error "Invalid Key %s in `org-key'" key))))
259 (defcustom org-ellipsis nil
260 "The ellipsis to use in the Org-mode outline.
261 When nil, just use the standard three dots. When a string, use that instead,
262 and just in Org-mode (which will then use its own display table).
263 Changing this requires executing `M-x org-mode' in a buffer to become
264 effective."
265 :group 'org-startup
266 :type '(choice (const :tag "Default" nil)
267 (string :tag "String" :value "...#")))
269 (defvar org-display-table nil
270 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
272 (defgroup org-keywords nil
273 "Keywords in Org-mode."
274 :tag "Org Keywords"
275 :group 'org)
277 (defcustom org-deadline-string "DEADLINE:"
278 "String to mark deadline entries.
279 A deadline is this string, followed by a time stamp. Should be a word,
280 terminated by a colon. You can insert a schedule keyword and
281 a timestamp with \\[org-deadline].
282 Changes become only effective after restarting Emacs."
283 :group 'org-keywords
284 :type 'string)
286 (defcustom org-scheduled-string "SCHEDULED:"
287 "String to mark scheduled TODO entries.
288 A schedule is this string, followed by a time stamp. Should be a word,
289 terminated by a colon. You can insert a schedule keyword and
290 a timestamp with \\[org-schedule].
291 Changes become only effective after restarting Emacs."
292 :group 'org-keywords
293 :type 'string)
295 (defcustom org-closed-string "CLOSED:"
296 "String used as the prefix for timestamps logging closing a TODO entry."
297 :group 'org-keywords
298 :type 'string)
300 (defcustom org-clock-string "CLOCK:"
301 "String used as prefix for timestamps clocking work hours on an item."
302 :group 'org-keywords
303 :type 'string)
305 (defcustom org-comment-string "COMMENT"
306 "Entries starting with this keyword will never be exported.
307 An entry can be toggled between COMMENT and normal with
308 \\[org-toggle-comment].
309 Changes become only effective after restarting Emacs."
310 :group 'org-keywords
311 :type 'string)
313 (defcustom org-quote-string "QUOTE"
314 "Entries starting with this keyword will be exported in fixed-width font.
315 Quoting applies only to the text in the entry following the headline, and does
316 not extend beyond the next headline, even if that is lower level.
317 An entry can be toggled between QUOTE and normal with
318 \\[org-toggle-fixed-width-section]."
319 :group 'org-keywords
320 :type 'string)
322 (defgroup org-structure nil
323 "Options concerning the general structure of Org-mode files."
324 :tag "Org Structure"
325 :group 'org)
327 (defgroup org-cycle nil
328 "Options concerning visibility cycling in Org-mode."
329 :tag "Org Cycle"
330 :group 'org-structure)
332 (defcustom org-cycle-global-at-bob t
333 "Cycle globally if cursor is at beginning of buffer and not at a headline.
334 This makes it possible to do global cycling without having to use S-TAB or
335 C-u TAB. For this special case to work, the first line of the buffer
336 must not be a headline - it may be empty ot some other text. When used in
337 this way, `org-cycle-hook' is disables temporarily, to make sure the
338 cursor stays at the beginning of the buffer.
339 When this option is nil, don't do anything special at the beginning
340 of the buffer."
341 :group 'org-cycle
342 :type 'boolean)
344 (defcustom org-cycle-emulate-tab t
345 "Where should `org-cycle' emulate TAB.
346 nil Never
347 white Only in completely white lines
348 whitestart Only at the beginning of lines, before the first non-white char.
349 t Everywhere except in headlines
350 If TAB is used in a place where it does not emulate TAB, the current subtree
351 visibility is cycled."
352 :group 'org-cycle
353 :type '(choice (const :tag "Never" nil)
354 (const :tag "Only in completely white lines" white)
355 (const :tag "Before first char in a line" whitestart)
356 (const :tag "Everywhere except in headlines" t)
359 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
360 org-optimize-window-after-visibility-change)
361 "Hook that is run after `org-cycle' has changed the buffer visibility.
362 The function(s) in this hook must accept a single argument which indicates
363 the new state that was set by the most recent `org-cycle' command. The
364 argument is a symbol. After a global state change, it can have the values
365 `overview', `content', or `all'. After a local state change, it can have
366 the values `folded', `children', or `subtree'."
367 :group 'org-cycle
368 :type 'hook)
371 (defgroup org-edit-structure nil
372 "Options concerning structure editing in Org-mode."
373 :tag "Org Edit Structure"
374 :group 'org-structure)
376 (defcustom org-odd-levels-only nil
377 "Non-nil means, skip even levels and only use odd levels for the outline.
378 This has the effect that two stars are being added/taken away in
379 promotion/demotion commands. It also influences how levels are
380 handled by the exporters.
381 Changing it requires restart of `font-lock-mode' to become effective
382 for fontification also in regions already fontified.
383 You may also set this on a per-file basis by adding one of the following
384 lines to the buffer:
386 #+STARTUP: odd
387 #+STARTUP: oddeven"
388 :group 'org-edit-structure
389 :group 'org-font-lock
390 :type 'boolean)
392 (defcustom org-adapt-indentation t
393 "Non-nil means, adapt indentation when promoting and demoting.
394 When this is set and the *entire* text in an entry is indented, the
395 indentation is increased by one space in a demotion command, and
396 decreased by one in a promotion command. If any line in the entry
397 body starts at column 0, indentation is not changed at all."
398 :group 'org-edit-structure
399 :type 'boolean)
401 (defcustom org-blank-before-new-entry '((heading . nil)
402 (plain-list-item . nil))
403 "Should `org-insert-heading' leave a blank line before new heading/item?
404 The value is an alist, with `heading' and `plain-list-item' as car,
405 and a boolean flag as cdr."
406 :group 'org-edit-structure
407 :type '(list
408 (cons (const heading) (boolean))
409 (cons (const plain-list-item) (boolean))))
411 (defcustom org-insert-heading-hook nil
412 "Hook being run after inserting a new heading."
413 :group 'org-edit-structure
414 :type 'boolean)
416 (defcustom org-enable-fixed-width-editor t
417 "Non-nil means, lines starting with \":\" are treated as fixed-width.
418 This currently only means, they are never auto-wrapped.
419 When nil, such lines will be treated like ordinary lines.
420 See also the QUOTE keyword."
421 :group 'org-edit-structure
422 :type 'boolean)
424 (defgroup org-sparse-trees nil
425 "Options concerning sparse trees in Org-mode."
426 :tag "Org Sparse Trees"
427 :group 'org-structure)
429 (defcustom org-highlight-sparse-tree-matches t
430 "Non-nil means, highlight all matches that define a sparse tree.
431 The highlights will automatically disappear the next time the buffer is
432 changed by an edit command."
433 :group 'org-sparse-trees
434 :type 'boolean)
436 (defcustom org-remove-highlights-with-change t
437 "Non-nil means, any change to the buffer will remove temporary highlights.
438 Such highlights are created by `org-occur' and `org-clock-display'.
439 When nil, `C-c C-c needs to be used to get rid of the highlights.
440 The highlights created by `org-preview-latex-fragment' always need
441 `C-c C-c' to be removed."
442 :group 'org-sparse-trees
443 :group 'org-time
444 :type 'boolean)
446 (defcustom org-show-hierarchy-above '((default . t))
447 "Non-nil means, show full hierarchy when showing a spot in the tree.
448 Turning this off makes sparse trees more compact, but also less clear.
449 Instead of t, this can also be an alist specifying this option for different
450 contexts. Valid contexts are
451 agenda when exposing an entry from the agenda
452 org-goto when using the command `org-goto' on key C-c C-j
453 occur-tree when using the command `org-occur' on key C-c /
454 tags-tree when constructing a sparse tree based on tags matches
455 link-search when exposing search matches associated with a link
456 mark-goto when exposing the jump goal of a mark
457 bookmark-jump when exposing a bookmark location
458 default default for all contexts not set explicitly"
459 :group 'org-sparse-trees
460 :type '(choice
461 (const :tag "Always" t)
462 (const :tag "Never" nil)
463 (repeat :greedy t :tag "Individual contexts"
464 (cons
465 (choice :tag "Context"
466 (const agenda)
467 (const org-goto)
468 (const occur-tree)
469 (const tags-tree)
470 (const link-search)
471 (const mark-goto)
472 (const bookmark-jump)
473 (const default))
474 (boolean)))))
476 (defcustom org-show-following-heading '((default . t))
477 "Non-nil means, show heading following match in `org-occur'.
478 When doing an `org-occur' it is useful to show the headline which
479 follows the match, even if they do not match the regexp. This makes it
480 easier to edit directly inside the sparse tree. However, if you use
481 `org-occur' mainly as an overview, the following headlines are
482 unnecessary clutter.
483 Instead of t, this can also be an alist specifying this option for different
484 contexts. See `org-show-hierarchy-above' for valid contexts."
485 :group 'org-sparse-trees
486 :type '(choice
487 (const :tag "Always" t)
488 (const :tag "Never" nil)
489 (repeat :greedy t :tag "Individual contexts"
490 (cons
491 (choice :tag "Context"
492 (const agenda)
493 (const org-goto)
494 (const occur-tree)
495 (const tags-tree)
496 (const link-search)
497 (const mark-goto)
498 (const bookmark-jump)
499 (const default))
500 (boolean)))))
502 (defcustom org-occur-hook '(org-first-headline-recenter)
503 "Hook that is run after `org-occur' has constructed a sparse tree.
504 This can be used to recenter the window to show as much of the structure
505 as possible."
506 :group 'org-sparse-trees
507 :type 'hook)
509 (defgroup org-plain-lists nil
510 "Options concerning plain lists in Org-mode."
511 :tag "Org Plain lists"
512 :group 'org-structure)
514 (defcustom org-cycle-include-plain-lists nil
515 "Non-nil means, include plain lists into visibility cycling.
516 This means that during cycling, plain list items will *temporarily* be
517 interpreted as outline headlines with a level given by 1000+i where i is the
518 indentation of the bullet. In all other operations, plain list items are
519 not seen as headlines. For example, you cannot assign a TODO keyword to
520 such an item."
521 :group 'org-plain-lists
522 :type 'boolean)
524 (defcustom org-plain-list-ordered-item-terminator t
525 "The character that makes a line with leading number an ordered list item.
526 Valid values are ?. and ?\). To get both terminators, use t. While
527 ?. may look nicer, it creates the danger that a line with leading
528 number may be incorrectly interpreted as an item. ?\) therefore is
529 the safe choice."
530 :group 'org-plain-lists
531 :type '(choice (const :tag "dot like in \"2.\"" ?.)
532 (const :tag "paren like in \"2)\"" ?\))
533 (const :tab "both" t)))
535 (defcustom org-auto-renumber-ordered-lists t
536 "Non-nil means, automatically renumber ordered plain lists.
537 Renumbering happens when the sequence have been changed with
538 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
539 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
540 :group 'org-plain-lists
541 :type 'boolean)
543 (defcustom org-provide-checkbox-statistics t
544 "Non-nil means, update checkbox statistics after insert and toggle.
545 When this is set, checkbox statistics is updated each time you either insert
546 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
547 with \\[org-ctrl-c-ctrl-c\\]."
548 :group 'org-plain-lists
549 :type 'boolean)
551 (defgroup org-archive nil
552 "Options concerning archiving in Org-mode."
553 :tag "Org Archive"
554 :group 'org-structure)
556 (defcustom org-archive-tag "ARCHIVE"
557 "The tag that marks a subtree as archived.
558 An archived subtree does not open during visibility cycling, and does
559 not contribute to the agenda listings."
560 :group 'org-archive
561 :group 'org-keywords
562 :type 'string)
564 (defcustom org-agenda-skip-archived-trees t
565 "Non-nil means, the agenda will skip any items located in archived trees.
566 An archived tree is a tree marked with the tag ARCHIVE."
567 :group 'org-archive
568 :group 'org-agenda-skip
569 :type 'boolean)
571 (defcustom org-cycle-open-archived-trees nil
572 "Non-nil means, `org-cycle' will open archived trees.
573 An archived tree is a tree marked with the tag ARCHIVE.
574 When nil, archived trees will stay folded. You can still open them with
575 normal outline commands like `show-all', but not with the cycling commands."
576 :group 'org-archive
577 :group 'org-cycle
578 :type 'boolean)
580 (defcustom org-sparse-tree-open-archived-trees nil
581 "Non-nil means sparse tree construction shows matches in archived trees.
582 When nil, matches in these trees are highlighted, but the trees are kept in
583 collapsed state."
584 :group 'org-archive
585 :group 'org-sparse-trees
586 :type 'boolean)
588 (defcustom org-archive-location "%s_archive::"
589 "The location where subtrees should be archived.
590 This string consists of two parts, separated by a double-colon.
592 The first part is a file name - when omitted, archiving happens in the same
593 file. %s will be replaced by the current file name (without directory part).
594 Archiving to a different file is useful to keep archived entries from
595 contributing to the Org-mode Agenda.
597 The part after the double colon is a headline. The archived entries will be
598 filed under that headline. When omitted, the subtrees are simply filed away
599 at the end of the file, as top-level entries.
601 Here are a few examples:
602 \"%s_archive::\"
603 If the current file is Projects.org, archive in file
604 Projects.org_archive, as top-level trees. This is the default.
606 \"::* Archived Tasks\"
607 Archive in the current file, under the top-level headline
608 \"* Archived Tasks\".
610 \"~/org/archive.org::\"
611 Archive in file ~/org/archive.org (absolute path), as top-level trees.
613 \"basement::** Finished Tasks\"
614 Archive in file ./basement (relative path), as level 3 trees
615 below the level 2 heading \"** Finished Tasks\".
617 You may set this option on a per-file basis by adding to the buffer a
618 line like
620 #+ARCHIVE: basement::** Finished Tasks"
621 :group 'org-archive
622 :type 'string)
624 (defcustom org-archive-mark-done t
625 "Non-nil means, mark entries as DONE when they are moved to the archive file."
626 :group 'org-archive
627 :type 'boolean)
629 (defcustom org-archive-stamp-time t
630 "Non-nil means, add a time stamp to entries moved to an archive file.
631 The time stamp will be added directly after the TODO state keyword in the
632 first line, so it is probably best to use this in combinations with
633 `org-archive-mark-done'."
634 :group 'org-archive
635 :type 'boolean)
637 (defgroup org-table nil
638 "Options concerning tables in Org-mode."
639 :tag "Org Table"
640 :group 'org)
642 (defcustom org-enable-table-editor 'optimized
643 "Non-nil means, lines starting with \"|\" are handled by the table editor.
644 When nil, such lines will be treated like ordinary lines.
646 When equal to the symbol `optimized', the table editor will be optimized to
647 do the following:
648 - Automatic overwrite mode in front of whitespace in table fields.
649 This makes the structure of the table stay in tact as long as the edited
650 field does not exceed the column width.
651 - Minimize the number of realigns. Normally, the table is aligned each time
652 TAB or RET are pressed to move to another field. With optimization this
653 happens only if changes to a field might have changed the column width.
654 Optimization requires replacing the functions `self-insert-command',
655 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
656 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
657 very good at guessing when a re-align will be necessary, but you can always
658 force one with \\[org-ctrl-c-ctrl-c].
660 If you would like to use the optimized version in Org-mode, but the
661 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
663 This variable can be used to turn on and off the table editor during a session,
664 but in order to toggle optimization, a restart is required.
666 See also the variable `org-table-auto-blank-field'."
667 :group 'org-table
668 :type '(choice
669 (const :tag "off" nil)
670 (const :tag "on" t)
671 (const :tag "on, optimized" optimized)))
673 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
674 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
675 In the optimized version, the table editor takes over all simple keys that
676 normally just insert a character. In tables, the characters are inserted
677 in a way to minimize disturbing the table structure (i.e. in overwrite mode
678 for empty fields). Outside tables, the correct binding of the keys is
679 restored.
681 The default for this option is t if the optimized version is also used in
682 Org-mode. See the variable `org-enable-table-editor' for details. Changing
683 this variable requires a restart of Emacs to become effective."
684 :group 'org-table
685 :type 'boolean)
687 (defgroup org-table-settings nil
688 "Settings for tables in Org-mode."
689 :tag "Org Table Settings"
690 :group 'org-table)
692 (defcustom org-table-default-size "5x2"
693 "The default size for newly created tables, Columns x Rows."
694 :group 'org-table-settings
695 :type 'string)
697 ;; FIXME: I am no longer sure if including HEX is a good idea.
698 (defcustom org-table-number-regexp
699 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)?[0-9a-fA-F]+\\)$"
700 "Regular expression for recognizing numbers in table columns.
701 If a table column contains mostly numbers, it will be aligned to the
702 right. If not, it will be aligned to the left.
704 The default value of this option is a regular expression which allows
705 anything which looks remotely like a number as used in scientific
706 context. For example, all of the following will be considered a
707 number:
708 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
710 Other options offered by the customize interface are more restrictive."
711 :group 'org-table-settings
712 :type '(choice
713 (const :tag "Positive Integers"
714 "^[0-9]+$")
715 (const :tag "Integers"
716 "^[-+]?[0-9]+$")
717 (const :tag "Floating Point Numbers"
718 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
719 (const :tag "Floating Point Number or Integer"
720 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
721 (const :tag "Exponential, Floating point, Integer"
722 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
723 (const :tag "Very General Number-Like, including hex"
724 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)?[0-9a-fA-F]+\\)$")
725 (string :tag "Regexp:")))
727 (defcustom org-table-number-fraction 0.5
728 "Fraction of numbers in a column required to make the column align right.
729 In a column all non-white fields are considered. If at least this
730 fraction of fields is matched by `org-table-number-fraction',
731 alignment to the right border applies."
732 :group 'org-table-settings
733 :type 'number)
735 (defgroup org-table-editing nil
736 "Bahavior of tables during editing in Org-mode."
737 :tag "Org Table Editing"
738 :group 'org-table)
740 (defcustom org-table-automatic-realign t
741 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
742 When nil, aligning is only done with \\[org-table-align], or after column
743 removal/insertion."
744 :group 'org-table-editing
745 :type 'boolean)
747 (defcustom org-table-limit-column-width t ;kw
748 "Non-nil means, allow to limit the width of table columns with <N> fields."
749 :group 'org-table-editing
750 :type 'boolean)
752 (defcustom org-table-auto-blank-field t
753 "Non-nil means, automatically blank table field when starting to type into it.
754 This only happens when typing immediately after a field motion
755 command (TAB, S-TAB or RET).
756 Only relevant when `org-enable-table-editor' is equal to `optimized'."
757 :group 'org-table-editing
758 :type 'boolean)
760 (defcustom org-table-tab-jumps-over-hlines t
761 "Non-nil means, tab in the last column of a table with jump over a hline.
762 If a horizontal separator line is following the current line,
763 `org-table-next-field' can either create a new row before that line, or jump
764 over the line. When this option is nil, a new line will be created before
765 this line."
766 :group 'org-table-editing
767 :type 'boolean)
769 (defcustom org-table-tab-recognizes-table.el t
770 "Non-nil means, TAB will automatically notice a table.el table.
771 When it sees such a table, it moves point into it and - if necessary -
772 calls `table-recognize-table'."
773 :group 'org-table-editing
774 :type 'boolean)
776 (defgroup org-table-calculation nil
777 "Options concerning tables in Org-mode."
778 :tag "Org Table Calculation"
779 :group 'org-table)
781 (defcustom org-table-copy-increment t
782 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
783 :group 'org-table-calculation
784 :type 'boolean)
786 (defcustom org-calc-default-modes
787 '(calc-internal-prec 12
788 calc-float-format (float 5)
789 calc-angle-mode deg
790 calc-prefer-frac nil
791 calc-symbolic-mode nil
792 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
793 calc-display-working-message t
795 "List with Calc mode settings for use in calc-eval for table formulas.
796 The list must contain alternating symbols (Calc modes variables and values).
797 Don't remove any of the default settings, just change the values. Org-mode
798 relies on the variables to be present in the list."
799 :group 'org-table-calculation
800 :type 'plist)
802 (defcustom org-table-formula-evaluate-inline t
803 "Non-nil means, TAB and RET evaluate a formula in current table field.
804 If the current field starts with an equal sign, it is assumed to be a formula
805 which should be evaluated as described in the manual and in the documentation
806 string of the command `org-table-eval-formula'. This feature requires the
807 Emacs calc package.
808 When this variable is nil, formula calculation is only available through
809 the command \\[org-table-eval-formula]."
810 :group 'org-table-calculation
811 :type 'boolean)
814 (defcustom org-table-formula-use-constants t
815 "Non-nil means, interpret constants in formulas in tables.
816 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
817 by the value given in `org-table-formula-constants', or by a value obtained
818 from the `constants.el' package."
819 :group 'org-table-calculation
820 :type 'boolean)
822 (defcustom org-table-formula-constants nil
823 "Alist with constant names and values, for use in table formulas.
824 The car of each element is a name of a constant, without the `$' before it.
825 The cdr is the value as a string. For example, if you'd like to use the
826 speed of light in a formula, you would configure
828 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
830 and then use it in an equation like `$1*$c'."
831 :group 'org-table-calculation
832 :type '(repeat
833 (cons (string :tag "name")
834 (string :tag "value"))))
836 (defcustom org-table-formula-numbers-only nil
837 "Non-nil means, calculate only with numbers in table formulas.
838 Then all input fields will be converted to a number, and the result
839 must also be a number. When nil, calc's full potential is available
840 in table calculations, including symbolics etc."
841 :group 'org-table-calculation
842 :type 'boolean)
844 (defcustom org-table-allow-automatic-line-recalculation t
845 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
846 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
847 :group 'org-table-calculation
848 :type 'boolean)
850 (defgroup org-link nil
851 "Options concerning links in Org-mode."
852 :tag "Org Link"
853 :group 'org)
855 (defvar org-link-abbrev-alist-local nil
856 "buffer-local version of `org-link-abbrev-alist', which see.
857 The value of this is taken from the #+LINK lines.")
858 (make-variable-buffer-local 'org-link-abbrev-alist-local)
860 (defcustom org-link-abbrev-alist nil
861 "Alist of link abbreviations.
862 The car of each element is a string, to be replaced at the start of a link.
863 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
864 links in Org-mode buffers can have an optional tag after a double colon, e.g.
866 [[linkkey::tag][description]]
868 If REPLACE is a string, the tag will simply be appended to create the link.
869 If the string contains \"%s\", the tag will be inserted there. REPLACE may
870 also be a function that will be called with the tag as the only argument to
871 create the link. See the manual for examples."
872 :group 'org-link
873 :type 'alist)
875 (defcustom org-descriptive-links t
876 "Non-nil means, hide link part and only show description of bracket links.
877 Bracket links are like [[link][descritpion]]. This variable sets the initial
878 state in new org-mode buffers. The setting can then be toggled on a
879 per-buffer basis from the Org->Hyperlinks menu."
880 :group 'org-link
881 :type 'boolean)
883 (defcustom org-link-style 'bracket
884 "The style of links to be inserted with \\[org-insert-link].
885 Possible values are:
886 bracket [[link][description]]. This is recommended
887 plain Description \\n link. The old way, no longer recommended."
888 :group 'org-link
889 :type '(choice
890 (const :tag "Bracket (recommended)" bracket)
891 (const :tag "Plain (no longer recommended)" plain)))
893 (defcustom org-link-format "%s"
894 "Default format for external, URL-like linkes in the buffer.
895 This is a format string for printf, %s will be replaced by the link text.
896 The recommended value is just \"%s\", since links will be protected by
897 enclosing them in double brackets. If you prefer plain links (see variable
898 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
899 additional URL: prefix, so the format would be \"<URL:%s>\"."
900 :group 'org-link
901 :type '(choice
902 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
903 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
904 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
905 (string :tag "Other" :value "<%s>")))
907 (defcustom org-link-file-path-type 'adaptive
908 "How the path name in file links should be stored.
909 Valid values are:
911 relative relative to the current directory, i.e. the directory of the file
912 into which the link is being inserted.
913 absolute absolute path, if possible with ~ for home directory.
914 noabbrev absolute path, no abbreviation of home directory.
915 adaptive Use relative path for files in the current directory and sub-
916 directories of it. For other files, use an absolute path."
917 :group 'org-link
918 :type '(choice
919 (const relative)
920 (const absolute)
921 (const noabbrev)
922 (const adaptive)))
924 (defcustom org-activate-links '(bracket angle plain radio tag date)
925 "Types of links that should be activated in Org-mode files.
926 This is a list of symbols, each leading to the activation of a certain link
927 type. In principle, it does not hurt to turn on most link types - there may
928 be a small gain when turning off unused link types. The types are:
930 bracket The recommended [[link][description]] or [[link]] links with hiding.
931 angular Links in angular brackes that may contain whitespace like
932 <bbdb:Carsten Dominik>.
933 plain Plain links in normal text, no whitespace, like http://google.com.
934 radio Text that is matched by a radio target, see manual for details.
935 tag Tag settings in a headline (link to tag search).
936 date Time stamps (link to calendar).
937 camel CamelCase words defining text searches.
939 Changing this variable requires a restart of Emacs to become effective."
940 :group 'org-link
941 :type '(set (const :tag "Double bracket links (new style)" bracket)
942 (const :tag "Angular bracket links (old style)" angular)
943 (const :tag "plain text links" plain)
944 (const :tag "Radio target matches" radio)
945 (const :tag "Tags" tag)
946 (const :tag "Timestamps" date)
947 (const :tag "CamelCase words" camel)))
949 (defgroup org-link-store nil
950 "Options concerning storing links in Org-mode"
951 :tag "Org Store Link"
952 :group 'org-link)
954 (defcustom org-context-in-file-links t
955 "Non-nil means, file links from `org-store-link' contain context.
956 A search string will be added to the file name with :: as separator and
957 used to find the context when the link is activated by the command
958 `org-open-at-point'.
959 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
960 negates this setting for the duration of the command."
961 :group 'org-link-store
962 :type 'boolean)
964 (defcustom org-file-link-context-use-camel-case nil
965 "Non-nil means, use CamelCase to store a search context in a file link.
966 When nil, the search string simply consists of the words of the string.
967 CamelCase is deprecated, and support for it may be dropped in the future."
968 :group 'org-link-store
969 :type 'boolean)
971 (defcustom org-keep-stored-link-after-insertion nil
972 "Non-nil means, keep link in list for entire session.
974 The command `org-store-link' adds a link pointing to the current
975 location to an internal list. These links accumulate during a session.
976 The command `org-insert-link' can be used to insert links into any
977 Org-mode file (offering completion for all stored links). When this
978 option is nil, every link which has been inserted once using \\[org-insert-link]
979 will be removed from the list, to make completing the unused links
980 more efficient."
981 :group 'org-link-store
982 :type 'boolean)
984 (defcustom org-usenet-links-prefer-google nil
985 "Non-nil means, `org-store-link' will create web links to Google groups.
986 When nil, Gnus will be used for such links.
987 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
988 negates this setting for the duration of the command."
989 :group 'org-link-store
990 :type 'boolean)
992 (defgroup org-link-follow nil
993 "Options concerning following links in Org-mode"
994 :tag "Org Follow Link"
995 :group 'org-link)
997 (defcustom org-tab-follows-link nil
998 "Non-nil means, on links TAB will follow the link.
999 Needs to be set before org.el is loaded."
1000 :group 'org-link-follow
1001 :type 'boolean)
1003 (defcustom org-return-follows-link nil
1004 "Non-nil means, on links RET will follow the link.
1005 Needs to be set before org.el is loaded."
1006 :group 'org-link-follow
1007 :type 'boolean)
1009 (defcustom org-mouse-1-follows-link t
1010 "Non-nil means, mouse-1 on a link will follow the link.
1011 A longer mouse click will still set point. Does not wortk on XEmacs.
1012 Needs to be set before org.el is loaded."
1013 :group 'org-link-follow
1014 :type 'boolean)
1016 (defcustom org-mark-ring-length 4
1017 "Number of different positions to be recorded in the ring
1018 Changing this requires a restart of Emacs to work correctly."
1019 :group 'org-link-follow
1020 :type 'interger)
1022 (defcustom org-link-frame-setup
1023 '((vm . vm-visit-folder-other-frame)
1024 (gnus . gnus-other-frame)
1025 (file . find-file-other-window))
1026 "Setup the frame configuration for following links.
1027 When following a link with Emacs, it may often be useful to display
1028 this link in another window or frame. This variable can be used to
1029 set this up for the different types of links.
1030 For VM, use any of
1031 `vm-visit-folder'
1032 `vm-visit-folder-other-frame'
1033 For Gnus, use any of
1034 `gnus'
1035 `gnus-other-frame'
1036 For FILE, use any of
1037 `find-file'
1038 `find-file-other-window'
1039 `find-file-other-frame'
1040 For the calendar, use the variable `calendar-setup'.
1041 For BBDB, it is currently only possible to display the matches in
1042 another window."
1043 :group 'org-link-follow
1044 :type '(list
1045 (cons (const vm)
1046 (choice
1047 (const vm-visit-folder)
1048 (const vm-visit-folder-other-window)
1049 (const vm-visit-folder-other-frame)))
1050 (cons (const gnus)
1051 (choice
1052 (const gnus)
1053 (const gnus-other-frame)))
1054 (cons (const file)
1055 (choice
1056 (const find-file)
1057 (const find-file-other-window)
1058 (const find-file-other-frame)))))
1060 (defcustom org-display-internal-link-with-indirect-buffer nil
1061 "Non-nil means, use indirect buffer to display infile links.
1062 Activating internal links (from one location in a file to another location
1063 in the same file) normally just jumps to the location. When the link is
1064 activated with a C-u prefix (or with mouse-3), the link is displayed in
1065 another window. When this option is set, the other window actually displays
1066 an indirect buffer clone of the current buffer, to avoid any visibility
1067 changes to the current buffer."
1068 :group 'org-link-follow
1069 :type 'boolean)
1072 (defcustom org-open-non-existing-files nil
1073 "Non-nil means, `org-open-file' will open non-existing file.
1074 When nil, an error will be generated."
1075 :group 'org-link-follow
1076 :type 'boolean)
1078 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1079 "Function and arguments to call for following mailto links.
1080 This is a list with the first element being a lisp function, and the
1081 remaining elements being arguments to the function. In string arguments,
1082 %a will be replaced by the address, and %s will be replaced by the subject
1083 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1084 :group 'org-link-follow
1085 :type '(choice
1086 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1087 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1088 (const :tag "message-mail" (message-mail "%a" "%s"))
1089 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1091 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1092 "Non-nil means, ask for confirmation before executing shell links.
1093 Shell links can be dangerous, just thing about a link
1095 [[shell:rm -rf ~/*][Google Search]]
1097 This link would show up in your Org-mode document as \"Google Search\"
1098 but really it would remove your entire home directory.
1099 Therefore I *definitely* advise against setting this variable to nil.
1100 Just change it to `y-or-n-p' of you want to confirm with a single key press
1101 rather than having to type \"yes\"."
1102 :group 'org-link-follow
1103 :type '(choice
1104 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1105 (const :tag "with y-or-n (faster)" y-or-n-p)
1106 (const :tag "no confirmation (dangerous)" nil)))
1108 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1109 "Non-nil means, ask for confirmation before executing elisp links.
1110 Elisp links can be dangerous, just think about a link
1112 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1114 This link would show up in your Org-mode document as \"Google Search\"
1115 but really it would remove your entire home directory.
1116 Therefore I *definitely* advise against setting this variable to nil.
1117 Just change it to `y-or-n-p' of you want to confirm with a single key press
1118 rather than having to type \"yes\"."
1119 :group 'org-link-follow
1120 :type '(choice
1121 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1122 (const :tag "with y-or-n (faster)" y-or-n-p)
1123 (const :tag "no confirmation (dangerous)" nil)))
1125 (defconst org-file-apps-defaults-gnu
1126 '((remote . emacs)
1127 (t . mailcap))
1128 "Default file applications on a UNIX or GNU/Linux system.
1129 See `org-file-apps'.")
1131 (defconst org-file-apps-defaults-macosx
1132 '((remote . emacs)
1133 (t . "open %s")
1134 ("ps" . "gv %s")
1135 ("ps.gz" . "gv %s")
1136 ("eps" . "gv %s")
1137 ("eps.gz" . "gv %s")
1138 ("dvi" . "xdvi %s")
1139 ("fig" . "xfig %s"))
1140 "Default file applications on a MacOS X system.
1141 The system \"open\" is known as a default, but we use X11 applications
1142 for some files for which the OS does not have a good default.
1143 See `org-file-apps'.")
1145 (defconst org-file-apps-defaults-windowsnt
1146 (list
1147 '(remote . emacs)
1148 (cons t
1149 (list (if (featurep 'xemacs)
1150 'mswindows-shell-execute
1151 'w32-shell-execute)
1152 "open" 'file)))
1153 "Default file applications on a Windows NT system.
1154 The system \"open\" is used for most files.
1155 See `org-file-apps'.")
1157 (defcustom org-file-apps
1159 ("txt" . emacs)
1160 ("tex" . emacs)
1161 ("ltx" . emacs)
1162 ("org" . emacs)
1163 ("el" . emacs)
1164 ("bib" . emacs)
1166 "External applications for opening `file:path' items in a document.
1167 Org-mode uses system defaults for different file types, but
1168 you can use this variable to set the application for a given file
1169 extension. The entries in this list are cons cells where the car identifies
1170 files and the cdr the corresponding command. Possible values for the
1171 file identifier are
1172 \"ext\" A string identifying an extension
1173 `directory' Matches a directory
1174 `remote' Matches a remote file, accessible through tramp or efs.
1175 Remote files most likely should be visited through Emacs
1176 because external applications cannot handle such paths.
1177 t Default for all remaining files
1179 Possible values for the command are:
1180 `emacs' The file will be visited by the current Emacs process.
1181 `default' Use the default application for this file type.
1182 string A command to be executed by a shell; %s will be replaced
1183 by the path to the file.
1184 sexp A Lisp form which will be evaluated. The file path will
1185 be available in the Lisp variable `file'.
1186 For more examples, see the system specific constants
1187 `org-file-apps-defaults-macosx'
1188 `org-file-apps-defaults-windowsnt'
1189 `org-file-apps-defaults-gnu'."
1190 :group 'org-link-follow
1191 :type '(repeat
1192 (cons (choice :value ""
1193 (string :tag "Extension")
1194 (const :tag "Default for unrecognized files" t)
1195 (const :tag "Remote file" remote)
1196 (const :tag "Links to a directory" directory))
1197 (choice :value ""
1198 (const :tag "Visit with Emacs" emacs)
1199 (const :tag "Use system default" default)
1200 (string :tag "Command")
1201 (sexp :tag "Lisp form")))))
1203 (defcustom org-mhe-search-all-folders nil
1204 "Non-nil means, that the search for the mh-message will be extended to
1205 all folders if the message cannot be found in the folder given in the link.
1206 Searching all folders is very effective with one of the search engines
1207 supported by MH-E, but will be slow with pick."
1208 :group 'org-link-follow
1209 :type 'boolean)
1211 (defgroup org-remember nil
1212 "Options concerning interaction with remember.el."
1213 :tag "Org Remember"
1214 :group 'org)
1216 (defcustom org-directory "~/org"
1217 "Directory with org files.
1218 This directory will be used as default to prompt for org files.
1219 Used by the hooks for remember.el."
1220 :group 'org-remember
1221 :type 'directory)
1223 (defcustom org-default-notes-file "~/.notes"
1224 "Default target for storing notes.
1225 Used by the hooks for remember.el. This can be a string, or nil to mean
1226 the value of `remember-data-file'."
1227 :group 'org-remember
1228 :type '(choice
1229 (const :tag "Default from remember-data-file" nil)
1230 file))
1232 (defcustom org-remember-templates nil
1233 "Templates for the creation of remember buffers.
1234 When nil, just let remember make the buffer.
1235 When not nil, this is a list of 3-element lists. In each entry, the first
1236 element is a character, a unique key to select this template.
1237 The second element is the template. The third element is optional and can
1238 specify a destination file for remember items created with this template.
1239 The default file is given by `org-default-notes-file'.
1241 The template specifies the structure of the remember buffer. It should have
1242 a first line starting with a star, to act as the org-mode headline.
1243 Furthermore, the following %-escapes will be replaced with content:
1244 %t time stamp, date only
1245 %T time stamp with date and time
1246 %u inactive time stamp, date only
1247 %U inactive time stamp with date and time
1248 %n user name
1249 %a annotation, normally the link created with org-store-link
1250 %i initial content, the region when remember is called with C-u.
1251 If %i is indented, the entire inserted text will be indented as well.
1252 %? This will be removed, and the cursor placed at this position."
1253 :group 'org-remember
1254 :type '(repeat :tag "enabled"
1255 (list :value (?a "\n" nil)
1256 (character :tag "Selection Key")
1257 (string :tag "Template")
1258 (file :tag "Destination file (optional)"))))
1260 (defcustom org-reverse-note-order nil
1261 "Non-nil means, store new notes at the beginning of a file or entry.
1262 When nil, new notes will be filed to the end of a file or entry."
1263 :group 'org-remember
1264 :type '(choice
1265 (const :tag "Reverse always" t)
1266 (const :tag "Reverse never" nil)
1267 (repeat :tag "By file name regexp"
1268 (cons regexp boolean))))
1270 (defgroup org-todo nil
1271 "Options concerning TODO items in Org-mode."
1272 :tag "Org TODO"
1273 :group 'org)
1275 (defcustom org-todo-keywords '("TODO" "DONE")
1276 "List of TODO entry keywords.
1277 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1278 considered to mean that the entry is \"done\". All the other mean that
1279 action is required, and will make the entry show up in todo lists, diaries
1280 etc.
1281 The command \\[org-todo] cycles an entry through these states, and an
1282 additional state where no keyword is present. For details about this
1283 cycling, see also the variable `org-todo-interpretation'
1284 Changes become only effective after restarting Emacs."
1285 :group 'org-todo
1286 :group 'org-keywords
1287 :type '(repeat (string :tag "Keyword")))
1289 (defcustom org-todo-interpretation 'sequence
1290 "Controls how TODO keywords are interpreted.
1291 This variable is only relevant if `org-todo-keywords' contains more than two
1292 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1294 When `sequence', \\[org-todo] will always switch to the next state in the
1295 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1296 to state when executed several times in direct succession. Otherwise, it
1297 switches directly to DONE from any state.
1298 See the manual for more information."
1299 :group 'org-todo
1300 :group 'org-keywords
1301 :type '(choice (const sequence)
1302 (const type)))
1304 (defcustom org-after-todo-state-change-hook nil
1305 "Hook which is run after the state of a TODO item was changed.
1306 The new state (a string with a TODO keyword, or nil) is available in the
1307 Lisp variable `state'."
1308 :group 'org-todo
1309 :type 'hook)
1311 (defcustom org-log-done nil
1312 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1313 When the state of an entry is changed from nothing to TODO, remove a previous
1314 closing date.
1316 This can also be a list of symbols indicating under which conditions
1317 the time stamp recording the action should be annotated with a short note.
1318 Valid members of this list are
1320 done Offer to record a note when marking entries done
1321 clock-out Offer to record a note when clocking out of an item.
1323 A separate window will then pop up and allow you to type a note.
1324 After finishing with C-c C-c, the note will be added directly after the
1325 timestamp, as a plain list item. See also the variable
1326 `org-log-note-headings'.
1328 Logging can also be configured on a per-file basis by adding one of
1329 the following lines anywhere in the buffer:
1331 #+STARTUP: logging
1332 #+STARTUP: nologging"
1333 ;; FIXME: in-buffer words for notes???????
1334 :group 'org-todo
1335 :type '(choice
1336 (const :tag "off" nil)
1337 (const :tag "on" t)
1338 (set :tag "on, with notes" :greedy t :value (done)
1339 (const done) (const clock-out))))
1341 (defcustom org-log-note-headings '((done . "CLOSING NOTE %t") (clock-out . ""))
1342 "Headings for notes added when clocking out or closing TODO items.
1343 The value is an alist, with the car being a sympol indicating the note
1344 context, and the cdr is the heading to be used. The heading may also be the
1345 empty string.
1346 %t in the heading will be replaced by a time stamp
1347 %u will be replaced by the user name
1348 %U will be replaced by the full user name."
1349 :group 'org-todo
1350 :type '(list :greedy t
1351 (cons (const :tag "Heading when closing an item" done) string)
1352 (cons (const :tag "Heading when clocking out" clock-out) string)))
1354 (defgroup org-priorities nil
1355 "Priorities in Org-mode."
1356 :tag "Org Priorities"
1357 :group 'org-todo)
1359 (defcustom org-default-priority ?B
1360 "The default priority of TODO items.
1361 This is the priority an item get if no explicit priority is given."
1362 :group 'org-priorities
1363 :type 'character)
1365 (defcustom org-lowest-priority ?C
1366 "The lowest priority of TODO items. A character like ?A, ?B etc."
1367 :group 'org-priorities
1368 :type 'character)
1370 (defgroup org-time nil
1371 "Options concerning time stamps and deadlines in Org-mode."
1372 :tag "Org Time"
1373 :group 'org)
1375 (defcustom org-insert-labeled-timestamps-at-point nil
1376 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1377 When nil, these labeled time stamps are forces into the second line of an
1378 entry, just after the headline. When scheduling from the global TODO list,
1379 the time stamp will always be forced into the second line."
1380 :group 'org-time
1381 :type 'boolean)
1383 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1384 "Formats for `format-time-string' which are used for time stamps.
1385 It is not recommended to change this constant.")
1387 (defcustom org-time-stamp-rounding-minutes 0
1388 "Number of minutes to round time stamps to upon insertion.
1389 When zero, insert the time unmodified. Useful rounding numbers
1390 should be factors of 60, so for example 5, 10, 15.
1391 When this is not zero, you can still force an exact time-stamp by using
1392 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1393 :group 'org-time
1394 :type 'integer)
1396 (defcustom org-display-custom-times nil
1397 "Non-nil means, overlay custom formats over all time stamps.
1398 The formats are defined through the variable `org-time-stamp-custom-formats'.
1399 To turn this on on a per-file basis, insert anywhere in the file:
1400 #+STARTUP: customtime"
1401 :group 'org-time
1402 :set 'set-default
1403 :type 'sexp)
1404 (make-variable-buffer-local 'org-display-custom-times)
1406 (defcustom org-time-stamp-custom-formats
1407 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1408 "Custom formats for time stamps. See `format-time-string' for the syntax.
1409 These are overlayed over the default ISO format if the variable
1410 `org-display-custom-times' is set."
1411 :group 'org-time
1412 :type 'sexp)
1414 (defun org-time-stamp-format (&optional long inactive)
1415 "Get the right format for a time string."
1416 (let ((f (if long (cdr org-time-stamp-formats)
1417 (car org-time-stamp-formats))))
1418 (if inactive
1419 (concat "[" (substring f 1 -1) "]")
1420 f)))
1422 (defcustom org-deadline-warning-days 30
1423 "No. of days before expiration during which a deadline becomes active.
1424 This variable governs the display in sparse trees and in the agenda."
1425 :group 'org-time
1426 :type 'number)
1428 (defcustom org-popup-calendar-for-date-prompt t
1429 "Non-nil means, pop up a calendar when prompting for a date.
1430 In the calendar, the date can be selected with mouse-1. However, the
1431 minibuffer will also be active, and you can simply enter the date as well.
1432 When nil, only the minibuffer will be available."
1433 :group 'org-time
1434 :type 'boolean)
1436 (defcustom org-calendar-follow-timestamp-change t
1437 "Non-nil means, make the calendar window follow timestamp changes.
1438 When a timestamp is modified and the calendar window is visible, it will be
1439 moved to the new date."
1440 :group 'org-time
1441 :type 'boolean)
1443 (defgroup org-tags nil
1444 "Options concerning tags in Org-mode."
1445 :tag "Org Tags"
1446 :group 'org)
1448 (defcustom org-tag-alist nil
1449 "List of tags allowed in Org-mode files.
1450 When this list is nil, Org-mode will base TAG input on what is already in the
1451 buffer.
1452 The value of this variable is an alist, the car may be (and should) be a
1453 character that is used to select that tag through the fast-tag-selection
1454 interface. See the manual for details."
1455 :group 'org-tags
1456 :type '(repeat
1457 (choice
1458 (cons (string :tag "Tag name")
1459 (character :tag "Access char"))
1460 (const :tag "Start radio group" (:startgroup))
1461 (const :tag "End radio group" (:endgroup)))))
1463 (defcustom org-use-fast-tag-selection 'auto
1464 "Non-nil means, use fast tag selection scheme.
1465 This is a special interface to select and deselect tags with single keys.
1466 When nil, fast selection is never used.
1467 When the symbol `auto', fast selection is used if and only if selection
1468 characters for tags have been configured, either through the variable
1469 `org-tag-alist' or through a #+TAGS line in the buffer.
1470 When t, fast selection is always used and selection keys are assigned
1471 automatically if necessary."
1472 :group 'org-tags
1473 :type '(choice
1474 (const :tag "Always" t)
1475 (const :tag "Never" nil)
1476 (const :tag "When selection characters are configured" 'auto)))
1478 (defcustom org-fast-tag-selection-single-key nil
1479 "Non-nil means, fast tag selection exits after first change.
1480 When nil, you have to press RET to exit it.
1481 During fast tag selection, you can toggle this flag with `C-c'."
1482 :group 'org-tags
1483 :type 'boolean)
1485 (defcustom org-tags-column 48
1486 "The column to which tags should be indented in a headline.
1487 If this number is positive, it specifies the column. If it is negative,
1488 it means that the tags should be flushright to that column. For example,
1489 -79 works well for a normal 80 character screen."
1490 :group 'org-tags
1491 :type 'integer)
1493 (defcustom org-auto-align-tags t
1494 "Non-nil means, realign tags after pro/demotion of TODO state change.
1495 These operations change the length of a headline and therefore shift
1496 the tags around. With this options turned on, after each such operation
1497 the tags are again aligned to `org-tags-column'."
1498 :group 'org-tags
1499 :type 'boolean)
1501 (defcustom org-use-tag-inheritance t
1502 "Non-nil means, tags in levels apply also for sublevels.
1503 When nil, only the tags directly given in a specific line apply there.
1504 If you turn off this option, you very likely want to turn on the
1505 companion option `org-tags-match-list-sublevels'."
1506 :group 'org-tags
1507 :type 'boolean)
1509 (defcustom org-tags-match-list-sublevels nil
1510 "Non-nil means list also sublevels of headlines matching tag search.
1511 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1512 the sublevels of a headline matching a tag search often also match
1513 the same search. Listing all of them can create very long lists.
1514 Setting this variable to nil causes subtrees of a match to be skipped.
1515 This option is off by default, because inheritance in on. If you turn
1516 inheritance off, you very likely want to turn this option on.
1518 As a special case, if the tag search is restricted to TODO items, the
1519 value of this variable is ignored and sublevels are always checked, to
1520 make sure all corresponding TODO items find their way into the list."
1521 :group 'org-tags
1522 :type 'boolean)
1524 (defvar org-tags-history nil
1525 "History of minibuffer reads for tags.")
1526 (defvar org-last-tags-completion-table nil
1527 "The last used completion table for tags.")
1529 (defgroup org-agenda nil
1530 "Options concerning agenda views in Org-mode."
1531 :tag "Org Agenda"
1532 :group 'org)
1534 (defvar org-category nil
1535 "Variable used by org files to set a category for agenda display.
1536 Such files should use a file variable to set it, for example
1538 -*- mode: org; org-category: \"ELisp\"
1540 or contain a special line
1542 #+CATEGORY: ELisp
1544 If the file does not specify a category, then file's base name
1545 is used instead.")
1546 (make-variable-buffer-local 'org-category)
1548 (defcustom org-agenda-files nil
1549 "The files to be used for agenda display.
1550 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1551 \\[org-remove-file]. You can also use customize to edit the list.
1553 If the value of the variable is not a list but a single file name, then
1554 the list of agenda files is actually stored and maintained in that file, one
1555 agenda file per line."
1556 :group 'org-agenda
1557 :type '(choice
1558 (repeat :tag "List of files" file)
1559 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1562 (defcustom org-agenda-confirm-kill 1
1563 "When set, remote killing from the agenda buffer needs confirmation.
1564 When t, a confirmation is always needed. When a number N, confirmation is
1565 only needed when the text to be killed contains more than N non-white lines."
1566 :group 'org-agenda
1567 :type '(choice
1568 (const :tag "Never" nil)
1569 (const :tag "Always" t)
1570 (number :tag "When more than N lines")))
1572 (defcustom org-calendar-to-agenda-key [?c]
1573 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1574 The command `org-calendar-goto-agenda' will be bound to this key. The
1575 default is the character `c' because then `c' can be used to switch back and
1576 forth between agenda and calendar."
1577 :group 'org-agenda
1578 :type 'sexp)
1580 (defgroup org-agenda-custom-commands nil
1581 "Options concerning agenda views in Org-mode."
1582 :tag "Org Agenda Custom Commands"
1583 :group 'org-agenda)
1585 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1586 "Custom commands for the agenda.
1587 These commands will be offered on the splash screen displayed by the
1588 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1590 (key type match options)
1592 key The key (a single char as a string) to be associated with the command.
1593 type The command type, any of the following symbols:
1594 todo Entries with a specific TODO keyword, in all agenda files.
1595 tags Tags match in all agenda files.
1596 tags-todo Tags match in all agenda files, TODO entries only.
1597 todo-tree Sparse tree of specific TODO keyword in *current* file.
1598 tags-tree Sparse tree with all tags matches in *current* file.
1599 occur-tree Occur sparse tree for *current* file.
1600 match What to search for:
1601 - a single keyword for TODO keyword searches
1602 - a tags match expression for tags searches
1603 - a regular expression for occur searches
1604 options A list of option setttings, similar to that in a let form, so like
1605 this: ((opt1 val1) (opt2 val2) ...)
1607 You can also define a set of commands, to create a composite agenda buffer.
1608 In this case, an entry looks like this:
1610 (key desc (cmd1 cmd2 ...) general-options)
1612 where
1614 desc A description string to be displayed in the dispatcher menu.
1615 cmd An agenda command, similar to the above. However, tree commands
1616 are no allowed, but instead you can get agenda and global todo list.
1617 So valid commands for a set are:
1618 (agenda)
1619 (alltodo)
1620 (todo \"match\" options)
1621 (tags \"match\" options )
1622 (tags-todo \"match\" options)
1624 Each command can carry a list of options, and another set of options can be
1625 given for the whole set of commands. Individual command options take
1626 precedence over the general options."
1627 :group 'org-agenda-custom-commands
1628 :type '(repeat
1629 (choice
1630 (list :tag "Single command"
1631 (string :tag "Key")
1632 (choice
1633 (const :tag "Tags search (all agenda files)" tags)
1634 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1635 (const :tag "TODO keyword search (all agenda files)" todo)
1636 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1637 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1638 (const :tag "Occur tree (current buffer)" occur-tree)
1639 (symbol :tag "Other, user-defined function"))
1640 (string :tag "Match")
1641 (repeat :tag "Local options"
1642 (list (variable :tag "Option") (sexp :tag "Value"))))
1643 (list :tag "Command series, all agenda files"
1644 (string :tag "Key")
1645 (string :tag "Description")
1646 (repeat
1647 (choice
1648 (const :tag "Agenda" (agenda))
1649 (const :tag "TODO list" (alltodo))
1650 (list :tag "Tags search"
1651 (const :format "" tags)
1652 (string :tag "Match")
1653 (repeat :tag "Local options"
1654 (list (variable :tag "Option")
1655 (sexp :tag "Value"))))
1657 (list :tag "Tags search, TODO entries only"
1658 (const :format "" tags-todo)
1659 (string :tag "Match")
1660 (repeat :tag "Local options"
1661 (list (variable :tag "Option")
1662 (sexp :tag "Value"))))
1664 (list :tag "TODO keyword search"
1665 (const :format "" todo)
1666 (string :tag "Match")
1667 (repeat :tag "Local options"
1668 (list (variable :tag "Option")
1669 (sexp :tag "Value"))))
1671 (list :tag "Other, user-defined function" ; FIXME: untested
1672 (symbol :tag "function")
1673 (string :tag "Match")
1674 (repeat :tag "Local options"
1675 (list (variable :tag "Option")
1676 (sexp :tag "Value"))))))
1678 (repeat :tag "General options"
1679 (list (variable :tag "Option")
1680 (sexp :tag "Value")))))))
1682 (defcustom org-stuck-projects
1683 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil)
1684 "How to identify stuck projects.
1685 This is a list of three items:
1686 1. A tags/todo matcher string that is used to identify a project.
1687 The entire tree below a headline matched by this is considered a project.
1688 2. A list of TODO keywords itentifying non-stuck projects.
1689 If the project subtree contains any headline with one of these todo
1690 keywords, the project is consitered to be not stuck.
1691 3. A list of tags identifying non-stuck projects.
1692 If the project subtree contains any headline with one of these tags,
1693 the project is consitered to be not stuck.
1695 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
1696 or `C-c a #' to produce the list."
1697 :group 'org-agenda-custom-commands
1698 :type '(list
1699 (string :tag "Tags/TODO match to identify a project")
1700 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
1701 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))))
1704 (defgroup org-agenda-skip nil
1705 "Options concerning skipping parts of agenda files."
1706 :tag "Org Agenda Skip"
1707 :group 'org-agenda)
1709 (defcustom org-agenda-todo-list-sublevels t
1710 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1711 When nil, the sublevels of a TODO entry are not checked, resulting in
1712 potentially much shorter TODO lists."
1713 :group 'org-agenda-skip
1714 :group 'org-todo
1715 :type 'boolean)
1717 (defcustom org-agenda-todo-ignore-scheduled nil
1718 "Non-nil means, don't show scheduled entries in the global todo list.
1719 The idea behind this is that by scheduling it, you have already taken care
1720 of this item."
1721 :group 'org-agenda-skip
1722 :group 'org-todo
1723 :type 'boolean)
1725 (defcustom org-agenda-todo-ignore-deadlines nil
1726 "Non-nil means, don't show near deadline entries in the global todo list.
1727 Near means closer than `org-deadline-warning-days' days.
1728 The idea behind this is that such items will appear in the agenda anyway."
1729 :group 'org-agenda-skip
1730 :group 'org-todo
1731 :type 'boolean)
1733 (defcustom org-agenda-skip-scheduled-if-done nil
1734 "Non-nil means don't show scheduled items in agenda when they are done.
1735 This is relevant for the daily/weekly agenda, not for the TODO list."
1736 :group 'org-agenda-skip
1737 :type 'boolean)
1739 (defcustom org-timeline-show-empty-dates 3
1740 "Non-nil means, `org-timeline' also shows dates without an entry.
1741 When nil, only the days which actually have entries are shown.
1742 When t, all days between the first and the last date are shown.
1743 When an integer, show also empty dates, but if there is a gap of more than
1744 N days, just insert a special line indicating the size of the gap."
1745 :group 'org-agenda-skip ; FIXME: not quite the right group...
1746 :type '(choice
1747 (const :tag "None" nil)
1748 (const :tag "All" t)
1749 (number :tag "at most")))
1752 (defgroup org-agenda-startup nil
1753 "Options concerning initial settings in the Agenda in Org Mode."
1754 :tag "Org Agenda Startup"
1755 :group 'org-agenda)
1757 (defcustom org-finalize-agenda-hook nil
1758 "Hook run just before displaying an agenda buffer."
1759 :group 'org-agenda-startup
1760 :type 'hook)
1762 (defcustom org-agenda-mouse-1-follows-link nil
1763 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1764 A longer mouse click will still set point. Does not wortk on XEmacs.
1765 Needs to be set before org.el is loaded."
1766 :group 'org-agenda-startup
1767 :type 'boolean)
1769 (defcustom org-agenda-start-with-follow-mode nil
1770 "The initial value of follwo-mode in a newly created agenda window."
1771 :group 'org-agenda-startup
1772 :type 'boolean)
1774 (defgroup org-agenda-windows nil
1775 "Options concerning the windows used by the Agenda in Org Mode."
1776 :tag "Org Agenda Windows"
1777 :group 'org-agenda)
1779 (defcustom org-agenda-window-setup 'reorganize-frame
1780 "How the agenda buffer should be displayed.
1781 Possible values for this option are:
1783 current-window Show agenda in the current window, keeping all other windows.
1784 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1785 other-window Use `switch-to-buffer-other-window' to display agenda.
1786 reorganize-frame Show only two windows on the current frame, the current
1787 window and the agenda. Also, if the option
1788 `org-fit-agenda-window' is set, resize the agenda window to
1789 try to show as much as possible of the buffer content.
1790 See also the variable `org-agenda-restore-windows-after-quit'."
1791 :group 'org-agenda-windows
1792 :type '(choice
1793 (const current-window)
1794 (const other-frame)
1795 (const other-window)
1796 (const reorganize-frame)))
1798 (defcustom org-agenda-restore-windows-after-quit nil
1799 "Non-nil means, restore window configuration open exiting agenda.
1800 Before the window configuration is changed for displaying the agenda,
1801 the current status is recorded. When the agenda is exited with
1802 `q' or `x' and this option is set, the old state is restored. If
1803 `org-agenda-window-setup' is `other-frame', the value of this
1804 option will be ignored.."
1805 :group 'org-agenda-windows
1806 :type 'boolean)
1808 ;; FIXME: I think this variable could be removed, default set to t
1809 (defcustom org-select-agenda-window t
1810 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1811 When nil, cursor will remain in the current window."
1812 :group 'org-agenda-windows
1813 :type 'boolean)
1815 ;; FIXME: I think this variable could be removed, default set to t
1816 (defcustom org-fit-agenda-window t
1817 "Non-nil means, change window size of agenda to fit content.
1818 This is only effective if `org-agenda-window-setup' is `reorganize-frame'."
1819 :group 'org-agenda-windows
1820 :type 'boolean)
1823 (defcustom org-indirect-tree-new-frame 'dedicated
1824 "How should indirect tree buffers be displayed?
1825 This applies to indirect buffers created with the commands
1826 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1827 Valid values are:
1828 nil Just display in another window.
1829 t Use a new frame for each indirect buffer created in this way.
1830 dedicated Create one new frame, and re-use it each time the command is
1831 used. This also means that old indirect buffers will be
1832 deleted when a new one is displayed. This is the default."
1833 :group 'org-structure
1834 :group 'org-agenda-windows
1835 :type '(choice
1836 (const :tag "In current frame" nil)
1837 (const :tag "Each time a new frame" t)
1838 (const :tag "One dedicated frame" 'dedicated)))
1840 (defgroup org-agenda-daily/weekly nil
1841 "Options concerning the daily/weekly agenda."
1842 :tag "Org Agenda Daily/Weekly"
1843 :group 'org-agenda)
1845 (defcustom org-agenda-ndays 7
1846 "Number of days to include in overview display.
1847 Should be 1 or 7."
1848 :group 'org-agenda-daily/weekly
1849 :type 'number)
1851 (defcustom org-agenda-start-on-weekday 1
1852 "Non-nil means, start the overview always on the specified weekday.
1853 0 denotes Sunday, 1 denotes Monday etc.
1854 When nil, always start on the current day."
1855 :group 'org-agenda-daily/weekly
1856 :type '(choice (const :tag "Today" nil)
1857 (number :tag "Weekday No.")))
1858 (defcustom org-agenda-show-all-dates t
1859 "Non-nil means, `org-agenda' shows every day in the selected range.
1860 When nil, only the days which actually have entries are shown."
1861 :group 'org-agenda-daily/weekly
1862 :type 'boolean)
1864 (defcustom org-agenda-include-diary nil
1865 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1866 :group 'org-agenda-daily/weekly
1867 :type 'boolean)
1869 ;; FIXME: This variable could be removed
1870 (defcustom org-agenda-include-all-todo nil
1871 "Set means weekly/daily agenda will always contain all TODO entries.
1872 The TODO entries will be listed at the top of the agenda, before
1873 the entries for specific days."
1874 :group 'org-agenda-daily/weekly
1875 :type 'boolean)
1877 (defgroup org-agenda-time-grid nil
1878 "Options concerning the time grid in the Org-mode Agenda."
1879 :tag "Org Agenda Time Grid"
1880 :group 'org-agenda)
1882 (defcustom org-agenda-use-time-grid t
1883 "Non-nil means, show a time grid in the agenda schedule.
1884 A time grid is a set of lines for specific times (like every two hours between
1885 8:00 and 20:00). The items scheduled for a day at specific times are
1886 sorted in between these lines.
1887 For details about when the grid will be shown, and what it will look like, see
1888 the variable `org-agenda-time-grid'."
1889 :group 'org-agenda-time-grid
1890 :type 'boolean)
1892 (defcustom org-agenda-time-grid
1893 '((daily today require-timed)
1894 "----------------"
1895 (800 1000 1200 1400 1600 1800 2000))
1897 "The settings for time grid for agenda display.
1898 This is a list of three items. The first item is again a list. It contains
1899 symbols specifying conditions when the grid should be displayed:
1901 daily if the agenda shows a single day
1902 weekly if the agenda shows an entire week
1903 today show grid on current date, independent of daily/weekly display
1904 require-timed show grid only if at least one item has a time specification
1906 The second item is a string which will be places behing the grid time.
1908 The third item is a list of integers, indicating the times that should have
1909 a grid line."
1910 :group 'org-agenda-time-grid
1911 :type
1912 '(list
1913 (set :greedy t :tag "Grid Display Options"
1914 (const :tag "Show grid in single day agenda display" daily)
1915 (const :tag "Show grid in weekly agenda display" weekly)
1916 (const :tag "Always show grid for today" today)
1917 (const :tag "Show grid only if any timed entries are present"
1918 require-timed)
1919 (const :tag "Skip grid times already present in an entry"
1920 remove-match))
1921 (string :tag "Grid String")
1922 (repeat :tag "Grid Times" (integer :tag "Time"))))
1924 (defgroup org-agenda-sorting nil
1925 "Options concerning sorting in the Org-mode Agenda."
1926 :tag "Org Agenda Sorting"
1927 :group 'org-agenda)
1929 (let ((sorting-choice
1930 '(choice
1931 (const time-up) (const time-down)
1932 (const category-keep) (const category-up) (const category-down)
1933 (const tag-down) (const tag-up)
1934 (const priority-up) (const priority-down))))
1936 (defcustom org-agenda-sorting-strategy
1937 '((agenda time-up category-keep priority-down)
1938 (todo category-keep priority-down)
1939 (tags category-keep))
1940 "Sorting structure for the agenda items of a single day.
1941 This is a list of symbols which will be used in sequence to determine
1942 if an entry should be listed before another entry. The following
1943 symbols are recognized:
1945 time-up Put entries with time-of-day indications first, early first
1946 time-down Put entries with time-of-day indications first, late first
1947 category-keep Keep the default order of categories, corresponding to the
1948 sequence in `org-agenda-files'.
1949 category-up Sort alphabetically by category, A-Z.
1950 category-down Sort alphabetically by category, Z-A.
1951 tag-up Sort alphabetically by last tag, A-Z.
1952 tag-down Sort alphabetically by last tag, Z-A.
1953 priority-up Sort numerically by priority, high priority last.
1954 priority-down Sort numerically by priority, high priority first.
1956 The different possibilities will be tried in sequence, and testing stops
1957 if one comparison returns a \"not-equal\". For example, the default
1958 '(time-up category-keep priority-down)
1959 means: Pull out all entries having a specified time of day and sort them,
1960 in order to make a time schedule for the current day the first thing in the
1961 agenda listing for the day. Of the entries without a time indication, keep
1962 the grouped in categories, don't sort the categories, but keep them in
1963 the sequence given in `org-agenda-files'. Within each category sort by
1964 priority.
1966 Leaving out `category-keep' would mean that items will be sorted across
1967 categories by priority."
1968 :group 'org-agenda-sorting
1969 :type `(choice
1970 (repeat :tag "General" ,sorting-choice)
1971 (list :tag "Individually"
1972 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
1973 (repeat ,sorting-choice))
1974 (cons (const :tag "Strategy for TODO lists" todo)
1975 (repeat ,sorting-choice))
1976 (cons (const :tag "Strategy for Tags matches" tags)
1977 (repeat ,sorting-choice))))))
1979 (defcustom org-sort-agenda-notime-is-late t
1980 "Non-nil means, items without time are considered late.
1981 This is only relevant for sorting. When t, items which have no explicit
1982 time like 15:30 will be considered as 99:01, i.e. later than any items which
1983 do have a time. When nil, the default time is before 0:00. You can use this
1984 option to decide if the schedule for today should come before or after timeless
1985 agenda entries."
1986 :group 'org-agenda-sorting
1987 :type 'boolean)
1989 (defgroup org-agenda-prefix nil
1990 "Options concerning the entry prefix in the Org-mode agenda display."
1991 :tag "Org Agenda Prefix"
1992 :group 'org-agenda)
1994 (defcustom org-agenda-prefix-format
1995 '((agenda . " %-12:c%?-12t% s")
1996 (timeline . " % s")
1997 (todo . " %-12:c")
1998 (tags . " %-12:c"))
1999 "Format specifications for the prefix of items in the agenda views.
2000 An alist with four entries, for the different agenda types. The keys to the
2001 sublists are `agenda', `timeline', `todo', and `tags'. The values
2002 are format strings.
2003 This format works similar to a printf format, with the following meaning:
2005 %c the category of the item, \"Diary\" for entries from the diary, or
2006 as given by the CATEGORY keyword or derived from the file name.
2007 %T the *last* tag of the item. Last because inherited tags come
2008 first in the list.
2009 %t the time-of-day specification if one applies to the entry, in the
2010 format HH:MM
2011 %s Scheduling/Deadline information, a short string
2013 All specifiers work basically like the standard `%s' of printf, but may
2014 contain two additional characters: A question mark just after the `%' and
2015 a whitespace/punctuation character just before the final letter.
2017 If the first character after `%' is a question mark, the entire field
2018 will only be included if the corresponding value applies to the
2019 current entry. This is useful for fields which should have fixed
2020 width when present, but zero width when absent. For example,
2021 \"%?-12t\" will result in a 12 character time field if a time of the
2022 day is specified, but will completely disappear in entries which do
2023 not contain a time.
2025 If there is punctuation or whitespace character just before the final
2026 format letter, this character will be appended to the field value if
2027 the value is not empty. For example, the format \"%-12:c\" leads to
2028 \"Diary: \" if the category is \"Diary\". If the category were be
2029 empty, no additional colon would be interted.
2031 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2032 - Indent the line with two space characters
2033 - Give the category in a 12 chars wide field, padded with whitespace on
2034 the right (because of `-'). Append a colon if there is a category
2035 (because of `:').
2036 - If there is a time-of-day, put it into a 12 chars wide field. If no
2037 time, don't put in an empty field, just skip it (because of '?').
2038 - Finally, put the scheduling information and append a whitespace.
2040 As another example, if you don't want the time-of-day of entries in
2041 the prefix, you could use:
2043 (setq org-agenda-prefix-format \" %-11:c% s\")
2045 See also the variables `org-agenda-remove-times-when-in-prefix' and
2046 `org-agenda-remove-tags-when-in-prefix'."
2047 :type '(choice
2048 (string :tag "General format")
2049 (list :greedy t :tag "View dependent"
2050 (cons (const agenda) (string :tag "Format"))
2051 (cons (const timeline) (string :tag "Format"))
2052 (cons (const todo) (string :tag "Format"))
2053 (cons (const tags) (string :tag "Format"))))
2054 :group 'org-agenda-prefix)
2056 (defvar org-prefix-format-compiled nil
2057 "The compiled version of the most recently used prefix format.
2058 See the variable `org-agenda-prefix-format'.")
2060 (defcustom org-agenda-remove-times-when-in-prefix t
2061 "Non-nil means, remove duplicate time specifications in agenda items.
2062 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2063 time-of-day specification in a headline or diary entry is extracted and
2064 placed into the prefix. If this option is non-nil, the original specification
2065 \(a timestamp or -range, or just a plain time(range) specification like
2066 11:30-4pm) will be removed for agenda display. This makes the agenda less
2067 cluttered.
2068 The option can be t or nil. It may also be the symbol `beg', indicating
2069 that the time should only be removed what it is located at the beginning of
2070 the headline/diary entry."
2071 :group 'org-agenda-prefix
2072 :type '(choice
2073 (const :tag "Always" t)
2074 (const :tag "Never" nil)
2075 (const :tag "When at beginning of entry" beg)))
2077 (defcustom org-agenda-remove-tags-when-in-prefix nil
2078 "Non-nil means, remove the tags from the headline copy in the agenda.
2079 When this is the symbol `prefix', only remove tags when
2080 `org-agenda-prefix-format' contains a `%T' specifier."
2081 :group 'org-agenda-prefix
2082 :type '(choice
2083 (const :tag "Always" t)
2084 (const :tag "Never" nil)
2085 (const :tag "When prefix format contains %T" prefix)))
2087 (defcustom org-agenda-align-tags-to-column 65
2088 "Shift tags in agenda items to this column."
2089 :group 'org-agenda-prefix
2090 :type 'integer)
2092 (defgroup org-latex nil
2093 "Options for embedding LaTeX code into Org-mode"
2094 :tag "Org LaTeX"
2095 :group 'org)
2097 (defcustom org-format-latex-options
2098 '(:foreground "Black" :background "Transparent" :scale 1.0
2099 :matchers ("begin" "$" "$$" "\\(" "\\["))
2100 "Options for creating images from LaTeX fragments.
2101 This is a property list with the following properties:
2102 :foreground the foreground color, for example \"Black\".
2103 :background the background color, or \"Transparent\".
2104 :scale a scaling factor for the size of the images
2105 :matchers a list indicating which matchers should be used to
2106 find LaTeX fragments. Valid members of this list are:
2107 \"begin\" find environments
2108 \"$\" find math expressions surrounded by $...$
2109 \"$$\" find math expressions surrounded by $$....$$
2110 \"\\(\" find math expressions surrounded by \\(...\\)
2111 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2112 :group 'org-latex
2113 :type 'plist)
2115 (defgroup org-export nil
2116 "Options for exporting org-listings."
2117 :tag "Org Export"
2118 :group 'org)
2120 (defgroup org-export-general nil
2121 "General options for exporting Org-mode files."
2122 :tag "Org Export General"
2123 :group 'org-export)
2125 (defcustom org-export-publishing-directory "."
2126 "Path to the location where exported files should be located.
2127 This path may be relative to the directory where the Org-mode file lives.
2128 The default is to put them into the same directory as the Org-mode file.
2129 The variable may also be an alist with export types `:html', `:ascii',
2130 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2131 is relative, it is interpreted relative to the directory where the exported
2132 Org-mode files lives."
2133 :group 'org-export-general
2134 :type '(choice
2135 (directory)
2136 (repeat
2137 (cons
2138 (choice :tag "Type"
2139 (const :html) (const :ascii) (const :ical) (const :xoxo))
2140 (directory)))))
2142 (defcustom org-export-language-setup
2143 '(("en" "Author" "Date" "Table of Contents")
2144 ("cs" "Autor" "Datum" "Obsah")
2145 ("da" "Ophavsmand" "Dato" "Indhold")
2146 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2147 ("es" "Autor" "Fecha" "\xccndice")
2148 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2149 ("it" "Autore" "Data" "Indice")
2150 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2151 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2152 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2153 "Terms used in export text, translated to different languages.
2154 Use the variable `org-export-default-language' to set the language,
2155 or use the +OPTION lines for a per-file setting."
2156 :group 'org-export-general
2157 :type '(repeat
2158 (list
2159 (string :tag "HTML language tag")
2160 (string :tag "Author")
2161 (string :tag "Date")
2162 (string :tag "Table of Contents"))))
2164 (defcustom org-export-default-language "en"
2165 "The default language of HTML export, as a string.
2166 This should have an association in `org-export-language-setup'."
2167 :group 'org-export-general
2168 :type 'string)
2170 (defcustom org-export-headline-levels 3
2171 "The last level which is still exported as a headline.
2172 Inferior levels will produce itemize lists when exported.
2173 Note that a numeric prefix argument to an exporter function overrides
2174 this setting.
2176 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2177 :group 'org-export-general
2178 :type 'number)
2180 (defcustom org-export-with-section-numbers t
2181 "Non-nil means, add section numbers to headlines when exporting.
2183 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2184 :group 'org-export-general
2185 :type 'boolean)
2187 (defcustom org-export-with-toc t
2188 "Non-nil means, create a table of contents in exported files.
2189 The TOC contains headlines with levels up to`org-export-headline-levels'.
2191 Headlines which contain any TODO items will be marked with \"(*)\" in
2192 ASCII export, and with red color in HTML output.
2194 In HTML output, the TOC will be clickable.
2196 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
2197 :group 'org-export-general
2198 :type 'boolean)
2200 (defcustom org-export-mark-todo-in-toc nil
2201 "Non-nil means, mark TOC lines that contain any open TODO items."
2202 :group 'org-export-general
2203 :type 'boolean)
2205 (defcustom org-export-preserve-breaks nil
2206 "Non-nil means, preserve all line breaks when exporting.
2207 Normally, in HTML output paragraphs will be reformatted. In ASCII
2208 export, line breaks will always be preserved, regardless of this variable.
2210 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2211 :group 'org-export-general
2212 :type 'boolean)
2214 (defcustom org-export-with-archived-trees 'headline
2215 "Whether subtrees with the ARCHIVE tag should be exported.
2216 This can have three different values
2217 nil Do not export, pretend this tree is not present
2218 t Do export the entire tree
2219 headline Only export the headline, but skip the tree below it."
2220 :group 'org-export-general
2221 :group 'org-archive
2222 :type '(choice
2223 (const :tag "not at all" nil)
2224 (const :tag "headline only" 'headline)
2225 (const :tag "entirely" t)))
2227 (defcustom org-export-with-timestamps t
2228 "If nil, do not export time stamps and associated keywords."
2229 :group 'org-export-general
2230 :type 'boolean)
2232 (defcustom org-export-remove-timestamps-from-toc t
2233 "If nil, remove timestamps from the table of contents entries."
2234 :group 'org-export-general
2235 :type 'boolean)
2237 (defcustom org-export-with-tags 'not-in-toc
2238 "If nil, do not export tags, just remove them from headlines.
2239 If this is the symbol `not-in-toc', tags will be removed from table of
2240 contents entries, but still be shown in the headlines of the document."
2241 :group 'org-export-general
2242 :type '(choice
2243 (const :tag "Off" nil)
2244 (const :tag "Not in TOC" not-in-toc)
2245 (const :tag "On" t)))
2247 (defgroup org-export-translation nil
2248 "Options for translating special ascii sequences for the export backends."
2249 :tag "Org Export Translation"
2250 :group 'org-export)
2252 (defcustom org-export-with-emphasize t
2253 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2254 If the export target supports emphasizing text, the word will be
2255 typeset in bold, italic, or underlined, respectively. Works only for
2256 single words, but you can say: I *really* *mean* *this*.
2257 Not all export backends support this.
2259 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2260 :group 'org-export-translation
2261 :type 'boolean)
2263 (defcustom org-export-with-sub-superscripts t
2264 "Non-nil means, interpret \"_\" and \"^\" for export.
2265 When this option is turned on, you can use TeX-like syntax for sub- and
2266 superscripts. Several characters after \"_\" or \"^\" will be
2267 considered as a single item - so grouping with {} is normally not
2268 needed. For example, the following things will be parsed as single
2269 sub- or superscripts.
2271 10^24 or 10^tau several digits will be considered 1 item.
2272 10^-12 or 10^-tau a leading sign with digits or a word
2273 x^2-y^3 will be read as x^2 - y^3, because items are
2274 terminated by almost any nonword/nondigit char.
2275 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2277 Still, ambiguity is possible - so when in doubt use {} to enclose the
2278 sub/superscript.
2279 Not all export backends support this, but HTML does.
2281 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2282 :group 'org-export-translation
2283 :type 'boolean)
2285 (defcustom org-export-with-TeX-macros t
2286 "Non-nil means, interpret simple TeX-like macros when exporting.
2287 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2288 No only real TeX macros will work here, but the standard HTML entities
2289 for math can be used as macro names as well. For a list of supported
2290 names in HTML export, see the constant `org-html-entities'.
2291 Not all export backends support this.
2293 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2294 :group 'org-export-translation
2295 :group 'org-latex
2296 :type 'boolean)
2298 (defcustom org-export-with-LaTeX-fragments nil
2299 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2300 When set, the exporter will find LaTeX environments if the \\begin line is
2301 the first non-white thing on a line. It will also find the math delimiters
2302 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2303 display math.
2305 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2306 :group 'org-export-translation
2307 :group 'org-latex
2308 :type 'boolean)
2310 (defcustom org-export-with-fixed-width t
2311 "Non-nil means, lines starting with \":\" will be in fixed width font.
2312 This can be used to have pre-formatted text, fragments of code etc. For
2313 example:
2314 : ;; Some Lisp examples
2315 : (while (defc cnt)
2316 : (ding))
2317 will be looking just like this in also HTML. See also the QUOTE keyword.
2318 Not all export backends support this.
2320 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2321 :group 'org-export-translation
2322 :type 'boolean)
2324 (defcustom org-match-sexp-depth 3
2325 "Number of stacked braces for sub/superscript matching.
2326 This has to be set before loading org.el to be effective."
2327 :group 'org-export-translation
2328 :type 'integer)
2330 (defgroup org-export-tables nil
2331 "Options for exporting tables in Org-mode."
2332 :tag "Org Export Tables"
2333 :group 'org-export)
2335 (defcustom org-export-with-tables t
2336 "If non-nil, lines starting with \"|\" define a table.
2337 For example:
2339 | Name | Address | Birthday |
2340 |-------------+----------+-----------|
2341 | Arthur Dent | England | 29.2.2100 |
2343 Not all export backends support this.
2345 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2346 :group 'org-export-tables
2347 :type 'boolean)
2349 (defcustom org-export-highlight-first-table-line t
2350 "Non-nil means, highlight the first table line.
2351 In HTML export, this means use <th> instead of <td>.
2352 In tables created with table.el, this applies to the first table line.
2353 In Org-mode tables, all lines before the first horizontal separator
2354 line will be formatted with <th> tags."
2355 :group 'org-export-tables
2356 :type 'boolean)
2358 (defcustom org-export-table-remove-special-lines t
2359 "Remove special lines and marking characters in calculating tables.
2360 This removes the special marking character column from tables that are set
2361 up for spreadsheet calculations. It also removes the entire lines
2362 marked with `!', `_', or `^'. The lines with `$' are kept, because
2363 the values of constants may be useful to have."
2364 :group 'org-export-tables
2365 :type 'boolean)
2367 (defcustom org-export-prefer-native-exporter-for-tables nil
2368 "Non-nil means, always export tables created with table.el natively.
2369 Natively means, use the HTML code generator in table.el.
2370 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2371 the table does not use row- or column-spanning). This has the
2372 advantage, that the automatic HTML conversions for math symbols and
2373 sub/superscripts can be applied. Org-mode's HTML generator is also
2374 much faster."
2375 :group 'org-export-tables
2376 :type 'boolean)
2378 (defgroup org-export-ascii nil
2379 "Options specific for ASCII export of Org-mode files."
2380 :tag "Org Export ASCII"
2381 :group 'org-export)
2383 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2384 "Characters for underlining headings in ASCII export.
2385 In the given sequence, these characters will be used for level 1, 2, ..."
2386 :group 'org-export-ascii
2387 :type '(repeat character))
2389 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2390 "Bullet characters for headlines converted to lists in ASCII export.
2391 The first character is is used for the first lest level generated in this
2392 way, and so on. If there are more levels than characters given here,
2393 the list will be repeated.
2394 Note that plain lists will keep the same bullets as the have in the
2395 Org-mode file."
2396 :group 'org-export-ascii
2397 :type '(repeat character))
2399 (defcustom org-export-ascii-show-new-buffer t
2400 "Non-nil means, popup buffer containing the exported ASCII text.
2401 Otherwise the buffer will just be saved to a file and stay hidden."
2402 :group 'org-export-ascii
2403 :type 'boolean)
2405 (defgroup org-export-xml nil
2406 "Options specific for XML export of Org-mode files."
2407 :tag "Org Export XML"
2408 :group 'org-export)
2410 (defgroup org-export-html nil
2411 "Options specific for HTML export of Org-mode files."
2412 :tag "Org Export HTML"
2413 :group 'org-export)
2415 (defcustom org-export-html-style
2416 "<style type=\"text/css\">
2417 html {
2418 font-family: Times, serif;
2419 font-size: 12pt;
2421 .title { text-align: center; }
2422 .todo { color: red; }
2423 .done { color: green; }
2424 .timestamp { color: grey }
2425 .timestamp-kwd { color: CadetBlue }
2426 .tag { background-color:lightblue; font-weight:normal }
2427 .target { background-color: lavender; }
2428 pre {
2429 border: 1pt solid #AEBDCC;
2430 background-color: #F3F5F7;
2431 padding: 5pt;
2432 font-family: courier, monospace;
2434 table { border-collapse: collapse; }
2435 td, th {
2436 vertical-align: top;
2437 border: 1pt solid #ADB9CC;
2439 </style>"
2440 "The default style specification for exported HTML files.
2441 Since there are different ways of setting style information, this variable
2442 needs to contain the full HTML structure to provide a style, including the
2443 surrounding HTML tags. The style specifications should include definitions
2444 for new classes todo, done, title, and deadline. For example, legal values
2445 would be:
2447 <style type=\"text/css\">
2448 p { font-weight: normal; color: gray; }
2449 h1 { color: black; }
2450 .title { text-align: center; }
2451 .todo, .deadline { color: red; }
2452 .done { color: green; }
2453 </style>
2455 or, if you want to keep the style in a file,
2457 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2459 As the value of this option simply gets inserted into the HTML <head> header,
2460 you can \"misuse\" it to add arbitrary text to the header."
2461 :group 'org-export-html
2462 :type 'string)
2464 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2465 "Format for typesetting the document title in HTML export."
2466 :group 'org-export-html
2467 :type 'string)
2469 (defcustom org-export-html-toplevel-hlevel 2
2470 "The <H> level for level 1 headings in HTML export."
2471 :group 'org-export-html
2472 :type 'string)
2474 (defcustom org-export-html-link-org-files-as-html t
2475 "Non-nil means, make file links to `file.org' point to `file.html'.
2476 When org-mode is exporting an org-mode file to HTML, links to
2477 non-html files are directly put into a href tag in HTML.
2478 However, links to other Org-mode files (recognized by the
2479 extension `.org.) should become links to the corresponding html
2480 file, assuming that the linked org-mode file will also be
2481 converted to HTML.
2482 When nil, the links still point to the plain `.org' file."
2483 :group 'org-export-html
2484 :type 'boolean)
2486 (defcustom org-export-html-inline-images 'maybe
2487 "Non-nil means, inline images into exported HTML pages.
2488 This is done using an <img> tag. When nil, an anchor with href is used to
2489 link to the image. If this option is `maybe', then images in links with
2490 an empty description will be inlined, while images with a description will
2491 be linked only."
2492 :group 'org-export-html
2493 :type '(choice (const :tag "Never" nil)
2494 (const :tag "Always" t)
2495 (const :tag "When there is no description" maybe)))
2497 (defcustom org-export-html-expand t
2498 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2499 When nil, these tags will be exported as plain text and therefore
2500 not be interpreted by a browser.
2502 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2503 :group 'org-export-html
2504 :type 'boolean)
2506 (defcustom org-export-html-table-tag
2507 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2508 "The HTML tag used to start a table.
2509 This must be a <table> tag, but you may change the options like
2510 borders and spacing."
2511 :group 'org-export-html
2512 :type 'string)
2514 (defcustom org-export-html-with-timestamp nil
2515 "If non-nil, write `org-export-html-html-helper-timestamp'
2516 into the exported HTML text. Otherwise, the buffer will just be saved
2517 to a file."
2518 :group 'org-export-html
2519 :type 'boolean)
2521 (defcustom org-export-html-html-helper-timestamp
2522 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2523 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2524 :group 'org-export-html
2525 :type 'string)
2527 (defcustom org-export-html-show-new-buffer nil
2528 "Non-nil means, popup buffer containing the exported html text.
2529 Otherwise, the buffer will just be saved to a file and stay hidden."
2530 :group 'org-export-html
2531 :type 'boolean)
2533 (defgroup org-export-icalendar nil
2534 "Options specific for iCalendar export of Org-mode files."
2535 :tag "Org Export iCalendar"
2536 :group 'org-export)
2538 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2539 "The file name for the iCalendar file covering all agenda files.
2540 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2541 The file name should be absolute."
2542 :group 'org-export-icalendar
2543 :type 'file)
2545 (defcustom org-icalendar-include-todo nil
2546 "Non-nil means, export to iCalendar files should also cover TODO items."
2547 :group 'org-export-icalendar
2548 :type 'boolean)
2550 (defcustom org-icalendar-combined-name "OrgMode"
2551 "Calendar name for the combined iCalendar representing all agenda files."
2552 :group 'org-export-icalendar
2553 :type 'string)
2555 (defgroup org-font-lock nil
2556 "Font-lock settings for highlighting in Org-mode."
2557 :tag "Org Font Lock"
2558 :group 'org)
2560 (defcustom org-level-color-stars-only nil
2561 "Non-nil means fontify only the stars in each headline.
2562 When nil, the entire headline is fontified.
2563 Changing it requires restart of `font-lock-mode' to become effective
2564 also in regions already fontified."
2565 :group 'org-font-lock
2566 :type 'boolean)
2568 (defcustom org-hide-leading-stars nil
2569 "Non-nil means, hide the first N-1 stars in a headline.
2570 This works by using the face `org-hide' for these stars. This
2571 face is white for a light background, and black for a dark
2572 background. You may have to customize the face `org-hide' to
2573 make this work.
2574 Changing it requires restart of `font-lock-mode' to become effective
2575 also in regions already fontified.
2576 You may also set this on a per-file basis by adding one of the following
2577 lines to the buffer:
2579 #+STARTUP: hidestars
2580 #+STARTUP: showstars"
2581 :group 'org-font-lock
2582 :type 'boolean)
2584 (defcustom org-fontify-done-headline nil
2585 "Non-nil means, change the face of a headline if it is marked DONE.
2586 Normally, only the TODO/DONE keyword indicates the state of a headline.
2587 When this is non-nil, the headline after the keyword is set to the
2588 `org-headline-done' as an additional indication."
2589 :group 'org-font-lock
2590 :type 'boolean)
2592 (defcustom org-fontify-emphasized-text t
2593 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2594 Changing this variable requires a restart of Emacs to take effect."
2595 :group 'org-font-lock
2596 :type 'boolean)
2598 (defvar org-emph-re nil
2599 "Regular expression for matching emphasis.")
2600 (defvar org-emphasis-regexp-components) ; defined just below
2601 (defvar org-emphasis-alist) ; defined just below
2602 (defun org-set-emph-re (var val)
2603 "Set variable and compute the emphasis regular expression."
2604 (set var val)
2605 (when (and (boundp 'org-emphasis-alist)
2606 (boundp 'org-emphasis-regexp-components)
2607 org-emphasis-alist org-emphasis-regexp-components)
2608 (let* ((e org-emphasis-regexp-components)
2609 (pre (car e))
2610 (post (nth 1 e))
2611 (border (nth 2 e))
2612 (body (nth 3 e))
2613 (nl (nth 4 e))
2614 (stacked (nth 5 e))
2615 (body1 (concat body "*?"))
2616 (markers (mapconcat 'car org-emphasis-alist "")))
2617 ;; make sure special characters appear at the right position in the class
2618 (if (string-match "\\^" markers)
2619 (setq markers (concat (replace-match "" t t markers) "^")))
2620 (if (string-match "-" markers)
2621 (setq markers (concat (replace-match "" t t markers) "-")))
2622 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2623 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2624 (if (> nl 0)
2625 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2626 (int-to-string nl) "\\}")))
2627 ;; Make the regexp
2628 (setq org-emph-re
2629 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2630 "\\("
2631 "\\([" markers "]\\)"
2632 "\\("
2633 "[^" border markers "]"
2634 body1
2635 "[^" border markers "]"
2636 "\\)"
2637 "\\3\\)"
2638 "\\([" post (if stacked markers) "]\\|$\\)")))))
2640 (defcustom org-emphasis-regexp-components
2641 '(" \t(" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2642 "Components used to build the reqular expression for emphasis.
2643 This is a list with 6 entries. Terminology: In an emphasis string
2644 like \" *strong word* \", we call the initial space PREMATCH, the final
2645 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2646 and \"trong wor\" is the body. The different components in this variable
2647 specify what is allowed/forbidden in each part:
2649 pre Chars allowed as prematch. Beginning of line will be allowed too.
2650 post Chars allowed as postmatch. End of line will be allowed too.
2651 border The chars *forbidden* as border characters. In addition to the
2652 characters given here, all marker characters are forbidden too.
2653 body-regexp A regexp like \".\" to match a body character. Don't use
2654 non-shy groups here, and don't allow newline here.
2655 newline The maximum number of newlines allowed in an emphasis exp.
2656 stacked Non-nil means, allow stacked styles. This works only in HTML
2657 export. When this is set, all marker characters (as given in
2658 `org-emphasis-alist') will be allowed as pre/post, aiding
2659 inside-out matching.
2660 Use customize to modify this, or restart Emacs after changing it."
2661 :group 'org-font-lock
2662 :set 'org-set-emph-re
2663 :type '(list
2664 (sexp :tag "Allowed chars in pre ")
2665 (sexp :tag "Allowed chars in post ")
2666 (sexp :tag "Forbidden chars in border ")
2667 (sexp :tag "Regexp for body ")
2668 (integer :tag "number of newlines allowed")
2669 (boolean :tag "Stacking allowed ")))
2671 (defcustom org-emphasis-alist
2672 '(("*" bold "<b>" "</b>")
2673 ("/" italic "<i>" "</i>")
2674 ("_" underline "<u>" "</u>")
2675 ("=" shadow "<code>" "</code>")
2676 ("+" (:strike-through t) "<del>" "</del>")
2678 "Special syntax for emphasized text.
2679 Text starting and ending with a special character will be emphasized, for
2680 example *bold*, _underlined_ and /italic/. This variable sets the marker
2681 characters, the face to bbe used by font-lock for highlighting in Org-mode
2682 Emacs buffers, and the HTML tags to be used for this.
2683 Use customize to modify this, or restart Emacs after changing it."
2684 :group 'org-font-lock
2685 :set 'org-set-emph-re
2686 :type '(repeat
2687 (list
2688 (string :tag "Marker character")
2689 (choice
2690 (face :tag "Font-lock-face")
2691 (plist :tag "Face property list"))
2692 (string :tag "HTML start tag")
2693 (string :tag "HTML end tag"))))
2695 (defgroup org-faces nil
2696 "Faces in Org-mode."
2697 :tag "Org Faces"
2698 :group 'org-font-lock)
2700 (defun org-compatible-face (specs)
2701 "Make a compatible face specification.
2702 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2703 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2704 to the top of the list. The `min-colors' attribute will be removed from
2705 any other entries, and any resulting duplicates will be removed entirely."
2706 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2707 (let (r e a)
2708 (while (setq e (pop specs))
2709 (cond
2710 ((memq (car e) '(t default)) (push e r))
2711 ((setq a (member '(min-colors 8) (car e)))
2712 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2713 (cdr e)))))
2714 ((setq a (assq 'min-colors (car e)))
2715 (setq e (cons (delq a (car e)) (cdr e)))
2716 (or (assoc (car e) r) (push e r)))
2717 (t (or (assoc (car e) r) (push e r)))))
2718 (nreverse r))
2719 specs))
2721 (defface org-hide
2722 '((((background light)) (:foreground "white"))
2723 (((background dark)) (:foreground "black")))
2724 "Face used to hide leading stars in headlines.
2725 The forground color of this face should be equal to the background
2726 color of the frame."
2727 :group 'org-faces)
2729 (defface org-level-1 ;; font-lock-function-name-face
2730 (org-compatible-face
2731 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2732 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2733 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2734 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2735 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2736 (t (:bold t))))
2737 "Face used for level 1 headlines."
2738 :group 'org-faces)
2740 (defface org-level-2 ;; font-lock-variable-name-face
2741 (org-compatible-face
2742 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2743 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2744 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2745 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2746 (t (:bold t))))
2747 "Face used for level 2 headlines."
2748 :group 'org-faces)
2750 (defface org-level-3 ;; font-lock-keyword-face
2751 (org-compatible-face
2752 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2753 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2754 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2755 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2756 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2757 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2758 (t (:bold t))))
2759 "Face used for level 3 headlines."
2760 :group 'org-faces)
2762 (defface org-level-4 ;; font-lock-comment-face
2763 (org-compatible-face
2764 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2765 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2766 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2767 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2768 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2769 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2770 (t (:bold t))))
2771 "Face used for level 4 headlines."
2772 :group 'org-faces)
2774 (defface org-level-5 ;; font-lock-type-face
2775 (org-compatible-face
2776 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2777 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2778 (((class color) (min-colors 8)) (:foreground "green"))))
2779 "Face used for level 5 headlines."
2780 :group 'org-faces)
2782 (defface org-level-6 ;; font-lock-constant-face
2783 (org-compatible-face
2784 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2785 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2786 (((class color) (min-colors 8)) (:foreground "magenta"))))
2787 "Face used for level 6 headlines."
2788 :group 'org-faces)
2790 (defface org-level-7 ;; font-lock-builtin-face
2791 (org-compatible-face
2792 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2793 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2794 (((class color) (min-colors 8)) (:foreground "blue"))))
2795 "Face used for level 7 headlines."
2796 :group 'org-faces)
2798 (defface org-level-8 ;; font-lock-string-face
2799 (org-compatible-face
2800 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2801 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2802 (((class color) (min-colors 8)) (:foreground "green"))))
2803 "Face used for level 8 headlines."
2804 :group 'org-faces)
2806 (defface org-special-keyword ;; font-lock-string-face
2807 (org-compatible-face
2808 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2809 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2810 (t (:italic t))))
2811 "Face used for special keywords."
2812 :group 'org-faces)
2814 (defface org-warning ;; font-lock-warning-face
2815 (org-compatible-face
2816 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2817 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2818 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2819 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2820 (t (:bold t))))
2821 "Face for deadlines and TODO keywords."
2822 :group 'org-faces)
2824 (defface org-headline-done ;; font-lock-string-face
2825 (org-compatible-face
2826 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2827 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2828 (((class color) (min-colors 8) (background light)) (:bold nil))))
2829 "Face used to indicate that a headline is DONE.
2830 This face is only used if `org-fontify-done-headline' is set."
2831 :group 'org-faces)
2833 (defface org-archived ; similar to shadow
2834 (org-compatible-face
2835 '((((class color grayscale) (min-colors 88) (background light))
2836 (:foreground "grey50"))
2837 (((class color grayscale) (min-colors 88) (background dark))
2838 (:foreground "grey70"))
2839 (((class color) (min-colors 8) (background light))
2840 (:foreground "green"))
2841 (((class color) (min-colors 8) (background dark))
2842 (:foreground "yellow"))))
2843 "Face for headline with the ARCHIVE tag."
2844 :group 'org-faces)
2846 (defface org-link
2847 '((((class color) (background light)) (:foreground "Purple" :underline t))
2848 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2849 (t (:underline t)))
2850 "Face for links."
2851 :group 'org-faces)
2853 (defface org-date
2854 '((((class color) (background light)) (:foreground "Purple" :underline t))
2855 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2856 (t (:underline t)))
2857 "Face for links."
2858 :group 'org-faces)
2860 (defface org-tag
2861 '((t (:bold t)))
2862 "Face for tags."
2863 :group 'org-faces)
2865 (defface org-todo ;; font-lock-warning-face
2866 (org-compatible-face
2867 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2868 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2869 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2870 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2871 (t (:inverse-video t :bold t))))
2872 "Face for TODO keywords."
2873 :group 'org-faces)
2875 (defface org-done ;; font-lock-type-face
2876 (org-compatible-face
2877 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2878 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2879 (((class color) (min-colors 8)) (:foreground "green"))
2880 (t (:bold t))))
2881 "Face used for DONE."
2882 :group 'org-faces)
2884 (defface org-table ;; font-lock-function-name-face
2885 (org-compatible-face
2886 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2887 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2888 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2889 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2890 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2891 (((class color) (min-colors 8) (background dark)))))
2892 "Face used for tables."
2893 :group 'org-faces)
2895 (defface org-formula
2896 (org-compatible-face
2897 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2898 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2899 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2900 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2901 (t (:bold t :italic t))))
2902 "Face for formulas."
2903 :group 'org-faces)
2905 (defface org-scheduled-today
2906 (org-compatible-face
2907 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2908 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2909 (((class color) (min-colors 8)) (:foreground "green"))
2910 (t (:bold t :italic t))))
2911 "Face for items scheduled for a certain day."
2912 :group 'org-faces)
2914 (defface org-scheduled-previously
2915 (org-compatible-face
2916 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2917 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2918 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2919 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2920 (t (:bold t))))
2921 "Face for items scheduled previously, and not yet done."
2922 :group 'org-faces)
2924 (defface org-upcoming-deadline
2925 (org-compatible-face
2926 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2927 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2928 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2929 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2930 (t (:bold t))))
2931 "Face for items scheduled previously, and not yet done."
2932 :group 'org-faces)
2934 (defface org-time-grid ;; font-lock-variable-name-face
2935 (org-compatible-face
2936 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2937 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2938 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2939 "Face used for time grids."
2940 :group 'org-faces)
2942 (defconst org-level-faces
2943 '(org-level-1 org-level-2 org-level-3 org-level-4
2944 org-level-5 org-level-6 org-level-7 org-level-8
2946 (defconst org-n-levels (length org-level-faces))
2949 ;; Variables for pre-computed regular expressions, all buffer local
2950 (defvar org-done-string nil
2951 "The last string in `org-todo-keywords', indicating an item is DONE.")
2952 (make-variable-buffer-local 'org-done-string)
2953 (defvar org-todo-regexp nil
2954 "Matches any of the TODO state keywords.")
2955 (make-variable-buffer-local 'org-todo-regexp)
2956 (defvar org-not-done-regexp nil
2957 "Matches any of the TODO state keywords except the last one.")
2958 (make-variable-buffer-local 'org-not-done-regexp)
2959 (defvar org-todo-line-regexp nil
2960 "Matches a headline and puts TODO state into group 2 if present.")
2961 (make-variable-buffer-local 'org-todo-line-regexp)
2962 (defvar org-todo-line-tags-regexp nil
2963 "Matches a headline and puts TODO state into group 2 if present.
2964 Also put tags into group 4 if tags are present.")
2965 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2966 (defvar org-nl-done-regexp nil
2967 "Matches newline followed by a headline with the DONE keyword.")
2968 (make-variable-buffer-local 'org-nl-done-regexp)
2969 (defvar org-looking-at-done-regexp nil
2970 "Matches the DONE keyword a point.")
2971 (make-variable-buffer-local 'org-looking-at-done-regexp)
2972 (defvar org-todo-kwd-priority-p nil
2973 "Do TODO items have priorities?")
2974 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2975 (defvar org-todo-kwd-max-priority nil
2976 "Maximum priority of TODO items.")
2977 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2978 (defvar org-ds-keyword-length 12
2979 "Maximum length of the Deadline and SCHEDULED keywords.")
2980 (make-variable-buffer-local 'org-ds-keyword-length)
2981 (defvar org-deadline-regexp nil
2982 "Matches the DEADLINE keyword.")
2983 (make-variable-buffer-local 'org-deadline-regexp)
2984 (defvar org-deadline-time-regexp nil
2985 "Matches the DEADLINE keyword together with a time stamp.")
2986 (make-variable-buffer-local 'org-deadline-time-regexp)
2987 (defvar org-deadline-line-regexp nil
2988 "Matches the DEADLINE keyword and the rest of the line.")
2989 (make-variable-buffer-local 'org-deadline-line-regexp)
2990 (defvar org-scheduled-regexp nil
2991 "Matches the SCHEDULED keyword.")
2992 (make-variable-buffer-local 'org-scheduled-regexp)
2993 (defvar org-scheduled-time-regexp nil
2994 "Matches the SCHEDULED keyword together with a time stamp.")
2995 (make-variable-buffer-local 'org-scheduled-time-regexp)
2996 (defvar org-closed-time-regexp nil
2997 "Matches the CLOSED keyword together with a time stamp.")
2998 (make-variable-buffer-local 'org-closed-time-regexp)
3000 (defvar org-keyword-time-regexp nil
3001 "Matches any of the 3 keywords, together with the time stamp.")
3002 (make-variable-buffer-local 'org-keyword-time-regexp)
3003 (defvar org-maybe-keyword-time-regexp nil
3004 "Matches a timestamp, possibly preceeded by a keyword.")
3005 (make-variable-buffer-local 'org-keyword-time-regexp)
3007 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3008 rear-nonsticky t mouse-map t)
3009 "Properties to remove when a string without properties is wanted.")
3011 (defsubst org-match-string-no-properties (num &optional string)
3012 (if (featurep 'xemacs)
3013 (let ((s (match-string num string)))
3014 (remove-text-properties 0 (length s) org-rm-props s)
3016 (match-string-no-properties num string)))
3018 (defsubst org-no-properties (s)
3019 (remove-text-properties 0 (length s) org-rm-props s)
3022 (defsubst org-get-alist-option (option key)
3023 (cond ((eq key t) t)
3024 ((eq option t) t)
3025 ((assoc key option) (cdr (assoc key option)))
3026 (t (cdr (assq 'default option)))))
3028 (defsubst org-set-local (var value)
3029 "Make VAR local in current buffer and set it to VALUE."
3030 (set (make-variable-buffer-local var) value))
3032 (defsubst org-mode-p ()
3033 "Check if the current buffer is in Org-mode."
3034 (eq major-mode 'org-mode))
3036 (defsubst org-last (list)
3037 "Return the last element of LIST."
3038 (car (last list)))
3040 (defun org-let (list &rest body)
3041 (eval (cons 'let (cons list body))))
3042 (put 'org-let 'lisp-indent-function 1)
3044 (defun org-let2 (list1 list2 &rest body)
3045 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3046 (put 'org-let2 'lisp-indent-function 2)
3048 (defconst org-startup-options
3049 '(("fold" org-startup-folded t)
3050 ("overview" org-startup-folded t)
3051 ("nofold" org-startup-folded nil)
3052 ("showall" org-startup-folded nil)
3053 ("content" org-startup-folded content)
3054 ("hidestars" org-hide-leading-stars t)
3055 ("showstars" org-hide-leading-stars nil)
3056 ("odd" org-odd-levels-only t)
3057 ("oddeven" org-odd-levels-only nil)
3058 ("align" org-startup-align-all-tables t)
3059 ("noalign" org-startup-align-all-tables nil)
3060 ("customtime" org-display-custom-times t)
3061 ("logging" org-log-done t)
3062 ("nologging" org-log-done nil)
3063 ("dlcheck" org-startup-with-deadline-check t)
3064 ("nodlcheck" org-startup-with-deadline-check nil)))
3066 (defun org-set-regexps-and-options ()
3067 "Precompute regular expressions for current buffer."
3068 (when (org-mode-p)
3069 (let ((re (org-make-options-regexp
3070 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
3071 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
3072 (splitre "[ \t]+")
3073 kwds int key value cat arch tags links)
3074 (save-excursion
3075 (save-restriction
3076 (widen)
3077 (goto-char (point-min))
3078 (while (re-search-forward re nil t)
3079 (setq key (match-string 1) value (org-match-string-no-properties 2))
3080 (cond
3081 ((equal key "CATEGORY")
3082 (if (string-match "[ \t]+$" value)
3083 (setq value (replace-match "" t t value)))
3084 (setq cat (intern value)))
3085 ((equal key "SEQ_TODO")
3086 (setq int 'sequence
3087 kwds (append kwds (org-split-string value splitre))))
3088 ((equal key "PRI_TODO")
3089 (setq int 'priority
3090 kwds (append kwds (org-split-string value splitre))))
3091 ((equal key "TYP_TODO")
3092 (setq int 'type
3093 kwds (append kwds (org-split-string value splitre))))
3094 ((equal key "TAGS")
3095 (setq tags (append tags (org-split-string value splitre))))
3096 ((equal key "LINK")
3097 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3098 (push (cons (match-string 1 value)
3099 (org-trim (match-string 2 value)))
3100 links)))
3101 ((equal key "STARTUP")
3102 (let ((opts (org-split-string value splitre))
3103 l var val)
3104 (while (setq l (assoc (pop opts) org-startup-options))
3105 (setq var (nth 1 l) val (nth 2 l))
3106 (set (make-local-variable var) val))))
3107 ((equal key "ARCHIVE")
3108 (string-match " *$" value)
3109 (setq arch (replace-match "" t t value))
3110 (remove-text-properties 0 (length arch)
3111 '(face t fontified t) arch)))
3113 (and cat (org-set-local 'org-category cat))
3114 (and kwds (org-set-local 'org-todo-keywords kwds))
3115 (and arch (org-set-local 'org-archive-location arch))
3116 (and int (org-set-local 'org-todo-interpretation int))
3117 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3118 (when tags
3119 (let (e tgs)
3120 (while (setq e (pop tags))
3121 (cond
3122 ((equal e "{") (push '(:startgroup) tgs))
3123 ((equal e "}") (push '(:endgroup) tgs))
3124 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3125 (push (cons (match-string 1 e)
3126 (string-to-char (match-string 2 e)))
3127 tgs))
3128 (t (push (list e) tgs))))
3129 (org-set-local 'org-tag-alist nil)
3130 (while (setq e (pop tgs))
3131 (or (and (stringp (car e))
3132 (assoc (car e) org-tag-alist))
3133 (push e org-tag-alist))))))
3135 ;; Compute the regular expressions and other local variables
3136 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
3137 org-todo-kwd-max-priority (1- (length org-todo-keywords))
3138 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3139 (length org-scheduled-string)))
3140 org-done-string
3141 (nth (1- (length org-todo-keywords)) org-todo-keywords)
3142 org-todo-regexp
3143 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
3144 "\\|") "\\)\\>")
3145 org-not-done-regexp
3146 (concat "\\<\\("
3147 (mapconcat 'regexp-quote
3148 (nreverse (cdr (reverse org-todo-keywords)))
3149 "\\|")
3150 "\\)\\>")
3151 org-todo-line-regexp
3152 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3153 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3154 "\\)\\>\\)? *\\(.*\\)")
3155 org-nl-done-regexp
3156 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
3157 org-todo-line-tags-regexp
3158 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3159 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3160 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3161 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
3162 org-deadline-regexp (concat "\\<" org-deadline-string)
3163 org-deadline-time-regexp
3164 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3165 org-deadline-line-regexp
3166 (concat "\\<\\(" org-deadline-string "\\).*")
3167 org-scheduled-regexp
3168 (concat "\\<" org-scheduled-string)
3169 org-scheduled-time-regexp
3170 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3171 org-closed-time-regexp
3172 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3173 org-keyword-time-regexp
3174 (concat "\\<\\(" org-scheduled-string
3175 "\\|" org-deadline-string
3176 "\\|" org-closed-string
3177 "\\|" org-clock-string "\\)"
3178 " *[[<]\\([^]>]+\\)[]>]")
3179 org-maybe-keyword-time-regexp
3180 (concat "\\(\\<\\(" org-scheduled-string
3181 "\\|" org-deadline-string
3182 "\\|" org-closed-string
3183 "\\|" org-clock-string "\\)\\)?"
3184 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3186 (org-set-font-lock-defaults)))
3188 ;;; Tell the compiler about dynamically scoped variables, or foreign vars
3189 (defvar calc-embedded-close-formula) ; defined by the calc package
3190 (defvar calc-embedded-open-formula) ; defined by the calc package
3191 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
3192 (defvar zmacs-regions) ; XEmacs regions
3193 (defvar original-date) ; dynamically scoped in calendar
3194 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
3195 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3196 (defvar org-html-entities) ; defined later in this file
3197 (defvar org-goto-start-pos) ; dynamically scoped parameter
3198 (defvar org-time-was-given) ; dynamically scoped parameter
3199 (defvar org-ts-what) ; dynamically scoped parameter
3200 (defvar org-current-export-file) ; dynamically scoped parameter
3201 (defvar org-current-export-dir) ; dynamically scoped parameter
3202 (defvar mark-active) ; Emacs only, not available in XEmacs.
3203 (defvar timecnt) ; dynamically scoped parameter
3204 (defvar levels-open) ; dynamically scoped parameter
3205 (defvar entry) ; dynamically scoped parameter
3206 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
3207 (defvar date) ; dynamically scoped parameter
3208 (defvar description) ; dynamically scoped parameter
3209 (defvar ans1) ; dynamically scoped parameter
3210 (defvar ans2) ; dynamically scoped parameter
3211 (defvar starting-day) ; local variable
3212 (defvar include-all-loc) ; local variable
3213 (defvar vm-message-pointer) ; from vm
3214 (defvar vm-folder-directory) ; from vm
3215 (defvar gnus-other-frame-object) ; from gnus
3216 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
3217 (defvar wl-summary-buffer-folder-name) ; from wanderlust
3218 (defvar gnus-group-name) ; from gnus
3219 (defvar gnus-article-current) ; from gnus
3220 (defvar w3m-current-url) ; from w3m
3221 (defvar w3m-current-title) ; from w3m
3222 (defvar mh-progs) ; from MH-E
3223 (defvar mh-current-folder) ; from MH-E
3224 (defvar mh-show-folder-buffer) ; from MH-E
3225 (defvar mh-index-folder) ; from MH-E
3226 (defvar mh-searcher) ; from MH-E
3227 (defvar org-selected-point) ; dynamically scoped parameter
3228 (defvar calendar-mode-map) ; from calendar.el
3229 (defvar last-arg) ; local variable
3230 (defvar remember-save-after-remembering) ; from remember.el
3231 (defvar remember-data-file) ; from remember.el
3232 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3233 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3234 (defvar orgtbl-mode) ; defined later in this file
3235 (defvar Info-current-file) ; from info.el
3236 (defvar Info-current-node) ; from info.el
3237 (defvar texmathp-why) ; from texmathp.el
3238 (defvar org-latex-regexps)
3239 (defvar outline-mode-menu-heading)
3240 (defvar outline-mode-menu-show)
3241 (defvar outline-mode-menu-hide)
3242 (defvar org-agenda-undo-list) ;; Defined later in this file
3243 (defvar org-agenda-pending-undo-list) ;; Defined later in this file
3244 (defvar org-agenda-overriding-header) ;; Defined later in this file
3246 ;;;; Define the mode
3248 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3249 (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."))
3251 (defvar org-struct-menu) ; defined later in this file
3252 (defvar org-org-menu) ; defined later in this file
3253 (defvar org-tbl-menu) ; defined later in this file
3255 ;; We use a before-change function to check if a table might need
3256 ;; an update.
3257 (defvar org-table-may-need-update t
3258 "Indicates that a table might need an update.
3259 This variable is set by `org-before-change-function'.
3260 `org-table-align' sets it back to nil.")
3261 (defvar org-mode-map)
3262 (defvar org-mode-hook nil)
3263 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3264 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3267 ;;;###autoload
3268 (define-derived-mode org-mode outline-mode "Org"
3269 "Outline-based notes management and organizer, alias
3270 \"Carsten's outline-mode for keeping track of everything.\"
3272 Org-mode develops organizational tasks around a NOTES file which
3273 contains information about projects as plain text. Org-mode is
3274 implemented on top of outline-mode, which is ideal to keep the content
3275 of large files well structured. It supports ToDo items, deadlines and
3276 time stamps, which magically appear in the diary listing of the Emacs
3277 calendar. Tables are easily created with a built-in table editor.
3278 Plain text URL-like links connect to websites, emails (VM), Usenet
3279 messages (Gnus), BBDB entries, and any files related to the project.
3280 For printing and sharing of notes, an Org-mode file (or a part of it)
3281 can be exported as a structured ASCII or HTML file.
3283 The following commands are available:
3285 \\{org-mode-map}"
3287 ;; Get rid of Outline menus, they are not needed
3288 ;; Need to do this here because define-derived-mode sets up
3289 ;; the keymap so late. Still, it is a waste to call this each time
3290 ;; we switch another buffer into org-mode.
3291 (if (featurep 'xemacs)
3292 (when (boundp 'outline-mode-menu-heading)
3293 ;; Assume this is Greg's port, it used easymenu
3294 (easy-menu-remove outline-mode-menu-heading)
3295 (easy-menu-remove outline-mode-menu-show)
3296 (easy-menu-remove outline-mode-menu-hide))
3297 (define-key org-mode-map [menu-bar headings] 'undefined)
3298 (define-key org-mode-map [menu-bar hide] 'undefined)
3299 (define-key org-mode-map [menu-bar show] 'undefined))
3301 (easy-menu-add org-org-menu)
3302 (easy-menu-add org-tbl-menu)
3303 (org-install-agenda-files-menu)
3304 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3305 (org-add-to-invisibility-spec '(org-cwidth))
3306 (when (featurep 'xemacs)
3307 (org-set-local 'line-move-ignore-invisible t))
3308 (setq outline-regexp "\\*+")
3309 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
3310 (setq outline-level 'org-outline-level)
3311 (when (and org-ellipsis (stringp org-ellipsis))
3312 (unless org-display-table
3313 (setq org-display-table (make-display-table)))
3314 (set-display-table-slot org-display-table
3315 4 (string-to-vector org-ellipsis))
3316 (setq buffer-display-table org-display-table))
3317 (org-set-regexps-and-options)
3318 ;; Calc embedded
3319 (org-set-local 'calc-embedded-open-mode "# ")
3320 (modify-syntax-entry ?# "<")
3321 (if org-startup-truncated (setq truncate-lines t))
3322 (org-set-local 'font-lock-unfontify-region-function
3323 'org-unfontify-region)
3324 ;; Activate before-change-function
3325 (org-set-local 'org-table-may-need-update t)
3326 (org-add-hook 'before-change-functions 'org-before-change-function nil
3327 'local)
3328 ;; Check for running clock before killing a buffer
3329 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3330 ;; Paragraphs and auto-filling
3331 (org-set-autofill-regexps)
3332 (org-update-radio-target-regexp)
3334 (if (and org-insert-mode-line-in-empty-file
3335 (interactive-p)
3336 (= (point-min) (point-max)))
3337 (insert " -*- mode: org -*-\n\n"))
3339 (unless org-inhibit-startup
3340 (when org-startup-align-all-tables
3341 (let ((bmp (buffer-modified-p)))
3342 (org-table-map-tables 'org-table-align)
3343 (set-buffer-modified-p bmp)))
3344 (if org-startup-with-deadline-check
3345 (call-interactively 'org-check-deadlines)
3346 (cond
3347 ((eq org-startup-folded t)
3348 (org-cycle '(4)))
3349 ((eq org-startup-folded 'content)
3350 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3351 (org-cycle '(4)) (org-cycle '(4))))))))
3353 (defsubst org-call-with-arg (command arg)
3354 "Call COMMAND interactively, but pretend prefix are was ARG."
3355 (let ((current-prefix-arg arg)) (call-interactively command)))
3357 (defsubst org-current-line (&optional pos)
3358 (save-excursion
3359 (and pos (goto-char pos))
3360 (+ (if (bolp) 1 0) (count-lines (point-min) (point)))))
3362 (defun org-current-time ()
3363 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3364 (if (> org-time-stamp-rounding-minutes 0)
3365 (let ((r org-time-stamp-rounding-minutes)
3366 (time (decode-time)))
3367 (apply 'encode-time
3368 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3369 (nthcdr 2 time))))
3370 (current-time)))
3372 (defun org-add-props (string plist &rest props)
3373 "Add text properties to entire string, from beginning to end.
3374 PLIST may be a list of properties, PROPS are individual properties and values
3375 that will be added to PLIST. Returns the string that was modified."
3376 (add-text-properties
3377 0 (length string) (if props (append plist props) plist) string)
3378 string)
3379 (put 'org-add-props 'lisp-indent-function 2)
3382 ;;;; Font-Lock stuff
3384 (defvar org-mouse-map (make-sparse-keymap))
3385 (define-key org-mouse-map
3386 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3387 (define-key org-mouse-map
3388 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3389 (when org-mouse-1-follows-link
3390 (define-key org-mouse-map [follow-link] 'mouse-face))
3391 (when org-tab-follows-link
3392 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3393 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3394 (when org-return-follows-link
3395 (define-key org-mouse-map [(return)] 'org-open-at-point)
3396 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3398 (require 'font-lock)
3400 (defconst org-non-link-chars "]\t\n\r<>")
3401 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3402 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3403 (defconst org-link-re-with-space
3404 (concat
3405 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3406 "\\([^" org-non-link-chars " ]"
3407 "[^" org-non-link-chars "]*"
3408 "[^" org-non-link-chars " ]\\)>?")
3409 "Matches a link with spaces, optional angular brackets around it.")
3411 (defconst org-link-re-with-space2
3412 (concat
3413 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3414 "\\([^" org-non-link-chars " ]"
3415 "[^]\t\n\r]*"
3416 "[^" org-non-link-chars " ]\\)>?")
3417 "Matches a link with spaces, optional angular brackets around it.")
3419 (defconst org-angle-link-re
3420 (concat
3421 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3422 "\\([^" org-non-link-chars " ]"
3423 "[^" org-non-link-chars "]*"
3424 "\\)>")
3425 "Matches link with angular brackets, spaces are allowed.")
3426 (defconst org-plain-link-re
3427 (concat
3428 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3429 "\\([^]\t\n\r<>,;() ]+\\)")
3430 "Matches plain link, without spaces.")
3432 (defconst org-bracket-link-regexp
3433 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3434 "Matches a link in double brackets.")
3436 (defconst org-bracket-link-analytic-regexp
3437 (concat
3438 "\\[\\["
3439 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3440 "\\([^]]+\\)"
3441 "\\]"
3442 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3443 "\\]"))
3444 ; 1: http:
3445 ; 2: http
3446 ; 3: path
3447 ; 4: [desc]
3448 ; 5: desc
3450 (defconst org-ts-lengths
3451 (cons (length (format-time-string (car org-time-stamp-formats)))
3452 (length (format-time-string (cdr org-time-stamp-formats))))
3453 "This holds the lengths of the two different time formats.")
3454 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3455 "Regular expression for fast time stamp matching.")
3456 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3457 "Regular expression for fast time stamp matching.")
3458 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3459 "Regular expression matching time strings for analysis.")
3460 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3461 "Regular expression matching time stamps, with groups.")
3462 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3463 "Regular expression matching time stamps (also [..]), with groups.")
3464 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3465 "Regular expression matching a time stamp range.")
3466 (defconst org-tr-regexp-both
3467 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3468 "Regular expression matching a time stamp range.")
3469 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3470 org-ts-regexp "\\)?")
3471 "Regular expression matching a time stamp or time stamp range.")
3472 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3473 org-ts-regexp-both "\\)?")
3474 "Regular expression matching a time stamp or time stamp range.
3475 The time stamps may be either active or inactive.")
3477 (defvar org-emph-face nil)
3479 (defun org-do-emphasis-faces (limit)
3480 "Run through the buffer and add overlays to links."
3481 (if (re-search-forward org-emph-re limit t)
3482 (progn
3483 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3484 'face
3485 (nth 1 (assoc (match-string 3)
3486 org-emphasis-alist)))
3487 (add-text-properties (match-beginning 2) (match-end 2)
3488 '(font-lock-multiline t))
3489 (backward-char 1)
3490 t)))
3492 (defun org-activate-plain-links (limit)
3493 "Run through the buffer and add overlays to links."
3494 (if (re-search-forward org-plain-link-re limit t)
3495 (progn
3496 (add-text-properties (match-beginning 0) (match-end 0)
3497 (list 'mouse-face 'highlight
3498 'rear-nonsticky t
3499 'keymap org-mouse-map
3501 t)))
3503 (defun org-activate-angle-links (limit)
3504 "Run through the buffer and add overlays to links."
3505 (if (re-search-forward org-angle-link-re limit t)
3506 (progn
3507 (add-text-properties (match-beginning 0) (match-end 0)
3508 (list 'mouse-face 'highlight
3509 'rear-nonsticky t
3510 'keymap org-mouse-map
3512 t)))
3514 (defmacro org-maybe-intangible (props)
3515 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3516 In emacs 21, invisible text is not avoided by the command loop, so the
3517 intangible property is needed to make sure point skips this text.
3518 In Emacs 22, this is not necessary. The intangible text property has
3519 led to problems with flyspell. These problems are fixed in flyspell.el,
3520 but we still avoid setting the property in Emacs 22 and later.
3521 We use a macro so that the test can happen at compilation time."
3522 (if (< emacs-major-version 22)
3523 `(append '(intangible t) ,props)
3524 props))
3526 (defun org-activate-bracket-links (limit)
3527 "Run through the buffer and add overlays to bracketed links."
3528 (if (re-search-forward org-bracket-link-regexp limit t)
3529 (let* ((help (concat "LINK: "
3530 (org-match-string-no-properties 1)))
3531 ;; FIXME: above we should remove the escapes.
3532 ;; but that requires another match, protecting match data,
3533 ;; a lot of overhead for font-lock.
3534 (ip (org-maybe-intangible
3535 (list 'invisible 'org-link 'rear-nonsticky t
3536 'keymap org-mouse-map 'mouse-face 'highlight
3537 'help-echo help)))
3538 (vp (list 'rear-nonsticky t
3539 'keymap org-mouse-map 'mouse-face 'highlight
3540 'help-echo help)))
3541 ;; We need to remove the invisible property here. Table narrowing
3542 ;; may have made some of this invisible.
3543 (remove-text-properties (match-beginning 0) (match-end 0)
3544 '(invisible nil))
3545 (if (match-end 3)
3546 (progn
3547 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3548 (add-text-properties (match-beginning 3) (match-end 3) vp)
3549 (add-text-properties (match-end 3) (match-end 0) ip))
3550 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3551 (add-text-properties (match-beginning 1) (match-end 1) vp)
3552 (add-text-properties (match-end 1) (match-end 0) ip))
3553 t)))
3555 (defun org-activate-dates (limit)
3556 "Run through the buffer and add overlays to dates."
3557 ; (if (re-search-forward org-tsr-regexp limit t)
3558 ; (if (re-search-forward
3559 ; (if org-display-custom-times org-ts-regexp-both org-tsr-regexp-both)
3560 ; limit t)
3561 (if (re-search-forward org-tsr-regexp-both limit t)
3562 (progn
3563 (add-text-properties (match-beginning 0) (match-end 0)
3564 (list 'mouse-face 'highlight
3565 'rear-nonsticky t
3566 'keymap org-mouse-map))
3567 (when org-display-custom-times
3568 (if (match-end 3)
3569 (org-display-custom-time (match-beginning 3) (match-end 3)))
3570 (org-display-custom-time (match-beginning 1) (match-end 1)))
3571 t)))
3573 (defvar org-target-link-regexp nil
3574 "Regular expression matching radio targets in plain text.")
3575 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3576 "Regular expression matching a link target.")
3577 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3578 "Regular expression matching a link target.")
3580 (defun org-activate-target-links (limit)
3581 "Run through the buffer and add overlays to target matches."
3582 (when org-target-link-regexp
3583 (let ((case-fold-search t))
3584 (if (re-search-forward org-target-link-regexp limit t)
3585 (progn
3586 (add-text-properties (match-beginning 0) (match-end 0)
3587 (list 'mouse-face 'highlight
3588 'rear-nonsticky t
3589 'keymap org-mouse-map
3590 'help-echo "Radio target link"
3591 'org-linked-text t))
3592 t)))))
3594 (defun org-update-radio-target-regexp ()
3595 "Find all radio targets in this file and update the regular expression."
3596 (interactive)
3597 (when (memq 'radio org-activate-links)
3598 (setq org-target-link-regexp
3599 (org-make-target-link-regexp (org-all-targets 'radio)))
3600 (org-restart-font-lock)))
3602 (defun org-hide-wide-columns (limit)
3603 (let (s e)
3604 (setq s (text-property-any (point) (or limit (point-max))
3605 'org-cwidth t))
3606 (when s
3607 (setq e (next-single-property-change s 'org-cwidth))
3608 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3609 (goto-char e)
3610 t)))
3612 (defun org-restart-font-lock ()
3613 "Restart font-lock-mode, to force refontification."
3614 (when (and (boundp 'font-lock-mode) font-lock-mode)
3615 (font-lock-mode -1)
3616 (font-lock-mode 1)))
3618 (defun org-all-targets (&optional radio)
3619 "Return a list of all targets in this file.
3620 With optional argument RADIO, only find radio targets."
3621 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3622 rtn)
3623 (save-excursion
3624 (goto-char (point-min))
3625 (while (re-search-forward re nil t)
3626 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3627 rtn)))
3629 (defun org-make-target-link-regexp (targets)
3630 "Make regular expression matching all strings in TARGETS.
3631 The regular expression finds the targets also if there is a line break
3632 between words."
3633 (and targets
3634 (concat
3635 "\\<\\("
3636 (mapconcat
3637 (lambda (x)
3638 (while (string-match " +" x)
3639 (setq x (replace-match "\\s-+" t t x)))
3641 targets
3642 "\\|")
3643 "\\)\\>")))
3645 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3646 "Matches CamelCase words, possibly with a star before it.")
3648 (defun org-activate-camels (limit)
3649 "Run through the buffer and add overlays to dates."
3650 (if (re-search-forward org-camel-regexp limit t)
3651 (progn
3652 (add-text-properties (match-beginning 0) (match-end 0)
3653 (list 'mouse-face 'highlight
3654 'rear-nonsticky t
3655 'keymap org-mouse-map))
3656 t)))
3658 (defun org-activate-tags (limit)
3659 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3660 (progn
3661 (add-text-properties (match-beginning 1) (match-end 1)
3662 (list 'mouse-face 'highlight
3663 'rear-nonsticky t
3664 'keymap org-mouse-map))
3665 t)))
3667 (defun org-font-lock-level ()
3668 (save-excursion
3669 (org-back-to-heading t)
3670 (- (match-end 0) (match-beginning 0))))
3672 (defun org-outline-level ()
3673 (save-excursion
3674 (looking-at outline-regexp)
3675 (if (match-beginning 1)
3676 (+ (org-get-string-indentation (match-string 1)) 1000)
3677 (- (match-end 0) (match-beginning 0)))))
3679 (defvar org-font-lock-keywords nil)
3681 (defun org-set-font-lock-defaults ()
3682 (let* ((em org-fontify-emphasized-text)
3683 (lk org-activate-links)
3684 (org-font-lock-extra-keywords
3685 ;; Headlines
3686 (list
3687 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3688 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3689 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3690 (1 'org-table))
3691 ;; Links
3692 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3693 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3694 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3695 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3696 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3697 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3698 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3699 (if org-table-limit-column-width
3700 '(org-hide-wide-columns (0 nil append)))
3701 ;; TODO lines
3702 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3703 '(1 'org-todo t))
3704 ;; Priorities
3705 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3706 ;; Special keywords
3707 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3708 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3709 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3710 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3711 ;; Emphasis
3712 (if em
3713 (if (featurep 'xemacs)
3714 '(org-do-emphasis-faces (0 nil append))
3715 '(org-do-emphasis-faces)))
3716 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3717 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3718 2 'bold prepend)
3719 (if org-provide-checkbox-statistics
3720 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3721 (0 (org-get-checkbox-statistics-face) t)))
3722 ;; COMMENT
3723 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3724 "\\|" org-quote-string "\\)\\>")
3725 '(1 'org-special-keyword t))
3726 '("^#.*" (0 'font-lock-comment-face t))
3727 ;; DONE
3728 (if org-fontify-done-headline
3729 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3730 '(1 'org-done t) '(2 'org-headline-done t))
3731 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3732 '(1 'org-done t)))
3733 ;; Table stuff
3734 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3735 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3736 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3737 (if org-format-transports-properties-p
3738 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3739 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3741 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3742 ;; Now set the full font-lock-keywords
3743 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3744 (org-set-local 'font-lock-defaults
3745 '(org-font-lock-keywords t nil nil backward-paragraph))
3746 (kill-local-variable 'font-lock-keywords) nil))
3748 (defvar org-m nil)
3749 (defvar org-l nil)
3750 (defvar org-f nil)
3751 (defun org-get-level-face (n)
3752 "Get the right face for match N in font-lock matching of healdines."
3753 (setq org-l (- (match-end 2) (match-beginning 1)))
3754 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3755 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3756 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3757 (cond
3758 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3759 ((eq n 2) org-f)
3760 (t (if org-level-color-stars-only nil org-f))))
3762 (defun org-unfontify-region (beg end &optional maybe_loudly)
3763 "Remove fontification and activation overlays from links."
3764 (font-lock-default-unfontify-region beg end)
3765 (let* ((buffer-undo-list t)
3766 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3767 (inhibit-modification-hooks t)
3768 deactivate-mark buffer-file-name buffer-file-truename)
3769 (remove-text-properties beg end
3770 '(mouse-face t keymap t org-linked-text t
3771 rear-nonsticky t
3772 invisible t intangible t))))
3774 ;;;; Visibility cycling
3776 (defvar org-cycle-global-status nil)
3777 (make-variable-buffer-local 'org-cycle-global-status)
3778 (defvar org-cycle-subtree-status nil)
3779 (make-variable-buffer-local 'org-cycle-subtree-status)
3781 ;;;###autoload
3782 (defun org-cycle (&optional arg)
3783 "Visibility cycling for Org-mode.
3785 - When this function is called with a prefix argument, rotate the entire
3786 buffer through 3 states (global cycling)
3787 1. OVERVIEW: Show only top-level headlines.
3788 2. CONTENTS: Show all headlines of all levels, but no body text.
3789 3. SHOW ALL: Show everything.
3791 - When point is at the beginning of a headline, rotate the subtree started
3792 by this line through 3 different states (local cycling)
3793 1. FOLDED: Only the main headline is shown.
3794 2. CHILDREN: The main headline and the direct children are shown.
3795 From this state, you can move to one of the children
3796 and zoom in further.
3797 3. SUBTREE: Show the entire subtree, including body text.
3799 - When there is a numeric prefix, go up to a heading with level ARG, do
3800 a `show-subtree' and return to the previous cursor position. If ARG
3801 is negative, go up that many levels.
3803 - When point is not at the beginning of a headline, execute
3804 `indent-relative', like TAB normally does. See the option
3805 `org-cycle-emulate-tab' for details.
3807 - Special case: if point is the the beginning of the buffer and there is
3808 no headline in line 1, this function will act as if called with prefix arg."
3809 (interactive "P")
3810 (let* ((outline-regexp
3811 (if (and (org-mode-p) org-cycle-include-plain-lists)
3812 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3813 outline-regexp))
3814 (bob-special (and org-cycle-global-at-bob (bobp)
3815 (not (looking-at outline-regexp))))
3816 (org-cycle-hook
3817 (if bob-special
3818 (delq 'org-optimize-window-after-visibility-change
3819 (copy-sequence org-cycle-hook))
3820 org-cycle-hook))
3821 (pos (point)))
3823 (if (or bob-special (equal arg '(4)))
3824 ;; special case: use global cycling
3825 (setq arg t))
3827 (cond
3829 ((org-at-table-p 'any)
3830 ;; Enter the table or move to the next field in the table
3831 (or (org-table-recognize-table.el)
3832 (progn
3833 (if arg (org-table-edit-field t)
3834 (org-table-justify-field-maybe)
3835 (call-interactively 'org-table-next-field)))))
3837 ((eq arg t) ;; Global cycling
3839 (cond
3840 ((and (eq last-command this-command)
3841 (eq org-cycle-global-status 'overview))
3842 ;; We just created the overview - now do table of contents
3843 ;; This can be slow in very large buffers, so indicate action
3844 (message "CONTENTS...")
3845 (org-content)
3846 (message "CONTENTS...done")
3847 (setq org-cycle-global-status 'contents)
3848 (run-hook-with-args 'org-cycle-hook 'contents))
3850 ((and (eq last-command this-command)
3851 (eq org-cycle-global-status 'contents))
3852 ;; We just showed the table of contents - now show everything
3853 (show-all)
3854 (message "SHOW ALL")
3855 (setq org-cycle-global-status 'all)
3856 (run-hook-with-args 'org-cycle-hook 'all))
3859 ;; Default action: go to overview
3860 (org-overview)
3861 (message "OVERVIEW")
3862 (setq org-cycle-global-status 'overview)
3863 (run-hook-with-args 'org-cycle-hook 'overview))))
3865 ((integerp arg)
3866 ;; Show-subtree, ARG levels up from here.
3867 (save-excursion
3868 (org-back-to-heading)
3869 (outline-up-heading (if (< arg 0) (- arg)
3870 (- (funcall outline-level) arg)))
3871 (org-show-subtree)))
3873 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3874 ;; At a heading: rotate between three different views
3875 (org-back-to-heading)
3876 (let ((goal-column 0) eoh eol eos)
3877 ;; First, some boundaries
3878 (save-excursion
3879 (org-back-to-heading)
3880 (save-excursion
3881 (beginning-of-line 2)
3882 (while (and (not (eobp)) ;; this is like `next-line'
3883 (get-char-property (1- (point)) 'invisible))
3884 (beginning-of-line 2)) (setq eol (point)))
3885 (outline-end-of-heading) (setq eoh (point))
3886 (org-end-of-subtree t) (setq eos (point))
3887 (outline-next-heading))
3888 ;; Find out what to do next and set `this-command'
3889 (cond
3890 ((and (= eos eoh)
3891 ;; Nothing is hidden behind this heading
3892 (message "EMPTY ENTRY")
3893 (setq org-cycle-subtree-status nil)))
3894 ((>= eol eos)
3895 ;; Entire subtree is hidden in one line: open it
3896 (org-show-entry)
3897 (show-children)
3898 (message "CHILDREN")
3899 (setq org-cycle-subtree-status 'children)
3900 (run-hook-with-args 'org-cycle-hook 'children))
3901 ((and (eq last-command this-command)
3902 (eq org-cycle-subtree-status 'children))
3903 ;; We just showed the children, now show everything.
3904 (org-show-subtree)
3905 (message "SUBTREE")
3906 (setq org-cycle-subtree-status 'subtree)
3907 (run-hook-with-args 'org-cycle-hook 'subtree))
3909 ;; Default action: hide the subtree.
3910 (hide-subtree)
3911 (message "FOLDED")
3912 (setq org-cycle-subtree-status 'folded)
3913 (run-hook-with-args 'org-cycle-hook 'folded)))))
3915 ;; TAB emulation
3916 (buffer-read-only (org-back-to-heading))
3918 ((org-try-cdlatex-tab))
3920 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3921 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3922 (or (and (eq org-cycle-emulate-tab 'white)
3923 (= (match-end 0) (point-at-eol)))
3924 (and (eq org-cycle-emulate-tab 'whitestart)
3925 (>= (match-end 0) pos))))
3927 (eq org-cycle-emulate-tab t))
3928 (if (and (looking-at "[ \n\r\t]")
3929 (string-match "^[ \t]*$" (buffer-substring
3930 (point-at-bol) (point))))
3931 (progn
3932 (beginning-of-line 1)
3933 (and (looking-at "[ \t]+") (replace-match ""))))
3934 (indent-relative))
3936 (t (save-excursion
3937 (org-back-to-heading)
3938 (org-cycle))))))
3940 ;;;###autoload
3941 (defun org-global-cycle (&optional arg)
3942 "Cycle the global visibility. For details see `org-cycle'."
3943 (interactive "P")
3944 (let ((org-cycle-include-plain-lists
3945 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3946 (if (integerp arg)
3947 (progn
3948 (show-all)
3949 (hide-sublevels arg)
3950 (setq org-cycle-global-status 'contents))
3951 (org-cycle '(4)))))
3953 (defun org-overview ()
3954 "Switch to overview mode, shoing only top-level headlines.
3955 Really, this shows all headlines with level equal or greater than the level
3956 of the first headline in the buffer. This is important, because if the
3957 first headline is not level one, then (hide-sublevels 1) gives confusing
3958 results."
3959 (interactive)
3960 (hide-sublevels (save-excursion
3961 (goto-char (point-min))
3962 (if (re-search-forward (concat "^" outline-regexp) nil t)
3963 (progn
3964 (goto-char (match-beginning 0))
3965 (funcall outline-level))
3966 1))))
3968 ;; FIXME: allow an argument to give a limiting level for this.
3969 (defun org-content ()
3970 "Show all headlines in the buffer, like a table of contents"
3971 (interactive)
3972 (save-excursion
3973 ;; Visit all headings and show their offspring
3974 (goto-char (point-max))
3975 (catch 'exit
3976 (while (and (progn (condition-case nil
3977 (outline-previous-visible-heading 1)
3978 (error (goto-char (point-min))))
3980 (looking-at outline-regexp))
3981 (show-branches)
3982 (if (bobp) (throw 'exit nil))))))
3985 (defun org-optimize-window-after-visibility-change (state)
3986 "Adjust the window after a change in outline visibility.
3987 This function is the default value of the hook `org-cycle-hook'."
3988 (when (get-buffer-window (current-buffer))
3989 (cond
3990 ((eq state 'overview) (org-first-headline-recenter 1))
3991 ((eq state 'content) nil)
3992 ((eq state 'all) nil)
3993 ((eq state 'folded) nil)
3994 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3995 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3997 (defun org-subtree-end-visible-p ()
3998 "Is the end of the current subtree visible?"
3999 (pos-visible-in-window-p
4000 (save-excursion (org-end-of-subtree t) (point))))
4002 (defun org-first-headline-recenter (&optional N)
4003 "Move cursor to the first headline and recenter the headline.
4004 Optional argument N means, put the headline into the Nth line of the window."
4005 (goto-char (point-min))
4006 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4007 (beginning-of-line)
4008 (recenter (prefix-numeric-value N))))
4010 (defvar org-goto-window-configuration nil)
4011 (defvar org-goto-marker nil)
4012 (defvar org-goto-map (make-sparse-keymap))
4013 (let ((cmds '(isearch-forward isearch-backward)) cmd)
4014 (while (setq cmd (pop cmds))
4015 (substitute-key-definition cmd cmd org-goto-map global-map)))
4016 (define-key org-goto-map "\C-m" 'org-goto-ret)
4017 (define-key org-goto-map [(left)] 'org-goto-left)
4018 (define-key org-goto-map [(right)] 'org-goto-right)
4019 (define-key org-goto-map [(?q)] 'org-goto-quit)
4020 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
4021 (define-key org-goto-map "\C-i" 'org-cycle)
4022 (define-key org-goto-map [(tab)] 'org-cycle)
4023 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
4024 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
4025 (define-key org-goto-map "n" 'outline-next-visible-heading)
4026 (define-key org-goto-map "p" 'outline-previous-visible-heading)
4027 (define-key org-goto-map "f" 'outline-forward-same-level)
4028 (define-key org-goto-map "b" 'outline-backward-same-level)
4029 (define-key org-goto-map "u" 'outline-up-heading)
4030 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
4031 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
4032 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
4033 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
4034 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
4035 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4036 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
4038 (defconst org-goto-help
4039 "Select a location to jump to, press RET
4040 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
4042 (defun org-goto ()
4043 "Go to a different location of the document, keeping current visibility.
4045 When you want to go to a different location in a document, the fastest way
4046 is often to fold the entire buffer and then dive into the tree. This
4047 method has the disadvantage, that the previous location will be folded,
4048 which may not be what you want.
4050 This command works around this by showing a copy of the current buffer in
4051 overview mode. You can dive into the tree in that copy, to find the
4052 location you want to reach. When pressing RET, the command returns to the
4053 original buffer in which the visibility is still unchanged. It then jumps
4054 to the new location, making it and the headline hierarchy above it visible."
4055 (interactive)
4056 (let* ((org-goto-start-pos (point))
4057 (selected-point
4058 (org-get-location (current-buffer) org-goto-help)))
4059 (if selected-point
4060 (progn
4061 (org-mark-ring-push org-goto-start-pos)
4062 (goto-char selected-point)
4063 (if (or (org-invisible-p) (org-invisible-p2))
4064 (org-show-context 'org-goto)))
4065 (error "Quit"))))
4067 (defun org-get-location (buf help)
4068 "Let the user select a location in the Org-mode buffer BUF.
4069 This function uses a recursive edit. It returns the selected position
4070 or nil."
4071 (let (org-selected-point)
4072 (save-excursion
4073 (save-window-excursion
4074 (delete-other-windows)
4075 (switch-to-buffer (get-buffer-create "*org-goto*"))
4076 (with-output-to-temp-buffer "*Help*"
4077 (princ help))
4078 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4079 (setq buffer-read-only nil)
4080 (erase-buffer)
4081 (insert-buffer-substring buf)
4082 (let ((org-startup-truncated t)
4083 (org-startup-folded t)
4084 (org-startup-align-all-tables nil)
4085 (org-startup-with-deadline-check nil))
4086 (org-mode))
4087 (setq buffer-read-only t)
4088 (if (boundp 'org-goto-start-pos)
4089 (goto-char org-goto-start-pos)
4090 (goto-char (point-min)))
4091 (org-beginning-of-line)
4092 (message "Select location and press RET")
4093 ;; now we make sure that during selection, ony very few keys work
4094 ;; and that it is impossible to switch to another window.
4095 (let ((gm (current-global-map))
4096 (overriding-local-map org-goto-map))
4097 (unwind-protect
4098 (progn
4099 (use-global-map org-goto-map)
4100 (recursive-edit))
4101 (use-global-map gm)))))
4102 (kill-buffer "*org-goto*")
4103 org-selected-point))
4105 (defun org-goto-ret (&optional arg)
4106 "Finish `org-goto' by going to the new location."
4107 (interactive "P")
4108 (setq org-selected-point (point)
4109 current-prefix-arg arg)
4110 (throw 'exit nil))
4112 (defun org-goto-left ()
4113 "Finish `org-goto' by going to the new location."
4114 (interactive)
4115 (if (org-on-heading-p)
4116 (progn
4117 (beginning-of-line 1)
4118 (setq org-selected-point (point)
4119 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4120 (throw 'exit nil))
4121 (error "Not on a heading")))
4123 (defun org-goto-right ()
4124 "Finish `org-goto' by going to the new location."
4125 (interactive)
4126 (if (org-on-heading-p)
4127 (progn
4128 (outline-end-of-subtree)
4129 (or (eobp) (forward-char 1))
4130 (setq org-selected-point (point)
4131 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4132 (throw 'exit nil))
4133 (error "Not on a heading")))
4135 (defun org-goto-quit ()
4136 "Finish `org-goto' without cursor motion."
4137 (interactive)
4138 (setq org-selected-point nil)
4139 (throw 'exit nil))
4141 ;;; Indirect buffer display of subtrees
4143 (defvar org-indirect-dedicated-frame nil
4144 "This is the frame being used for indirect tree display.")
4145 (defvar org-last-indirect-buffer nil)
4147 (defun org-tree-to-indirect-buffer (&optional arg)
4148 "Create indirect buffer and narrow it to current subtree.
4149 With numerical prefix arg ARG, go up to this level and then take that tree.
4150 If ARG is negative, go up that many levels.
4151 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
4152 dedicated frame)."
4153 (interactive "P")
4154 (let ((cbuf (current-buffer))
4155 (pos (point))
4156 (bname (buffer-name (current-buffer)))
4157 (org-indirect-tree-new-frame
4158 (if (equal arg '(4)) t org-indirect-tree-new-frame))
4159 beg end level heading)
4161 (save-excursion
4162 (org-back-to-heading t)
4163 (when (numberp arg)
4164 (setq level (org-outline-level))
4165 (if (< arg 0) (setq arg (+ level arg)))
4166 (while (> (setq level (org-outline-level)) arg)
4167 (outline-up-heading 1 t)))
4168 (setq beg (point)
4169 heading (org-get-heading))
4170 (org-end-of-subtree t) (setq end (point)))
4171 (cond
4172 ((eq org-indirect-tree-new-frame 'dedicated)
4173 (raise-frame
4174 (select-frame (or (and org-indirect-dedicated-frame
4175 (frame-live-p org-indirect-dedicated-frame)
4176 org-indirect-dedicated-frame)
4177 (setq org-indirect-dedicated-frame (make-frame)))))
4178 (delete-other-windows)
4179 (if (equal cbuf (buffer-base-buffer))
4180 ;; Re-use this buffer
4181 (widen)
4182 ;; clean up from last time
4183 (if (buffer-base-buffer (current-buffer))
4184 (kill-buffer (current-buffer)))
4185 (if (buffer-live-p org-last-indirect-buffer)
4186 (kill-buffer org-last-indirect-buffer))
4187 ;; make and select the new indirect buffer
4188 (switch-to-buffer
4189 (setq org-last-indirect-buffer (org-get-indirect-buffer cbuf))))
4190 (org-set-frame-title (concat "Indirect: " heading)))
4191 ((eq org-indirect-tree-new-frame t)
4192 (select-frame (make-frame))
4193 (delete-other-windows)
4194 (switch-to-buffer (org-get-indirect-buffer cbuf))
4195 (org-set-frame-title heading))
4196 (t (pop-to-buffer (org-get-indirect-buffer cbuf))))
4197 (if (featurep 'xemacs)
4198 (save-excursion (org-mode) (turn-on-font-lock)))
4199 (narrow-to-region beg end)
4200 (show-all)
4201 (goto-char pos)))
4203 (defun org-get-indirect-buffer (&optional buffer)
4204 (setq buffer (or buffer (current-buffer)))
4205 (let ((n 1) (base (buffer-name buffer)) bname)
4206 (while (buffer-live-p
4207 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4208 (setq n (1+ n)))
4209 (condition-case nil
4210 (make-indirect-buffer buffer bname 'clone)
4211 (error (make-indirect-buffer buffer bname)))))
4213 (defun org-set-frame-title (title)
4214 "Set the title of the current frame to the string TITLE."
4215 ;; FIXME: how to name a single frame in XEmacs???
4216 (unless (featurep 'xemacs)
4217 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4219 ;;;; Promotion, Demotion, Inserting new headlines
4221 (defvar org-ignore-region nil
4222 "To temporarily disable the active region.")
4224 (defun org-insert-heading (&optional force-heading)
4225 "Insert a new heading or item with same depth at point.
4226 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4227 If point is at the beginning of a headline, insert a sibling before the
4228 current headline. If point is in the middle of a headline, split the headline
4229 at that position and make the rest of the headline part of the sibling below
4230 the current headline."
4231 (interactive "P")
4232 (if (= (buffer-size) 0)
4233 (insert "\n* ")
4234 (when (or force-heading (not (org-insert-item)))
4235 (let* ((head (save-excursion
4236 (condition-case nil
4237 (progn
4238 (org-back-to-heading)
4239 (match-string 0))
4240 (error "*"))))
4241 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4242 pos)
4243 (cond
4244 ((and (org-on-heading-p) (bolp)
4245 (save-excursion (backward-char 1) (not (org-invisible-p))))
4246 (open-line (if blank 2 1)))
4247 ((and (bolp) (save-excursion
4248 (backward-char 1) (not (org-invisible-p))))
4249 nil)
4250 (t (newline (if blank 2 1))))
4251 (insert head) (just-one-space)
4252 (setq pos (point))
4253 (end-of-line 1)
4254 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4255 (run-hooks 'org-insert-heading-hook)))))
4257 (defun org-in-item-p ()
4258 "It the cursor inside a plain list item.
4259 Does not have to be the first line."
4260 (save-excursion
4261 (condition-case nil
4262 (progn
4263 (org-beginning-of-item)
4264 (org-at-item-p)
4266 (error nil))))
4268 (defun org-insert-item (&optional checkbox)
4269 "Insert a new item at the current level.
4270 Return t when things worked, nil when we are not in an item."
4271 (when (save-excursion
4272 (condition-case nil
4273 (progn
4274 (org-beginning-of-item)
4275 (org-at-item-p)
4276 (if (org-invisible-p) (error "Invisible item"))
4278 (error nil)))
4279 (let* ((bul (match-string 0))
4280 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
4281 (match-end 0)))
4282 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
4283 pos)
4284 (cond
4285 ((and (org-at-item-p) (<= (point) eow))
4286 ;; before the bullet
4287 (beginning-of-line 1)
4288 (open-line (if blank 2 1)))
4289 ((<= (point) eow)
4290 (beginning-of-line 1))
4291 (t (newline (if blank 2 1))))
4292 (insert bul (if checkbox "[ ]" ""))
4293 (just-one-space)
4294 (setq pos (point))
4295 (end-of-line 1)
4296 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
4297 (org-maybe-renumber-ordered-list)
4298 (and checkbox (org-update-checkbox-count-maybe))
4301 (defun org-insert-todo-heading (arg)
4302 "Insert a new heading with the same level and TODO state as current heading.
4303 If the heading has no TODO state, or if the state is DONE, use the first
4304 state (TODO by default). Also with prefix arg, force first state."
4305 (interactive "P")
4306 (when (not (org-insert-item 'checkbox))
4307 (org-insert-heading)
4308 (save-excursion
4309 (org-back-to-heading)
4310 (outline-previous-heading)
4311 (looking-at org-todo-line-regexp))
4312 (if (or arg
4313 (not (match-beginning 2))
4314 (equal (match-string 2) org-done-string))
4315 (insert (car org-todo-keywords) " ")
4316 (insert (match-string 2) " "))))
4318 (defun org-promote-subtree ()
4319 "Promote the entire subtree.
4320 See also `org-promote'."
4321 (interactive)
4322 (save-excursion
4323 (org-map-tree 'org-promote))
4324 (org-fix-position-after-promote))
4326 (defun org-demote-subtree ()
4327 "Demote the entire subtree. See `org-demote'.
4328 See also `org-promote'."
4329 (interactive)
4330 (save-excursion
4331 (org-map-tree 'org-demote))
4332 (org-fix-position-after-promote))
4335 (defun org-do-promote ()
4336 "Promote the current heading higher up the tree.
4337 If the region is active in `transient-mark-mode', promote all headings
4338 in the region."
4339 (interactive)
4340 (save-excursion
4341 (if (org-region-active-p)
4342 (org-map-region 'org-promote (region-beginning) (region-end))
4343 (org-promote)))
4344 (org-fix-position-after-promote))
4346 (defun org-do-demote ()
4347 "Demote the current heading lower down the tree.
4348 If the region is active in `transient-mark-mode', demote all headings
4349 in the region."
4350 (interactive)
4351 (save-excursion
4352 (if (org-region-active-p)
4353 (org-map-region 'org-demote (region-beginning) (region-end))
4354 (org-demote)))
4355 (org-fix-position-after-promote))
4357 (defun org-fix-position-after-promote ()
4358 "Make sure that after pro/demotion cursor position is right."
4359 (if (and (equal (char-after) ?\n)
4360 (save-excursion
4361 (skip-chars-backward "a-zA-Z0-9_@")
4362 (looking-at org-todo-regexp)))
4363 (insert " "))
4364 (and (equal (char-after) ?\ )
4365 (equal (char-before) ?*)
4366 (forward-char 1)))
4368 (defun org-get-legal-level (level &optional change)
4369 "Rectify a level change under the influence of `org-odd-levels-only'
4370 LEVEL is a current level, CHANGE is by how much the level should be
4371 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4372 even level numbers will become the next higher odd number."
4373 (if org-odd-levels-only
4374 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4375 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4376 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4377 (max 1 (+ level change))))
4379 (defun org-promote ()
4380 "Promote the current heading higher up the tree.
4381 If the region is active in `transient-mark-mode', promote all headings
4382 in the region."
4383 (org-back-to-heading t)
4384 (let* ((level (save-match-data (funcall outline-level)))
4385 (up-head (make-string (org-get-legal-level level -1) ?*))
4386 (diff (abs (- level (length up-head)))))
4387 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4388 (replace-match up-head nil t)
4389 ;; Fixup tag positioning
4390 (and org-auto-align-tags (org-set-tags nil t))
4391 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4393 (defun org-demote ()
4394 "Demote the current heading lower down the tree.
4395 If the region is active in `transient-mark-mode', demote all headings
4396 in the region."
4397 (org-back-to-heading t)
4398 (let* ((level (save-match-data (funcall outline-level)))
4399 (down-head (make-string (org-get-legal-level level 1) ?*))
4400 (diff (abs (- level (length down-head)))))
4401 (replace-match down-head nil t)
4402 ;; Fixup tag positioning
4403 (and org-auto-align-tags (org-set-tags nil t))
4404 (if org-adapt-indentation (org-fixup-indentation diff))))
4406 (defun org-sort (with-case)
4407 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
4408 (interactive "P")
4409 (if (org-at-table-p)
4410 (org-call-with-arg 'org-table-sort-lines with-case)
4411 (org-call-with-arg 'org-sort-entries with-case)))
4413 (defun org-sort-entries (&optional with-case sorting-type)
4414 "Sort entries on a certain level of an outline tree.
4415 If there is an active region, the entries in the region are sorted.
4416 If not, the children of the entry at point are sorted.
4418 Sorting can be alphabetically, numerically, and by date/time as given by
4419 the first time stamp in the entry. The command prompts for the sorting
4420 type unless it has been given to the function through the SORTING-TYPE
4421 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
4423 Comparing entries ignores case by default. However, with an optional argument
4424 WITH-CASE, the sorting considers case as well. With two prefix arguments
4425 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
4426 (interactive "P")
4427 (let ((unique (equal with-case '(16)))
4428 start beg end entries stars re re2 p nentries (nremoved 0) last txt)
4430 ;; Find beginning and end of region to sort
4431 (if (org-region-active-p)
4432 (progn
4433 ;; we will sort the region
4434 (setq end (region-end))
4435 (goto-char (1- (setq start (region-beginning)))))
4436 ;; we will sort the children of the current headline
4437 (setq start (point) end (org-end-of-subtree))
4438 (goto-char start)
4439 (show-subtree))
4440 (outline-next-heading) ; this is the first heading to be included
4441 (setq beg (point))
4442 (if (>= (point) end) (error "Nothing to sort"))
4443 (looking-at "\\(\\*+\\)")
4444 (setq stars (match-string 1)
4445 re (concat "^" (regexp-quote stars) " +")
4446 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4447 txt (buffer-substring beg end))
4448 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4449 (if (string-match re2 txt)
4450 (error "Region to sort contains a level above the first entry"))
4451 ;; Make a list that can be sorted.
4452 ;; The car is the string for comparison, the cdr is the subtree
4453 (message "Sorting entries...")
4454 (setq entries
4455 (mapcar
4456 (lambda (x)
4457 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
4458 (cons (match-string 0 x) x))
4459 (org-split-string txt re)))
4461 ;; Sort the list
4462 (setq entries (org-do-sort
4463 entries
4464 (if (org-region-active-p) "region" "children")
4465 with-case sorting-type))
4467 ;; Delete the old stuff
4468 (goto-char beg)
4469 (kill-region beg end)
4470 (setq nentries (length entries))
4471 ;; Insert the sorted entries, and remove duplicates if this is required
4472 (while (setq p (pop entries))
4473 (if (and unique (equal last (setq last (org-trim (cdr p)))))
4474 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
4475 (insert stars " " (cdr p))))
4476 (goto-char start)
4477 (message "Sorting entries...done (%d entries%s)"
4478 nentries
4479 (if unique (format ", %d duplicates removed" nremoved) ""))))
4481 (defun org-do-sort (table what &optional with-case sorting-type)
4482 "Sort TABLE of WHAT according to SORTING-TYPE.
4483 The user will be prompted for the SORTING-TYPE if the call to this
4484 function does not specify it. WHAT is only for the prompt, to indicate
4485 what is being sorted. The sorting key will be extracted from
4486 the car of the elements of the table.
4487 If WITH-CASE is non-nil, the sorting will be case-sensitive."
4488 (unless sorting-type
4489 (message
4490 "Sort %s:[a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
4491 what)
4492 (setq sorting-type (read-char-exclusive)))
4493 (let ((dcst (downcase sorting-type))
4494 extractfun comparefun)
4495 ;; Define the appropriate functions
4496 (cond
4497 ((= dcst ?n)
4498 (setq extractfun 'string-to-number
4499 comparefun (if (= dcst sorting-type) '< '>)))
4500 ((= dcst ?a)
4501 (setq extractfun (if with-case 'identity 'downcase)
4502 comparefun (if (= dcst sorting-type)
4503 'string<
4504 (lambda (a b) (and (not (string< a b))
4505 (not (string= a b)))))))
4506 ((= dcst ?t)
4507 (setq extractfun
4508 (lambda (x)
4509 (if (string-match org-ts-regexp x)
4510 (time-to-seconds
4511 (org-time-string-to-time (match-string 0 x)))
4512 0))
4513 comparefun (if (= dcst sorting-type) '< '>)))
4514 (t (error "Invalid sorting type `%c'" sorting-type)))
4516 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
4517 table)
4518 (lambda (a b) (funcall comparefun (car a) (car b))))))
4520 (defun org-map-tree (fun)
4521 "Call FUN for every heading underneath the current one."
4522 (org-back-to-heading)
4523 (let ((level (funcall outline-level)))
4524 (save-excursion
4525 (funcall fun)
4526 (while (and (progn
4527 (outline-next-heading)
4528 (> (funcall outline-level) level))
4529 (not (eobp)))
4530 (funcall fun)))))
4532 (defun org-map-region (fun beg end)
4533 "Call FUN for every heading between BEG and END."
4534 (let ((org-ignore-region t))
4535 (save-excursion
4536 (setq end (copy-marker end))
4537 (goto-char beg)
4538 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4539 (< (point) end))
4540 (funcall fun))
4541 (while (and (progn
4542 (outline-next-heading)
4543 (< (point) end))
4544 (not (eobp)))
4545 (funcall fun)))))
4547 (defun org-fixup-indentation (diff)
4548 "Change the indentation in the current entry by DIFF
4549 However, if any line in the current entry has no indentation, or if it
4550 would end up with no indentation after the change, nothing at all is done."
4551 (save-excursion
4552 (let ((end (save-excursion (outline-next-heading)
4553 (point-marker)))
4554 (prohibit (if (> diff 0)
4555 "^\\S-"
4556 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4557 col)
4558 (unless (save-excursion (re-search-forward prohibit end t))
4559 (while (re-search-forward "^[ \t]+" end t)
4560 (goto-char (match-end 0))
4561 (setq col (current-column))
4562 (if (< diff 0) (replace-match ""))
4563 (indent-to (+ diff col))))
4564 (move-marker end nil))))
4566 ;;; Vertical tree motion, cutting and pasting of subtrees
4568 (defun org-move-subtree-up (&optional arg)
4569 "Move the current subtree up past ARG headlines of the same level."
4570 (interactive "p")
4571 (org-move-subtree-down (- (prefix-numeric-value arg))))
4573 (defun org-move-subtree-down (&optional arg)
4574 "Move the current subtree down past ARG headlines of the same level."
4575 (interactive "p")
4576 (setq arg (prefix-numeric-value arg))
4577 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4578 'outline-get-last-sibling))
4579 (ins-point (make-marker))
4580 (cnt (abs arg))
4581 beg end txt folded)
4582 ;; Select the tree
4583 (org-back-to-heading)
4584 (setq beg (point))
4585 (save-match-data
4586 (save-excursion (outline-end-of-heading)
4587 (setq folded (org-invisible-p)))
4588 (outline-end-of-subtree))
4589 (outline-next-heading)
4590 (setq end (point))
4591 ;; Find insertion point, with error handling
4592 (goto-char beg)
4593 (while (> cnt 0)
4594 (or (and (funcall movfunc) (looking-at outline-regexp))
4595 (progn (goto-char beg)
4596 (error "Cannot move past superior level or buffer limit")))
4597 (setq cnt (1- cnt)))
4598 (if (> arg 0)
4599 ;; Moving forward - still need to move over subtree
4600 (progn (outline-end-of-subtree)
4601 (outline-next-heading)
4602 (if (not (or (looking-at (concat "^" outline-regexp))
4603 (bolp)))
4604 (newline))))
4605 (move-marker ins-point (point))
4606 (setq txt (buffer-substring beg end))
4607 (delete-region beg end)
4608 (insert txt)
4609 (goto-char ins-point)
4610 (if folded (hide-subtree))
4611 (move-marker ins-point nil)))
4613 (defvar org-subtree-clip ""
4614 "Clipboard for cut and paste of subtrees.
4615 This is actually only a copy of the kill, because we use the normal kill
4616 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4618 (defvar org-subtree-clip-folded nil
4619 "Was the last copied subtree folded?
4620 This is used to fold the tree back after pasting.")
4622 (defun org-cut-subtree ()
4623 "Cut the current subtree into the clipboard.
4624 This is a short-hand for marking the subtree and then cutting it."
4625 (interactive)
4626 (org-copy-subtree 'cut))
4628 (defun org-copy-subtree (&optional cut)
4629 "Cut the current subtree into the clipboard.
4630 This is a short-hand for marking the subtree and then copying it.
4631 If CUT is non-nil, actually cut the subtree."
4632 (interactive)
4633 (let (beg end folded)
4634 (org-back-to-heading)
4635 (setq beg (point))
4636 (save-match-data
4637 (save-excursion (outline-end-of-heading)
4638 (setq folded (org-invisible-p)))
4639 (outline-end-of-subtree))
4640 (if (equal (char-after) ?\n) (forward-char 1))
4641 (setq end (point))
4642 (goto-char beg)
4643 (when (> end beg)
4644 (setq org-subtree-clip-folded folded)
4645 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4646 (setq org-subtree-clip (current-kill 0))
4647 (message "%s: Subtree with %d characters"
4648 (if cut "Cut" "Copied")
4649 (length org-subtree-clip)))))
4651 (defun org-paste-subtree (&optional level tree)
4652 "Paste the clipboard as a subtree, with modification of headline level.
4653 The entire subtree is promoted or demoted in order to match a new headline
4654 level. By default, the new level is derived from the visible headings
4655 before and after the insertion point, and taken to be the inferior headline
4656 level of the two. So if the previous visible heading is level 3 and the
4657 next is level 4 (or vice versa), level 4 will be used for insertion.
4658 This makes sure that the subtree remains an independent subtree and does
4659 not swallow low level entries.
4661 You can also force a different level, either by using a numeric prefix
4662 argument, or by inserting the heading marker by hand. For example, if the
4663 cursor is after \"*****\", then the tree will be shifted to level 5.
4665 If you want to insert the tree as is, just use \\[yank].
4667 If optional TREE is given, use this text instead of the kill ring."
4668 (interactive "P")
4669 (unless (org-kill-is-subtree-p tree)
4670 (error
4671 (substitute-command-keys
4672 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4673 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4674 (^re (concat "^\\(" outline-regexp "\\)"))
4675 (re (concat "\\(" outline-regexp "\\)"))
4676 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4678 (old-level (if (string-match ^re txt)
4679 (- (match-end 0) (match-beginning 0))
4680 -1))
4681 (force-level (cond (level (prefix-numeric-value level))
4682 ((string-match
4683 ^re_ (buffer-substring (point-at-bol) (point)))
4684 (- (match-end 0) (match-beginning 0)))
4685 (t nil)))
4686 (previous-level (save-excursion
4687 (condition-case nil
4688 (progn
4689 (outline-previous-visible-heading 1)
4690 (if (looking-at re)
4691 (- (match-end 0) (match-beginning 0))
4693 (error 1))))
4694 (next-level (save-excursion
4695 (condition-case nil
4696 (progn
4697 (outline-next-visible-heading 1)
4698 (if (looking-at re)
4699 (- (match-end 0) (match-beginning 0))
4701 (error 1))))
4702 (new-level (or force-level (max previous-level next-level)))
4703 (shift (if (or (= old-level -1)
4704 (= new-level -1)
4705 (= old-level new-level))
4707 (- new-level old-level)))
4708 (shift1 shift)
4709 (delta (if (> shift 0) -1 1))
4710 (func (if (> shift 0) 'org-demote 'org-promote))
4711 (org-odd-levels-only nil)
4712 beg end)
4713 ;; Remove the forces level indicator
4714 (if force-level
4715 (delete-region (point-at-bol) (point)))
4716 ;; Make sure we start at the beginning of an empty line
4717 (if (not (bolp)) (insert "\n"))
4718 (if (not (looking-at "[ \t]*$"))
4719 (progn (insert "\n") (backward-char 1)))
4720 ;; Paste
4721 (setq beg (point))
4722 (if (string-match "[ \t\r\n]+\\'" txt)
4723 (setq txt (replace-match "\n" t t txt)))
4724 (insert txt)
4725 (setq end (point))
4726 (if (looking-at "[ \t\r\n]+")
4727 (replace-match "\n"))
4728 (goto-char beg)
4729 ;; Shift if necessary
4730 (if (= shift 0)
4731 (message "Pasted at level %d, without shift" new-level)
4732 (save-restriction
4733 (narrow-to-region beg end)
4734 (while (not (= shift 0))
4735 (org-map-region func (point-min) (point-max))
4736 (setq shift (+ delta shift)))
4737 (goto-char (point-min))
4738 (message "Pasted at level %d, with shift by %d levels"
4739 new-level shift1)))
4740 (if (and kill-ring
4741 (eq org-subtree-clip (current-kill 0))
4742 org-subtree-clip-folded)
4743 ;; The tree was folded before it was killed/copied
4744 (hide-subtree))))
4746 (defun org-kill-is-subtree-p (&optional txt)
4747 "Check if the current kill is an outline subtree, or a set of trees.
4748 Returns nil if kill does not start with a headline, or if the first
4749 headline level is not the largest headline level in the tree.
4750 So this will actually accept several entries of equal levels as well,
4751 which is OK for `org-paste-subtree'.
4752 If optional TXT is given, check this string instead of the current kill."
4753 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4754 (start-level (and kill
4755 (string-match (concat "\\`" outline-regexp) kill)
4756 (- (match-end 0) (match-beginning 0))))
4757 (re (concat "^" outline-regexp))
4758 (start 1))
4759 (if (not start-level)
4760 nil ;; does not even start with a heading
4761 (catch 'exit
4762 (while (setq start (string-match re kill (1+ start)))
4763 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4764 (throw 'exit nil)))
4765 t))))
4767 (defun org-narrow-to-subtree ()
4768 "Narrow buffer to the current subtree."
4769 (interactive)
4770 (save-excursion
4771 (narrow-to-region
4772 (progn (org-back-to-heading) (point))
4773 (progn (org-end-of-subtree t) (point)))))
4775 ;;;; Plain list items
4777 (defun org-at-item-p ()
4778 "Is point in a line starting a hand-formatted item?"
4779 (let ((llt org-plain-list-ordered-item-terminator))
4780 (save-excursion
4781 (goto-char (point-at-bol))
4782 (looking-at
4783 (cond
4784 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4785 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4786 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4787 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4789 (defun org-at-item-checkbox-p ()
4790 "Is point at a line starting a plain-list item with a checklet?"
4791 (and (org-at-item-p)
4792 (save-excursion
4793 (goto-char (match-end 0))
4794 (skip-chars-forward " \t")
4795 (looking-at "\\[[ X]\\]"))))
4797 (defun org-toggle-checkbox (&optional arg)
4798 "Toggle the checkbox in the current line."
4799 (interactive "P")
4800 (catch 'exit
4801 (let (beg end status (firstnew 'unknown))
4802 (cond
4803 ((org-region-active-p)
4804 (setq beg (region-beginning) end (region-end)))
4805 ((org-on-heading-p)
4806 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4807 ((org-at-item-checkbox-p)
4808 (save-excursion
4809 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4810 (throw 'exit t))
4811 (t (error "Not at a checkbox or heading, and no active region")))
4812 (save-excursion
4813 (goto-char beg)
4814 (while (< (point) end)
4815 (when (org-at-item-checkbox-p)
4816 (setq status (equal (match-string 0) "[X]"))
4817 (when (eq firstnew 'unknown)
4818 (setq firstnew (not status)))
4819 (replace-match
4820 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4821 (beginning-of-line 2)))))
4822 (org-update-checkbox-count-maybe))
4824 (defun org-update-checkbox-count-maybe ()
4825 "Update checkbox statistics unless turned off by user."
4826 (when org-provide-checkbox-statistics
4827 (org-update-checkbox-count)))
4829 (defun org-update-checkbox-count (&optional all)
4830 "Update the checkbox statistics in the current section.
4831 This will find all statistic cookies like [57%] and [6/12] and update them
4832 with the current numbers. With optional prefix argument ALL, do this for
4833 the whole buffer."
4834 (interactive "P")
4835 (save-excursion
4836 (let* ((buffer-invisibility-spec nil) ; Emacs 21 compatibility
4837 (beg (progn (outline-back-to-heading) (point)))
4838 (end (move-marker (make-marker)
4839 (progn (outline-next-heading) (point))))
4840 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
4841 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
4842 b1 e1 f1 c-on c-off lim (cstat 0))
4843 (when all
4844 (goto-char (point-min))
4845 (outline-next-heading)
4846 (setq beg (point) end (point-max)))
4847 (goto-char beg)
4848 (while (re-search-forward re end t)
4849 (setq cstat (1+ cstat)
4850 b1 (match-beginning 0)
4851 e1 (match-end 0)
4852 f1 (match-beginning 1)
4853 lim (cond
4854 ((org-on-heading-p) (outline-next-heading) (point))
4855 ((org-at-item-p) (org-end-of-item) (point))
4856 (t nil))
4857 c-on 0 c-off 0)
4858 (goto-char e1)
4859 (when lim
4860 (while (re-search-forward re-box lim t)
4861 (if (equal (match-string 2) "[ ]")
4862 (setq c-off (1+ c-off))
4863 (setq c-on (1+ c-on))))
4864 (delete-region b1 e1)
4865 (goto-char b1)
4866 (insert (if f1
4867 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
4868 (format "[%d/%d]" c-on (+ c-on c-off))))))
4869 (when (interactive-p)
4870 (message "Checkbox satistics updated %s (%d places)"
4871 (if all "in entire file" "in current outline entry") cstat)))))
4873 (defun org-get-checkbox-statistics-face ()
4874 "Select the face for checkbox statistics.
4875 The face will be `org-done' when all relevant boxes are checked. Otherwise
4876 it will be `org-todo'."
4877 (if (match-end 1)
4878 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
4879 (if (and (> (match-end 2) (match-beginning 2))
4880 (equal (match-string 2) (match-string 3)))
4881 'org-done
4882 'org-todo)))
4884 (defun org-get-indentation (&optional line)
4885 "Get the indentation of the current line, interpreting tabs.
4886 When LINE is given, assume it represents a line and compute its indentation."
4887 (if line
4888 (if (string-match "^ *" (org-remove-tabs line))
4889 (match-end 0))
4890 (save-excursion
4891 (beginning-of-line 1)
4892 (skip-chars-forward " \t")
4893 (current-column))))
4895 (defun org-remove-tabs (s &optional width)
4896 "Replace tabulators in S with spaces.
4897 Assumes that s is a single line, starting in column 0."
4898 (setq width (or width tab-width))
4899 (while (string-match "\t" s)
4900 (setq s (replace-match
4901 (make-string
4902 (- (* width (/ (+ (match-beginning 0) width) width))
4903 (match-beginning 0)) ?\ )
4904 t t s)))
4907 ;; FIXME: document properly.
4908 (defun org-fix-indentation (line ind)
4909 "If the current indenation is smaller than ind1, leave it alone.
4910 If it is larger than ind, reduce it by ind."
4911 (let* ((l (org-remove-tabs line))
4912 (i (org-get-indentation l))
4913 (i1 (car ind)) (i2 (cdr ind)))
4914 (if (>= i i2) (setq l (substring line i2)))
4915 (if (> i1 0)
4916 (concat (make-string i1 ?\ ) l)
4917 l)))
4919 (defun org-beginning-of-item ()
4920 "Go to the beginning of the current hand-formatted item.
4921 If the cursor is not in an item, throw an error."
4922 (interactive)
4923 (let ((pos (point))
4924 (limit (save-excursion (org-back-to-heading)
4925 (beginning-of-line 2) (point)))
4926 ind ind1)
4927 (if (org-at-item-p)
4928 (beginning-of-line 1)
4929 (beginning-of-line 1)
4930 (skip-chars-forward " \t")
4931 (setq ind (current-column))
4932 (if (catch 'exit
4933 (while t
4934 (beginning-of-line 0)
4935 (if (< (point) limit) (throw 'exit nil))
4936 (unless (looking-at "[ \t]*$")
4937 (skip-chars-forward " \t")
4938 (setq ind1 (current-column))
4939 (if (< ind1 ind)
4940 (throw 'exit (org-at-item-p))))))
4942 (goto-char pos)
4943 (error "Not in an item")))))
4945 (defun org-end-of-item ()
4946 "Go to the end of the current hand-formatted item.
4947 If the cursor is not in an item, throw an error."
4948 (interactive)
4949 (let ((pos (point))
4950 (limit (save-excursion (outline-next-heading) (point)))
4951 (ind (save-excursion
4952 (org-beginning-of-item)
4953 (skip-chars-forward " \t")
4954 (current-column)))
4955 ind1)
4956 (if (catch 'exit
4957 (while t
4958 (beginning-of-line 2)
4959 (if (>= (point) limit) (throw 'exit t))
4960 (unless (looking-at "[ \t]*$")
4961 (skip-chars-forward " \t")
4962 (setq ind1 (current-column))
4963 (if (<= ind1 ind) (throw 'exit t)))))
4964 (beginning-of-line 1)
4965 (goto-char pos)
4966 (error "Not in an item"))))
4968 (defun org-next-item ()
4969 "Move to the beginning of the next item in the current plain list.
4970 Error if not at a plain list, or if this is the last item in the list."
4971 (interactive)
4972 (let (ind ind1 (pos (point)))
4973 (org-beginning-of-item)
4974 (setq ind (org-get-indentation))
4975 (org-end-of-item)
4976 (setq ind1 (org-get-indentation))
4977 (unless (and (org-at-item-p) (= ind ind1))
4978 (goto-char pos)
4979 (error "On last item"))))
4981 (defun org-previous-item ()
4982 "Move to the beginning of the previous item in the current plain list.
4983 Error if not at a plain list, or if this is the last item in the list."
4984 (interactive)
4985 (let (beg ind (pos (point)))
4986 (org-beginning-of-item)
4987 (setq beg (point))
4988 (setq ind (org-get-indentation))
4989 (goto-char beg)
4990 (catch 'exit
4991 (while t
4992 (beginning-of-line 0)
4993 (if (looking-at "[ \t]*$")
4995 (if (<= (org-get-indentation) ind)
4996 (throw 'exit t)))))
4997 (condition-case nil
4998 (org-beginning-of-item)
4999 (error (goto-char pos)
5000 (error "On first item")))))
5002 (defun org-move-item-down ()
5003 "Move the plain list item at point down, i.e. swap with following item.
5004 Subitems (items with larger indentation) are considered part of the item,
5005 so this really moves item trees."
5006 (interactive)
5007 (let (beg end ind ind1 (pos (point)) txt)
5008 (org-beginning-of-item)
5009 (setq beg (point))
5010 (setq ind (org-get-indentation))
5011 (org-end-of-item)
5012 (setq end (point))
5013 (setq ind1 (org-get-indentation))
5014 (if (and (org-at-item-p) (= ind ind1))
5015 (progn
5016 (org-end-of-item)
5017 (setq txt (buffer-substring beg end))
5018 (save-excursion
5019 (delete-region beg end))
5020 (setq pos (point))
5021 (insert txt)
5022 (goto-char pos)
5023 (org-maybe-renumber-ordered-list))
5024 (goto-char pos)
5025 (error "Cannot move this item further down"))))
5027 (defun org-move-item-up (arg)
5028 "Move the plain list item at point up, i.e. swap with previous item.
5029 Subitems (items with larger indentation) are considered part of the item,
5030 so this really moves item trees."
5031 (interactive "p")
5032 (let (beg end ind ind1 (pos (point)) txt)
5033 (org-beginning-of-item)
5034 (setq beg (point))
5035 (setq ind (org-get-indentation))
5036 (org-end-of-item)
5037 (setq end (point))
5038 (goto-char beg)
5039 (catch 'exit
5040 (while t
5041 (beginning-of-line 0)
5042 (if (looking-at "[ \t]*$")
5044 (if (<= (setq ind1 (org-get-indentation)) ind)
5045 (throw 'exit t)))))
5046 (condition-case nil
5047 (org-beginning-of-item)
5048 (error (goto-char beg)
5049 (error "Cannot move this item further up")))
5050 (setq ind1 (org-get-indentation))
5051 (if (and (org-at-item-p) (= ind ind1))
5052 (progn
5053 (setq txt (buffer-substring beg end))
5054 (save-excursion
5055 (delete-region beg end))
5056 (setq pos (point))
5057 (insert txt)
5058 (goto-char pos)
5059 (org-maybe-renumber-ordered-list))
5060 (goto-char pos)
5061 (error "Cannot move this item further up"))))
5063 (defun org-maybe-renumber-ordered-list ()
5064 "Renumber the ordered list at point if setup allows it.
5065 This tests the user option `org-auto-renumber-ordered-lists' before
5066 doing the renumbering."
5067 (and org-auto-renumber-ordered-lists
5068 (org-at-item-p)
5069 (match-beginning 3)
5070 (org-renumber-ordered-list 1)))
5072 (defun org-get-string-indentation (s)
5073 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5074 (let ((n -1) (i 0) (w tab-width) c)
5075 (catch 'exit
5076 (while (< (setq n (1+ n)) (length s))
5077 (setq c (aref s n))
5078 (cond ((= c ?\ ) (setq i (1+ i)))
5079 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5080 (t (throw 'exit t)))))
5083 (defun org-renumber-ordered-list (arg)
5084 "Renumber an ordered plain list.
5085 Cursor needs to be in the first line of an item, the line that starts
5086 with something like \"1.\" or \"2)\"."
5087 (interactive "p")
5088 (unless (and (org-at-item-p)
5089 (match-beginning 3))
5090 (error "This is not an ordered list"))
5091 (let ((line (org-current-line))
5092 (col (current-column))
5093 (ind (org-get-string-indentation
5094 (buffer-substring (point-at-bol) (match-beginning 3))))
5095 ;; (term (substring (match-string 3) -1))
5096 ind1 (n (1- arg)))
5097 ;; find where this list begins
5098 (catch 'exit
5099 (while t
5100 (catch 'next
5101 (beginning-of-line 0)
5102 (if (looking-at "[ \t]*$") (throw 'next t))
5103 (skip-chars-forward " \t") (setq ind1 (current-column))
5104 (if (or (< ind1 ind)
5105 (and (= ind1 ind)
5106 (not (org-at-item-p))))
5107 (throw 'exit t)))))
5108 ;; Walk forward and replace these numbers
5109 (catch 'exit
5110 (while t
5111 (catch 'next
5112 (beginning-of-line 2)
5113 (if (eobp) (throw 'exit nil))
5114 (if (looking-at "[ \t]*$") (throw 'next nil))
5115 (skip-chars-forward " \t") (setq ind1 (current-column))
5116 (if (> ind1 ind) (throw 'next t))
5117 (if (< ind1 ind) (throw 'exit t))
5118 (if (not (org-at-item-p)) (throw 'exit nil))
5119 (if (not (match-beginning 3))
5120 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
5121 (delete-region (match-beginning 3) (1- (match-end 3)))
5122 (goto-char (match-beginning 3))
5123 (insert (format "%d" (setq n (1+ n)))))))
5124 (goto-line line)
5125 (move-to-column col)))
5127 (defvar org-last-indent-begin-marker (make-marker))
5128 (defvar org-last-indent-end-marker (make-marker))
5130 (defun org-outdent-item (arg)
5131 "Outdent a local list item."
5132 (interactive "p")
5133 (org-indent-item (- arg)))
5135 (defun org-indent-item (arg)
5136 "Indent a local list item."
5137 (interactive "p")
5138 (unless (org-at-item-p)
5139 (error "Not on an item"))
5140 (save-excursion
5141 (let (beg end ind ind1)
5142 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5143 (setq beg org-last-indent-begin-marker
5144 end org-last-indent-end-marker)
5145 (org-beginning-of-item)
5146 (setq beg (move-marker org-last-indent-begin-marker (point)))
5147 (org-end-of-item)
5148 (setq end (move-marker org-last-indent-end-marker (point))))
5149 (goto-char beg)
5150 (skip-chars-forward " \t") (setq ind (current-column))
5151 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
5152 (while (< (point) end)
5153 (beginning-of-line 1)
5154 (skip-chars-forward " \t") (setq ind1 (current-column))
5155 (delete-region (point-at-bol) (point))
5156 (indent-to-column (+ ind1 arg))
5157 (beginning-of-line 2)))))
5159 ;;; Archiving
5161 (defun org-archive-subtree (&optional find-done)
5162 "Move the current subtree to the archive.
5163 The archive can be a certain top-level heading in the current file, or in
5164 a different file. The tree will be moved to that location, the subtree
5165 heading be marked DONE, and the current time will be added.
5167 When called with prefix argument FIND-DONE, find whole trees without any
5168 open TODO items and archive them (after getting confirmation from the user).
5169 If the cursor is not at a headline when this comand is called, try all level
5170 1 trees. If the cursor is on a headline, only try the direct children of
5171 this heading. "
5172 (interactive "P")
5173 (if find-done
5174 (org-archive-all-done)
5175 ;; Save all relevant TODO keyword-relatex variables
5177 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
5178 (tr-org-todo-keywords org-todo-keywords)
5179 (tr-org-todo-interpretation org-todo-interpretation)
5180 (tr-org-done-string org-done-string)
5181 (tr-org-todo-regexp org-todo-regexp)
5182 (tr-org-todo-line-regexp org-todo-line-regexp)
5183 (this-buffer (current-buffer))
5184 file heading buffer level newfile-p)
5185 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
5186 (progn
5187 (setq file (format (match-string 1 org-archive-location)
5188 (file-name-nondirectory buffer-file-name))
5189 heading (match-string 2 org-archive-location)))
5190 (error "Invalid `org-archive-location'"))
5191 (if (> (length file) 0)
5192 (setq newfile-p (not (file-exists-p file))
5193 buffer (find-file-noselect file))
5194 (setq buffer (current-buffer)))
5195 (unless buffer
5196 (error "Cannot access file \"%s\"" file))
5197 (if (and (> (length heading) 0)
5198 (string-match "^\\*+" heading))
5199 (setq level (match-end 0))
5200 (setq heading nil level 0))
5201 (save-excursion
5202 ;; We first only copy, in case something goes wrong
5203 ;; we need to protect this-command, to avoid kill-region sets it,
5204 ;; which would lead to duplication of subtrees
5205 (let (this-command) (org-copy-subtree))
5206 (set-buffer buffer)
5207 ;; Enforce org-mode for the archive buffer
5208 (if (not (org-mode-p))
5209 ;; Force the mode for future visits.
5210 (let ((org-insert-mode-line-in-empty-file t))
5211 (call-interactively 'org-mode)))
5212 (when newfile-p
5213 (goto-char (point-max))
5214 (insert (format "\nArchived entries from file %s\n\n"
5215 (buffer-file-name this-buffer))))
5216 ;; Force the TODO keywords of the original buffer
5217 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
5218 (org-todo-keywords tr-org-todo-keywords)
5219 (org-todo-interpretation tr-org-todo-interpretation)
5220 (org-done-string tr-org-done-string)
5221 (org-todo-regexp tr-org-todo-regexp)
5222 (org-todo-line-regexp tr-org-todo-line-regexp))
5223 (goto-char (point-min))
5224 (if heading
5225 (progn
5226 (if (re-search-forward
5227 (concat "\\(^\\|\r\\)"
5228 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
5229 nil t)
5230 (goto-char (match-end 0))
5231 ;; Heading not found, just insert it at the end
5232 (goto-char (point-max))
5233 (or (bolp) (insert "\n"))
5234 (insert "\n" heading "\n")
5235 (end-of-line 0))
5236 ;; Make the subtree visible
5237 (show-subtree)
5238 (org-end-of-subtree t)
5239 (skip-chars-backward " \t\r\n")
5240 (and (looking-at "[ \t\r\n]*")
5241 (replace-match "\n\n")))
5242 ;; No specific heading, just go to end of file.
5243 (goto-char (point-max)) (insert "\n"))
5244 ;; Paste
5245 (org-paste-subtree (1+ level))
5246 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
5247 (if org-archive-mark-done
5248 (let (org-log-done)
5249 (org-todo (length org-todo-keywords))))
5250 ;; Move cursor to right after the TODO keyword
5251 (when org-archive-stamp-time
5252 (beginning-of-line 1)
5253 (looking-at org-todo-line-regexp)
5254 (goto-char (or (match-end 2) (match-beginning 3)))
5255 (org-insert-time-stamp (org-current-time) t t "(" ")"))
5256 ;; Save the buffer, if it is not the same buffer.
5257 (if (not (eq this-buffer buffer)) (save-buffer))))
5258 ;; Here we are back in the original buffer. Everything seems to have
5259 ;; worked. So now cut the tree and finish up.
5260 (let (this-command) (org-cut-subtree))
5261 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
5262 (message "Subtree archived %s"
5263 (if (eq this-buffer buffer)
5264 (concat "under heading: " heading)
5265 (concat "in file: " (abbreviate-file-name file)))))))
5267 (defun org-archive-all-done (&optional tag)
5268 "Archive sublevels of the current tree without open TODO items.
5269 If the cursor is not on a headline, try all level 1 trees. If
5270 it is on a headline, try all direct children.
5271 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
5272 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
5273 (rea (concat ".*:" org-archive-tag ":"))
5274 (begm (make-marker))
5275 (endm (make-marker))
5276 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
5277 "Move subtree to archive (no open TODO items)? "))
5278 beg end (cntarch 0))
5279 (if (org-on-heading-p)
5280 (progn
5281 (setq re1 (concat "^" (regexp-quote
5282 (make-string
5283 (1+ (- (match-end 0) (match-beginning 0)))
5284 ?*))
5285 " "))
5286 (move-marker begm (point))
5287 (move-marker endm (org-end-of-subtree t)))
5288 (setq re1 "^* ")
5289 (move-marker begm (point-min))
5290 (move-marker endm (point-max)))
5291 (save-excursion
5292 (goto-char begm)
5293 (while (re-search-forward re1 endm t)
5294 (setq beg (match-beginning 0)
5295 end (save-excursion (org-end-of-subtree t) (point)))
5296 (goto-char beg)
5297 (if (re-search-forward re end t)
5298 (goto-char end)
5299 (goto-char beg)
5300 (if (and (or (not tag) (not (looking-at rea)))
5301 (y-or-n-p question))
5302 (progn
5303 (if tag
5304 (org-toggle-tag org-archive-tag 'on)
5305 (org-archive-subtree))
5306 (setq cntarch (1+ cntarch)))
5307 (goto-char end)))))
5308 (message "%d trees archived" cntarch)))
5310 (defun org-cycle-hide-archived-subtrees (state)
5311 "Re-hide all archived subtrees after a visibility state change."
5312 (when (and (not org-cycle-open-archived-trees)
5313 (not (memq state '(overview folded))))
5314 (save-excursion
5315 (let* ((globalp (memq state '(contents all)))
5316 (beg (if globalp (point-min) (point)))
5317 (end (if globalp (point-max) (org-end-of-subtree t))))
5318 (org-hide-archived-subtrees beg end)
5319 (goto-char beg)
5320 (if (looking-at (concat ".*:" org-archive-tag ":"))
5321 (message (substitute-command-keys
5322 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5324 (defun org-force-cycle-archived ()
5325 "Cycle subtree even if it is archived."
5326 (interactive)
5327 (setq this-command 'org-cycle)
5328 (let ((org-cycle-open-archived-trees t))
5329 (call-interactively 'org-cycle)))
5331 (defun org-hide-archived-subtrees (beg end)
5332 "Re-hide all archived subtrees after a visibility state change."
5333 (save-excursion
5334 (let* ((re (concat ":" org-archive-tag ":")))
5335 (goto-char beg)
5336 (while (re-search-forward re end t)
5337 (and (org-on-heading-p) (hide-subtree))
5338 (org-end-of-subtree t)))))
5340 (defun org-toggle-tag (tag &optional onoff)
5341 "Toggle the tag TAG for the current line.
5342 If ONOFF is `on' or `off', don't toggle but set to this state."
5343 (unless (org-on-heading-p) (error "Not on headling"))
5344 (let (res current)
5345 (save-excursion
5346 (beginning-of-line)
5347 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5348 (point-at-eol) t)
5349 (progn
5350 (setq current (match-string 1))
5351 (replace-match ""))
5352 (setq current ""))
5353 (setq current (nreverse (org-split-string current ":")))
5354 (cond
5355 ((eq onoff 'on)
5356 (setq res t)
5357 (or (member tag current) (push tag current)))
5358 ((eq onoff 'off)
5359 (or (not (member tag current)) (setq current (delete tag current))))
5360 (t (if (member tag current)
5361 (setq current (delete tag current))
5362 (setq res t)
5363 (push tag current))))
5364 (end-of-line 1)
5365 (when current
5366 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5367 (org-set-tags nil t))
5368 res))
5370 (defun org-toggle-archive-tag (&optional arg)
5371 "Toggle the archive tag for the current headline.
5372 With prefix ARG, check all children of current headline and offer tagging
5373 the children that do not contain any open TODO items."
5374 (interactive "P")
5375 (if arg
5376 (org-archive-all-done 'tag)
5377 (let (set)
5378 (save-excursion
5379 (org-back-to-heading t)
5380 (setq set (org-toggle-tag org-archive-tag))
5381 (when set (hide-subtree)))
5382 (and set (beginning-of-line 1))
5383 (message "Subtree %s" (if set "archived" "unarchived")))))
5385 (defvar org-agenda-multi nil) ; dynammically scoped
5386 (defvar org-agenda-buffer-name "*Org Agenda*")
5387 (defvar org-pre-agenda-window-conf nil)
5388 (defun org-prepare-agenda ()
5389 (if org-agenda-multi
5390 (progn
5391 (setq buffer-read-only nil)
5392 (goto-char (point-max))
5393 (unless (= (point) 1)
5394 (insert "\n" (make-string (window-width) ?=) "\n"))
5395 (narrow-to-region (point) (point-max)))
5396 (org-agenda-maybe-reset-markers 'force)
5397 (org-prepare-agenda-buffers (org-agenda-files))
5398 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
5399 (awin (get-buffer-window abuf)))
5400 (cond
5401 ((equal (current-buffer) abuf) nil)
5402 (awin (select-window awin))
5403 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
5404 ((equal org-agenda-window-setup 'current-window)
5405 (switch-to-buffer abuf))
5406 ((equal org-agenda-window-setup 'other-window)
5407 (switch-to-buffer-other-window abuf))
5408 ((equal org-agenda-window-setup 'other-frame)
5409 (switch-to-buffer-other-frame abuf))
5410 ((equal org-agenda-window-setup 'reorganize-frame)
5411 (delete-other-windows)
5412 (switch-to-buffer-other-window abuf))))
5413 (setq buffer-read-only nil)
5414 (erase-buffer)
5415 (org-agenda-mode))
5416 (setq buffer-read-only nil))
5418 (defun org-finalize-agenda ()
5419 "Finishing touch for the agenda buffer, called just before displaying it."
5420 (unless org-agenda-multi
5421 (org-agenda-align-tags)
5422 (save-excursion
5423 (let ((buffer-read-only))
5424 (goto-char (point-min))
5425 (while (org-activate-bracket-links (point-max))
5426 (add-text-properties (match-beginning 0) (match-end 0)
5427 '(face org-link))))
5428 (run-hooks 'org-finalize-agenda-hook))))
5430 (defun org-prepare-agenda-buffers (files)
5431 "Create buffers for all agenda files, protect archived trees and comments."
5432 (interactive)
5433 (let ((pa '(:org-archived t))
5434 (pc '(:org-comment t))
5435 (pall '(:org-archived t :org-comment t))
5436 (rea (concat ":" org-archive-tag ":"))
5437 bmp file re)
5438 (save-excursion
5439 (while (setq file (pop files))
5440 (org-check-agenda-file file)
5441 (set-buffer (org-get-agenda-file-buffer file))
5442 (widen)
5443 (setq bmp (buffer-modified-p))
5444 (save-excursion
5445 (remove-text-properties (point-min) (point-max) pall)
5446 (when org-agenda-skip-archived-trees
5447 (goto-char (point-min))
5448 (while (re-search-forward rea nil t)
5449 (if (org-on-heading-p)
5450 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
5451 (goto-char (point-min))
5452 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
5453 (while (re-search-forward re nil t)
5454 (add-text-properties
5455 (match-beginning 0) (org-end-of-subtree t) pc)))
5456 (set-buffer-modified-p bmp)))))
5458 (defvar org-agenda-skip-function nil
5459 "Function to be called at each match during agenda construction.
5460 If this function return nil, the current match should not be skipped.
5461 Otherwise, the function must return a position from where the search
5462 should be continued.
5463 Never set this variable using `setq' or so, because then it will apply
5464 to all future agenda commands. Instead, bind it with `let' to scope
5465 it dynamically into the agenda-constructing command.")
5467 (defun org-agenda-skip ()
5468 "Throw to `:skip' in places that should be skipped."
5469 (let ((p (point-at-bol)) to)
5470 (and org-agenda-skip-archived-trees
5471 (get-text-property p :org-archived)
5472 (org-end-of-subtree t)
5473 (throw :skip t))
5474 (and (get-text-property p :org-comment)
5475 (org-end-of-subtree t)
5476 (throw :skip t))
5477 (if (equal (char-after p) ?#) (throw :skip t))
5478 (when (and (functionp org-agenda-skip-function)
5479 (setq to (save-excursion
5480 (save-match-data
5481 (funcall org-agenda-skip-function)))))
5482 (goto-char to)
5483 (throw :skip t))))
5485 ;;;; Dynamic blocks
5487 (defun org-find-dblock (name)
5488 "Find the first dynamic block with name NAME in the buffer.
5489 If not found, stay at current position and return nil."
5490 (let (pos)
5491 (save-excursion
5492 (goto-char (point-min))
5493 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
5494 nil t)
5495 (match-beginning 0))))
5496 (if pos (goto-char pos))
5497 pos))
5499 (defconst org-dblock-start-re
5500 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
5501 "Matches the startline of a dynamic block, with parameters.")
5503 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
5504 "Matches the end of a dyhamic block.")
5506 (defun org-create-dblock (plist)
5507 "Create a dynamic block section, with parameters taken from PLIST.
5508 PLIST must containe a :name entry which is used as name of the block."
5509 (unless (bolp) (newline))
5510 (let ((name (plist-get plist :name)))
5511 (insert "#+BEGIN: " name)
5512 (while plist
5513 (if (eq (car plist) :name)
5514 (setq plist (cddr plist))
5515 (insert " " (prin1-to-string (pop plist)))))
5516 (insert "\n\n#+END:\n")
5517 (beginning-of-line -2)))
5519 (defun org-prepare-dblock ()
5520 "Prepare dynamic block for refresh.
5521 This empties the block, puts the cursor at the insert position and returns
5522 the property list including an extra property :name with the block name."
5523 (unless (looking-at org-dblock-start-re)
5524 (error "Not at a dynamic block"))
5525 (let* ((begdel (1+ (match-end 0)))
5526 (name (match-string 1))
5527 (params (append (list :name name)
5528 (read (concat "(" (match-string 3) ")")))))
5529 (unless (re-search-forward org-dblock-end-re nil t)
5530 (error "Dynamic block not terminated"))
5531 (delete-region begdel (match-beginning 0))
5532 (goto-char begdel)
5533 (open-line 1)
5534 params))
5536 (defun org-map-dblocks (&optional command)
5537 "Apply COMMAND to all dynamic blocks in the current buffer.
5538 If COMMAND is not given, use `org-update-dblock'."
5539 (let ((cmd (or command 'org-update-dblock))
5540 pos)
5541 (save-excursion
5542 (goto-char (point-min))
5543 (while (re-search-forward org-dblock-start-re nil t)
5544 (goto-char (setq pos (match-beginning 0)))
5545 (condition-case nil
5546 (funcall cmd)
5547 (error (message "Error during update of dynamic block")))
5548 (goto-char pos)
5549 (unless (re-search-forward org-dblock-end-re nil t)
5550 (error "Dynamic block not terminated"))))))
5552 (defun org-dblock-update (&optional arg)
5553 "User command for updating dynamic blocks.
5554 Update the dynamic block at point. With prefix ARG, update all dynamic
5555 blocks in the buffer."
5556 (interactive "P")
5557 (if arg
5558 (org-update-all-dblocks)
5559 (or (looking-at org-dblock-start-re)
5560 (org-beginning-of-dblock))
5561 (org-update-dblock)))
5563 (defun org-update-dblock ()
5564 "Update the dynamic block at point
5565 This means to empty the block, parse for parameters and then call
5566 the correct writing function."
5567 (let* ((pos (point))
5568 (params (org-prepare-dblock))
5569 (name (plist-get params :name))
5570 (cmd (intern (concat "org-dblock-write:" name))))
5571 (funcall cmd params)
5572 (goto-char pos)))
5574 (defun org-beginning-of-dblock ()
5575 "Find the beginning of the dynamic block at point.
5576 Error if there is no scuh block at point."
5577 (let ((pos (point))
5578 beg)
5579 (end-of-line 1)
5580 (if (and (re-search-backward org-dblock-start-re nil t)
5581 (setq beg (match-beginning 0))
5582 (re-search-forward org-dblock-end-re nil t)
5583 (> (match-end 0) pos))
5584 (goto-char beg)
5585 (goto-char pos)
5586 (error "Not in a dynamic block"))))
5588 (defun org-update-all-dblocks ()
5589 "Update all dynamic blocks in the buffer.
5590 This function can be used in a hook."
5591 (when (org-mode-p)
5592 (org-map-dblocks 'org-update-dblock)))
5595 ;;;; Completion
5597 (defun org-complete (&optional arg)
5598 "Perform completion on word at point.
5599 At the beginning of a headline, this completes TODO keywords as given in
5600 `org-todo-keywords'.
5601 If the current word is preceded by a backslash, completes the TeX symbols
5602 that are supported for HTML support.
5603 If the current word is preceded by \"#+\", completes special words for
5604 setting file options.
5605 In the line after \"#+STARTUP:, complete valid keywords.\"
5606 At all other locations, this simply calls `ispell-complete-word'."
5607 (interactive "P")
5608 (catch 'exit
5609 (let* ((end (point))
5610 (beg1 (save-excursion
5611 (skip-chars-backward "a-zA-Z_@0-9")
5612 (point)))
5613 (beg (save-excursion
5614 (skip-chars-backward "a-zA-Z0-9_:$")
5615 (point)))
5616 (confirm (lambda (x) (stringp (car x))))
5617 (camel (equal (char-before beg) ?*))
5618 (tag (equal (char-before beg1) ?:))
5619 (texp (equal (char-before beg) ?\\))
5620 (link (equal (char-before beg) ?\[))
5621 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
5622 beg)
5623 "#+"))
5624 (startup (string-match "^#\\+STARTUP:.*"
5625 (buffer-substring (point-at-bol) (point))))
5626 (completion-ignore-case opt)
5627 (type nil)
5628 (tbl nil)
5629 (table (cond
5630 (opt
5631 (setq type :opt)
5632 (mapcar (lambda (x)
5633 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
5634 (cons (match-string 2 x) (match-string 1 x)))
5635 (org-split-string (org-get-current-options) "\n")))
5636 (startup
5637 (setq type :startup)
5638 org-startup-options)
5639 (link (append org-link-abbrev-alist-local
5640 org-link-abbrev-alist))
5641 (texp
5642 (setq type :tex)
5643 org-html-entities)
5644 ((string-match "\\`\\*+[ \t]*\\'"
5645 (buffer-substring (point-at-bol) beg))
5646 (setq type :todo)
5647 (mapcar 'list org-todo-keywords))
5648 (camel
5649 (setq type :camel)
5650 (save-excursion
5651 (goto-char (point-min))
5652 (while (re-search-forward org-todo-line-regexp nil t)
5653 (push (list
5654 (if org-file-link-context-use-camel-case
5655 (org-make-org-heading-camel (match-string 3) t)
5656 (org-make-org-heading-search-string
5657 (match-string 3) t)))
5658 tbl)))
5659 tbl)
5660 (tag (setq type :tag beg beg1)
5661 (or org-tag-alist (org-get-buffer-tags)))
5662 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
5663 (pattern (buffer-substring-no-properties beg end))
5664 (completion (try-completion pattern table confirm)))
5665 (cond ((eq completion t)
5666 (if (equal type :opt)
5667 (insert (substring (cdr (assoc (upcase pattern) table))
5668 (length pattern)))
5669 (if (equal type :tag) (insert ":"))))
5670 ((null completion)
5671 (message "Can't find completion for \"%s\"" pattern)
5672 (ding))
5673 ((not (string= pattern completion))
5674 (delete-region beg end)
5675 (if (string-match " +$" completion)
5676 (setq completion (replace-match "" t t completion)))
5677 (insert completion)
5678 (if (get-buffer-window "*Completions*")
5679 (delete-window (get-buffer-window "*Completions*")))
5680 (if (assoc completion table)
5681 (if (eq type :todo) (insert " ")
5682 (if (eq type :tag) (insert ":"))))
5683 (if (and (equal type :opt) (assoc completion table))
5684 (message "%s" (substitute-command-keys
5685 "Press \\[org-complete] again to insert example settings"))))
5687 (message "Making completion list...")
5688 (let ((list (sort (all-completions pattern table confirm)
5689 'string<)))
5690 (with-output-to-temp-buffer "*Completions*"
5691 (condition-case nil
5692 ;; Protection needed for XEmacs and emacs 21
5693 (display-completion-list list pattern)
5694 (error (display-completion-list list)))))
5695 (message "Making completion list...%s" "done"))))))
5697 ;;;; Comments, TODO and DEADLINE
5699 (defun org-toggle-comment ()
5700 "Change the COMMENT state of an entry."
5701 (interactive)
5702 (save-excursion
5703 (org-back-to-heading)
5704 (if (looking-at (concat outline-regexp
5705 "\\( +\\<" org-comment-string "\\>\\)"))
5706 (replace-match "" t t nil 1)
5707 (if (looking-at outline-regexp)
5708 (progn
5709 (goto-char (match-end 0))
5710 (insert " " org-comment-string))))))
5712 (defvar org-last-todo-state-is-todo nil
5713 "This is non-nil when the last TODO state change led to a TODO state.
5714 If the last change removed the TODO tag or switched to DONE, then
5715 this is nil.")
5717 (defun org-todo (&optional arg)
5718 "Change the TODO state of an item.
5719 The state of an item is given by a keyword at the start of the heading,
5720 like
5721 *** TODO Write paper
5722 *** DONE Call mom
5724 The different keywords are specified in the variable `org-todo-keywords'.
5725 By default the available states are \"TODO\" and \"DONE\".
5726 So for this example: when the item starts with TODO, it is changed to DONE.
5727 When it starts with DONE, the DONE is removed. And when neither TODO nor
5728 DONE are present, add TODO at the beginning of the heading.
5730 With prefix arg, use completion to determine the new state. With numeric
5731 prefix arg, switch to that state."
5732 (interactive "P")
5733 (save-excursion
5734 (org-back-to-heading)
5735 (if (looking-at outline-regexp) (goto-char (match-end 0)))
5736 (or (looking-at (concat " +" org-todo-regexp " *"))
5737 (looking-at " *"))
5738 (let* ((this (match-string 1))
5739 (completion-ignore-case t)
5740 (member (member this org-todo-keywords))
5741 (tail (cdr member))
5742 (state (cond
5743 ((equal arg '(4))
5744 ;; Read a state with completion
5745 (completing-read "State: " (mapcar (lambda(x) (list x))
5746 org-todo-keywords)
5747 nil t))
5748 ((eq arg 'right)
5749 (if this
5750 (if tail (car tail) nil)
5751 (car org-todo-keywords)))
5752 ((eq arg 'left)
5753 (if (equal member org-todo-keywords)
5755 (if this
5756 (nth (- (length org-todo-keywords) (length tail) 2)
5757 org-todo-keywords)
5758 org-done-string)))
5759 (arg
5760 ;; user requests a specific state
5761 (nth (1- (prefix-numeric-value arg))
5762 org-todo-keywords))
5763 ((null member) (car org-todo-keywords))
5764 ((null tail) nil) ;; -> first entry
5765 ((eq org-todo-interpretation 'sequence)
5766 (car tail))
5767 ((memq org-todo-interpretation '(type priority))
5768 (if (eq this-command last-command)
5769 (car tail)
5770 (if (> (length tail) 0) org-done-string nil)))
5771 (t nil)))
5772 (next (if state (concat " " state " ") " ")))
5773 (replace-match next t t)
5774 (setq org-last-todo-state-is-todo
5775 (not (equal state org-done-string)))
5776 (when org-log-done
5777 (if (equal state org-done-string)
5778 (org-add-planning-info 'closed (org-current-time) 'scheduled)
5779 (if (not this)
5780 (org-add-planning-info nil nil 'closed))))
5781 ;; Fixup tag positioning
5782 (and org-auto-align-tags (org-set-tags nil t))
5783 (run-hooks 'org-after-todo-state-change-hook)))
5784 ;; Fixup cursor location if close to the keyword
5785 (if (and (outline-on-heading-p)
5786 (not (bolp))
5787 (save-excursion (beginning-of-line 1)
5788 (looking-at org-todo-line-regexp))
5789 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5790 (progn
5791 (goto-char (or (match-end 2) (match-end 1)))
5792 (just-one-space))))
5794 (defun org-show-todo-tree (arg)
5795 "Make a compact tree which shows all headlines marked with TODO.
5796 The tree will show the lines where the regexp matches, and all higher
5797 headlines above the match.
5798 With \\[universal-argument] prefix, also show the DONE entries.
5799 With a numeric prefix N, construct a sparse tree for the Nth element
5800 of `org-todo-keywords'."
5801 (interactive "P")
5802 (let ((case-fold-search nil)
5803 (kwd-re
5804 (cond ((null arg) org-not-done-regexp)
5805 ((equal arg '(4)) org-todo-regexp)
5806 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5807 (regexp-quote (nth (1- (prefix-numeric-value arg))
5808 org-todo-keywords)))
5809 (t (error "Invalid prefix argument: %s" arg)))))
5810 (message "%d TODO entries found"
5811 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5813 (defun org-deadline ()
5814 "Insert the DEADLINE: string to make a deadline.
5815 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5816 to modify it to the correct date."
5817 (interactive)
5818 (org-add-planning-info 'deadline nil 'closed))
5820 (defun org-schedule ()
5821 "Insert the SCHEDULED: string to schedule a TODO item.
5822 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5823 to modify it to the correct date."
5824 (interactive)
5825 (org-add-planning-info 'scheduled nil 'closed))
5827 (defun org-add-planning-info (what &optional time &rest remove)
5828 "Insert new timestamp with keyword in the line directly after the headline.
5829 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5830 If non is given, the user is prompted for a date.
5831 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5832 be removed."
5833 (interactive)
5834 (when what (setq time (or time (org-read-date nil 'to-time))))
5835 (when (and org-insert-labeled-timestamps-at-point
5836 (member what '(scheduled deadline)))
5837 (insert
5838 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
5839 (org-insert-time-stamp time)
5840 (setq what nil))
5841 (save-excursion
5842 (save-restriction
5843 (let (col list elt ts buffer-invisibility-spec)
5844 (org-back-to-heading t)
5845 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5846 (goto-char (match-end 1))
5847 (setq col (current-column))
5848 (goto-char (1+ (match-end 0)))
5849 (if (and (not (looking-at outline-regexp))
5850 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5851 "[^\r\n]*"))
5852 (not (equal (match-string 1) org-clock-string)))
5853 (narrow-to-region (match-beginning 0) (match-end 0))
5854 (insert "\n")
5855 (backward-char 1)
5856 (narrow-to-region (point) (point))
5857 (indent-to-column col))
5858 ;; Check if we have to remove something.
5859 (setq list (cons what remove))
5860 (while list
5861 (setq elt (pop list))
5862 (goto-char (point-min))
5863 (when (or (and (eq elt 'scheduled)
5864 (re-search-forward org-scheduled-time-regexp nil t))
5865 (and (eq elt 'deadline)
5866 (re-search-forward org-deadline-time-regexp nil t))
5867 (and (eq elt 'closed)
5868 (re-search-forward org-closed-time-regexp nil t)))
5869 (replace-match "")
5870 (if (looking-at "--+<[^>]+>") (replace-match ""))
5871 (if (looking-at " +") (replace-match ""))))
5872 (goto-char (point-max))
5873 (when what
5874 (insert
5875 (if (not (equal (char-before) ?\ )) " " "")
5876 (cond ((eq what 'scheduled) org-scheduled-string)
5877 ((eq what 'deadline) org-deadline-string)
5878 ((eq what 'closed) org-closed-string))
5879 " ")
5880 (org-insert-time-stamp time nil (eq what 'closed))
5881 (end-of-line 1)
5882 (and (eq what 'closed) (org-add-log-maybe 'done)))
5883 (goto-char (point-min))
5884 (widen)
5885 (if (looking-at "[ \t]+\r?\n")
5886 (replace-match ""))
5887 ts))))
5889 (defvar org-log-note-marker (make-marker))
5890 (defvar org-log-note-purpose nil)
5891 (defvar org-log-note-window-configuration nil)
5893 (defun org-add-log-maybe (&optional purpose)
5894 (when (and (listp org-log-done)
5895 (memq purpose org-log-done))
5896 (move-marker org-log-note-marker (point))
5897 (setq org-log-note-purpose purpose)
5898 (add-hook 'post-command-hook 'org-add-log-note 'append)))
5900 (defun org-add-log-note (&optional purpose)
5901 "Pop up a window for taking a note, and add this note later at point."
5902 (remove-hook 'post-command-hook 'org-add-log-note)
5903 (setq org-log-note-window-configuration (current-window-configuration))
5904 (delete-other-windows)
5905 (switch-to-buffer (marker-buffer org-log-note-marker))
5906 (goto-char org-log-note-marker)
5907 (switch-to-buffer-other-window "*Org Note*")
5908 (erase-buffer)
5909 (org-mode)
5910 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
5911 (cond
5912 ((eq org-log-note-purpose 'clock-out) "stopped clock")
5913 ((eq org-log-note-purpose 'done) "closed todo item")
5914 (t (error "This should not happen")))))
5915 (org-set-local 'org-finish-function 'org-store-log-note))
5917 (defun org-store-log-note ()
5918 "Finish taking a log note, and insert it to where it belongs."
5919 (let ((txt (buffer-string))
5920 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
5921 lines ind)
5922 (kill-buffer (current-buffer))
5923 (if (string-match "^#.*\n[ \t\\n]*" txt)
5924 (setq txt (replace-match "" t t txt)))
5925 (when (string-match "\\S-" txt)
5926 (if (string-match "\\s-+\\'" txt)
5927 (setq txt (replace-match "" t t txt)))
5928 (setq lines (org-split-string txt "\n"))
5929 (when (and note (string-match "\\S-" note))
5930 (setq note
5931 (org-replace-escapes
5932 note
5933 (list (cons "%u" user-login-name)
5934 (cons "%U" user-full-name)
5935 (cons "%t" (format-time-string
5936 (org-time-stamp-format 'long 'inactive)
5937 (current-time))))))
5938 (push note lines))
5939 (save-excursion
5940 (set-buffer (marker-buffer org-log-note-marker))
5941 (save-excursion
5942 (goto-char org-log-note-marker)
5943 (if (not (bolp)) (newline))
5944 (indent-relative t)
5945 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
5946 (insert " - " (pop lines))
5947 (while lines
5948 (insert "\n" ind (pop lines))))))
5949 (set-window-configuration org-log-note-window-configuration)))
5951 (defvar org-occur-highlights nil)
5952 (make-variable-buffer-local 'org-occur-highlights)
5954 (defun org-occur (regexp &optional keep-previous callback)
5955 "Make a compact tree which shows all matches of REGEXP.
5956 The tree will show the lines where the regexp matches, and all higher
5957 headlines above the match. It will also show the heading after the match,
5958 to make sure editing the matching entry is easy.
5959 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
5960 call to `org-occur' will be kept, to allow stacking of calls to this
5961 command.
5962 If CALLBACK is non-nil, it is a function which is called to confirm
5963 that the match should indeed be shown."
5964 (interactive "sRegexp: \nP")
5965 (or keep-previous (org-remove-occur-highlights nil nil t))
5966 (let ((cnt 0))
5967 (save-excursion
5968 (goto-char (point-min))
5969 (if (or (not keep-previous) ; do not want to keep
5970 (not org-occur-highlights)) ; no previous matches
5971 ;; hide everything
5972 (org-overview))
5973 (while (re-search-forward regexp nil t)
5974 (when (or (not callback)
5975 (save-match-data (funcall callback)))
5976 (setq cnt (1+ cnt))
5977 (org-highlight-new-match (match-beginning 0) (match-end 0))
5978 (org-show-context 'occur-tree))))
5979 (when org-remove-highlights-with-change
5980 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5981 nil 'local))
5982 (unless org-sparse-tree-open-archived-trees
5983 (org-hide-archived-subtrees (point-min) (point-max)))
5984 (run-hooks 'org-occur-hook)
5985 (if (interactive-p)
5986 (message "%d match(es) for regexp %s" cnt regexp))
5987 cnt))
5989 (defun org-show-context (&optional key siblings)
5990 "Make sure point and context and visible.
5991 How much context is shown depends upon the variables
5992 `org-show-hierarchy-above' and `org-show-following-heading'.
5993 When SIBLINGS is non-nil, show all siblings on each hierarchy level."
5994 (let ((heading-p (org-on-heading-p t))
5995 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
5996 (following-p (org-get-alist-option org-show-following-heading key)))
5997 (catch 'exit
5998 ;; Show heading or entry text
5999 (if heading-p
6000 (org-flag-heading nil) ; only show the heading
6001 (and (or (org-invisible-p) (org-invisible-p2))
6002 (org-show-hidden-entry))) ; show entire entry
6003 (when following-p
6004 ;; Show next sibling, or heading below text
6005 (save-excursion
6006 (and (if heading-p (org-goto-sibling) (outline-next-heading))
6007 (org-flag-heading nil))))
6008 (when hierarchy-p
6009 ;; show all higher headings, possibly with siblings
6010 (save-excursion
6011 (while (and (condition-case nil
6012 (progn (org-up-heading-all 1) t)
6013 (error nil))
6014 (not (bobp)))
6015 (org-flag-heading nil)
6016 (when siblings
6017 (save-excursion
6018 (while (org-goto-sibling) (org-flag-heading nil)))
6019 (save-excursion
6020 (while (org-goto-sibling 'previous)
6021 (org-flag-heading nil))))))))))
6023 (defun org-reveal (&optional siblings)
6024 "Show current entry, hierarchy above it, and the following headline.
6025 This can be used to show a consistent set of context around locations
6026 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
6027 not t for the search context.
6029 With optional argument SIBLINGS, on each level of the hierarchy all
6030 siblings are shown. This repairs the tree structure so what it would
6031 look like when opend with successive calls to `org-cycle'."
6032 (interactive "P")
6033 (let ((org-show-hierarchy-above t)
6034 (org-show-following-heading t))
6035 (org-show-context nil siblings)))
6037 ;; Overlay compatibility functions
6038 (defun org-make-overlay (beg end &optional buffer)
6039 (if (featurep 'xemacs)
6040 (make-extent beg end buffer)
6041 (make-overlay beg end buffer)))
6042 (defun org-delete-overlay (ovl)
6043 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
6044 (defun org-detach-overlay (ovl)
6045 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
6046 (defun org-move-overlay (ovl beg end &optional buffer)
6047 (if (featurep 'xemacs)
6048 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
6049 (move-overlay ovl beg end buffer)))
6050 (defun org-overlay-put (ovl prop value)
6051 (if (featurep 'xemacs)
6052 (set-extent-property ovl prop value)
6053 (overlay-put ovl prop value)))
6054 (defun org-overlay-display (ovl text &optional face)
6055 "Make overlay OVL display TEXT with face FACE."
6056 (if (featurep 'xemacs)
6057 (let ((gl (make-glyph text)))
6058 (and face (set-glyph-face gl face))
6059 (set-extent-property ovl 'invisible t)
6060 (set-extent-property ovl 'end-glyph gl))
6061 (overlay-put ovl 'display text)
6062 (if face (overlay-put ovl 'face face))))
6063 (defun org-overlay-get (ovl prop)
6064 (if (featurep 'xemacs)
6065 (extent-property ovl prop)
6066 (overlay-get ovl prop)))
6067 (defun org-overlays-at (pos)
6068 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
6069 (defun org-overlays-in (&optional start end)
6070 (if (featurep 'xemacs)
6071 (extent-list nil start end)
6072 (overlays-in start end)))
6073 (defun org-overlay-start (o)
6074 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
6075 (defun org-overlay-end (o)
6076 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
6077 (defun org-find-overlays (prop &optional pos delete)
6078 "Find all overlays specifying PROP at POS or point.
6079 If DELETE is non-nil, delete all those overlays."
6080 (let ((overlays (org-overlays-at (or pos (point))))
6081 ov found)
6082 (while (setq ov (pop overlays))
6083 (if (org-overlay-get ov prop)
6084 (if delete (org-delete-overlay ov) (push ov found))))
6085 found))
6087 (defun org-highlight-new-match (beg end)
6088 "Highlight from BEG to END and mark the highlight is an occur headline."
6089 (let ((ov (org-make-overlay beg end)))
6090 (org-overlay-put ov 'face 'secondary-selection)
6091 (push ov org-occur-highlights)))
6093 (defvar org-inhibit-highlight-removal nil)
6094 (defun org-remove-occur-highlights (&optional beg end noremove)
6095 "Remove the occur highlights from the buffer.
6096 BEG and END are ignored. If NOREMOVE is nil, remove this function
6097 from the `before-change-functions' in the current buffer."
6098 (interactive)
6099 (unless org-inhibit-highlight-removal
6100 (mapc 'org-delete-overlay org-occur-highlights)
6101 (setq org-occur-highlights nil)
6102 (unless noremove
6103 (remove-hook 'before-change-functions
6104 'org-remove-occur-highlights 'local))))
6106 ;;;; Priorities
6108 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
6109 "Regular expression matching the priority indicator.")
6111 (defvar org-remove-priority-next-time nil)
6113 (defun org-priority-up ()
6114 "Increase the priority of the current item."
6115 (interactive)
6116 (org-priority 'up))
6118 (defun org-priority-down ()
6119 "Decrease the priority of the current item."
6120 (interactive)
6121 (org-priority 'down))
6123 (defun org-priority (&optional action)
6124 "Change the priority of an item by ARG.
6125 ACTION can be set, up, or down."
6126 (interactive)
6127 (setq action (or action 'set))
6128 (let (current new news have remove)
6129 (save-excursion
6130 (org-back-to-heading)
6131 (if (looking-at org-priority-regexp)
6132 (setq current (string-to-char (match-string 2))
6133 have t)
6134 (setq current org-default-priority))
6135 (cond
6136 ((eq action 'set)
6137 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
6138 (setq new (read-char-exclusive))
6139 (cond ((equal new ?\ ) (setq remove t))
6140 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
6141 (error "Priority must be between `%c' and `%c'"
6142 ?A org-lowest-priority))))
6143 ((eq action 'up)
6144 (setq new (1- current)))
6145 ((eq action 'down)
6146 (setq new (1+ current)))
6147 (t (error "Invalid action")))
6148 (setq new (min (max ?A (upcase new)) org-lowest-priority))
6149 (setq news (format "%c" new))
6150 (if have
6151 (if remove
6152 (replace-match "" t t nil 1)
6153 (replace-match news t t nil 2))
6154 (if remove
6155 (error "No priority cookie found in line")
6156 (looking-at org-todo-line-regexp)
6157 (if (match-end 2)
6158 (progn
6159 (goto-char (match-end 2))
6160 (insert " [#" news "]"))
6161 (goto-char (match-beginning 3))
6162 (insert "[#" news "] ")))))
6163 (if remove
6164 (message "Priority removed")
6165 (message "Priority of current item set to %s" news))))
6168 (defun org-get-priority (s)
6169 "Find priority cookie and return priority."
6170 (save-match-data
6171 (if (not (string-match org-priority-regexp s))
6172 (* 1000 (- org-lowest-priority org-default-priority))
6173 (* 1000 (- org-lowest-priority
6174 (string-to-char (match-string 2 s)))))))
6176 ;;;; Timestamps
6178 (defvar org-last-changed-timestamp nil)
6180 (defun org-time-stamp (arg)
6181 "Prompt for a date/time and insert a time stamp.
6182 If the user specifies a time like HH:MM, or if this command is called
6183 with a prefix argument, the time stamp will contain date and time.
6184 Otherwise, only the date will be included. All parts of a date not
6185 specified by the user will be filled in from the current date/time.
6186 So if you press just return without typing anything, the time stamp
6187 will represent the current date/time. If there is already a timestamp
6188 at the cursor, it will be modified."
6189 (interactive "P")
6190 (let (org-time-was-given time)
6191 (cond
6192 ((and (org-at-timestamp-p)
6193 (eq last-command 'org-time-stamp)
6194 (eq this-command 'org-time-stamp))
6195 (insert "--")
6196 (setq time (let ((this-command this-command))
6197 (org-read-date arg 'totime)))
6198 (org-insert-time-stamp time (or org-time-was-given arg)))
6199 ((org-at-timestamp-p)
6200 (setq time (let ((this-command this-command))
6201 (org-read-date arg 'totime)))
6202 (when (org-at-timestamp-p) ; just to get the match data
6203 (replace-match "")
6204 (setq org-last-changed-timestamp
6205 (org-insert-time-stamp time (or org-time-was-given arg))))
6206 (message "Timestamp updated"))
6208 (setq time (let ((this-command this-command))
6209 (org-read-date arg 'totime)))
6210 (org-insert-time-stamp time (or org-time-was-given arg))))))
6212 (defun org-time-stamp-inactive (&optional arg)
6213 "Insert an inactive time stamp.
6214 An inactive time stamp is enclosed in square brackets instead of angle
6215 brackets. It is inactive in the sense that it does not trigger agenda entries,
6216 does not link to the calendar and cannot be changed with the S-cursor keys.
6217 So these are more for recording a certain time/date."
6218 (interactive "P")
6219 (let (org-time-was-given time)
6220 (setq time (org-read-date arg 'totime))
6221 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
6223 (defvar org-date-ovl (org-make-overlay 1 1))
6224 (org-overlay-put org-date-ovl 'face 'org-warning)
6225 (org-detach-overlay org-date-ovl)
6227 (defun org-read-date (&optional with-time to-time from-string)
6228 "Read a date and make things smooth for the user.
6229 The prompt will suggest to enter an ISO date, but you can also enter anything
6230 which will at least partially be understood by `parse-time-string'.
6231 Unrecognized parts of the date will default to the current day, month, year,
6232 hour and minute. For example,
6233 3-2-5 --> 2003-02-05
6234 feb 15 --> currentyear-02-15
6235 sep 12 9 --> 2009-09-12
6236 12:45 --> today 12:45
6237 22 sept 0:34 --> currentyear-09-22 0:34
6238 12 --> currentyear-currentmonth-12
6239 Fri --> nearest Friday (today or later)
6240 +4 --> four days from today (only if +N is the only thing given)
6241 etc.
6242 The function understands only English month and weekday abbreviations,
6243 but this can be configured with the variables `parse-time-months' and
6244 `parse-time-weekdays'.
6246 While prompting, a calendar is popped up - you can also select the
6247 date with the mouse (button 1). The calendar shows a period of three
6248 months. To scroll it to other months, use the keys `>' and `<'.
6249 If you don't like the calendar, turn it off with
6250 \(setq org-popup-calendar-for-date-prompt nil)
6252 With optional argument TO-TIME, the date will immediately be converted
6253 to an internal time.
6254 With an optional argument WITH-TIME, the prompt will suggest to also
6255 insert a time. Note that when WITH-TIME is not set, you can still
6256 enter a time, and this function will inform the calling routine about
6257 this change. The calling routine may then choose to change the format
6258 used to insert the time stamp into the buffer to include the time."
6259 (require 'parse-time)
6260 (let* ((org-time-stamp-rounding-minutes
6261 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
6262 (ct (org-current-time))
6263 (default-time
6264 ;; Default time is either today, or, when entering a range,
6265 ;; the range start.
6266 (if (save-excursion
6267 (re-search-backward
6268 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
6269 (- (point) 20) t))
6270 (apply
6271 'encode-time
6272 (mapcar (lambda(x) (or x 0))
6273 (parse-time-string (match-string 1))))
6274 ct))
6275 (calendar-move-hook nil)
6276 (view-diary-entries-initially nil)
6277 (view-calendar-holidays-initially nil)
6278 (timestr (format-time-string
6279 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
6280 (prompt (format "YYYY-MM-DD [%s]: " timestr))
6281 ans ans1 ans2 (deltadays 0)
6282 second minute hour day month year tl wday wday1)
6284 (cond
6285 (from-string (setq ans from-string))
6286 (org-popup-calendar-for-date-prompt
6287 (save-excursion
6288 (save-window-excursion
6289 (calendar)
6290 (calendar-forward-day (- (time-to-days default-time)
6291 (calendar-absolute-from-gregorian
6292 (calendar-current-date))))
6293 (org-eval-in-calendar nil)
6294 (let* ((old-map (current-local-map))
6295 (map (copy-keymap calendar-mode-map))
6296 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
6297 (define-key map (kbd "RET") 'org-calendar-select)
6298 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
6299 'org-calendar-select-mouse)
6300 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
6301 'org-calendar-select-mouse)
6302 (define-key minibuffer-local-map [(meta shift left)]
6303 (lambda () (interactive)
6304 (org-eval-in-calendar '(calendar-backward-month 1))))
6305 (define-key minibuffer-local-map [(meta shift right)]
6306 (lambda () (interactive)
6307 (org-eval-in-calendar '(calendar-forward-month 1))))
6308 (define-key minibuffer-local-map [(shift up)]
6309 (lambda () (interactive)
6310 (org-eval-in-calendar '(calendar-backward-week 1))))
6311 (define-key minibuffer-local-map [(shift down)]
6312 (lambda () (interactive)
6313 (org-eval-in-calendar '(calendar-forward-week 1))))
6314 (define-key minibuffer-local-map [(shift left)]
6315 (lambda () (interactive)
6316 (org-eval-in-calendar '(calendar-backward-day 1))))
6317 (define-key minibuffer-local-map [(shift right)]
6318 (lambda () (interactive)
6319 (org-eval-in-calendar '(calendar-forward-day 1))))
6320 (define-key minibuffer-local-map ">"
6321 (lambda () (interactive)
6322 (org-eval-in-calendar '(scroll-calendar-left 1))))
6323 (define-key minibuffer-local-map "<"
6324 (lambda () (interactive)
6325 (org-eval-in-calendar '(scroll-calendar-right 1))))
6326 (unwind-protect
6327 (progn
6328 (use-local-map map)
6329 (setq ans (read-string prompt "" nil nil))
6330 (if (not (string-match "\\S-" ans)) (setq ans nil))
6331 (setq ans (or ans1 ans ans2)))
6332 (use-local-map old-map))))))
6333 (t ; Naked prompt only
6334 (setq ans (read-string prompt "" nil timestr))))
6335 (org-detach-overlay org-date-ovl)
6337 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" ans)
6338 (setq deltadays (string-to-number ans) ans ""))
6340 (if (string-match
6341 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
6342 (progn
6343 (setq year (if (match-end 2)
6344 (string-to-number (match-string 2 ans))
6345 (string-to-number (format-time-string "%Y")))
6346 month (string-to-number (match-string 3 ans))
6347 day (string-to-number (match-string 4 ans)))
6348 (if (< year 100) (setq year (+ 2000 year)))
6349 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
6350 t nil ans))))
6351 (setq tl (parse-time-string ans)
6352 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
6353 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
6354 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
6355 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
6356 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
6357 second (or (nth 0 tl) 0)
6358 wday (nth 6 tl))
6359 (setq day (+ day deltadays))
6360 (when (and wday (not (nth 3 tl)))
6361 ;; Weekday was given, but no day, so pick that day in the week
6362 ;; on or after the derived date.
6363 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
6364 (unless (equal wday wday1)
6365 (setq day (+ day (% (- wday wday1 -7) 7)))))
6366 (if (and (boundp 'org-time-was-given)
6367 (nth 2 tl))
6368 (setq org-time-was-given t))
6369 (if (< year 100) (setq year (+ 2000 year)))
6370 (if to-time
6371 (encode-time second minute hour day month year)
6372 (if (or (nth 1 tl) (nth 2 tl))
6373 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
6374 (format "%04d-%02d-%02d" year month day)))))
6376 (defun org-eval-in-calendar (form)
6377 "Eval FORM in the calendar window and return to current window.
6378 Also, store the cursor date in variable ans2."
6379 (let ((sw (selected-window)))
6380 (select-window (get-buffer-window "*Calendar*"))
6381 (eval form)
6382 (when (calendar-cursor-to-date)
6383 (let* ((date (calendar-cursor-to-date))
6384 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
6385 (setq ans2 (format-time-string "%Y-%m-%d" time))))
6386 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
6387 (select-window sw)))
6389 (defun org-calendar-select ()
6390 "Return to `org-read-date' with the date currently selected.
6391 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
6392 (interactive)
6393 (when (calendar-cursor-to-date)
6394 (let* ((date (calendar-cursor-to-date))
6395 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
6396 (setq ans1 (format-time-string "%Y-%m-%d" time)))
6397 (if (active-minibuffer-window) (exit-minibuffer))))
6399 (defun org-insert-time-stamp (time &optional with-hm inactive pre post)
6400 "Insert a date stamp for the date given by the internal TIME.
6401 WITH-HM means, use the stamp format that includes the time of the day.
6402 INACTIVE means use square brackets instead of angular ones, so that the
6403 stamp will not contribute to the agenda.
6404 PRE and POST are optional strings to be inserted before and after the
6405 stamp.
6406 The command returns the inserted time stamp."
6407 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
6408 stamp)
6409 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
6410 (insert (or pre ""))
6411 (insert (setq stamp (format-time-string fmt time)))
6412 (insert (or post ""))
6413 stamp))
6415 (defun org-toggle-time-stamp-overlays ()
6416 "Toggle the use of custom time stamp formats."
6417 (interactive)
6418 (setq org-display-custom-times (not org-display-custom-times))
6419 (unless org-display-custom-times
6420 (let ((p (point-min)) (bmp (buffer-modified-p)))
6421 (while (setq p (next-single-property-change p 'display))
6422 (if (and (get-text-property p 'display)
6423 (eq (get-text-property p 'face) 'org-date))
6424 (remove-text-properties
6425 p (setq p (next-single-property-change p 'display))
6426 '(display t))))
6427 (set-buffer-modified-p bmp)))
6428 (if (featurep 'xemacs)
6429 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
6430 (org-restart-font-lock)
6431 (setq org-table-may-need-update t)
6432 (if org-display-custom-times
6433 (message "Time stamps are overlayed with custom format")
6434 (message "Time stamp overlays removed")))
6436 (defun org-display-custom-time (beg end)
6437 "Overlay modified time stamp format over timestamp between BED and END."
6438 (let* ((t1 (save-match-data
6439 (org-parse-time-string (buffer-substring beg end) t)))
6440 (w1 (- end beg))
6441 (with-hm (and (nth 1 t1) (nth 2 t1)))
6442 (inactive (= (char-before (1- beg)) ?\[))
6443 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
6444 (time (org-fix-decoded-time t1))
6445 (str (org-add-props
6446 (format-time-string
6447 (substring tf 1 -1) (apply 'encode-time time))
6448 nil 'mouse-face 'highlight))
6449 (w2 (length str)))
6450 (if (not (= w2 w1))
6451 (add-text-properties (1+ beg) (+ 2 beg)
6452 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
6453 (if (featurep 'xemacs)
6454 (progn
6455 (put-text-property beg end 'invisible t)
6456 (put-text-property beg end 'end-glyph (make-glyph str)))
6457 (put-text-property beg end 'display str))))
6459 (defun org-translate-time (string)
6460 "Translate all timestamps in STRING to custom format.
6461 But do this only if the variable `org-display-custom-times' is set."
6462 (when org-display-custom-times
6463 (save-match-data
6464 (let* ((start 0)
6465 (re org-ts-regexp-both)
6466 t1 with-hm inactive tf time str beg end)
6467 (while (setq start (string-match re string start))
6468 (setq beg (match-beginning 0)
6469 end (match-end 0)
6470 t1 (save-match-data
6471 (org-parse-time-string (substring string beg end) t))
6472 with-hm (and (nth 1 t1) (nth 2 t1))
6473 inactive (equal (substring string beg (1+ beg)) "[")
6474 tf (funcall (if with-hm 'cdr 'car)
6475 org-time-stamp-custom-formats)
6476 time (org-fix-decoded-time t1)
6477 str (format-time-string
6478 (concat
6479 (if inactive "[" "<") (substring tf 1 -1)
6480 (if inactive "]" ">"))
6481 (apply 'encode-time time))
6482 string (replace-match str t t string)
6483 start (+ start (length str)))))))
6484 string)
6486 (defun org-fix-decoded-time (time)
6487 "Set 0 instead of nil for the first 6 elements of time.
6488 Don't touch the rest."
6489 (let ((n 0))
6490 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
6492 (defun org-days-to-time (timestamp-string)
6493 "Difference between TIMESTAMP-STRING and now in days."
6494 (- (time-to-days (org-time-string-to-time timestamp-string))
6495 (time-to-days (current-time))))
6497 (defun org-deadline-close (timestamp-string &optional ndays)
6498 "Is the time in TIMESTAMP-STRING close to the current date?"
6499 (and (< (org-days-to-time timestamp-string)
6500 (or ndays org-deadline-warning-days))
6501 (not (org-entry-is-done-p))))
6503 (defun org-calendar-select-mouse (ev)
6504 "Return to `org-read-date' with the date currently selected.
6505 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
6506 (interactive "e")
6507 (mouse-set-point ev)
6508 (when (calendar-cursor-to-date)
6509 (let* ((date (calendar-cursor-to-date))
6510 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
6511 (setq ans1 (format-time-string "%Y-%m-%d" time)))
6512 (if (active-minibuffer-window) (exit-minibuffer))))
6514 (defun org-check-deadlines (ndays)
6515 "Check if there are any deadlines due or past due.
6516 A deadline is considered due if it happens within `org-deadline-warning-days'
6517 days from today's date. If the deadline appears in an entry marked DONE,
6518 it is not shown. The prefix arg NDAYS can be used to test that many
6519 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
6520 (interactive "P")
6521 (let* ((org-warn-days
6522 (cond
6523 ((equal ndays '(4)) 100000)
6524 (ndays (prefix-numeric-value ndays))
6525 (t org-deadline-warning-days)))
6526 (case-fold-search nil)
6527 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
6528 (callback
6529 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
6531 (message "%d deadlines past-due or due within %d days"
6532 (org-occur regexp nil callback)
6533 org-warn-days)))
6535 (defun org-evaluate-time-range (&optional to-buffer)
6536 "Evaluate a time range by computing the difference between start and end.
6537 Normally the result is just printed in the echo area, but with prefix arg
6538 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
6539 If the time range is actually in a table, the result is inserted into the
6540 next column.
6541 For time difference computation, a year is assumed to be exactly 365
6542 days in order to avoid rounding problems."
6543 (interactive "P")
6545 (org-clock-update-time-maybe)
6546 (save-excursion
6547 (unless (org-at-date-range-p)
6548 (goto-char (point-at-bol))
6549 (re-search-forward org-tr-regexp (point-at-eol) t))
6550 (if (not (org-at-date-range-p))
6551 (error "Not at a time-stamp range, and none found in current line")))
6552 (let* ((ts1 (match-string 1))
6553 (ts2 (match-string 2))
6554 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
6555 (match-end (match-end 0))
6556 (time1 (org-time-string-to-time ts1))
6557 (time2 (org-time-string-to-time ts2))
6558 (t1 (time-to-seconds time1))
6559 (t2 (time-to-seconds time2))
6560 (diff (abs (- t2 t1)))
6561 (negative (< (- t2 t1) 0))
6562 ;; (ys (floor (* 365 24 60 60)))
6563 (ds (* 24 60 60))
6564 (hs (* 60 60))
6565 (fy "%dy %dd %02d:%02d")
6566 (fy1 "%dy %dd")
6567 (fd "%dd %02d:%02d")
6568 (fd1 "%dd")
6569 (fh "%02d:%02d")
6570 y d h m align)
6571 (if havetime
6572 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
6574 d (floor (/ diff ds)) diff (mod diff ds)
6575 h (floor (/ diff hs)) diff (mod diff hs)
6576 m (floor (/ diff 60)))
6577 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
6579 d (floor (+ (/ diff ds) 0.5))
6580 h 0 m 0))
6581 (if (not to-buffer)
6582 (message (org-make-tdiff-string y d h m))
6583 (when (org-at-table-p)
6584 (goto-char match-end)
6585 (setq align t)
6586 (and (looking-at " *|") (goto-char (match-end 0))))
6587 (if (looking-at
6588 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
6589 (replace-match ""))
6590 (if negative (insert " -"))
6591 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
6592 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
6593 (insert " " (format fh h m))))
6594 (if align (org-table-align))
6595 (message "Time difference inserted")))))
6597 (defun org-make-tdiff-string (y d h m)
6598 (let ((fmt "")
6599 (l nil))
6600 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
6601 l (push y l)))
6602 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
6603 l (push d l)))
6604 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
6605 l (push h l)))
6606 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
6607 l (push m l)))
6608 (apply 'format fmt (nreverse l))))
6610 (defun org-time-string-to-time (s)
6611 (apply 'encode-time (org-parse-time-string s)))
6613 (defun org-parse-time-string (s &optional nodefault)
6614 "Parse the standard Org-mode time string.
6615 This should be a lot faster than the normal `parse-time-string'.
6616 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
6617 hour and minute fields will be nil if not given."
6618 (if (string-match org-ts-regexp1 s)
6619 (list 0
6620 (if (or (match-beginning 8) (not nodefault))
6621 (string-to-number (or (match-string 8 s) "0")))
6622 (if (or (match-beginning 7) (not nodefault))
6623 (string-to-number (or (match-string 7 s) "0")))
6624 (string-to-number (match-string 4 s))
6625 (string-to-number (match-string 3 s))
6626 (string-to-number (match-string 2 s))
6627 nil nil nil)
6628 (make-list 9 0)))
6630 (defun org-timestamp-up (&optional arg)
6631 "Increase the date item at the cursor by one.
6632 If the cursor is on the year, change the year. If it is on the month or
6633 the day, change that.
6634 With prefix ARG, change by that many units."
6635 (interactive "p")
6636 (org-timestamp-change (prefix-numeric-value arg)))
6638 (defun org-timestamp-down (&optional arg)
6639 "Decrease the date item at the cursor by one.
6640 If the cursor is on the year, change the year. If it is on the month or
6641 the day, change that.
6642 With prefix ARG, change by that many units."
6643 (interactive "p")
6644 (org-timestamp-change (- (prefix-numeric-value arg))))
6646 (defun org-timestamp-up-day (&optional arg)
6647 "Increase the date in the time stamp by one day.
6648 With prefix ARG, change that many days."
6649 (interactive "p")
6650 (if (and (not (org-at-timestamp-p t))
6651 (org-on-heading-p))
6652 (org-todo 'up)
6653 (org-timestamp-change (prefix-numeric-value arg) 'day)))
6655 (defun org-timestamp-down-day (&optional arg)
6656 "Decrease the date in the time stamp by one day.
6657 With prefix ARG, change that many days."
6658 (interactive "p")
6659 (if (and (not (org-at-timestamp-p t))
6660 (org-on-heading-p))
6661 (org-todo 'down)
6662 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
6664 (defsubst org-pos-in-match-range (pos n)
6665 (and (match-beginning n)
6666 (<= (match-beginning n) pos)
6667 (>= (match-end n) pos)))
6669 (defun org-at-timestamp-p (&optional inactive-ok)
6670 "Determine if the cursor is in or at a timestamp."
6671 (interactive)
6672 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
6673 (pos (point))
6674 (ans (or (looking-at tsr)
6675 (save-excursion
6676 (skip-chars-backward "^[<\n\r\t")
6677 (if (> (point) 1) (backward-char 1))
6678 (and (looking-at tsr)
6679 (> (- (match-end 0) pos) -1))))))
6680 (and (boundp 'org-ts-what)
6681 (setq org-ts-what
6682 (cond
6683 ((org-pos-in-match-range pos 2) 'year)
6684 ((org-pos-in-match-range pos 3) 'month)
6685 ((org-pos-in-match-range pos 7) 'hour)
6686 ((org-pos-in-match-range pos 8) 'minute)
6687 ((or (org-pos-in-match-range pos 4)
6688 (org-pos-in-match-range pos 5)) 'day)
6689 (t 'day))))
6690 ans))
6692 (defun org-timestamp-change (n &optional what)
6693 "Change the date in the time stamp at point.
6694 The date will be changed by N times WHAT. WHAT can be `day', `month',
6695 `year', `minute', `second'. If WHAT is not given, the cursor position
6696 in the timestamp determines what will be changed."
6697 (let ((pos (point))
6698 with-hm inactive
6699 org-ts-what
6700 ts time time0)
6701 (if (not (org-at-timestamp-p t))
6702 (error "Not at a timestamp"))
6703 (if (and (not what) (not (eq org-ts-what 'day))
6704 org-display-custom-times
6705 (get-text-property (point) 'display)
6706 (not (get-text-property (1- (point)) 'display)))
6707 (setq org-ts-what 'day))
6708 (setq org-ts-what (or what org-ts-what)
6709 with-hm (<= (abs (- (cdr org-ts-lengths)
6710 (- (match-end 0) (match-beginning 0))))
6712 inactive (= (char-after (match-beginning 0)) ?\[)
6713 ts (match-string 0))
6714 (replace-match "")
6715 (setq time0 (org-parse-time-string ts))
6716 (setq time
6717 (apply 'encode-time
6718 (append
6719 (list (or (car time0) 0))
6720 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
6721 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
6722 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
6723 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
6724 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
6725 (nthcdr 6 time0))))
6726 (if (eq what 'calendar)
6727 (let ((cal-date
6728 (save-excursion
6729 (save-match-data
6730 (set-buffer "*Calendar*")
6731 (calendar-cursor-to-date)))))
6732 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
6733 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
6734 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
6735 (setcar time0 (or (car time0) 0))
6736 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
6737 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
6738 (setq time (apply 'encode-time time0))))
6739 (setq org-last-changed-timestamp
6740 (org-insert-time-stamp time with-hm inactive))
6741 (org-clock-update-time-maybe)
6742 (goto-char pos)
6743 ;; Try to recenter the calendar window, if any
6744 (if (and org-calendar-follow-timestamp-change
6745 (get-buffer-window "*Calendar*" t)
6746 (memq org-ts-what '(day month year)))
6747 (org-recenter-calendar (time-to-days time)))))
6749 (defun org-recenter-calendar (date)
6750 "If the calendar is visible, recenter it to DATE."
6751 (let* ((win (selected-window))
6752 (cwin (get-buffer-window "*Calendar*" t))
6753 (calendar-move-hook nil))
6754 (when cwin
6755 (select-window cwin)
6756 (calendar-goto-date (if (listp date) date
6757 (calendar-gregorian-from-absolute date)))
6758 (select-window win))))
6760 (defun org-goto-calendar (&optional arg)
6761 "Go to the Emacs calendar at the current date.
6762 If there is a time stamp in the current line, go to that date.
6763 A prefix ARG can be used to force the current date."
6764 (interactive "P")
6765 (let ((tsr org-ts-regexp) diff
6766 (calendar-move-hook nil)
6767 (view-calendar-holidays-initially nil)
6768 (view-diary-entries-initially nil))
6769 (if (or (org-at-timestamp-p)
6770 (save-excursion
6771 (beginning-of-line 1)
6772 (looking-at (concat ".*" tsr))))
6773 (let ((d1 (time-to-days (current-time)))
6774 (d2 (time-to-days
6775 (org-time-string-to-time (match-string 1)))))
6776 (setq diff (- d2 d1))))
6777 (calendar)
6778 (calendar-goto-today)
6779 (if (and diff (not arg)) (calendar-forward-day diff))))
6781 (defun org-date-from-calendar ()
6782 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
6783 If there is already a time stamp at the cursor position, update it."
6784 (interactive)
6785 (org-timestamp-change 0 'calendar))
6787 ;;; The clock for measuring work time.
6789 (defvar org-clock-marker (make-marker)
6790 "Marker recording the last clock-in.")
6792 (defun org-clock-in ()
6793 "Start the clock on the current item.
6794 If necessary, clock-out of the currently active clock."
6795 (interactive)
6796 (org-clock-out t)
6797 (let (ts)
6798 (save-excursion
6799 (org-back-to-heading t)
6800 (beginning-of-line 2)
6801 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6802 (not (equal (match-string 1) org-clock-string)))
6803 (beginning-of-line 1))
6804 (insert "\n") (backward-char 1)
6805 (indent-relative)
6806 (insert org-clock-string " ")
6807 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
6808 (move-marker org-clock-marker (point))
6809 (message "Clock started at %s" ts))))
6811 (defun org-clock-out (&optional fail-quietly)
6812 "Stop the currently running clock.
6813 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
6814 (interactive)
6815 (catch 'exit
6816 (if (not (marker-buffer org-clock-marker))
6817 (if fail-quietly (throw 'exit t) (error "No active clock")))
6818 (let (ts te s h m)
6819 (save-excursion
6820 (set-buffer (marker-buffer org-clock-marker))
6821 (goto-char org-clock-marker)
6822 (beginning-of-line 1)
6823 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6824 (equal (match-string 1) org-clock-string))
6825 (setq ts (match-string 2))
6826 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
6827 (goto-char org-clock-marker)
6828 (insert "--")
6829 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
6830 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
6831 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
6832 h (floor (/ s 3600))
6833 s (- s (* 3600 h))
6834 m (floor (/ s 60))
6835 s (- s (* 60 s)))
6836 (insert " => " (format "%2d:%02d" h m))
6837 (move-marker org-clock-marker nil)
6838 (org-add-log-maybe 'clock-out)
6839 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
6841 (defun org-clock-cancel ()
6842 "Cancel the running clock be removing the start timestamp."
6843 (interactive)
6844 (if (not (marker-buffer org-clock-marker))
6845 (error "No active clock"))
6846 (save-excursion
6847 (set-buffer (marker-buffer org-clock-marker))
6848 (goto-char org-clock-marker)
6849 (delete-region (1- (point-at-bol)) (point-at-eol)))
6850 (message "Clock canceled"))
6852 (defvar org-clock-file-total-minutes nil
6853 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
6854 (make-variable-buffer-local 'org-clock-file-total-minutes)
6856 (defun org-clock-sum (&optional tstart tend)
6857 "Sum the times for each subtree.
6858 Puts the resulting times in minutes as a text property on each headline."
6859 (interactive)
6860 (let* ((bmp (buffer-modified-p))
6861 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
6862 org-clock-string
6863 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
6864 (lmax 30)
6865 (ltimes (make-vector lmax 0))
6866 (t1 0)
6867 (level 0)
6868 ts te dt
6869 time)
6870 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
6871 (save-excursion
6872 (goto-char (point-max))
6873 (while (re-search-backward re nil t)
6874 (if (match-end 2)
6875 ;; A time
6876 (setq ts (match-string 2)
6877 te (match-string 3)
6878 ts (time-to-seconds
6879 (apply 'encode-time (org-parse-time-string ts)))
6880 te (time-to-seconds
6881 (apply 'encode-time (org-parse-time-string te)))
6882 ts (if tstart (max ts tstart) ts)
6883 te (if tend (min te tend) te)
6884 dt (- te ts)
6885 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
6886 ;; A headline
6887 (setq level (- (match-end 1) (match-beginning 1)))
6888 (when (or (> t1 0) (> (aref ltimes level) 0))
6889 (loop for l from 0 to level do
6890 (aset ltimes l (+ (aref ltimes l) t1)))
6891 (setq t1 0 time (aref ltimes level))
6892 (loop for l from level to (1- lmax) do
6893 (aset ltimes l 0))
6894 (goto-char (match-beginning 0))
6895 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
6896 (setq org-clock-file-total-minutes (aref ltimes 0)))
6897 (set-buffer-modified-p bmp)))
6899 (defun org-clock-display (&optional total-only)
6900 "Show subtree times in the entire buffer.
6901 If TOTAL-ONLY is non-nil, only show the total time for the entire file
6902 in the echo area."
6903 (interactive)
6904 (org-remove-clock-overlays)
6905 (let (time h m p)
6906 (org-clock-sum)
6907 (unless total-only
6908 (save-excursion
6909 (goto-char (point-min))
6910 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6911 (goto-char p)
6912 (when (setq time (get-text-property p :org-clock-minutes))
6913 (org-put-clock-overlay time (funcall outline-level))))
6914 (setq h (/ org-clock-file-total-minutes 60)
6915 m (- org-clock-file-total-minutes (* 60 h)))
6916 ;; Arrange to remove the overlays upon next change.
6917 (when org-remove-highlights-with-change
6918 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
6919 nil 'local))))
6920 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
6922 (defvar org-clock-overlays nil)
6923 (make-variable-buffer-local 'org-clock-overlays)
6925 (defun org-put-clock-overlay (time &optional level)
6926 "Put an overlays on the current line, displaying TIME.
6927 If LEVEL is given, prefix time with a corresponding number of stars.
6928 This creates a new overlay and stores it in `org-clock-overlays', so that it
6929 will be easy to remove."
6930 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
6931 (l (if level (org-get-legal-level level 0) 0))
6932 (off 0)
6933 ov tx)
6934 (move-to-column c)
6935 (unless (eolp) (skip-chars-backward "^ \t"))
6936 (skip-chars-backward " \t")
6937 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6938 tx (concat (buffer-substring (1- (point)) (point))
6939 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6940 (org-add-props (format "%s %2d:%02d%s"
6941 (make-string l ?*) h m
6942 (make-string (- 10 l) ?\ ))
6943 '(face secondary-selection))
6944 ""))
6945 (if (not (featurep 'xemacs))
6946 (org-overlay-put ov 'display tx)
6947 (org-overlay-put ov 'invisible t)
6948 (org-overlay-put ov 'end-glyph (make-glyph tx)))
6949 (push ov org-clock-overlays)))
6951 (defun org-remove-clock-overlays (&optional beg end noremove)
6952 "Remove the occur highlights from the buffer.
6953 BEG and END are ignored. If NOREMOVE is nil, remove this function
6954 from the `before-change-functions' in the current buffer."
6955 (interactive)
6956 (unless org-inhibit-highlight-removal
6957 (mapc 'org-delete-overlay org-clock-overlays)
6958 (setq org-clock-overlays nil)
6959 (unless noremove
6960 (remove-hook 'before-change-functions
6961 'org-remove-clock-overlays 'local))))
6963 (defun org-clock-out-if-current ()
6964 "Clock out if the current entry contains the running clock.
6965 This is used to stop the clock after a TODO entry is marked DONE."
6966 (when (and (equal state org-done-string)
6967 (equal (marker-buffer org-clock-marker) (current-buffer))
6968 (< (point) org-clock-marker)
6969 (> (save-excursion (outline-next-heading) (point))
6970 org-clock-marker))
6971 ;; Clock out, but don't accept a logging message for this.
6972 (let ((org-log-done (if (and (listp org-log-done)
6973 (member 'clock-out org-log-done))
6974 '(done)
6975 org-log-done)))
6976 (org-clock-out))))
6978 (add-hook 'org-after-todo-state-change-hook
6979 'org-clock-out-if-current)
6981 (defun org-check-running-clock ()
6982 "Check if the current buffer contains the running clock.
6983 If yes, offer to stop it and to save the buffer with the changes."
6984 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6985 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6986 (buffer-name))))
6987 (org-clock-out)
6988 (when (y-or-n-p "Save changed buffer?")
6989 (save-buffer))))
6991 (defun org-clock-report ()
6992 "Create a table containing a report about clocked time.
6993 If the buffer contains lines
6994 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6996 #+END: clocktable
6997 then the table will be inserted between these lines, replacing whatever
6998 is was there before. If these lines are not in the buffer, the table
6999 is inserted at point, surrounded by the special lines.
7000 The BEGIN line can contain parameters. Allowed are:
7001 :maxlevel The maximum level to be included in the table. Default is 3.
7002 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
7003 (interactive)
7004 (org-remove-clock-overlays)
7005 (unless (org-find-dblock "clocktable")
7006 (org-create-dblock (list :name "clocktable"
7007 :maxlevel 2 :emphasize nil)))
7008 (org-update-dblock))
7010 (defun org-clock-update-time-maybe ()
7011 "If this is a CLOCK line, update it and return t.
7012 Otherwise, return nil."
7013 (interactive)
7014 (save-excursion
7015 (beginning-of-line 1)
7016 (skip-chars-forward " \t")
7017 (when (looking-at org-clock-string)
7018 (let ((re (concat "[ \t]*" org-clock-string
7019 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
7020 "\\([ \t]*=>.*\\)?"))
7021 ts te h m s)
7022 (if (not (looking-at re))
7024 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
7025 (end-of-line 1)
7026 (setq ts (match-string 1)
7027 te (match-string 2))
7028 (setq s (- (time-to-seconds
7029 (apply 'encode-time (org-parse-time-string te)))
7030 (time-to-seconds
7031 (apply 'encode-time (org-parse-time-string ts))))
7032 h (floor (/ s 3600))
7033 s (- s (* 3600 h))
7034 m (floor (/ s 60))
7035 s (- s (* 60 s)))
7036 (insert " => " (format "%2d:%02d" h m))
7037 t)))))
7039 (defun org-clock-special-range (key &optional time as-strings)
7040 "Return two times bordering a special time range.
7041 Key is a symbol specifying the range and can be one of `today', `yesterday',
7042 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
7043 A week starts Monday 0:00 and ends Sunday 24:00.
7044 The range is determined relative to TIME. TIME defaults to the current time.
7045 The return value is a cons cell with two internal times like the ones
7046 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
7047 the returned times will be formatted strings."
7048 (let* ((tm (decode-time (or time (current-time))))
7049 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
7050 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
7051 (dow (nth 6 tm))
7052 s1 m1 h1 d1 month1 y1 diff ts te fm)
7053 (cond
7054 ((eq key 'today)
7055 (setq h 0 m 0 h1 24 m1 0))
7056 ((eq key 'yesterday)
7057 (setq d (1- d) h 0 m 0 h1 24 m1 0))
7058 ((eq key 'thisweek)
7059 (setq diff (if (= dow 0) 6 (1- dow))
7060 m 0 h 0 d (- d diff) d1 (+ 7 d)))
7061 ((eq key 'lastweek)
7062 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
7063 m 0 h 0 d (- d diff) d1 (+ 7 d)))
7064 ((eq key 'thismonth)
7065 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
7066 ((eq key 'lastmonth)
7067 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
7068 ((eq key 'thisyear)
7069 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
7070 ((eq key 'lastyear)
7071 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
7072 (t (error "No such time block %s" key)))
7073 (setq ts (encode-time s m h d month y)
7074 te (encode-time (or s1 s) (or m1 m) (or h1 h)
7075 (or d1 d) (or month1 month) (or y1 y)))
7076 (setq fm (cdr org-time-stamp-formats))
7077 (if as-strings
7078 (cons (format-time-string fm ts) (format-time-string fm te))
7079 (cons ts te))))
7081 (defun org-dblock-write:clocktable (params)
7082 "Write the standard clocktable."
7083 (let ((hlchars '((1 . "*") (2 . ?/)))
7084 (emph nil)
7085 (ins (make-marker))
7086 ipos time h m p level hlc hdl maxlevel
7087 ts te cc block)
7088 (setq maxlevel (or (plist-get params :maxlevel) 3)
7089 emph (plist-get params :emphasize)
7090 ts (plist-get params :tstart)
7091 te (plist-get params :tend)
7092 block (plist-get params :block))
7093 (when block
7094 (setq cc (org-clock-special-range block nil t)
7095 ts (car cc) te (cdr cc)))
7096 (if ts (setq ts (time-to-seconds
7097 (apply 'encode-time (org-parse-time-string ts)))))
7098 (if te (setq te (time-to-seconds
7099 (apply 'encode-time (org-parse-time-string te)))))
7100 (move-marker ins (point))
7101 (setq ipos (point))
7102 ;; FIXME: does not yet use org-insert-time-stamp
7103 (insert-before-markers "Clock summary at ["
7104 (substring
7105 (format-time-string (cdr org-time-stamp-formats))
7106 1 -1)
7107 "]."
7108 (if block
7109 (format " Considered range is /%s/." block)
7111 "\n\n|L|Headline|Time|\n")
7112 (org-clock-sum ts te)
7113 (setq h (/ org-clock-file-total-minutes 60)
7114 m (- org-clock-file-total-minutes (* 60 h)))
7115 (insert-before-markers "|-\n|0|" "*Total file time*| "
7116 (format "*%d:%02d*" h m)
7117 "|\n")
7118 (goto-char (point-min))
7119 (while (setq p (next-single-property-change (point) :org-clock-minutes))
7120 (goto-char p)
7121 (when (setq time (get-text-property p :org-clock-minutes))
7122 (save-excursion
7123 (beginning-of-line 1)
7124 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
7125 (setq level (- (match-end 1) (match-beginning 1)))
7126 (<= level maxlevel))
7127 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
7128 hdl (match-string 2)
7129 h (/ time 60)
7130 m (- time (* 60 h)))
7131 (goto-char ins)
7132 (if (= level 1) (insert-before-markers "|-\n"))
7133 (insert-before-markers
7134 "| " (int-to-string level) "|" hlc hdl hlc " |"
7135 (make-string (1- level) ?|)
7137 (format "%d:%02d" h m)
7139 " |\n")))))
7140 (goto-char ins)
7141 (backward-delete-char 1)
7142 (goto-char ipos)
7143 (skip-chars-forward "^|")
7144 (org-table-align)))
7146 (defun org-collect-clock-time-entries ()
7147 "Return an internal list with clocking information.
7148 This list has one entry for each CLOCK interval.
7149 FIXME: describe the elements."
7150 (interactive)
7151 (let ((re (concat "^[ \t]*" org-clock-string
7152 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
7153 rtn beg end next cont level title total closedp leafp
7154 clockpos titlepos h m donep)
7155 (save-excursion
7156 (org-clock-sum)
7157 (goto-char (point-min))
7158 (while (re-search-forward re nil t)
7159 (setq clockpos (match-beginning 0)
7160 beg (match-string 1) end (match-string 2)
7161 cont (match-end 0))
7162 (setq beg (apply 'encode-time (org-parse-time-string beg))
7163 end (apply 'encode-time (org-parse-time-string end)))
7164 (org-back-to-heading t)
7165 (setq donep (org-entry-is-done-p))
7166 (setq titlepos (point)
7167 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
7168 h (/ total 60) m (- total (* 60 h))
7169 total (cons h m))
7170 (looking-at "\\(\\*+\\) +\\(.*\\)")
7171 (setq level (- (match-end 1) (match-beginning 1))
7172 title (org-match-string-no-properties 2))
7173 (save-excursion (outline-next-heading) (setq next (point)))
7174 (setq closedp (re-search-forward org-closed-time-regexp next t))
7175 (goto-char next)
7176 (setq leafp (and (looking-at "^\\*+ ")
7177 (<= (- (match-end 0) (point)) level)))
7178 (push (list beg end clockpos closedp donep
7179 total title titlepos level leafp)
7180 rtn)
7181 (goto-char cont)))
7182 (nreverse rtn)))
7184 ;;;; Agenda, and Diary Integration
7186 ;;; Define the mode
7188 (defvar org-agenda-mode-map (make-sparse-keymap)
7189 "Keymap for `org-agenda-mode'.")
7191 (defvar org-agenda-menu) ; defined later in this file.
7192 (defvar org-agenda-follow-mode nil)
7193 (defvar org-agenda-show-log nil)
7194 (defvar org-agenda-redo-command nil)
7195 (defvar org-agenda-mode-hook nil)
7196 (defvar org-agenda-type nil)
7197 (defvar org-agenda-force-single-file nil)
7199 (defun org-agenda-mode ()
7200 "Mode for time-sorted view on action items in Org-mode files.
7202 The following commands are available:
7204 \\{org-agenda-mode-map}"
7205 (interactive)
7206 (kill-all-local-variables)
7207 (setq org-agenda-undo-list nil
7208 org-agenda-pending-undo-list nil)
7209 (setq major-mode 'org-agenda-mode)
7210 (setq mode-name "Org-Agenda")
7211 (use-local-map org-agenda-mode-map)
7212 (easy-menu-add org-agenda-menu)
7213 (if org-startup-truncated (setq truncate-lines t))
7214 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
7215 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
7216 (unless org-agenda-keep-modes
7217 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
7218 org-agenda-show-log nil))
7219 (easy-menu-change
7220 '("Agenda") "Agenda Files"
7221 (append
7222 (list
7223 (vector
7224 (if (get 'org-agenda-files 'org-restrict)
7225 "Restricted to single file"
7226 "Edit File List")
7227 '(org-edit-agenda-file-list)
7228 (not (get 'org-agenda-files 'org-restrict)))
7229 "--")
7230 (mapcar 'org-file-menu-entry (org-agenda-files))))
7231 (org-agenda-set-mode-name)
7232 (apply
7233 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
7234 (list 'org-agenda-mode-hook)))
7236 (substitute-key-definition 'undo 'org-agenda-undo
7237 org-agenda-mode-map global-map)
7238 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
7239 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
7240 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
7241 (define-key org-agenda-mode-map "\C-k" 'org-agenda-kill)
7242 (define-key org-agenda-mode-map "\C-c$" 'org-agenda-archive)
7243 (define-key org-agenda-mode-map "$" 'org-agenda-archive)
7244 (define-key org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
7245 (define-key org-agenda-mode-map " " 'org-agenda-show)
7246 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
7247 (define-key org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
7248 (define-key org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
7249 (define-key org-agenda-mode-map "o" 'delete-other-windows)
7250 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
7251 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
7252 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
7253 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
7254 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
7255 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
7256 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
7257 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
7258 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
7259 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
7260 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
7262 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
7263 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
7264 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
7265 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
7266 (while l (define-key org-agenda-mode-map
7267 (int-to-string (pop l)) 'digit-argument)))
7269 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
7270 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
7271 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
7272 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
7273 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
7274 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
7275 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
7276 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
7277 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
7278 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
7279 (define-key org-agenda-mode-map "n" 'next-line)
7280 (define-key org-agenda-mode-map "p" 'previous-line)
7281 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
7282 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
7283 (define-key org-agenda-mode-map "," 'org-agenda-priority)
7284 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
7285 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
7286 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
7287 (eval-after-load "calendar"
7288 '(define-key calendar-mode-map org-calendar-to-agenda-key
7289 'org-calendar-goto-agenda))
7290 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
7291 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
7292 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
7293 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
7294 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
7295 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
7296 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
7297 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
7298 (define-key org-agenda-mode-map "O" 'org-agenda-clock-out)
7299 (define-key org-agenda-mode-map "X" 'org-agenda-clock-cancel)
7300 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
7301 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
7302 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
7303 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
7304 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
7305 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
7306 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
7307 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
7308 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
7309 "Local keymap for agenda entries from Org-mode.")
7311 (define-key org-agenda-keymap
7312 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
7313 (define-key org-agenda-keymap
7314 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
7315 (when org-agenda-mouse-1-follows-link
7316 (define-key org-agenda-keymap [follow-link] 'mouse-face))
7317 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
7318 '("Agenda"
7319 ("Agenda Files")
7320 "--"
7321 ["Show" org-agenda-show t]
7322 ["Go To (other window)" org-agenda-goto t]
7323 ["Go To (this window)" org-agenda-switch-to t]
7324 ["Follow Mode" org-agenda-follow-mode
7325 :style toggle :selected org-agenda-follow-mode :active t]
7326 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
7327 "--"
7328 ["Cycle TODO" org-agenda-todo t]
7329 ["Archive subtree" org-agenda-archive t]
7330 ["Delete subtree" org-agenda-kill t]
7331 "--"
7332 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
7333 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
7334 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
7335 "--"
7336 ("Tags"
7337 ["Show all Tags" org-agenda-show-tags t]
7338 ["Set Tags" org-agenda-set-tags t])
7339 ("Date/Schedule"
7340 ["Schedule" org-agenda-schedule t]
7341 ["Set Deadline" org-agenda-deadline t]
7342 "--"
7343 ["Change date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
7344 ["Change date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
7345 ["Change date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
7346 ("Priority"
7347 ["Set Priority" org-agenda-priority t]
7348 ["Increase Priority" org-agenda-priority-up t]
7349 ["Decrease Priority" org-agenda-priority-down t]
7350 ["Show Priority" org-agenda-show-priority t])
7351 ("Calendar/Diary"
7352 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
7353 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
7354 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
7355 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
7356 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
7357 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
7358 "--"
7359 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
7360 "--"
7361 ("View"
7362 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
7363 :style radio :selected (equal org-agenda-ndays 1)]
7364 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
7365 :style radio :selected (equal org-agenda-ndays 7)]
7366 "--"
7367 ["Show Logbook entries" org-agenda-log-mode
7368 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
7369 ["Include Diary" org-agenda-toggle-diary
7370 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
7371 ["Use Time Grid" org-agenda-toggle-time-grid
7372 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
7373 ["Rebuild buffer" org-agenda-redo t]
7374 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
7375 "--"
7376 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
7377 "--"
7378 ["Quit" org-agenda-quit t]
7379 ["Exit and Release Buffers" org-agenda-exit t]
7382 ;;; Agenda undo
7384 (defvar org-agenda-allow-remote-undo t
7385 "Non-nil means, allow remote undo from the agenda buffer.")
7386 (defvar org-agenda-undo-list nil
7387 "List of undoable operations in the agenda since last refresh.")
7388 (defvar org-agenda-undo-has-started-in nil
7389 "Buffers that have already seen `undo-start' in the current undo sequence.")
7390 (defvar org-agenda-pending-undo-list nil
7391 "In a series of undo commands, this is the list of remaning undo items.")
7393 (defmacro org-with-remote-undo (_buffer &rest _body)
7394 "Execute BODY while recording undo information in two buffers."
7395 (declare (indent 1) (debug t))
7396 `(let ((_cline (org-current-line))
7397 (_cmd this-command)
7398 (_buf1 (current-buffer))
7399 (_buf2 ,_buffer)
7400 (_undo1 buffer-undo-list)
7401 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
7402 _c1 _c2)
7403 ,@_body
7404 (when org-agenda-allow-remote-undo
7405 (setq _c1 (org-verify-change-for-undo
7406 _undo1 (with-current-buffer _buf1 buffer-undo-list))
7407 _c2 (org-verify-change-for-undo
7408 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
7409 (when (or _c1 _c2)
7410 ;; make sure there are undo boundaries
7411 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
7412 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
7413 ;; remember which buffer to undo
7414 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
7415 org-agenda-undo-list)))))
7417 (defun org-agenda-undo ()
7418 "Undo a remote editing step in the agenda.
7419 This undoes changes both in the agenda buffer and in the remote buffer
7420 that have been changed along."
7421 (interactive)
7422 (or org-agenda-allow-remote-undo
7423 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
7424 (if (not (eq this-command last-command))
7425 (setq org-agenda-undo-has-started-in nil
7426 org-agenda-pending-undo-list org-agenda-undo-list))
7427 (if (not org-agenda-pending-undo-list)
7428 (error "No further undo information"))
7429 (let* ((entry (pop org-agenda-pending-undo-list))
7430 buf line cmd rembuf)
7431 (setq cmd (pop entry) line (pop entry))
7432 (setq rembuf (nth 2 entry))
7433 (org-with-remote-undo rembuf
7434 (while (bufferp (setq buf (pop entry)))
7435 (if (pop entry)
7436 (with-current-buffer buf
7437 (let ((last-undo-buffer buf)
7438 buffer-read-only)
7439 (unless (memq buf org-agenda-undo-has-started-in)
7440 (push buf org-agenda-undo-has-started-in)
7441 (make-local-variable 'pending-undo-list)
7442 (undo-start))
7443 (while (and pending-undo-list
7444 (listp pending-undo-list)
7445 (not (car pending-undo-list)))
7446 (pop pending-undo-list))
7447 (undo-more 1))))))
7448 (goto-line line)
7449 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
7451 (defun org-verify-change-for-undo (l1 l2)
7452 "Verify that a real change occurred between the undo lists L1 and L2."
7453 (while (and l1 (listp l1) (null (car l1))) (pop l1))
7454 (while (and l2 (listp l2) (null (car l2))) (pop l2))
7455 (not (eq l1 l2)))
7457 ;;; Agenda dispatch
7459 (defvar org-agenda-restrict nil)
7460 (defvar org-agenda-restrict-begin (make-marker))
7461 (defvar org-agenda-restrict-end (make-marker))
7462 (defvar org-agenda-last-dispatch-buffer nil)
7464 ;;;###autoload
7465 (defun org-agenda (arg)
7466 "Dispatch agenda commands to collect entries to the agenda buffer.
7467 Prompts for a character to select a command. Any prefix arg will be passed
7468 on to the selected command. The default selections are:
7470 a Call `org-agenda-list' to display the agenda for current day or week.
7471 t Call `org-todo-list' to display the global todo list.
7472 T Call `org-todo-list' to display the global todo list, select only
7473 entries with a specific TODO keyword (the user gets a prompt).
7474 m Call `org-tags-view' to display headlines with tags matching
7475 a condition (the user is prompted for the condition).
7476 M Like `m', but select only TODO entries, no ordinary headlines.
7477 l Create a timeeline for the current buffer.
7479 More commands can be added by configuring the variable
7480 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
7481 searches can be pre-defined in this way.
7483 If the current buffer is in Org-mode and visiting a file, you can also
7484 first press `1' to indicate that the agenda should be temporarily (until the
7485 next use of \\[org-agenda]) restricted to the current file."
7486 (interactive "P")
7487 (catch 'exit
7488 (let* ((buf (current-buffer))
7489 (bfn (buffer-file-name (buffer-base-buffer)))
7490 (restrict-ok (and bfn (org-mode-p)))
7491 (custom org-agenda-custom-commands)
7492 c entry key type match lprops header)
7493 ;; Turn off restriction
7494 (put 'org-agenda-files 'org-restrict nil)
7495 (setq org-agenda-restrict nil)
7496 (move-marker org-agenda-restrict-begin nil)
7497 (move-marker org-agenda-restrict-end nil)
7498 ;; Remember where this call originated
7499 (setq org-agenda-last-dispatch-buffer (current-buffer))
7500 (save-window-excursion
7501 (delete-other-windows)
7502 (switch-to-buffer-other-window " *Agenda Commands*")
7503 (erase-buffer)
7504 (insert (eval-when-compile
7505 (let ((header
7506 "Press key for an agenda command:
7507 -------------------------------- C Configure custom agenda commands
7508 a Agenda for current week or day
7509 t List of all TODO entries T Entries with special TODO kwd
7510 m Match a TAGS query M Like m, but only TODO entries
7511 L Timeline for current buffer # List stuck projects (!=configure)
7513 (start 0))
7514 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
7515 (setq start (match-end 0))
7516 (add-text-properties (match-beginning 2) (match-end 2)
7517 '(face bold) header))
7518 header)))
7519 (while (setq entry (pop custom))
7520 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
7521 (insert (format "\n%-4s%-14s: %s"
7522 (org-add-props (copy-sequence key)
7523 '(face bold))
7524 (cond
7525 ((stringp type) type)
7526 ((eq type 'tags) "Tags query")
7527 ((eq type 'todo) "TODO keyword")
7528 ((eq type 'tags-tree) "Tags tree")
7529 ((eq type 'todo-tree) "TODO kwd tree")
7530 ((eq type 'occur-tree) "Occur tree")
7531 ((functionp type) (symbol-name type))
7532 (t "???"))
7533 (if (stringp match)
7534 (org-add-props match nil 'face 'org-warning)
7535 (format "set of %d commands" (+ -2 (length entry)))))))
7536 (if restrict-ok
7537 (insert "\n"
7538 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
7540 (goto-char (point-min))
7541 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
7542 (message "Press key for agenda command%s"
7543 (if restrict-ok ", or [1] or [0] to restrict" ""))
7544 (setq c (read-char-exclusive))
7545 (message "")
7546 (when (memq c '(?L ?1 ?0))
7547 (if restrict-ok
7548 (put 'org-agenda-files 'org-restrict (list bfn))
7549 (error "Cannot restrict agenda to current buffer"))
7550 (with-current-buffer " *Agenda Commands*"
7551 (goto-char (point-max))
7552 (delete-region (point-at-bol) (point))
7553 (goto-char (point-min)))
7554 (when (eq c ?0)
7555 (setq org-agenda-restrict t)
7556 (with-current-buffer buf
7557 (if (org-region-active-p)
7558 (progn
7559 (move-marker org-agenda-restrict-begin (region-beginning))
7560 (move-marker org-agenda-restrict-end (region-end)))
7561 (save-excursion
7562 (org-back-to-heading t)
7563 (move-marker org-agenda-restrict-begin (point))
7564 (move-marker org-agenda-restrict-end
7565 (progn (org-end-of-subtree t)))))))
7566 (unless (eq c ?L)
7567 (message "Press key for agenda command%s"
7568 (if restrict-ok " (restricted to current file)" ""))
7569 (setq c (read-char-exclusive)))
7570 (message "")))
7571 (require 'calendar) ; FIXME: can we avoid this for some commands?
7572 ;; For example the todo list should not need it (but does...)
7573 (cond
7574 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
7575 (if (symbolp (nth 1 entry))
7576 (progn
7577 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
7578 lprops (nth 3 entry))
7579 (cond
7580 ((eq type 'tags)
7581 (org-let lprops '(org-tags-view current-prefix-arg match)))
7582 ((eq type 'tags-todo)
7583 (org-let lprops '(org-tags-view '(4) match)))
7584 ((eq type 'todo)
7585 (org-let lprops '(org-todo-list match)))
7586 ((eq type 'tags-tree)
7587 (org-check-for-org-mode)
7588 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
7589 ((eq type 'todo-tree)
7590 (org-check-for-org-mode)
7591 (org-let lprops
7592 '(org-occur (concat "^" outline-regexp "[ \t]*"
7593 (regexp-quote match) "\\>"))))
7594 ((eq type 'occur-tree)
7595 (org-check-for-org-mode)
7596 (org-let lprops '(org-occur match)))
7597 ((fboundp type)
7598 (org-let lprops '(funcall type match)))
7599 (t (error "Invalid custom agenda command type %s" type))))
7600 (org-run-agenda-series (cddr entry))))
7601 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
7602 ((equal c ?a) (call-interactively 'org-agenda-list))
7603 ((equal c ?t) (call-interactively 'org-todo-list))
7604 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
7605 ((equal c ?m) (call-interactively 'org-tags-view))
7606 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
7607 ((equal c ?L)
7608 (unless restrict-ok
7609 (error "This is not an Org-mode file"))
7610 (org-call-with-arg 'org-timeline arg))
7611 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
7612 ((equal c ?!) (customize-variable 'org-stuck-projects))
7613 (t (error "Invalid key"))))))
7615 ;; FIXME: what is the meaning of WINDOW?????
7616 (defun org-run-agenda-series (series &optional window)
7617 (org-prepare-agenda)
7618 (let* ((org-agenda-multi t)
7619 (redo (list 'org-run-agenda-series (list 'quote series)))
7620 (org-select-agenda-window t)
7621 (cmds (car series))
7622 (gprops (nth 1 series))
7623 match ;; The byte compiler incorrectly complains about this. Keep it!
7624 cmd type lprops)
7625 (while (setq cmd (pop cmds))
7626 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
7627 (cond
7628 ((eq type 'agenda)
7629 (call-interactively 'org-agenda-list))
7630 ((eq type 'alltodo)
7631 (call-interactively 'org-todo-list))
7632 ((eq type 'tags)
7633 (org-let2 gprops lprops
7634 '(org-tags-view current-prefix-arg match)))
7635 ((eq type 'tags-todo)
7636 (org-let2 gprops lprops
7637 '(org-tags-view '(4) match)))
7638 ((eq type 'todo)
7639 (org-let2 gprops lprops
7640 '(org-todo-list match)))
7641 ((fboundp type)
7642 (org-let2 gprops lprops
7643 '(funcall type match)))
7644 (t (error "Invalid type in command series"))))
7645 (widen)
7646 (setq org-agenda-redo-command redo)
7647 (goto-char (point-min)))
7648 (org-finalize-agenda))
7650 ;;;###autoload
7651 (defmacro org-batch-agenda (cmd-key &rest parameters)
7652 "Run an agenda command in batch mode, send result to STDOUT.
7653 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
7654 Paramters are alternating variable names and values that will be bound
7655 before running the agenda command."
7656 (let (pars)
7657 (while parameters
7658 (push (list (pop parameters) (if parameters (pop parameters))) pars))
7659 (flet ((read-char-exclusive () (string-to-char cmd-key)))
7660 (eval (list 'let (nreverse pars) '(org-agenda nil))))
7661 (set-buffer "*Org Agenda*")
7662 (princ (buffer-string))))
7664 (defmacro org-no-read-only (&rest body)
7665 "Inhibit read-only for BODY."
7666 `(let ((inhibit-read-only t)) ,@body))
7668 (defun org-check-for-org-mode ()
7669 "Make sure current buffer is in org-mode. Error if not."
7670 (or (org-mode-p)
7671 (error "Cannot execute org-mode agenda command on buffer in %s."
7672 major-mode)))
7674 (defun org-fit-agenda-window ()
7675 "Fit the window to the buffer size."
7676 (and org-fit-agenda-window
7677 (memq org-agenda-window-setup '(reorganize-frame))
7678 (fboundp 'fit-window-to-buffer)
7679 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
7680 (/ (frame-height) 2))))
7682 (defun org-agenda-files (&optional unrestricted)
7683 "Get the list of agenda files.
7684 Optional UNRESTRICTED means return the full list even if a restriction
7685 is currently in place."
7686 (cond
7687 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
7688 ((stringp org-agenda-files) (org-read-agenda-file-list))
7689 ((listp org-agenda-files) org-agenda-files)
7690 (t (error "Invalid value of `org-agenda-files'"))))
7692 (defvar org-window-configuration)
7694 (defun org-edit-agenda-file-list ()
7695 "Edit the list of agenda files.
7696 Depending on setup, this either uses customize to edit the variable
7697 `org-agenda-files', or it visits the file that is holding the list. In the
7698 latter case, the buffer is set up in a way that saving it automatically kills
7699 the buffer and restores the previous window configuration."
7700 (interactive)
7701 (if (stringp org-agenda-files)
7702 (let ((cw (current-window-configuration)))
7703 (find-file org-agenda-files)
7704 (org-set-local 'org-window-configuration cw)
7705 (org-add-hook 'after-save-hook
7706 (lambda ()
7707 (set-window-configuration
7708 (prog1 org-window-configuration
7709 (kill-buffer (current-buffer))))
7710 (org-install-agenda-files-menu)
7711 (message "New agenda file list installed"))
7712 nil 'local)
7713 (message (substitute-command-keys
7714 "Edit list and finish with \\[save-buffer]")))
7715 (customize-variable 'org-agenda-files)))
7717 (defun org-store-new-agenda-file-list (list)
7718 "Set new value for the agenda file list and save it correcly."
7719 (if (stringp org-agenda-files)
7720 (let ((f org-agenda-files) b)
7721 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
7722 (with-temp-file f
7723 (insert (mapconcat 'identity list "\n") "\n")))
7724 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
7725 (setq org-agenda-files list)
7726 (customize-save-variable 'org-agenda-files org-agenda-files))))
7728 (defun org-read-agenda-file-list ()
7729 "Read the list of agenda files from a file."
7730 (when (stringp org-agenda-files)
7731 (with-temp-buffer
7732 (insert-file-contents org-agenda-files)
7733 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
7735 (defvar org-agenda-markers nil
7736 "List of all currently active markers created by `org-agenda'.")
7737 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
7738 "Creation time of the last agenda marker.")
7740 (defun org-agenda-new-marker (&optional pos)
7741 "Return a new agenda marker.
7742 Org-mode keeps a list of these markers and resets them when they are
7743 no longer in use."
7744 (let ((m (copy-marker (or pos (point)))))
7745 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
7746 (push m org-agenda-markers)
7749 (defun org-agenda-maybe-reset-markers (&optional force)
7750 "Reset markers created by `org-agenda'. But only if they are old enough."
7751 (if (or (and force (not org-agenda-multi))
7752 (> (- (time-to-seconds (current-time))
7753 org-agenda-last-marker-time)
7755 (while org-agenda-markers
7756 (move-marker (pop org-agenda-markers) nil))))
7758 (defvar org-agenda-new-buffers nil
7759 "Buffers created to visit agenda files.")
7761 (defun org-get-agenda-file-buffer (file)
7762 "Get a buffer visiting FILE. If the buffer needs to be created, add
7763 it to the list of buffers which might be released later."
7764 (let ((buf (find-buffer-visiting file)))
7765 (if buf
7766 buf ; just return it
7767 ;; Make a new buffer and remember it
7768 (setq buf (find-file-noselect file))
7769 (if buf (push buf org-agenda-new-buffers))
7770 buf)))
7772 (defun org-release-buffers (blist)
7773 "Release all buffers in list, asking the user for confirmation when needed.
7774 When a buffer is unmodified, it is just killed. When modified, it is saved
7775 \(if the user agrees) and then killed."
7776 (let (buf file)
7777 (while (setq buf (pop blist))
7778 (setq file (buffer-file-name buf))
7779 (when (and (buffer-modified-p buf)
7780 file
7781 (y-or-n-p (format "Save file %s? " file)))
7782 (with-current-buffer buf (save-buffer)))
7783 (kill-buffer buf))))
7785 (defun org-timeline (&optional include-all)
7786 "Show a time-sorted view of the entries in the current org file.
7787 Only entries with a time stamp of today or later will be listed. With
7788 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
7789 under the current date.
7790 If the buffer contains an active region, only check the region for
7791 dates."
7792 (interactive "P")
7793 (require 'calendar)
7794 (org-compile-prefix-format 'timeline)
7795 (org-set-sorting-strategy 'timeline)
7796 (let* ((dopast t)
7797 (dotodo include-all)
7798 (doclosed org-agenda-show-log)
7799 (entry buffer-file-name)
7800 (date (calendar-current-date))
7801 (win (selected-window))
7802 (pos1 (point))
7803 (beg (if (org-region-active-p) (region-beginning) (point-min)))
7804 (end (if (org-region-active-p) (region-end) (point-max)))
7805 (day-numbers (org-get-all-dates beg end 'no-ranges
7806 t doclosed ; always include today
7807 org-timeline-show-empty-dates))
7808 (today (time-to-days (current-time)))
7809 (past t)
7810 args
7811 s e rtn d emptyp)
7812 (setq org-agenda-redo-command
7813 (list 'progn
7814 (list 'switch-to-buffer-other-window (current-buffer))
7815 (list 'org-timeline (list 'quote include-all))))
7816 (if (not dopast)
7817 ;; Remove past dates from the list of dates.
7818 (setq day-numbers (delq nil (mapcar (lambda(x)
7819 (if (>= x today) x nil))
7820 day-numbers))))
7821 (org-prepare-agenda)
7822 (if doclosed (push :closed args))
7823 (push :timestamp args)
7824 (if dotodo (push :todo args))
7825 (while (setq d (pop day-numbers))
7826 (if (and (listp d) (eq (car d) :omitted))
7827 (progn
7828 (setq s (point))
7829 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
7830 (put-text-property s (1- (point)) 'face 'org-level-3))
7831 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
7832 (if (and (>= d today)
7833 dopast
7834 past)
7835 (progn
7836 (setq past nil)
7837 (insert (make-string 79 ?-) "\n")))
7838 (setq date (calendar-gregorian-from-absolute d))
7839 (setq s (point))
7840 (setq rtn (and (not emptyp)
7841 (apply 'org-agenda-get-day-entries
7842 entry date args)))
7843 (if (or rtn (equal d today) org-timeline-show-empty-dates)
7844 (progn
7845 (insert (calendar-day-name date) " "
7846 (number-to-string (extract-calendar-day date)) " "
7847 (calendar-month-name (extract-calendar-month date)) " "
7848 (number-to-string (extract-calendar-year date)) "\n")
7849 (put-text-property s (1- (point)) 'face
7850 'org-level-3)
7851 (if (equal d today)
7852 (put-text-property s (1- (point)) 'org-today t))
7853 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
7854 (put-text-property s (1- (point)) 'day d)))))
7855 (goto-char (point-min))
7856 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
7857 (point-min)))
7858 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
7859 (org-finalize-agenda)
7860 (setq buffer-read-only t)
7861 (when (not org-select-agenda-window)
7862 (select-window win)
7863 (goto-char pos1))))
7865 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
7866 (defvar org-agenda-last-arguments nil
7867 "The arguments of the previous call to org-agenda")
7869 ;;;###autoload
7870 (defun org-agenda-list (&optional include-all start-day ndays)
7871 "Produce a weekly view from all files in variable `org-agenda-files'.
7872 The view will be for the current week, but from the overview buffer you
7873 will be able to go to other weeks.
7874 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
7875 also be shown, under the current date.
7876 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
7877 on the days are also shown. See the variable `org-log-done' for how
7878 to turn on logging.
7879 START-DAY defaults to TODAY, or to the most recent match for the weekday
7880 given in `org-agenda-start-on-weekday'.
7881 NDAYS defaults to `org-agenda-ndays'."
7882 (interactive "P")
7883 (if org-agenda-overriding-arguments
7884 (setq include-all (car org-agenda-overriding-arguments)
7885 start-day (nth 1 org-agenda-overriding-arguments)
7886 ndays (nth 2 org-agenda-overriding-arguments)))
7887 (setq org-agenda-last-arguments (list include-all start-day ndays))
7888 (org-compile-prefix-format 'agenda)
7889 (org-set-sorting-strategy 'agenda)
7890 (require 'calendar)
7891 (let* ((org-agenda-start-on-weekday
7892 (if (or (equal ndays 1)
7893 (and (null ndays) (equal 1 org-agenda-ndays)))
7894 nil org-agenda-start-on-weekday))
7895 (thefiles (org-agenda-files))
7896 (files thefiles)
7897 (win (selected-window))
7898 (today (time-to-days (current-time)))
7899 (sd (or start-day today))
7900 (start (if (or (null org-agenda-start-on-weekday)
7901 (< org-agenda-ndays 7))
7903 (let* ((nt (calendar-day-of-week
7904 (calendar-gregorian-from-absolute sd)))
7905 (n1 org-agenda-start-on-weekday)
7906 (d (- nt n1)))
7907 (- sd (+ (if (< d 0) 7 0) d)))))
7908 (day-numbers (list start))
7909 (inhibit-redisplay t)
7910 s e rtn rtnall file date d start-pos end-pos todayp nd)
7911 (setq org-agenda-redo-command
7912 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
7913 ;; Make the list of days
7914 (setq ndays (or ndays org-agenda-ndays)
7915 nd ndays)
7916 (while (> ndays 1)
7917 (push (1+ (car day-numbers)) day-numbers)
7918 (setq ndays (1- ndays)))
7919 (setq day-numbers (nreverse day-numbers))
7920 (org-prepare-agenda)
7921 (org-set-local 'starting-day (car day-numbers))
7922 (org-set-local 'include-all-loc include-all)
7923 (when (and (or include-all org-agenda-include-all-todo)
7924 (member today day-numbers))
7925 (setq files thefiles
7926 rtnall nil)
7927 (while (setq file (pop files))
7928 (catch 'nextfile
7929 (org-check-agenda-file file)
7930 (setq date (calendar-gregorian-from-absolute today)
7931 rtn (org-agenda-get-day-entries
7932 file date :todo))
7933 (setq rtnall (append rtnall rtn))))
7934 (when rtnall
7935 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
7936 (add-text-properties (point-min) (1- (point))
7937 (list 'face 'org-level-3))
7938 (insert (org-finalize-agenda-entries rtnall) "\n")))
7939 (setq s (point))
7940 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
7941 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
7942 (while (setq d (pop day-numbers))
7943 (setq date (calendar-gregorian-from-absolute d)
7944 s (point))
7945 (if (or (setq todayp (= d today))
7946 (and (not start-pos) (= d sd)))
7947 (setq start-pos (point))
7948 (if (and start-pos (not end-pos))
7949 (setq end-pos (point))))
7950 (setq files thefiles
7951 rtnall nil)
7952 (while (setq file (pop files))
7953 (catch 'nextfile
7954 (org-check-agenda-file file)
7955 (if org-agenda-show-log
7956 (setq rtn (org-agenda-get-day-entries
7957 file date
7958 :deadline :scheduled :timestamp :closed))
7959 (setq rtn (org-agenda-get-day-entries
7960 file date
7961 :deadline :scheduled :timestamp)))
7962 (setq rtnall (append rtnall rtn))))
7963 (if org-agenda-include-diary
7964 (progn
7965 (require 'diary-lib)
7966 (setq rtn (org-get-entries-from-diary date))
7967 (setq rtnall (append rtnall rtn))))
7968 (if (or rtnall org-agenda-show-all-dates)
7969 (progn
7970 (insert (format "%-9s %2d %s %4d\n"
7971 (calendar-day-name date)
7972 (extract-calendar-day date)
7973 (calendar-month-name (extract-calendar-month date))
7974 (extract-calendar-year date)))
7975 (put-text-property s (1- (point)) 'face
7976 'org-level-3)
7977 (if todayp (put-text-property s (1- (point)) 'org-today t))
7979 (if rtnall (insert
7980 (org-finalize-agenda-entries
7981 (org-agenda-add-time-grid-maybe
7982 rtnall nd todayp))
7983 "\n"))
7984 (put-text-property s (1- (point)) 'day d))))
7985 (goto-char (point-min))
7986 (org-fit-agenda-window)
7987 (unless (and (pos-visible-in-window-p (point-min))
7988 (pos-visible-in-window-p (point-max)))
7989 (goto-char (1- (point-max)))
7990 (recenter -1)
7991 (if (not (pos-visible-in-window-p (or start-pos 1)))
7992 (progn
7993 (goto-char (or start-pos 1))
7994 (recenter 1))))
7995 (goto-char (or start-pos 1))
7996 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
7997 (org-finalize-agenda)
7998 (setq buffer-read-only t)
7999 (if (not org-select-agenda-window) (select-window win))
8000 (message "")))
8002 (defvar org-select-this-todo-keyword nil)
8004 ;;;###autoload
8005 (defun org-todo-list (arg)
8006 "Show all TODO entries from all agenda file in a single list.
8007 The prefix arg can be used to select a specific TODO keyword and limit
8008 the list to these. When using \\[universal-argument], you will be prompted
8009 for a keyword. A numeric prefix directly selects the Nth keyword in
8010 `org-todo-keywords'."
8011 (interactive "P")
8012 (require 'calendar)
8013 (org-compile-prefix-format 'todo)
8014 (org-set-sorting-strategy 'todo)
8015 (let* ((today (time-to-days (current-time)))
8016 (date (calendar-gregorian-from-absolute today))
8017 (win (selected-window))
8018 (kwds org-todo-keywords)
8019 (completion-ignore-case t)
8020 (org-select-this-todo-keyword
8021 (if (stringp arg) arg
8022 (and arg (integerp arg) (> arg 0)
8023 (nth (1- arg) org-todo-keywords))))
8024 rtn rtnall files file pos)
8025 (when (equal arg '(4))
8026 (setq org-select-this-todo-keyword
8027 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
8028 nil t)))
8029 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
8030 (org-prepare-agenda)
8031 (org-set-local 'last-arg arg)
8032 (org-set-local 'org-todo-keywords kwds)
8033 (setq org-agenda-redo-command
8034 '(org-todo-list (or current-prefix-arg last-arg)))
8035 (setq files (org-agenda-files)
8036 rtnall nil)
8037 (while (setq file (pop files))
8038 (catch 'nextfile
8039 (org-check-agenda-file file)
8040 (setq rtn (org-agenda-get-day-entries file date :todo))
8041 (setq rtnall (append rtnall rtn))))
8042 (if org-agenda-overriding-header
8043 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
8044 nil 'face 'org-level-3) "\n")
8045 (insert "Global list of TODO items of type: ")
8046 (add-text-properties (point-min) (1- (point))
8047 (list 'face 'org-level-3))
8048 (setq pos (point))
8049 (insert (or org-select-this-todo-keyword "ALL") "\n")
8050 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
8051 (setq pos (point))
8052 (unless org-agenda-multi
8053 (insert
8054 "Available with `N r': (0)ALL "
8055 (let ((n 0))
8056 (mapconcat (lambda (x)
8057 (format "(%d)%s" (setq n (1+ n)) x))
8058 org-todo-keywords " "))
8059 "\n"))
8060 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
8061 (when rtnall
8062 (insert (org-finalize-agenda-entries rtnall) "\n"))
8063 (goto-char (point-min))
8064 (org-fit-agenda-window)
8065 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
8066 (org-finalize-agenda)
8067 (setq buffer-read-only t)
8068 (if (not org-select-agenda-window) (select-window win))))
8070 ;;; Finding stuck projects
8071 (defvar org-agenda-skip-regexp nil
8072 "Regular expression used in skipping subtrees for the agenda.
8073 This is basically a temporary global variable that can be set and then
8074 used by user-defined selections using `org-agenda-skip-function'.")
8076 (defvar org-agenda-overriding-header nil
8077 "When this is set during todo and tags searches, will replace header.")
8079 (defun org-agenda-skip-subtree-when-regexp-matches ()
8080 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
8081 If yes, it returns the end position of this tree, causing agenda commands
8082 to skip this subtree. This is a function that can be put into
8083 `org-agenda-skip-function' for the duration of a command."
8084 (save-match-data
8085 (let ((end (save-excursion (org-end-of-subtree t)))
8086 skip)
8087 (save-excursion
8088 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
8089 (and skip end))))
8091 (defun org-agenda-list-stuck-projects (match)
8092 "Create agenda view for projects that are stuck.
8093 Stuck projects are project that have no next actions. For the definitions
8094 of what a project is and how to check if it stuck, customize the variable
8095 `org-stuck-projects'.
8096 MATCH is being ignored."
8097 (interactive)
8098 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
8099 (org-agenda-overriding-header "List of stuck projects: ")
8100 (matcher (nth 0 org-stuck-projects))
8101 (todo (nth 1 org-stuck-projects))
8102 (tags (nth 2 org-stuck-projects))
8103 (todo-re (concat "^\\*+[ \t]+\\("
8104 (mapconcat 'identity todo "\\|")
8105 "\\)\\>"))
8106 (tags-re (concat "^\\*+.*:\\("
8107 (mapconcat 'identity tags "\\|")
8108 "\\):[a-zA-Z0-9_@:]*[ \t]*$")))
8110 (setq org-agenda-skip-regexp
8111 (cond
8112 ((and todo tags)
8113 (concat todo-re "\\|" tags-re))
8114 (todo todo-re)
8115 (tags tags-re)
8116 (t (error "No information how to identify unstuck projects"))))
8117 (org-tags-view nil matcher)))
8119 (defun org-check-agenda-file (file)
8120 "Make sure FILE exists. If not, ask user what to do."
8121 (when (not (file-exists-p file))
8122 (message "non-existent file %s. [R]emove from list or [A]bort?"
8123 (abbreviate-file-name file))
8124 (let ((r (downcase (read-char-exclusive))))
8125 (cond
8126 ((equal r ?r)
8127 (org-remove-file file)
8128 (throw 'nextfile t))
8129 (t (error "Abort"))))))
8131 (defun org-agenda-check-type (error &rest types)
8132 "Check if agenda buffer is of allowed type.
8133 If ERROR is non-nil, throw an error, otherwise just return nil."
8134 (if (memq org-agenda-type types)
8136 (if error
8137 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
8138 nil)))
8140 (defun org-agenda-quit ()
8141 "Exit agenda by removing the window or the buffer."
8142 (interactive)
8143 (let ((buf (current-buffer)))
8144 (if (not (one-window-p)) (delete-window))
8145 (kill-buffer buf)
8146 (org-agenda-maybe-reset-markers 'force))
8147 ;; Maybe restore the pre-agenda window configuration.
8148 (and org-agenda-restore-windows-after-quit
8149 (not (eq org-agenda-window-setup 'other-frame))
8150 org-pre-agenda-window-conf
8151 (set-window-configuration org-pre-agenda-window-conf)))
8153 (defun org-agenda-exit ()
8154 "Exit agenda by removing the window or the buffer.
8155 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
8156 Org-mode buffers visited directly by the user will not be touched."
8157 (interactive)
8158 (org-release-buffers org-agenda-new-buffers)
8159 (setq org-agenda-new-buffers nil)
8160 (org-agenda-quit))
8162 (defun org-save-all-org-buffers ()
8163 "Save all Org-mode buffers without user confirmation."
8164 (interactive)
8165 (message "Saving all Org-mode buffers...")
8166 (save-some-buffers t 'org-mode-p)
8167 (message "Saving all Org-mode buffers... done"))
8169 (defun org-agenda-redo ()
8170 "Rebuild Agenda.
8171 When this is the global TODO list, a prefix argument will be interpreted."
8172 (interactive)
8173 (let* ((org-agenda-keep-modes t)
8174 (line (org-current-line))
8175 (window-line (- line (org-current-line (window-start)))))
8176 (message "Rebuilding agenda buffer...")
8177 (eval org-agenda-redo-command)
8178 (setq org-agenda-undo-list nil
8179 org-agenda-pending-undo-list nil)
8180 (message "Rebuilding agenda buffer...done")
8181 (goto-line line)
8182 (recenter window-line)))
8184 (defun org-agenda-goto-today ()
8185 "Go to today."
8186 (interactive)
8187 (org-agenda-check-type t 'timeline 'agenda)
8188 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
8189 (cond
8190 (tdpos (goto-char tdpos))
8191 ((eq org-agenda-type 'agenda)
8192 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
8193 (setf (nth 1 org-agenda-overriding-arguments) nil)
8194 (org-agenda-redo)
8195 (org-agenda-find-today-or-agenda)))
8196 (t (error "Cannot find today")))))
8198 (defun org-agenda-find-today-or-agenda ()
8199 (goto-char
8200 (or (text-property-any (point-min) (point-max) 'org-today t)
8201 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
8202 (point-min))))
8204 (defun org-agenda-later (arg)
8205 "Go forward in time by `org-agenda-ndays' days.
8206 With prefix ARG, go forward that many times `org-agenda-ndays'."
8207 (interactive "p")
8208 (org-agenda-check-type t 'agenda)
8209 (let ((org-agenda-overriding-arguments
8210 (list (car org-agenda-last-arguments)
8211 (+ starting-day (* arg org-agenda-ndays))
8212 nil t)))
8213 (org-agenda-redo)
8214 (org-agenda-find-today-or-agenda)))
8216 (defun org-agenda-earlier (arg)
8217 "Go back in time by `org-agenda-ndays' days.
8218 With prefix ARG, go back that many times `org-agenda-ndays'."
8219 (interactive "p")
8220 (org-agenda-check-type t 'agenda)
8221 (let ((org-agenda-overriding-arguments
8222 (list (car org-agenda-last-arguments)
8223 (- starting-day (* arg org-agenda-ndays))
8224 nil t)))
8225 (org-agenda-redo)
8226 (org-agenda-find-today-or-agenda)))
8228 (defun org-agenda-week-view ()
8229 "Switch to weekly view for agenda."
8230 (interactive)
8231 (org-agenda-check-type t 'agenda)
8232 (if (= org-agenda-ndays 7)
8233 (error "This is already the week view"))
8234 (setq org-agenda-ndays 7)
8235 (let ((org-agenda-overriding-arguments
8236 (list (car org-agenda-last-arguments)
8237 (or (get-text-property (point) 'day)
8238 starting-day)
8239 nil t)))
8240 (org-agenda-redo)
8241 (org-agenda-find-today-or-agenda))
8242 (org-agenda-set-mode-name)
8243 (message "Switched to week view"))
8245 (defun org-agenda-day-view ()
8246 "Switch to daily view for agenda."
8247 (interactive)
8248 (org-agenda-check-type t 'agenda)
8249 (if (= org-agenda-ndays 1)
8250 (error "This is already the day view"))
8251 (setq org-agenda-ndays 1)
8252 (let ((org-agenda-overriding-arguments
8253 (list (car org-agenda-last-arguments)
8254 (or (get-text-property (point) 'day)
8255 starting-day)
8256 nil t)))
8257 (org-agenda-redo)
8258 (org-agenda-find-today-or-agenda))
8259 (org-agenda-set-mode-name)
8260 (message "Switched to day view"))
8262 (defun org-agenda-next-date-line (&optional arg)
8263 "Jump to the next line indicating a date in agenda buffer."
8264 (interactive "p")
8265 (org-agenda-check-type t 'agenda 'timeline)
8266 (beginning-of-line 1)
8267 (if (looking-at "^\\S-") (forward-char 1))
8268 (if (not (re-search-forward "^\\S-" nil t arg))
8269 (progn
8270 (backward-char 1)
8271 (error "No next date after this line in this buffer")))
8272 (goto-char (match-beginning 0)))
8274 (defun org-agenda-previous-date-line (&optional arg)
8275 "Jump to the previous line indicating a date in agenda buffer."
8276 (interactive "p")
8277 (org-agenda-check-type t 'agenda 'timeline)
8278 (beginning-of-line 1)
8279 (if (not (re-search-backward "^\\S-" nil t arg))
8280 (error "No previous date before this line in this buffer")))
8282 ;; Initialize the highlight
8283 (defvar org-hl (org-make-overlay 1 1))
8284 (org-overlay-put org-hl 'face 'highlight)
8286 (defun org-highlight (begin end &optional buffer)
8287 "Highlight a region with overlay."
8288 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
8289 org-hl begin end (or buffer (current-buffer))))
8291 (defun org-unhighlight ()
8292 "Detach overlay INDEX."
8293 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
8296 (defun org-agenda-follow-mode ()
8297 "Toggle follow mode in an agenda buffer."
8298 (interactive)
8299 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
8300 (org-agenda-set-mode-name)
8301 (message "Follow mode is %s"
8302 (if org-agenda-follow-mode "on" "off")))
8304 (defun org-agenda-log-mode ()
8305 "Toggle log mode in an agenda buffer."
8306 (interactive)
8307 (org-agenda-check-type t 'agenda 'timeline)
8308 (setq org-agenda-show-log (not org-agenda-show-log))
8309 (org-agenda-set-mode-name)
8310 (org-agenda-redo)
8311 (message "Log mode is %s"
8312 (if org-agenda-show-log "on" "off")))
8314 (defun org-agenda-toggle-diary ()
8315 "Toggle diary inclusion in an agenda buffer."
8316 (interactive)
8317 (org-agenda-check-type t 'agenda)
8318 (setq org-agenda-include-diary (not org-agenda-include-diary))
8319 (org-agenda-redo)
8320 (org-agenda-set-mode-name)
8321 (message "Diary inclusion turned %s"
8322 (if org-agenda-include-diary "on" "off")))
8324 (defun org-agenda-toggle-time-grid ()
8325 "Toggle time grid in an agenda buffer."
8326 (interactive)
8327 (org-agenda-check-type t 'agenda)
8328 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
8329 (org-agenda-redo)
8330 (org-agenda-set-mode-name)
8331 (message "Time-grid turned %s"
8332 (if org-agenda-use-time-grid "on" "off")))
8334 (defun org-agenda-set-mode-name ()
8335 "Set the mode name to indicate all the small mode settings."
8336 (setq mode-name
8337 (concat "Org-Agenda"
8338 (if (equal org-agenda-ndays 1) " Day" "")
8339 (if (equal org-agenda-ndays 7) " Week" "")
8340 (if org-agenda-follow-mode " Follow" "")
8341 (if org-agenda-include-diary " Diary" "")
8342 (if org-agenda-use-time-grid " Grid" "")
8343 (if org-agenda-show-log " Log" "")))
8344 (force-mode-line-update))
8346 (defun org-agenda-post-command-hook ()
8347 (and (eolp) (not (bolp)) (backward-char 1))
8348 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
8349 (if (and org-agenda-follow-mode
8350 (get-text-property (point) 'org-marker))
8351 (org-agenda-show)))
8353 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
8355 (defun org-get-entries-from-diary (date)
8356 "Get the (Emacs Calendar) diary entries for DATE."
8357 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
8358 (diary-display-hook '(fancy-diary-display))
8359 (list-diary-entries-hook
8360 (cons 'org-diary-default-entry list-diary-entries-hook))
8361 (diary-file-name-prefix-function nil) ; turn this feature off
8362 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
8363 entries
8364 (org-disable-agenda-to-diary t))
8365 (save-excursion
8366 (save-window-excursion
8367 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
8368 (if (not (get-buffer fancy-diary-buffer))
8369 (setq entries nil)
8370 (with-current-buffer fancy-diary-buffer
8371 (setq buffer-read-only nil)
8372 (if (= (point-max) 1)
8373 ;; No entries
8374 (setq entries nil)
8375 ;; Omit the date and other unnecessary stuff
8376 (org-agenda-cleanup-fancy-diary)
8377 ;; Add prefix to each line and extend the text properties
8378 (if (= (point-max) 1)
8379 (setq entries nil)
8380 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
8381 (set-buffer-modified-p nil)
8382 (kill-buffer fancy-diary-buffer)))
8383 (when entries
8384 (setq entries (org-split-string entries "\n"))
8385 (setq entries
8386 (mapcar
8387 (lambda (x)
8388 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
8389 ;; Extend the text properties to the beginning of the line
8390 (org-add-props x (text-properties-at (1- (length x)) x)))
8391 entries)))))
8393 (defun org-agenda-cleanup-fancy-diary ()
8394 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
8395 This gets rid of the date, the underline under the date, and
8396 the dummy entry installed by `org-mode' to ensure non-empty diary for each
8397 date. It also removes lines that contain only whitespace."
8398 (goto-char (point-min))
8399 (if (looking-at ".*?:[ \t]*")
8400 (progn
8401 (replace-match "")
8402 (re-search-forward "\n=+$" nil t)
8403 (replace-match "")
8404 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
8405 (re-search-forward "\n=+$" nil t)
8406 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
8407 (goto-char (point-min))
8408 (while (re-search-forward "^ +\n" nil t)
8409 (replace-match ""))
8410 (goto-char (point-min))
8411 (if (re-search-forward "^Org-mode dummy\n?" nil t)
8412 (replace-match "")))
8414 ;; Make sure entries from the diary have the right text properties.
8415 (eval-after-load "diary-lib"
8416 '(if (boundp 'diary-modify-entry-list-string-function)
8417 ;; We can rely on the hook, nothing to do
8419 ;; Hook not avaiable, must use advice to make this work
8420 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
8421 "Make the position visible."
8422 (if (and org-disable-agenda-to-diary ;; called from org-agenda
8423 (stringp string)
8424 buffer-file-name)
8425 (setq string (org-modify-diary-entry-string string))))))
8427 (defun org-modify-diary-entry-string (string)
8428 "Add text properties to string, allowing org-mode to act on it."
8429 (org-add-props string nil
8430 'mouse-face 'highlight
8431 'keymap org-agenda-keymap
8432 'help-echo (format "mouse-2 or RET jump to diary file %s"
8433 (abbreviate-file-name buffer-file-name))
8434 'org-agenda-diary-link t
8435 'org-marker (org-agenda-new-marker (point-at-bol))))
8437 (defun org-diary-default-entry ()
8438 "Add a dummy entry to the diary.
8439 Needed to avoid empty dates which mess up holiday display."
8440 ;; Catch the error if dealing with the new add-to-diary-alist
8441 (when org-disable-agenda-to-diary
8442 (condition-case nil
8443 (add-to-diary-list original-date "Org-mode dummy" "")
8444 (error
8445 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
8447 ;;;###autoload
8448 (defun org-cycle-agenda-files ()
8449 "Cycle through the files in `org-agenda-files'.
8450 If the current buffer visits an agenda file, find the next one in the list.
8451 If the current buffer does not, find the first agenda file."
8452 (interactive)
8453 (let* ((fs (org-agenda-files t))
8454 (files (append fs (list (car fs))))
8455 (tcf (if buffer-file-name (file-truename buffer-file-name)))
8456 file)
8457 (unless files (error "No agenda files"))
8458 (catch 'exit
8459 (while (setq file (pop files))
8460 (if (equal (file-truename file) tcf)
8461 (when (car files)
8462 (find-file (car files))
8463 (throw 'exit t))))
8464 (find-file (car fs)))))
8466 (defun org-agenda-file-to-end ()
8467 "Move/add the current file to the end of the agenda file list.
8468 If the file is not present in the list, it is appended to the list. If it is
8469 present, it is moved there."
8470 (interactive)
8471 (org-agenda-file-to-front 'to-end))
8473 (defun org-agenda-file-to-front (&optional to-end)
8474 "Move/add the current file to the top of the agenda file list.
8475 If the file is not present in the list, it is added to the front. If it is
8476 present, it is moved there. With optional argument TO-END, add/move to the
8477 end of the list."
8478 (interactive "P")
8479 (let ((file-alist (mapcar (lambda (x)
8480 (cons (file-truename x) x))
8481 (org-agenda-files t)))
8482 (ctf (file-truename buffer-file-name))
8483 x had)
8484 (setq x (assoc ctf file-alist) had x)
8486 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
8487 (if to-end
8488 (setq file-alist (append (delq x file-alist) (list x)))
8489 (setq file-alist (cons x (delq x file-alist))))
8490 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
8491 (org-install-agenda-files-menu)
8492 (message "File %s to %s of agenda file list"
8493 (if had "moved" "added") (if to-end "end" "front"))))
8495 (defun org-remove-file (&optional file)
8496 "Remove current file from the list of files in variable `org-agenda-files'.
8497 These are the files which are being checked for agenda entries.
8498 Optional argument FILE means, use this file instead of the current."
8499 (interactive)
8500 (let* ((file (or file buffer-file-name))
8501 (true-file (file-truename file))
8502 (afile (abbreviate-file-name file))
8503 (files (delq nil (mapcar
8504 (lambda (x)
8505 (if (equal true-file
8506 (file-truename x))
8507 nil x))
8508 (org-agenda-files t)))))
8509 (if (not (= (length files) (length (org-agenda-files t))))
8510 (progn
8511 (org-store-new-agenda-file-list files)
8512 (org-install-agenda-files-menu)
8513 (message "Removed file: %s" afile))
8514 (message "File was not in list: %s" afile))))
8516 (defun org-file-menu-entry (file)
8517 (vector file (list 'find-file file) t))
8519 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
8520 "Return a list of all relevant day numbers from BEG to END buffer positions.
8521 If NO-RANGES is non-nil, include only the start and end dates of a range,
8522 not every single day in the range. If FORCE-TODAY is non-nil, make
8523 sure that TODAY is included in the list. If INACTIVE is non-nil, also
8524 inactive time stamps (those in square brackets) are included.
8525 When EMPTY is non-nil, also include days without any entries."
8526 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
8527 dates dates1 date day day1 day2 ts1 ts2)
8528 (if force-today
8529 (setq dates (list (time-to-days (current-time)))))
8530 (save-excursion
8531 (goto-char beg)
8532 (while (re-search-forward re end t)
8533 (setq day (time-to-days (org-time-string-to-time
8534 (substring (match-string 1) 0 10))))
8535 (or (memq day dates) (push day dates)))
8536 (unless no-ranges
8537 (goto-char beg)
8538 (while (re-search-forward org-tr-regexp end t)
8539 (setq ts1 (substring (match-string 1) 0 10)
8540 ts2 (substring (match-string 2) 0 10)
8541 day1 (time-to-days (org-time-string-to-time ts1))
8542 day2 (time-to-days (org-time-string-to-time ts2)))
8543 (while (< (setq day1 (1+ day1)) day2)
8544 (or (memq day1 dates) (push day1 dates)))))
8545 (setq dates (sort dates '<))
8546 (when empty
8547 (while (setq day (pop dates))
8548 (setq day2 (car dates))
8549 (push day dates1)
8550 (when (and day2 empty)
8551 (if (or (eq empty t)
8552 (and (numberp empty) (<= (- day2 day) empty)))
8553 (while (< (setq day (1+ day)) day2)
8554 (push (list day) dates1))
8555 (push (cons :omitted (- day2 day)) dates1))))
8556 (setq dates (nreverse dates1)))
8557 dates)))
8559 ;;;###autoload
8560 (defun org-diary (&rest args)
8561 "Return diary information from org-files.
8562 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
8563 It accesses org files and extracts information from those files to be
8564 listed in the diary. The function accepts arguments specifying what
8565 items should be listed. The following arguments are allowed:
8567 :timestamp List the headlines of items containing a date stamp or
8568 date range matching the selected date. Deadlines will
8569 also be listed, on the expiration day.
8571 :deadline List any deadlines past due, or due within
8572 `org-deadline-warning-days'. The listing occurs only
8573 in the diary for *today*, not at any other date. If
8574 an entry is marked DONE, it is no longer listed.
8576 :scheduled List all items which are scheduled for the given date.
8577 The diary for *today* also contains items which were
8578 scheduled earlier and are not yet marked DONE.
8580 :todo List all TODO items from the org-file. This may be a
8581 long list - so this is not turned on by default.
8582 Like deadlines, these entries only show up in the
8583 diary for *today*, not at any other date.
8585 The call in the diary file should look like this:
8587 &%%(org-diary) ~/path/to/some/orgfile.org
8589 Use a separate line for each org file to check. Or, if you omit the file name,
8590 all files listed in `org-agenda-files' will be checked automatically:
8592 &%%(org-diary)
8594 If you don't give any arguments (as in the example above), the default
8595 arguments (:deadline :scheduled :timestamp) are used. So the example above may
8596 also be written as
8598 &%%(org-diary :deadline :timestamp :scheduled)
8600 The function expects the lisp variables `entry' and `date' to be provided
8601 by the caller, because this is how the calendar works. Don't use this
8602 function from a program - use `org-agenda-get-day-entries' instead."
8603 (org-agenda-maybe-reset-markers)
8604 (org-compile-prefix-format 'agenda)
8605 (org-set-sorting-strategy 'agenda)
8606 (setq args (or args '(:deadline :scheduled :timestamp)))
8607 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
8608 (list entry)
8609 (org-agenda-files t)))
8610 file rtn results)
8611 ;; If this is called during org-agenda, don't return any entries to
8612 ;; the calendar. Org Agenda will list these entries itself.
8613 (if org-disable-agenda-to-diary (setq files nil))
8614 (while (setq file (pop files))
8615 (setq rtn (apply 'org-agenda-get-day-entries file date args))
8616 (setq results (append results rtn)))
8617 (if results
8618 (concat (org-finalize-agenda-entries results) "\n"))))
8619 (defvar org-category-table nil)
8620 (defun org-get-category-table ()
8621 "Get the table of categories and positions in current buffer."
8622 (let (tbl)
8623 (save-excursion
8624 (goto-char (point-min))
8625 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
8626 (push (cons (point) (org-trim (match-string 2))) tbl)))
8627 tbl))
8628 (defun org-get-category (&optional pos)
8629 "Get the category applying to position POS."
8630 (if (not org-category-table)
8631 (cond
8632 ((null org-category)
8633 (setq org-category
8634 (if buffer-file-name
8635 (file-name-sans-extension
8636 (file-name-nondirectory buffer-file-name))
8637 "???")))
8638 ((symbolp org-category) (symbol-name org-category))
8639 (t org-category))
8640 (let ((tbl org-category-table)
8641 (pos (or pos (point))))
8642 (while (and tbl (> (caar tbl) pos))
8643 (pop tbl))
8644 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
8645 org-category-table))))))
8647 (defun org-agenda-get-day-entries (file date &rest args)
8648 "Does the work for `org-diary' and `org-agenda'.
8649 FILE is the path to a file to be checked for entries. DATE is date like
8650 the one returned by `calendar-current-date'. ARGS are symbols indicating
8651 which kind of entries should be extracted. For details about these, see
8652 the documentation of `org-diary'."
8653 (setq args (or args '(:deadline :scheduled :timestamp)))
8654 (let* ((org-startup-with-deadline-check nil)
8655 (org-startup-folded nil)
8656 (org-startup-align-all-tables nil)
8657 (buffer (if (file-exists-p file)
8658 (org-get-agenda-file-buffer file)
8659 (error "No such file %s" file)))
8660 arg results rtn)
8661 (if (not buffer)
8662 ;; If file does not exist, make sure an error message ends up in diary
8663 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8664 (with-current-buffer buffer
8665 (unless (org-mode-p)
8666 (error "Agenda file %s is not in `org-mode'" file))
8667 (setq org-category-table (org-get-category-table))
8668 (let ((case-fold-search nil))
8669 (save-excursion
8670 (save-restriction
8671 (if org-agenda-restrict
8672 (narrow-to-region org-agenda-restrict-begin
8673 org-agenda-restrict-end)
8674 (widen))
8675 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
8676 (while (setq arg (pop args))
8677 (cond
8678 ((and (eq arg :todo)
8679 (equal date (calendar-current-date)))
8680 (setq rtn (org-agenda-get-todos))
8681 (setq results (append results rtn)))
8682 ((eq arg :timestamp)
8683 (setq rtn (org-agenda-get-blocks))
8684 (setq results (append results rtn))
8685 (setq rtn (org-agenda-get-timestamps))
8686 (setq results (append results rtn)))
8687 ((eq arg :scheduled)
8688 (setq rtn (org-agenda-get-scheduled))
8689 (setq results (append results rtn)))
8690 ((eq arg :closed)
8691 (setq rtn (org-agenda-get-closed))
8692 (setq results (append results rtn)))
8693 ((and (eq arg :deadline)
8694 (equal date (calendar-current-date)))
8695 (setq rtn (org-agenda-get-deadlines))
8696 (setq results (append results rtn))))))))
8697 results))))
8699 (defun org-entry-is-done-p ()
8700 "Is the current entry marked DONE?"
8701 (save-excursion
8702 (and (re-search-backward "[\r\n]\\*" nil t)
8703 (looking-at org-nl-done-regexp))))
8705 (defun org-at-date-range-p (&optional inactive-ok)
8706 "Is the cursor inside a date range?"
8707 (interactive)
8708 (save-excursion
8709 (catch 'exit
8710 (let ((pos (point)))
8711 (skip-chars-backward "^[<\r\n")
8712 (skip-chars-backward "<[")
8713 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8714 (>= (match-end 0) pos)
8715 (throw 'exit t))
8716 (skip-chars-backward "^<[\r\n")
8717 (skip-chars-backward "<[")
8718 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8719 (>= (match-end 0) pos)
8720 (throw 'exit t)))
8721 nil)))
8723 (defun org-agenda-get-todos ()
8724 "Return the TODO information for agenda display."
8725 (let* ((props (list 'face nil
8726 'done-face 'org-done
8727 'org-not-done-regexp org-not-done-regexp
8728 'mouse-face 'highlight
8729 'keymap org-agenda-keymap
8730 'help-echo
8731 (format "mouse-2 or RET jump to org file %s"
8732 (abbreviate-file-name buffer-file-name))))
8733 (regexp (concat "[\n\r]\\*+ *\\("
8734 (if org-select-this-todo-keyword
8735 (concat "\\<\\(" org-select-this-todo-keyword
8736 "\\)\\>")
8737 org-not-done-regexp)
8738 "[^\n\r]*\\)"))
8739 (deadline-re (concat ".*\\(\n[^*].*\\)?" org-deadline-time-regexp))
8740 (sched-re (concat ".*\\(\n[^*].*\\)?" org-scheduled-time-regexp))
8741 ; FIXME why was this wrong? (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
8742 marker priority category tags
8743 ee txt)
8744 (goto-char (point-min))
8745 (while (re-search-forward regexp nil t)
8746 (catch :skip
8747 (save-match-data
8748 (beginning-of-line)
8749 (when (or (and org-agenda-todo-ignore-scheduled
8750 (looking-at sched-re))
8751 (and org-agenda-todo-ignore-deadlines
8752 (looking-at deadline-re)
8753 (org-deadline-close (match-string 2))))
8755 ;; FIXME: the following test also happens below, but we need it here
8756 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
8757 (throw :skip nil)))
8758 (org-agenda-skip)
8759 (goto-char (match-beginning 1))
8760 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
8761 category (org-get-category)
8762 tags (org-get-tags-at (point))
8763 txt (org-format-agenda-item "" (match-string 1) category tags)
8764 priority
8765 (+ (org-get-priority txt)
8766 (if org-todo-kwd-priority-p
8767 (- org-todo-kwd-max-priority -2
8768 (length
8769 (member (match-string 2) org-todo-keywords)))
8770 1)))
8771 (org-add-props txt props
8772 'org-marker marker 'org-hd-marker marker
8773 'priority priority 'category category)
8774 (push txt ee)
8775 (if org-agenda-todo-list-sublevels
8776 (goto-char (match-end 1))
8777 (org-end-of-subtree 'invisible))))
8778 (nreverse ee)))
8780 (defconst org-agenda-no-heading-message
8781 "No heading for this item in buffer or region.")
8783 (defun org-agenda-get-timestamps ()
8784 "Return the date stamp information for agenda display."
8785 (let* ((props (list 'face nil
8786 'org-not-done-regexp org-not-done-regexp
8787 'mouse-face 'highlight
8788 'keymap org-agenda-keymap
8789 'help-echo
8790 (format "mouse-2 or RET jump to org file %s"
8791 (abbreviate-file-name buffer-file-name))))
8792 (regexp (regexp-quote
8793 (substring
8794 (format-time-string
8795 (car org-time-stamp-formats)
8796 (apply 'encode-time ; DATE bound by calendar
8797 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
8798 0 11)))
8799 marker hdmarker deadlinep scheduledp donep tmp priority category
8800 ee txt timestr tags)
8801 (goto-char (point-min))
8802 (while (re-search-forward regexp nil t)
8803 (catch :skip
8804 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
8805 (org-agenda-skip)
8806 (setq marker (org-agenda-new-marker (match-beginning 0))
8807 category (org-get-category (match-beginning 0))
8808 tmp (buffer-substring (max (point-min)
8809 (- (match-beginning 0)
8810 org-ds-keyword-length))
8811 (match-beginning 0))
8812 timestr (buffer-substring (match-beginning 0) (point-at-eol))
8813 deadlinep (string-match org-deadline-regexp tmp)
8814 scheduledp (string-match org-scheduled-regexp tmp)
8815 donep (org-entry-is-done-p))
8816 (and org-agenda-skip-scheduled-if-done
8817 scheduledp donep
8818 (throw :skip t))
8819 (if (string-match ">" timestr)
8820 ;; substring should only run to end of time stamp
8821 (setq timestr (substring timestr 0 (match-end 0))))
8822 (save-excursion
8823 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8824 (progn
8825 (goto-char (match-end 1))
8826 (setq hdmarker (org-agenda-new-marker)
8827 tags (org-get-tags-at))
8828 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8829 (setq txt (org-format-agenda-item
8830 (format "%s%s"
8831 (if deadlinep "Deadline: " "")
8832 (if scheduledp "Scheduled: " ""))
8833 (match-string 1) category tags timestr)))
8834 (setq txt org-agenda-no-heading-message))
8835 (setq priority (org-get-priority txt))
8836 (org-add-props txt props
8837 'org-marker marker 'org-hd-marker hdmarker)
8838 (if deadlinep
8839 (org-add-props txt nil
8840 'face (if donep 'org-done 'org-warning)
8841 'undone-face 'org-warning 'done-face 'org-done
8842 'category category 'priority (+ 100 priority))
8843 (if scheduledp
8844 (org-add-props txt nil
8845 'face 'org-scheduled-today
8846 'undone-face 'org-scheduled-today 'done-face 'org-done
8847 'category category 'priority (+ 99 priority))
8848 (org-add-props txt nil 'priority priority 'category category)))
8849 (push txt ee))
8850 (outline-next-heading)))
8851 (nreverse ee)))
8853 (defun org-agenda-get-closed ()
8854 "Return the logged TODO entries for agenda display."
8855 (let* ((props (list 'mouse-face 'highlight
8856 'org-not-done-regexp org-not-done-regexp
8857 'keymap org-agenda-keymap
8858 'help-echo
8859 (format "mouse-2 or RET jump to org file %s"
8860 (abbreviate-file-name buffer-file-name))))
8861 (regexp (concat
8862 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
8863 (regexp-quote
8864 (substring
8865 (format-time-string
8866 (car org-time-stamp-formats)
8867 (apply 'encode-time ; DATE bound by calendar
8868 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
8869 1 11))))
8870 marker hdmarker priority category tags closedp
8871 ee txt timestr)
8872 (goto-char (point-min))
8873 (while (re-search-forward regexp nil t)
8874 (catch :skip
8875 (org-agenda-skip)
8876 (setq marker (org-agenda-new-marker (match-beginning 0))
8877 closedp (equal (match-string 1) org-closed-string)
8878 category (org-get-category (match-beginning 0))
8879 timestr (buffer-substring (match-beginning 0) (point-at-eol))
8880 ;; donep (org-entry-is-done-p)
8882 (if (string-match "\\]" timestr)
8883 ;; substring should only run to end of time stamp
8884 (setq timestr (substring timestr 0 (match-end 0))))
8885 (save-excursion
8886 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8887 (progn
8888 (goto-char (match-end 1))
8889 (setq hdmarker (org-agenda-new-marker)
8890 tags (org-get-tags-at))
8891 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8892 (setq txt (org-format-agenda-item
8893 (if closedp "Closed: " "Clocked: ")
8894 (match-string 1) category tags timestr)))
8895 (setq txt org-agenda-no-heading-message))
8896 (setq priority 100000)
8897 (org-add-props txt props
8898 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
8899 'priority priority 'category category
8900 'undone-face 'org-warning 'done-face 'org-done)
8901 (push txt ee))
8902 (outline-next-heading)))
8903 (nreverse ee)))
8905 (defun org-agenda-get-deadlines ()
8906 "Return the deadline information for agenda display."
8907 (let* ((wdays org-deadline-warning-days)
8908 (props (list 'mouse-face 'highlight
8909 'org-not-done-regexp org-not-done-regexp
8910 'keymap org-agenda-keymap
8911 'help-echo
8912 (format "mouse-2 or RET jump to org file %s"
8913 (abbreviate-file-name buffer-file-name))))
8914 (regexp org-deadline-time-regexp)
8915 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
8916 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
8917 d2 diff pos pos1 category tags
8918 ee txt head face)
8919 (goto-char (point-min))
8920 (while (re-search-forward regexp nil t)
8921 (catch :skip
8922 (org-agenda-skip)
8923 (setq pos (1- (match-beginning 1))
8924 d2 (time-to-days
8925 (org-time-string-to-time (match-string 1)))
8926 diff (- d2 d1))
8927 ;; When to show a deadline in the calendar:
8928 ;; If the expiration is within wdays warning time.
8929 ;; Past-due deadlines are only shown on the current date
8930 (if (and (< diff wdays) todayp (not (= diff 0)))
8931 (save-excursion
8932 (setq category (org-get-category))
8933 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
8934 (progn
8935 (goto-char (match-end 0))
8936 (setq pos1 (match-end 1))
8937 (setq tags (org-get-tags-at pos1))
8938 (setq head (buffer-substring-no-properties
8939 (point)
8940 (progn (skip-chars-forward "^\r\n")
8941 (point))))
8942 (if (string-match org-looking-at-done-regexp head)
8943 (setq txt nil)
8944 (setq txt (org-format-agenda-item
8945 (format "In %3d d.: " diff) head category tags))))
8946 (setq txt org-agenda-no-heading-message))
8947 (when txt
8948 (setq face (cond ((<= diff 0) 'org-warning)
8949 ((<= diff 5) 'org-upcoming-deadline)
8950 (t nil)))
8951 (org-add-props txt props
8952 'org-marker (org-agenda-new-marker pos)
8953 'org-hd-marker (org-agenda-new-marker pos1)
8954 'priority (+ (- 10 diff) (org-get-priority txt))
8955 'category category
8956 'face face 'undone-face face 'done-face 'org-done)
8957 (push txt ee))))))
8958 ee))
8960 (defun org-agenda-get-scheduled ()
8961 "Return the scheduled information for agenda display."
8962 (let* ((props (list 'face 'org-scheduled-previously
8963 'org-not-done-regexp org-not-done-regexp
8964 'undone-face 'org-scheduled-previously
8965 'done-face 'org-done
8966 'mouse-face 'highlight
8967 'keymap org-agenda-keymap
8968 'help-echo
8969 (format "mouse-2 or RET jump to org file %s"
8970 (abbreviate-file-name buffer-file-name))))
8971 (regexp org-scheduled-time-regexp)
8972 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
8973 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
8974 d2 diff pos pos1 category tags donep
8975 ee txt head)
8976 (goto-char (point-min))
8977 (while (re-search-forward regexp nil t)
8978 (catch :skip
8979 (org-agenda-skip)
8980 (setq pos (1- (match-beginning 1))
8981 d2 (time-to-days
8982 (org-time-string-to-time (match-string 1)))
8983 diff (- d2 d1))
8984 ;; When to show a scheduled item in the calendar:
8985 ;; If it is on or past the date.
8986 (if (and (< diff 0) todayp)
8987 (save-excursion
8988 (setq category (org-get-category))
8989 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
8990 (progn
8991 (goto-char (match-end 0))
8992 (setq pos1 (match-end 1))
8993 (setq tags (org-get-tags-at))
8994 (setq head (buffer-substring-no-properties
8995 (point)
8996 (progn (skip-chars-forward "^\r\n") (point))))
8997 (if (string-match org-looking-at-done-regexp head)
8998 (setq txt nil)
8999 (setq txt (org-format-agenda-item
9000 (format "Sched.%2dx: " (- 1 diff)) head
9001 category tags))))
9002 (setq txt org-agenda-no-heading-message))
9003 (when txt
9004 (org-add-props txt props
9005 'org-marker (org-agenda-new-marker pos)
9006 'org-hd-marker (org-agenda-new-marker pos1)
9007 'priority (+ (- 5 diff) (org-get-priority txt))
9008 'category category)
9009 (push txt ee))))))
9010 ee))
9012 (defun org-agenda-get-blocks ()
9013 "Return the date-range information for agenda display."
9014 (let* ((props (list 'face nil
9015 'org-not-done-regexp org-not-done-regexp
9016 'mouse-face 'highlight
9017 'keymap org-agenda-keymap
9018 'help-echo
9019 (format "mouse-2 or RET jump to org file %s"
9020 (abbreviate-file-name buffer-file-name))))
9021 (regexp org-tr-regexp)
9022 (d0 (calendar-absolute-from-gregorian date))
9023 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
9024 (goto-char (point-min))
9025 (while (re-search-forward regexp nil t)
9026 (catch :skip
9027 (org-agenda-skip)
9028 (setq pos (point))
9029 (setq timestr (match-string 0)
9030 s1 (match-string 1)
9031 s2 (match-string 2)
9032 d1 (time-to-days (org-time-string-to-time s1))
9033 d2 (time-to-days (org-time-string-to-time s2)))
9034 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
9035 ;; Only allow days between the limits, because the normal
9036 ;; date stamps will catch the limits.
9037 (save-excursion
9038 (setq marker (org-agenda-new-marker (point)))
9039 (setq category (org-get-category))
9040 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
9041 (progn
9042 (setq hdmarker (org-agenda-new-marker (match-end 1)))
9043 (goto-char (match-end 1))
9044 (setq tags (org-get-tags-at))
9045 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
9046 (setq txt (org-format-agenda-item
9047 (format (if (= d1 d2) "" "(%d/%d): ")
9048 (1+ (- d0 d1)) (1+ (- d2 d1)))
9049 (match-string 1) category tags
9050 (if (= d0 d1) timestr))))
9051 (setq txt org-agenda-no-heading-message))
9052 (org-add-props txt props
9053 'org-marker marker 'org-hd-marker hdmarker
9054 'priority (org-get-priority txt) 'category category)
9055 (push txt ee)))
9056 (goto-char pos)))
9057 ;; Sort the entries by expiration date.
9058 (nreverse ee)))
9060 ;; FIXME: should I allow spaces around the dash?
9061 (defconst org-plain-time-of-day-regexp
9062 (concat
9063 "\\(\\<[012]?[0-9]"
9064 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
9065 "\\(--?"
9066 "\\(\\<[012]?[0-9]"
9067 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
9068 "\\)?")
9069 "Regular expression to match a plain time or time range.
9070 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
9071 groups carry important information:
9072 0 the full match
9073 1 the first time, range or not
9074 8 the second time, if it is a range.")
9076 (defconst org-stamp-time-of-day-regexp
9077 (concat
9078 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
9079 "\\([012][0-9]:[0-5][0-9]\\)>"
9080 "\\(--?"
9081 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
9082 "Regular expression to match a timestamp time or time range.
9083 After a match, the following groups carry important information:
9084 0 the full match
9085 1 date plus weekday, for backreferencing to make sure both times on same day
9086 2 the first time, range or not
9087 4 the second time, if it is a range.")
9089 (defvar org-prefix-has-time nil
9090 "A flag, set by `org-compile-prefix-format'.
9091 The flag is set if the currently compiled format contains a `%t'.")
9092 (defvar org-prefix-has-tag nil
9093 "A flag, set by `org-compile-prefix-format'.
9094 The flag is set if the currently compiled format contains a `%T'.")
9096 (defun org-format-agenda-item (extra txt &optional category tags dotime
9097 noprefix)
9098 "Format TXT to be inserted into the agenda buffer.
9099 In particular, it adds the prefix and corresponding text properties. EXTRA
9100 must be a string and replaces the `%s' specifier in the prefix format.
9101 CATEGORY (string, symbol or nil) may be used to overrule the default
9102 category taken from local variable or file name. It will replace the `%c'
9103 specifier in the format. DOTIME, when non-nil, indicates that a
9104 time-of-day should be extracted from TXT for sorting of this entry, and for
9105 the `%t' specifier in the format. When DOTIME is a string, this string is
9106 searched for a time before TXT is. NOPREFIX is a flag and indicates that
9107 only the correctly processes TXT should be returned - this is used by
9108 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
9109 (save-match-data
9110 ;; Diary entries sometimes have extra whitespace at the beginning
9111 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
9112 (let* ((category (or category
9113 org-category
9114 (if buffer-file-name
9115 (file-name-sans-extension
9116 (file-name-nondirectory buffer-file-name))
9117 "")))
9118 (tag (if tags (nth (1- (length tags)) tags) ""))
9119 time ;; needed for the eval of the prefix format
9120 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
9121 (time-of-day (and dotime (org-get-time-of-day ts)))
9122 stamp plain s0 s1 s2 rtn)
9123 (when (and dotime time-of-day org-prefix-has-time)
9124 ;; Extract starting and ending time and move them to prefix
9125 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
9126 (setq plain (string-match org-plain-time-of-day-regexp ts)))
9127 (setq s0 (match-string 0 ts)
9128 s1 (match-string (if plain 1 2) ts)
9129 s2 (match-string (if plain 8 4) ts))
9131 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
9132 ;; them, we might want to remove them there to avoid duplication.
9133 ;; The user can turn this off with a variable.
9134 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
9135 (string-match (concat (regexp-quote s0) " *") txt)
9136 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
9137 (= (match-beginning 0) 0)
9139 (setq txt (replace-match "" nil nil txt))))
9140 ;; Normalize the time(s) to 24 hour
9141 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
9142 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
9144 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
9145 ;; Tags are in the string
9146 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
9147 (and org-agenda-remove-tags-when-in-prefix
9148 org-prefix-has-tag))
9149 (setq txt (replace-match "" t t txt))
9150 (setq txt (replace-match
9151 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
9152 (match-string 2 txt))
9153 t t txt))))
9155 ;; Create the final string
9156 (if noprefix
9157 (setq rtn txt)
9158 ;; Prepare the variables needed in the eval of the compiled format
9159 (setq time (cond (s2 (concat s1 "-" s2))
9160 (s1 (concat s1 "......"))
9161 (t ""))
9162 extra (or extra "")
9163 category (if (symbolp category) (symbol-name category) category))
9164 ;; Evaluate the compiled format
9165 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
9167 ;; And finally add the text properties
9168 (org-add-props rtn nil
9169 'category (downcase category) 'tags tags
9170 'prefix-length (- (length rtn) (length txt))
9171 'time-of-day time-of-day
9172 'dotime dotime))))
9174 (defvar org-agenda-sorting-strategy)
9175 (defvar org-agenda-sorting-strategy-selected nil)
9177 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
9178 (catch 'exit
9179 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
9180 ((and todayp (member 'today (car org-agenda-time-grid))))
9181 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
9182 ((member 'weekly (car org-agenda-time-grid)))
9183 (t (throw 'exit list)))
9184 (let* ((have (delq nil (mapcar
9185 (lambda (x) (get-text-property 1 'time-of-day x))
9186 list)))
9187 (string (nth 1 org-agenda-time-grid))
9188 (gridtimes (nth 2 org-agenda-time-grid))
9189 (req (car org-agenda-time-grid))
9190 (remove (member 'remove-match req))
9191 new time)
9192 (if (and (member 'require-timed req) (not have))
9193 ;; don't show empty grid
9194 (throw 'exit list))
9195 (while (setq time (pop gridtimes))
9196 (unless (and remove (member time have))
9197 (setq time (int-to-string time))
9198 (push (org-format-agenda-item
9199 nil string "" nil
9200 (concat (substring time 0 -2) ":" (substring time -2)))
9201 new)
9202 (put-text-property
9203 1 (length (car new)) 'face 'org-time-grid (car new))))
9204 (if (member 'time-up org-agenda-sorting-strategy-selected)
9205 (append new list)
9206 (append list new)))))
9208 (defun org-compile-prefix-format (key)
9209 "Compile the prefix format into a Lisp form that can be evaluated.
9210 The resulting form is returned and stored in the variable
9211 `org-prefix-format-compiled'."
9212 (setq org-prefix-has-time nil org-prefix-has-tag nil)
9213 (let ((s (cond
9214 ((stringp org-agenda-prefix-format)
9215 org-agenda-prefix-format)
9216 ((assq key org-agenda-prefix-format)
9217 (cdr (assq key org-agenda-prefix-format)))
9218 (t " %-12:c%?-12t% s")))
9219 (start 0)
9220 varform vars var e c f opt)
9221 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
9222 s start)
9223 (setq var (cdr (assoc (match-string 4 s)
9224 '(("c" . category) ("t" . time) ("s" . extra)
9225 ("T" . tag))))
9226 c (or (match-string 3 s) "")
9227 opt (match-beginning 1)
9228 start (1+ (match-beginning 0)))
9229 (if (equal var 'time) (setq org-prefix-has-time t))
9230 (if (equal var 'tag) (setq org-prefix-has-tag t))
9231 (setq f (concat "%" (match-string 2 s) "s"))
9232 (if opt
9233 (setq varform
9234 `(if (equal "" ,var)
9236 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
9237 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
9238 (setq s (replace-match "%s" t nil s))
9239 (push varform vars))
9240 (setq vars (nreverse vars))
9241 (setq org-prefix-format-compiled `(format ,s ,@vars))))
9243 (defun org-set-sorting-strategy (key)
9244 (if (symbolp (car org-agenda-sorting-strategy))
9245 ;; the old format
9246 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
9247 (setq org-agenda-sorting-strategy-selected
9248 (or (cdr (assq key org-agenda-sorting-strategy))
9249 (cdr (assq 'agenda org-agenda-sorting-strategy))
9250 '(time-up category-keep priority-down)))))
9252 (defun org-get-time-of-day (s &optional string mod24)
9253 "Check string S for a time of day.
9254 If found, return it as a military time number between 0 and 2400.
9255 If not found, return nil.
9256 The optional STRING argument forces conversion into a 5 character wide string
9257 HH:MM."
9258 (save-match-data
9259 (when
9261 (string-match
9262 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
9263 (string-match
9264 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
9265 (let* ((h (string-to-number (match-string 1 s)))
9266 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
9267 (ampm (if (match-end 4) (downcase (match-string 4 s))))
9268 (am-p (equal ampm "am"))
9269 (h1 (cond ((not ampm) h)
9270 ((= h 12) (if am-p 0 12))
9271 (t (+ h (if am-p 0 12)))))
9272 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
9273 (mod h1 24) h1))
9274 (t0 (+ (* 100 h2) m))
9275 (t1 (concat (if (>= h1 24) "+" " ")
9276 (if (< t0 100) "0" "")
9277 (if (< t0 10) "0" "")
9278 (int-to-string t0))))
9279 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
9281 (defun org-finalize-agenda-entries (list &optional nosort)
9282 "Sort and concatenate the agenda items."
9283 (setq list (mapcar 'org-agenda-highlight-todo list))
9284 (if nosort
9285 list
9286 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
9288 (defun org-agenda-highlight-todo (x)
9289 (let (re pl)
9290 (if (eq x 'line)
9291 (save-excursion
9292 (beginning-of-line 1)
9293 (setq re (get-text-property (point) 'org-not-done-regexp))
9294 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
9295 (and (looking-at (concat "[ \t]*\\.*" re))
9296 (add-text-properties (match-beginning 0) (match-end 0)
9297 '(face org-todo))))
9298 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
9299 pl (get-text-property 0 'prefix-length x))
9300 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
9301 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
9302 '(face org-todo) x))
9303 x)))
9305 (defsubst org-cmp-priority (a b)
9306 "Compare the priorities of string A and B."
9307 (let ((pa (or (get-text-property 1 'priority a) 0))
9308 (pb (or (get-text-property 1 'priority b) 0)))
9309 (cond ((> pa pb) +1)
9310 ((< pa pb) -1)
9311 (t nil))))
9313 (defsubst org-cmp-category (a b)
9314 "Compare the string values of categories of strings A and B."
9315 (let ((ca (or (get-text-property 1 'category a) ""))
9316 (cb (or (get-text-property 1 'category b) "")))
9317 (cond ((string-lessp ca cb) -1)
9318 ((string-lessp cb ca) +1)
9319 (t nil))))
9321 (defsubst org-cmp-tag (a b)
9322 "Compare the string values of categories of strings A and B."
9323 (let ((ta (car (last (get-text-property 1 'tags a))))
9324 (tb (car (last (get-text-property 1 'tags b)))))
9325 (cond ((not ta) +1)
9326 ((not tb) -1)
9327 ((string-lessp ta tb) -1)
9328 ((string-lessp tb ta) +1)
9329 (t nil))))
9331 (defsubst org-cmp-time (a b)
9332 "Compare the time-of-day values of strings A and B."
9333 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
9334 (ta (or (get-text-property 1 'time-of-day a) def))
9335 (tb (or (get-text-property 1 'time-of-day b) def)))
9336 (cond ((< ta tb) -1)
9337 ((< tb ta) +1)
9338 (t nil))))
9340 (defun org-entries-lessp (a b)
9341 "Predicate for sorting agenda entries."
9342 ;; The following variables will be used when the form is evaluated.
9343 (let* ((time-up (org-cmp-time a b))
9344 (time-down (if time-up (- time-up) nil))
9345 (priority-up (org-cmp-priority a b))
9346 (priority-down (if priority-up (- priority-up) nil))
9347 (category-up (org-cmp-category a b))
9348 (category-down (if category-up (- category-up) nil))
9349 (category-keep (if category-up +1 nil))
9350 (tag-up (org-cmp-tag a b))
9351 (tag-down (if tag-up (- tag-up) nil)))
9352 (cdr (assoc
9353 (eval (cons 'or org-agenda-sorting-strategy-selected))
9354 '((-1 . t) (1 . nil) (nil . nil))))))
9356 (defun org-agenda-show-priority ()
9357 "Show the priority of the current item.
9358 This priority is composed of the main priority given with the [#A] cookies,
9359 and by additional input from the age of a schedules or deadline entry."
9360 (interactive)
9361 (let* ((pri (get-text-property (point-at-bol) 'priority)))
9362 (message "Priority is %d" (if pri pri -1000))))
9364 (defun org-agenda-show-tags ()
9365 "Show the tags applicable to the current item."
9366 (interactive)
9367 (let* ((tags (get-text-property (point-at-bol) 'tags)))
9368 (if tags
9369 (message "Tags are :%s:"
9370 (org-no-properties (mapconcat 'identity tags ":")))
9371 (message "No tags associated with this line"))))
9373 (defun org-agenda-goto (&optional highlight)
9374 "Go to the Org-mode file which contains the item at point."
9375 (interactive)
9376 (let* ((marker (or (get-text-property (point) 'org-marker)
9377 (org-agenda-error)))
9378 (buffer (marker-buffer marker))
9379 (pos (marker-position marker)))
9380 (switch-to-buffer-other-window buffer)
9381 (widen)
9382 (goto-char pos)
9383 (when (org-mode-p)
9384 (org-show-context 'agenda)
9385 (save-excursion
9386 (and (outline-next-heading)
9387 (org-flag-heading nil)))) ; show the next heading
9388 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
9390 (defun org-agenda-kill ()
9391 "Kill the entry or subtree belonging to the current agenda entry."
9392 (interactive)
9393 (let* ((marker (or (get-text-property (point) 'org-marker)
9394 (org-agenda-error)))
9395 (hdmarker (get-text-property (point) 'org-hd-marker))
9396 (buffer (marker-buffer marker))
9397 (pos (marker-position marker))
9398 dbeg dend (n 0) conf)
9399 (org-with-remote-undo buffer
9400 (with-current-buffer buffer
9401 (save-excursion
9402 (goto-char pos)
9403 (if (org-mode-p)
9404 (setq dbeg (progn (org-back-to-heading t) (point))
9405 dend (org-end-of-subtree t))
9406 (setq dbeg (point-at-bol)
9407 dend (min (point-max) (1+ (point-at-eol)))))
9408 (goto-char dbeg)
9409 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
9410 (setq conf (or (eq t org-agenda-confirm-kill)
9411 (and (numberp org-agenda-confirm-kill)
9412 (> n org-agenda-confirm-kill))))
9413 (and conf
9414 (not (y-or-n-p
9415 (format "Delete entry with %d lines in buffer \"%s\"? "
9416 n (buffer-name buffer))))
9417 (error "Abort"))
9418 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
9419 (with-current-buffer buffer (delete-region dbeg dend))
9420 (message "Agenda item and source killed"))))
9422 (defun org-agenda-archive ()
9423 "Kill the entry or subtree belonging to the current agenda entry."
9424 (interactive)
9425 (let* ((marker (or (get-text-property (point) 'org-marker)
9426 (org-agenda-error)))
9427 (hdmarker (get-text-property (point) 'org-hd-marker))
9428 (buffer (marker-buffer marker))
9429 (pos (marker-position marker))
9430 dbeg dend txt n conf)
9431 (org-with-remote-undo buffer
9432 (with-current-buffer buffer
9433 (if (org-mode-p)
9434 (save-excursion
9435 (goto-char pos)
9436 (org-remove-subtree-entries-from-agenda)
9437 (org-back-to-heading t)
9438 (org-archive-subtree))
9439 (error "Archiving works only in Org-mode files"))))))
9441 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
9442 "Remove all lines in the agenda that correspond to a given subtree.
9443 The subtree is the one in buffer BUF, starting at BEG and ending at END.
9444 If this information is not given, the function uses the tree at point."
9445 (let ((buf (or buf (current-buffer))) m p)
9446 (save-excursion
9447 (unless (and beg end)
9448 (org-back-to-heading t)
9449 (setq beg (point))
9450 (org-end-of-subtree t)
9451 (setq end (point)))
9452 (set-buffer (get-buffer org-agenda-buffer-name))
9453 (save-excursion
9454 (goto-char (point-max))
9455 (beginning-of-line 1)
9456 (while (not (bobp))
9457 (when (and (setq m (get-text-property (point) 'org-marker))
9458 (equal buf (marker-buffer m))
9459 (setq p (marker-position m))
9460 (>= p beg)
9461 (<= p end))
9462 (let (buffer-read-only)
9463 (delete-region (point-at-bol) (1+ (point-at-eol)))))
9464 (beginning-of-line 0))))))
9466 (defun org-agenda-open-link ()
9467 "Follow the link in the current line, if any."
9468 (interactive)
9469 (let ((eol (point-at-eol)))
9470 (save-excursion
9471 (if (or (re-search-forward org-bracket-link-regexp eol t)
9472 (re-search-forward org-angle-link-re eol t)
9473 (re-search-forward org-plain-link-re eol t))
9474 (call-interactively 'org-open-at-point)
9475 (error "No link in current line")))))
9477 (defun org-agenda-switch-to (&optional delete-other-windows)
9478 "Go to the Org-mode file which contains the item at point."
9479 (interactive)
9480 (let* ((marker (or (get-text-property (point) 'org-marker)
9481 (org-agenda-error)))
9482 (buffer (marker-buffer marker))
9483 (pos (marker-position marker)))
9484 (switch-to-buffer buffer)
9485 (and delete-other-windows (delete-other-windows))
9486 (widen)
9487 (goto-char pos)
9488 (when (org-mode-p)
9489 (org-show-context 'agenda)
9490 (save-excursion
9491 (and (outline-next-heading)
9492 (org-flag-heading nil)))))) ; show the next heading
9494 (defun org-agenda-goto-mouse (ev)
9495 "Go to the Org-mode file which contains the item at the mouse click."
9496 (interactive "e")
9497 (mouse-set-point ev)
9498 (org-agenda-goto))
9500 (defun org-agenda-show ()
9501 "Display the Org-mode file which contains the item at point."
9502 (interactive)
9503 (let ((win (selected-window)))
9504 (org-agenda-goto t)
9505 (select-window win)))
9507 (defun org-agenda-recenter (arg)
9508 "Display the Org-mode file which contains the item at point and recenter."
9509 (interactive "P")
9510 (let ((win (selected-window)))
9511 (org-agenda-goto t)
9512 (recenter arg)
9513 (select-window win)))
9515 (defun org-agenda-show-mouse (ev)
9516 "Display the Org-mode file which contains the item at the mouse click."
9517 (interactive "e")
9518 (mouse-set-point ev)
9519 (org-agenda-show))
9521 (defun org-agenda-check-no-diary ()
9522 "Check if the entry is a diary link and abort if yes."
9523 (if (get-text-property (point) 'org-agenda-diary-link)
9524 (org-agenda-error)))
9526 (defun org-agenda-error ()
9527 (error "Command not allowed in this line"))
9529 (defun org-agenda-tree-to-indirect-buffer ()
9530 "Show the subtree corresponding to the current entry in an indirect buffer.
9531 This calls the command `org-tree-to-indirect-buffer' from the original
9532 Org-mode buffer.
9533 With numerical prefix arg ARG, go up to this level and then take that tree.
9534 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
9535 dedicated frame)."
9536 (interactive)
9537 (org-agenda-check-no-diary)
9538 (let* ((marker (or (get-text-property (point) 'org-marker)
9539 (org-agenda-error)))
9540 (buffer (marker-buffer marker))
9541 (pos (marker-position marker)))
9542 (with-current-buffer buffer
9543 (save-excursion
9544 (goto-char pos)
9545 (org-tree-to-indirect-buffer)))))
9547 (defvar org-last-heading-marker (make-marker)
9548 "Marker pointing to the headline that last changed its TODO state
9549 by a remote command from the agenda.")
9551 (defun org-agenda-todo (&optional arg)
9552 "Cycle TODO state of line at point, also in Org-mode file.
9553 This changes the line at point, all other lines in the agenda referring to
9554 the same tree node, and the headline of the tree node in the Org-mode file."
9555 (interactive "P")
9556 (org-agenda-check-no-diary)
9557 (let* ((col (current-column))
9558 (marker (or (get-text-property (point) 'org-marker)
9559 (org-agenda-error)))
9560 (buffer (marker-buffer marker))
9561 (pos (marker-position marker))
9562 (hdmarker (get-text-property (point) 'org-hd-marker))
9563 (buffer-read-only nil)
9564 newhead)
9565 (org-with-remote-undo buffer
9566 (with-current-buffer buffer
9567 (widen)
9568 (goto-char pos)
9569 (org-show-context 'agenda)
9570 (save-excursion
9571 (and (outline-next-heading)
9572 (org-flag-heading nil))) ; show the next heading
9573 (org-todo arg)
9574 (and (bolp) (forward-char 1))
9575 (setq newhead (org-get-heading))
9576 (save-excursion
9577 (org-back-to-heading)
9578 (move-marker org-last-heading-marker (point))))
9579 (beginning-of-line 1)
9580 (save-excursion
9581 (org-agenda-change-all-lines newhead hdmarker 'fixface))
9582 (move-to-column col))))
9584 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
9585 "Change all lines in the agenda buffer which match HDMARKER.
9586 The new content of the line will be NEWHEAD (as modified by
9587 `org-format-agenda-item'). HDMARKER is checked with
9588 `equal' against all `org-hd-marker' text properties in the file.
9589 If FIXFACE is non-nil, the face of each item is modified acording to
9590 the new TODO state."
9591 (let* ((buffer-read-only nil)
9592 props m pl undone-face done-face finish new dotime cat tags)
9593 (save-excursion
9594 (goto-char (point-max))
9595 (beginning-of-line 1)
9596 (while (not finish)
9597 (setq finish (bobp))
9598 (when (and (setq m (get-text-property (point) 'org-hd-marker))
9599 (equal m hdmarker))
9600 (setq props (text-properties-at (point))
9601 dotime (get-text-property (point) 'dotime)
9602 cat (get-text-property (point) 'category)
9603 tags (get-text-property (point) 'tags)
9604 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
9605 pl (get-text-property (point) 'prefix-length)
9606 undone-face (get-text-property (point) 'undone-face)
9607 done-face (get-text-property (point) 'done-face))
9608 (move-to-column pl)
9609 (cond
9610 ((equal new "")
9611 (beginning-of-line 1)
9612 (and (looking-at ".*\n?") (replace-match "")))
9613 ((looking-at ".*")
9614 (replace-match new t t)
9615 (beginning-of-line 1)
9616 (add-text-properties (point-at-bol) (point-at-eol) props)
9617 (when fixface
9618 (add-text-properties
9619 (point-at-bol) (point-at-eol)
9620 (list 'face
9621 (if org-last-todo-state-is-todo
9622 undone-face done-face))))
9623 (org-agenda-highlight-todo 'line)
9624 (beginning-of-line 1))
9625 (t (error "Line update did not work"))))
9626 (beginning-of-line 0)))
9627 (org-finalize-agenda)))
9629 (defun org-agenda-align-tags (&optional line)
9630 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
9631 (let ((buffer-read-only))
9632 (save-excursion
9633 (goto-char (if line (point-at-bol) (point-min)))
9634 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
9635 (if line (point-at-eol) nil) t)
9636 (delete-region (match-beginning 1) (match-end 1))
9637 (goto-char (match-beginning 1))
9638 (insert (org-add-props
9639 (make-string (max 1 (- org-agenda-align-tags-to-column
9640 (current-column))) ?\ )
9641 (text-properties-at (point))))))))
9643 (defun org-agenda-priority-up ()
9644 "Increase the priority of line at point, also in Org-mode file."
9645 (interactive)
9646 (org-agenda-priority 'up))
9648 (defun org-agenda-priority-down ()
9649 "Decrease the priority of line at point, also in Org-mode file."
9650 (interactive)
9651 (org-agenda-priority 'down))
9653 (defun org-agenda-priority (&optional force-direction)
9654 "Set the priority of line at point, also in Org-mode file.
9655 This changes the line at point, all other lines in the agenda referring to
9656 the same tree node, and the headline of the tree node in the Org-mode file."
9657 (interactive)
9658 (org-agenda-check-no-diary)
9659 (let* ((marker (or (get-text-property (point) 'org-marker)
9660 (org-agenda-error)))
9661 (buffer (marker-buffer marker))
9662 (pos (marker-position marker))
9663 (hdmarker (get-text-property (point) 'org-hd-marker))
9664 (buffer-read-only nil)
9665 newhead)
9666 (org-with-remote-undo buffer
9667 (with-current-buffer buffer
9668 (widen)
9669 (goto-char pos)
9670 (org-show-context 'agenda)
9671 (save-excursion
9672 (and (outline-next-heading)
9673 (org-flag-heading nil))) ; show the next heading
9674 (funcall 'org-priority force-direction)
9675 (end-of-line 1)
9676 (setq newhead (org-get-heading)))
9677 (org-agenda-change-all-lines newhead hdmarker)
9678 (beginning-of-line 1))))
9680 (defun org-get-tags-at (&optional pos)
9681 "Get a list of all headline tags applicable at POS.
9682 POS defaults to point. If tags are inherited, the list contains
9683 the targets in the same sequence as the headlines appear, i.e.
9684 the tags of the current headline come last."
9685 (interactive)
9686 (let (tags)
9687 (save-excursion
9688 (goto-char (or pos (point)))
9689 (save-match-data
9690 (org-back-to-heading t)
9691 (condition-case nil
9692 (while t
9693 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
9694 (setq tags (append (org-split-string
9695 (org-match-string-no-properties 1) ":")
9696 tags)))
9697 (or org-use-tag-inheritance (error ""))
9698 (org-up-heading-all 1))
9699 (error nil))))
9700 tags))
9702 ;; FIXME: should fix the tags property of the agenda line.
9703 (defun org-agenda-set-tags ()
9704 "Set tags for the current headline."
9705 (interactive)
9706 (org-agenda-check-no-diary)
9707 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
9708 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
9709 (org-agenda-error)))
9710 (buffer (marker-buffer hdmarker))
9711 (pos (marker-position hdmarker))
9712 (buffer-read-only nil)
9713 newhead)
9714 (org-with-remote-undo buffer
9715 (with-current-buffer buffer
9716 (widen)
9717 (goto-char pos)
9718 (org-show-context 'agenda)
9719 (save-excursion
9720 (and (outline-next-heading)
9721 (org-flag-heading nil))) ; show the next heading
9722 (call-interactively 'org-set-tags)
9723 (end-of-line 1)
9724 (setq newhead (org-get-heading)))
9725 (org-agenda-change-all-lines newhead hdmarker)
9726 (beginning-of-line 1))))
9728 (defun org-agenda-toggle-archive-tag ()
9729 "Toggle the archive tag for the current entry."
9730 (interactive)
9731 (org-agenda-check-no-diary)
9732 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
9733 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
9734 (org-agenda-error)))
9735 (buffer (marker-buffer hdmarker))
9736 (pos (marker-position hdmarker))
9737 (buffer-read-only nil)
9738 newhead)
9739 (org-with-remote-undo buffer
9740 (with-current-buffer buffer
9741 (widen)
9742 (goto-char pos)
9743 (org-show-context 'agenda)
9744 (save-excursion
9745 (and (outline-next-heading)
9746 (org-flag-heading nil))) ; show the next heading
9747 (call-interactively 'org-toggle-archive-tag)
9748 (end-of-line 1)
9749 (setq newhead (org-get-heading)))
9750 (org-agenda-change-all-lines newhead hdmarker)
9751 (beginning-of-line 1))))
9753 (defun org-agenda-date-later (arg &optional what)
9754 "Change the date of this item to one day later."
9755 (interactive "p")
9756 (org-agenda-check-type t 'agenda 'timeline)
9757 (org-agenda-check-no-diary)
9758 (let* ((marker (or (get-text-property (point) 'org-marker)
9759 (org-agenda-error)))
9760 (buffer (marker-buffer marker))
9761 (pos (marker-position marker)))
9762 (org-with-remote-undo buffer
9763 (with-current-buffer buffer
9764 (widen)
9765 (goto-char pos)
9766 (if (not (org-at-timestamp-p))
9767 (error "Cannot find time stamp"))
9768 (org-timestamp-change arg (or what 'day)))
9769 (org-agenda-show-new-time marker org-last-changed-timestamp))
9770 (message "Time stamp changed to %s" org-last-changed-timestamp)))
9772 (defun org-agenda-date-earlier (arg &optional what)
9773 "Change the date of this item to one day earlier."
9774 (interactive "p")
9775 (org-agenda-date-later (- arg) what))
9777 (defun org-agenda-show-new-time (marker stamp)
9778 "Show new date stamp via text properties."
9779 ;; We use text properties to make this undoable
9780 (let ((buffer-read-only nil)
9781 ovs ov)
9782 (setq stamp (concat " => " stamp))
9783 (save-excursion
9784 (goto-char (point-max))
9785 (while (not (bobp))
9786 (when (equal marker (get-text-property (point) 'org-marker))
9787 (move-to-column (- (window-width) (length stamp)) t)
9788 (if (featurep 'xemacs)
9789 ;; Use `duplicable' property to trigger undo recording
9790 (let ((ex (make-extent nil nil))
9791 (gl (make-glyph stamp)))
9792 (set-glyph-face gl 'secondary-selection)
9793 (set-extent-properties
9794 ex (list 'invisible t 'end-glyph gl 'duplicable t))
9795 (insert-extent ex (1- (point)) (point-at-eol)))
9796 (add-text-properties
9797 (1- (point)) (point-at-eol)
9798 (list 'display (org-add-props stamp nil
9799 'face 'secondary-selection))))
9800 (beginning-of-line 1))
9801 (beginning-of-line 0)))))
9803 (defun org-agenda-date-prompt (arg)
9804 "Change the date of this item. Date is prompted for, with default today.
9805 The prefix ARG is passed to the `org-time-stamp' command and can therefore
9806 be used to request time specification in the time stamp."
9807 (interactive "P")
9808 (org-agenda-check-type t 'agenda 'timeline)
9809 (org-agenda-check-no-diary)
9810 (let* ((marker (or (get-text-property (point) 'org-marker)
9811 (org-agenda-error)))
9812 (buffer (marker-buffer marker))
9813 (pos (marker-position marker)))
9814 (org-with-remote-undo buffer
9815 (with-current-buffer buffer
9816 (widen)
9817 (goto-char pos)
9818 (if (not (org-at-timestamp-p))
9819 (error "Cannot find time stamp"))
9820 (org-time-stamp arg)
9821 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
9823 (defun org-agenda-schedule (arg)
9824 "Schedule the item at point."
9825 (interactive "P")
9826 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
9827 (org-agenda-check-no-diary)
9828 (let* ((marker (or (get-text-property (point) 'org-marker)
9829 (org-agenda-error)))
9830 (buffer (marker-buffer marker))
9831 (pos (marker-position marker))
9832 (org-insert-labeled-timestamps-at-point nil)
9834 (org-with-remote-undo buffer
9835 (with-current-buffer buffer
9836 (widen)
9837 (goto-char pos)
9838 (setq ts (org-schedule))
9839 (message "Item scheduled for %s" ts)))))
9841 (defun org-agenda-deadline (arg)
9842 "Schedule the item at point."
9843 (interactive "P")
9844 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
9845 (org-agenda-check-no-diary)
9846 (let* ((marker (or (get-text-property (point) 'org-marker)
9847 (org-agenda-error)))
9848 (buffer (marker-buffer marker))
9849 (pos (marker-position marker))
9850 (org-insert-labeled-timestamps-at-point nil)
9852 (org-with-remote-undo buffer
9853 (with-current-buffer buffer
9854 (widen)
9855 (goto-char pos)
9856 (setq ts (org-deadline))
9857 (message "Deadline for this item set to %s" ts)))))
9859 (defun org-get-heading ()
9860 "Return the heading of the current entry, without the stars."
9861 (save-excursion
9862 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
9863 (if (and (re-search-backward "[\r\n]\\*" nil t)
9864 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
9865 (match-string 1)
9866 "")))
9868 (defun org-agenda-clock-in (&optional arg)
9869 "Start the clock on the currently selected item."
9870 (interactive "P")
9871 (org-agenda-check-no-diary)
9872 (let* ((marker (or (get-text-property (point) 'org-marker)
9873 (org-agenda-error)))
9874 (pos (marker-position marker)))
9875 (org-with-remote-undo (marker-buffer marker)
9876 (with-current-buffer (marker-buffer marker)
9877 (widen)
9878 (goto-char pos)
9879 (org-clock-in)))))
9881 (defun org-agenda-clock-out (&optional arg)
9882 "Stop the currently running clock."
9883 (interactive "P")
9884 (unless (marker-buffer org-clock-marker)
9885 (error "No running clock"))
9886 (org-with-remote-undo (marker-buffer org-clock-marker)
9887 (org-clock-out)))
9889 (defun org-agenda-clock-cancel (&optional arg)
9890 "Cancel the currently running clock."
9891 (interactive "P")
9892 (unless (marker-buffer org-clock-marker)
9893 (error "No running clock"))
9894 (org-with-remote-undo (marker-buffer org-clock-marker)
9895 (org-clock-cancel)))
9897 (defun org-agenda-diary-entry ()
9898 "Make a diary entry, like the `i' command from the calendar.
9899 All the standard commands work: block, weekly etc."
9900 (interactive)
9901 (org-agenda-check-type t 'agenda 'timeline)
9902 (require 'diary-lib)
9903 (let* ((char (progn
9904 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
9905 (read-char-exclusive)))
9906 (cmd (cdr (assoc char
9907 '((?d . insert-diary-entry)
9908 (?w . insert-weekly-diary-entry)
9909 (?m . insert-monthly-diary-entry)
9910 (?y . insert-yearly-diary-entry)
9911 (?a . insert-anniversary-diary-entry)
9912 (?b . insert-block-diary-entry)
9913 (?c . insert-cyclic-diary-entry)))))
9914 (oldf (symbol-function 'calendar-cursor-to-date))
9915 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
9916 (point (point))
9917 (mark (or (mark t) (point))))
9918 (unless cmd
9919 (error "No command associated with <%c>" char))
9920 (unless (and (get-text-property point 'day)
9921 (or (not (equal ?b char))
9922 (get-text-property mark 'day)))
9923 (error "Don't know which date to use for diary entry"))
9924 ;; We implement this by hacking the `calendar-cursor-to-date' function
9925 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
9926 (let ((calendar-mark-ring
9927 (list (calendar-gregorian-from-absolute
9928 (or (get-text-property mark 'day)
9929 (get-text-property point 'day))))))
9930 (unwind-protect
9931 (progn
9932 (fset 'calendar-cursor-to-date
9933 (lambda (&optional error)
9934 (calendar-gregorian-from-absolute
9935 (get-text-property point 'day))))
9936 (call-interactively cmd))
9937 (fset 'calendar-cursor-to-date oldf)))))
9940 (defun org-agenda-execute-calendar-command (cmd)
9941 "Execute a calendar command from the agenda, with the date associated to
9942 the cursor position."
9943 (org-agenda-check-type t 'agenda 'timeline)
9944 (require 'diary-lib)
9945 (unless (get-text-property (point) 'day)
9946 (error "Don't know which date to use for calendar command"))
9947 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
9948 (point (point))
9949 (date (calendar-gregorian-from-absolute
9950 (get-text-property point 'day)))
9951 (displayed-day (extract-calendar-day date))
9952 (displayed-month (extract-calendar-month date))
9953 (displayed-year (extract-calendar-year date)))
9954 (unwind-protect
9955 (progn
9956 (fset 'calendar-cursor-to-date
9957 (lambda (&optional error)
9958 (calendar-gregorian-from-absolute
9959 (get-text-property point 'day))))
9960 (call-interactively cmd))
9961 (fset 'calendar-cursor-to-date oldf))))
9963 (defun org-agenda-phases-of-moon ()
9964 "Display the phases of the moon for the 3 months around the cursor date."
9965 (interactive)
9966 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
9968 (defun org-agenda-holidays ()
9969 "Display the holidays for the 3 months around the cursor date."
9970 (interactive)
9971 (org-agenda-execute-calendar-command 'list-calendar-holidays))
9973 (defun org-agenda-sunrise-sunset (arg)
9974 "Display sunrise and sunset for the cursor date.
9975 Latitude and longitude can be specified with the variables
9976 `calendar-latitude' and `calendar-longitude'. When called with prefix
9977 argument, latitude and longitude will be prompted for."
9978 (interactive "P")
9979 (let ((calendar-longitude (if arg nil calendar-longitude))
9980 (calendar-latitude (if arg nil calendar-latitude))
9981 (calendar-location-name
9982 (if arg "the given coordinates" calendar-location-name)))
9983 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
9985 (defun org-agenda-goto-calendar ()
9986 "Open the Emacs calendar with the date at the cursor."
9987 (interactive)
9988 (org-agenda-check-type t 'agenda 'timeline)
9989 (let* ((day (or (get-text-property (point) 'day)
9990 (error "Don't know which date to open in calendar")))
9991 (date (calendar-gregorian-from-absolute day))
9992 (calendar-move-hook nil)
9993 (view-calendar-holidays-initially nil)
9994 (view-diary-entries-initially nil))
9995 (calendar)
9996 (calendar-goto-date date)))
9998 (defun org-calendar-goto-agenda ()
9999 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
10000 This is a command that has to be installed in `calendar-mode-map'."
10001 (interactive)
10002 (org-agenda-list nil (calendar-absolute-from-gregorian
10003 (calendar-cursor-to-date))
10004 nil))
10006 (defun org-agenda-convert-date ()
10007 (interactive)
10008 (org-agenda-check-type t 'agenda 'timeline)
10009 (let ((day (get-text-property (point) 'day))
10010 date s)
10011 (unless day
10012 (error "Don't know which date to convert"))
10013 (setq date (calendar-gregorian-from-absolute day))
10014 (setq s (concat
10015 "Gregorian: " (calendar-date-string date) "\n"
10016 "ISO: " (calendar-iso-date-string date) "\n"
10017 "Day of Yr: " (calendar-day-of-year-string date) "\n"
10018 "Julian: " (calendar-julian-date-string date) "\n"
10019 "Astron. JD: " (calendar-astro-date-string date)
10020 " (Julian date number at noon UTC)\n"
10021 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
10022 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
10023 "French: " (calendar-french-date-string date) "\n"
10024 "Mayan: " (calendar-mayan-date-string date) "\n"
10025 "Coptic: " (calendar-coptic-date-string date) "\n"
10026 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
10027 "Persian: " (calendar-persian-date-string date) "\n"
10028 "Chinese: " (calendar-chinese-date-string date) "\n"))
10029 (with-output-to-temp-buffer "*Dates*"
10030 (princ s))
10031 (if (fboundp 'fit-window-to-buffer)
10032 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
10034 ;;;; Tags
10036 (defun org-scan-tags (action matcher &optional todo-only)
10037 "Scan headline tags with inheritance and produce output ACTION.
10038 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
10039 evaluated, testing if a given set of tags qualifies a headline for
10040 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
10041 are included in the output."
10042 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
10043 (mapconcat 'regexp-quote
10044 (nreverse (cdr (reverse org-todo-keywords)))
10045 "\\|")
10046 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*$"))
10047 (props (list 'face nil
10048 'done-face 'org-done
10049 'undone-face nil
10050 'mouse-face 'highlight
10051 'org-not-done-regexp org-not-done-regexp
10052 'keymap org-agenda-keymap
10053 'help-echo
10054 (format "mouse-2 or RET jump to org file %s"
10055 (abbreviate-file-name buffer-file-name))))
10056 (case-fold-search nil)
10057 lspos
10058 tags tags-list tags-alist (llast 0) rtn level category i txt
10059 todo marker)
10060 (save-excursion
10061 (goto-char (point-min))
10062 (when (eq action 'sparse-tree) (org-overview))
10063 (while (re-search-forward re nil t)
10064 (catch :skip
10065 (and (eq action 'agenda) (org-agenda-skip))
10066 (setq todo (if (match-end 1) (match-string 2))
10067 tags (if (match-end 4) (match-string 4)))
10068 (goto-char (setq lspos (1+ (match-beginning 0))))
10069 (setq level (funcall outline-level)
10070 category (org-get-category))
10071 (setq i llast llast level)
10072 ;; remove tag lists from same and sublevels
10073 (while (>= i level)
10074 (when (setq entry (assoc i tags-alist))
10075 (setq tags-alist (delete entry tags-alist)))
10076 (setq i (1- i)))
10077 ;; add the nex tags
10078 (when tags
10079 (setq tags (mapcar 'downcase (org-split-string tags ":"))
10080 tags-alist
10081 (cons (cons level tags) tags-alist)))
10082 ;; compile tags for current headline
10083 (setq tags-list
10084 (if org-use-tag-inheritance
10085 (apply 'append (mapcar 'cdr tags-alist))
10086 tags))
10087 (when (and (or (not todo-only) todo)
10088 (eval matcher)
10089 (or (not org-agenda-skip-archived-trees)
10090 (not (member org-archive-tag tags-list))))
10091 ;; list this headline
10092 (if (eq action 'sparse-tree)
10093 (progn
10094 (org-show-context 'tags-tree))
10095 (setq txt (org-format-agenda-item
10097 (concat
10098 (if org-tags-match-list-sublevels
10099 (make-string (1- level) ?.) "")
10100 (org-get-heading))
10101 category tags-list))
10102 (goto-char lspos)
10103 (setq marker (org-agenda-new-marker))
10104 (org-add-props txt props
10105 'org-marker marker 'org-hd-marker marker 'category category)
10106 (push txt rtn))
10107 ;; if we are to skip sublevels, jump to end of subtree
10108 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
10109 (when (and (eq action 'sparse-tree)
10110 (not org-sparse-tree-open-archived-trees))
10111 (org-hide-archived-subtrees (point-min) (point-max)))
10112 (nreverse rtn)))
10114 (defvar todo-only) ;; dynamically scoped
10116 (defun org-tags-sparse-tree (&optional todo-only match)
10117 "Create a sparse tree according to tags string MATCH.
10118 MATCH can contain positive and negative selection of tags, like
10119 \"+WORK+URGENT-WITHBOSS\".
10120 If optional argument TODO_ONLY is non-nil, only select lines that are
10121 also TODO lines."
10122 (interactive "P")
10123 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10125 ;; FIXME: implement search for a specific level.
10126 (defun org-make-tags-matcher (match)
10127 "Create the TAGS//TODO matcher form for the selection string MATCH."
10128 ;; todo-only is scoped dynamically into this function, and the function
10129 ;; may change it it the matcher asksk for it.
10130 (unless match
10131 ;; Get a new match request, with completion
10132 (setq org-last-tags-completion-table
10133 (or org-tag-alist
10134 org-last-tags-completion-table))
10135 (setq match (completing-read
10136 "Match: " 'org-tags-completion-function nil nil nil
10137 'org-tags-history))) ; FIXME: Separate history for this?
10139 ;; Parse the string and create a lisp form
10140 (let ((match0 match)
10141 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|[A-Za-z_@0-9]+\\)")
10142 minus tag mm
10143 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10144 orterms term orlist re-p level-p)
10145 (if (string-match "/+" match)
10146 ;; match contains also a todo-matching request
10147 (progn
10148 (setq tagsmatch (substring match 0 (match-beginning 0))
10149 todomatch (substring match (match-end 0)))
10150 (if (string-match "^!" todomatch)
10151 (setq todo-only t todomatch (substring todomatch 1)))
10152 (if (string-match "^\\s-*$" todomatch)
10153 (setq todomatch nil)))
10154 ;; only matching tags
10155 (setq tagsmatch match todomatch nil))
10157 ;; Make the tags matcher
10158 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10159 (setq tagsmatcher t)
10160 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10161 (while (setq term (pop orterms))
10162 (while (and (equal (substring term -1) "\\") orterms)
10163 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10164 (while (string-match re term)
10165 (setq minus (and (match-end 1)
10166 (equal (match-string 1 term) "-"))
10167 tag (match-string 2 term)
10168 re-p (equal (string-to-char tag) ?{)
10169 level-p (match-end 3)
10170 mm (cond
10171 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10172 (level-p `(= level ,(string-to-number
10173 (match-string 3 term))))
10174 (t `(member ,(downcase tag) tags-list)))
10175 mm (if minus (list 'not mm) mm)
10176 term (substring term (match-end 0)))
10177 (push mm tagsmatcher))
10178 (push (if (> (length tagsmatcher) 1)
10179 (cons 'and tagsmatcher)
10180 (car tagsmatcher))
10181 orlist)
10182 (setq tagsmatcher nil))
10183 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
10185 ;; Make the todo matcher
10186 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10187 (setq todomatcher t)
10188 (setq orterms (org-split-string todomatch "|") orlist nil)
10189 (while (setq term (pop orterms))
10190 (while (string-match re term)
10191 (setq minus (and (match-end 1)
10192 (equal (match-string 1 term) "-"))
10193 kwd (match-string 2 term)
10194 re-p (equal (string-to-char kwd) ?{)
10195 term (substring term (match-end 0))
10196 mm (if re-p
10197 `(string-match ,(substring kwd 1 -1) todo)
10198 (list 'equal 'todo kwd))
10199 mm (if minus (list 'not mm) mm))
10200 (push mm todomatcher))
10201 (push (if (> (length todomatcher) 1)
10202 (cons 'and todomatcher)
10203 (car todomatcher))
10204 orlist)
10205 (setq todomatcher nil))
10206 (setq todomatcher (if (> (length orlist) 1)
10207 (cons 'or orlist) (car orlist))))
10209 ;; Return the string and lisp forms of the matcher
10210 (setq matcher (if todomatcher
10211 (list 'and tagsmatcher todomatcher)
10212 tagsmatcher))
10213 (cons match0 matcher)))
10215 (defun org-match-any-p (re list)
10216 "Does re match any element of list?"
10217 (setq list (mapcar (lambda (x) (string-match re x)) list))
10218 (delq nil list))
10220 ;;;###autoload
10221 (defun org-tags-view (&optional todo-only match)
10222 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
10223 The prefix arg TODO-ONLY limits the search to TODO entries."
10224 (interactive "P")
10225 (org-compile-prefix-format 'tags)
10226 (org-set-sorting-strategy 'tags)
10227 (let* ((org-tags-match-list-sublevels
10228 (if todo-only t org-tags-match-list-sublevels))
10229 (win (selected-window))
10230 (completion-ignore-case t)
10231 rtn rtnall files file pos matcher
10232 buffer)
10233 (setq matcher (org-make-tags-matcher match)
10234 match (car matcher) matcher (cdr matcher))
10235 (org-prepare-agenda)
10236 (setq org-agenda-redo-command
10237 (list 'org-tags-view (list 'quote todo-only)
10238 (list 'if 'current-prefix-arg nil match)))
10239 (setq files (org-agenda-files)
10240 rtnall nil)
10241 (while (setq file (pop files))
10242 (catch 'nextfile
10243 (org-check-agenda-file file)
10244 (setq buffer (if (file-exists-p file)
10245 (org-get-agenda-file-buffer file)
10246 (error "No such file %s" file)))
10247 (if (not buffer)
10248 ;; If file does not exist, merror message to agenda
10249 (setq rtn (list
10250 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
10251 rtnall (append rtnall rtn))
10252 (with-current-buffer buffer
10253 (unless (org-mode-p)
10254 (error "Agenda file %s is not in `org-mode'" file))
10255 (setq org-category-table (org-get-category-table))
10256 (save-excursion
10257 (save-restriction
10258 (if org-agenda-restrict
10259 (narrow-to-region org-agenda-restrict-begin
10260 org-agenda-restrict-end)
10261 (widen))
10262 (setq rtn (org-scan-tags 'agenda matcher todo-only))
10263 (setq rtnall (append rtnall rtn))))))))
10264 (if org-agenda-overriding-header
10265 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
10266 nil 'face 'org-level-3) "\n")
10267 (insert "Headlines with TAGS match: ")
10268 (add-text-properties (point-min) (1- (point))
10269 (list 'face 'org-level-3))
10270 (setq pos (point))
10271 (insert match "\n")
10272 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
10273 (setq pos (point))
10274 (unless org-agenda-multi
10275 (insert "Press `C-u r' to search again with new search string\n"))
10276 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
10277 (when rtnall
10278 (insert (org-finalize-agenda-entries rtnall) "\n"))
10279 (goto-char (point-min))
10280 (org-fit-agenda-window)
10281 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
10282 (org-finalize-agenda)
10283 (setq buffer-read-only t)
10284 (if (not org-select-agenda-window) (select-window win))))
10286 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
10287 (defvar org-tags-overlay (org-make-overlay 1 1))
10288 (org-detach-overlay org-tags-overlay)
10290 (defun org-set-tags (&optional arg just-align)
10291 "Set the tags for the current headline.
10292 With prefix ARG, realign all tags in headings in the current buffer."
10293 (interactive "P")
10294 (let* ((re (concat "^" outline-regexp))
10295 (current (org-get-tags))
10296 table current-tags inherited-tags ; computed below when needed
10297 tags p0 c0 c1 rpl)
10298 (if arg
10299 (save-excursion
10300 (goto-char (point-min))
10301 (let (buffer-invisibility-spec) ; Emacs 21 compatibility
10302 (while (re-search-forward re nil t)
10303 (org-set-tags nil t)
10304 (end-of-line 1)))
10305 (message "All tags realigned to column %d" org-tags-column))
10306 (if just-align
10307 (setq tags current)
10308 ;; Get a new set of tags from the user
10309 (setq table (or org-tag-alist (org-get-buffer-tags))
10310 org-last-tags-completion-table table
10311 current-tags (org-split-string current ":")
10312 inherited-tags (nreverse
10313 (nthcdr (length current-tags)
10314 (nreverse (org-get-tags-at))))
10315 tags
10316 (if (or (eq t org-use-fast-tag-selection)
10317 (and org-use-fast-tag-selection
10318 (delq nil (mapcar 'cdr table))))
10319 (org-fast-tag-selection current-tags inherited-tags table)
10320 (let ((org-add-colon-after-tag-completion t))
10321 (org-trim
10322 (completing-read "Tags: " 'org-tags-completion-function
10323 nil nil current 'org-tags-history)))))
10324 (while (string-match "[-+&]+" tags)
10325 ;; No boolean logic, just a list
10326 (setq tags (replace-match ":" t t tags))))
10327 (if (string-match "\\`[\t ]*\\'" tags)
10328 (setq tags "")
10329 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10330 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10332 ;; Insert new tags at the correct column
10333 (beginning-of-line 1)
10334 (if (re-search-forward
10335 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10336 (point-at-eol) t)
10337 (progn
10338 (if (equal tags "")
10339 (setq rpl "")
10340 (goto-char (match-beginning 0))
10341 (setq c0 (current-column) p0 (point)
10342 c1 (max (1+ c0) (if (> org-tags-column 0)
10343 org-tags-column
10344 (- (- org-tags-column) (length tags))))
10345 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10346 (replace-match rpl)
10347 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
10348 tags)
10349 (error "Tags alignment failed")))))
10351 (defun org-tags-completion-function (string predicate &optional flag)
10352 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10353 (confirm (lambda (x) (stringp (car x)))))
10354 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10355 (setq s1 (match-string 1 string)
10356 s2 (match-string 2 string))
10357 (setq s1 "" s2 string))
10358 (cond
10359 ((eq flag nil)
10360 ;; try completion
10361 (setq rtn (try-completion s2 ctable confirm))
10362 (if (stringp rtn)
10363 (concat s1 s2 (substring rtn (length s2))
10364 (if (and org-add-colon-after-tag-completion
10365 (assoc rtn ctable))
10366 ":" "")))
10368 ((eq flag t)
10369 ;; all-completions
10370 (all-completions s2 ctable confirm)
10372 ((eq flag 'lambda)
10373 ;; exact match?
10374 (assoc s2 ctable)))
10377 (defun org-fast-tag-insert (kwd tags face &optional end)
10378 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
10379 (insert (format "%-12s" (concat kwd ":"))
10380 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10381 (or end "")))
10383 (defun org-fast-tag-show-exit (flag)
10384 (save-excursion
10385 (goto-line 3)
10386 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10387 (replace-match ""))
10388 (when flag
10389 (end-of-line 1)
10390 (move-to-column (- (window-width) 19) t)
10391 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10393 (defun org-set-current-tags-overlay (current prefix)
10394 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10395 (if (featurep 'xemacs)
10396 (org-overlay-display org-tags-overlay (concat prefix s)
10397 'secondary-selection)
10398 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10399 (org-overlay-display org-tags-overlay (concat prefix s)))))
10401 (defun org-fast-tag-selection (current inherited table)
10402 "Fast tag selection with single keys.
10403 CURRENT is the current list of tags in the headline, INHERITED is the
10404 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10405 possibly with grouping information.
10406 If the keys are nil, a-z are automatically assigned.
10407 Returns the new tags string, or nil to not change the current settings."
10408 (let* ((maxlen (apply 'max (mapcar
10409 (lambda (x)
10410 (if (stringp (car x)) (string-width (car x)) 0))
10411 table)))
10412 (buf (current-buffer))
10413 (buffer-tags nil)
10414 (fwidth (+ maxlen 3 1 3))
10415 (ncol (/ (- (window-width) 4) fwidth))
10416 (i-face 'org-done)
10417 (c-face 'org-tag)
10418 tg cnt e c char c1 c2 ntable tbl rtn
10419 ov-start ov-end ov-prefix
10420 (exit-after-next org-fast-tag-selection-single-key)
10421 groups ingroup)
10422 (save-excursion
10423 (beginning-of-line 1)
10424 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
10425 (setq ov-start (match-beginning 1)
10426 ov-end (match-end 1)
10427 ov-prefix "")
10428 (setq ov-start (1- (point-at-eol))
10429 ov-end (1+ ov-start))
10430 (skip-chars-forward "^\n\r")
10431 (setq ov-prefix
10432 (concat
10433 (buffer-substring (1- (point)) (point))
10434 (if (> (current-column) org-tags-column)
10436 (make-string (- org-tags-column (current-column)) ?\ ))))))
10437 (org-move-overlay org-tags-overlay ov-start ov-end)
10438 (save-window-excursion
10439 ;; FIXME: would it be better to keep the other windows?
10440 (delete-other-windows)
10441 (split-window-vertically)
10442 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
10443 (erase-buffer)
10444 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10445 (org-fast-tag-insert "Current" current c-face "\n\n")
10446 (org-fast-tag-show-exit exit-after-next)
10447 (org-set-current-tags-overlay current ov-prefix)
10448 (setq tbl table char ?a cnt 0)
10449 (while (setq e (pop tbl))
10450 (cond
10451 ((equal e '(:startgroup))
10452 (push '() groups) (setq ingroup t)
10453 (when (not (= cnt 0))
10454 (setq cnt 0)
10455 (insert "\n"))
10456 (insert "{ "))
10457 ((equal e '(:endgroup))
10458 (setq ingroup nil cnt 0)
10459 (insert "}\n"))
10461 (setq tg (car e) c2 nil)
10462 (if (cdr e)
10463 (setq c (cdr e))
10464 ;; automatically assign a character.
10465 (setq c1 (string-to-char
10466 (downcase (substring
10467 tg (if (= (string-to-char tg) ?@) 1 0)))))
10468 (if (or (rassoc c1 ntable) (rassoc c1 table))
10469 (while (or (rassoc char ntable) (rassoc char table))
10470 (setq char (1+ char)))
10471 (setq c2 c1))
10472 (setq c (or c2 char)))
10473 (if ingroup (push tg (car groups)))
10474 (setq tg (org-add-props tg nil 'face
10475 (cond
10476 ((member tg current) c-face)
10477 ((member tg inherited) i-face)
10478 (t nil))))
10479 (if (and (= cnt 0) (not ingroup)) (insert " "))
10480 (insert "[" c "] " tg (make-string
10481 (- fwidth 4 (length tg)) ?\ ))
10482 (push (cons tg c) ntable)
10483 (when (= (setq cnt (1+ cnt)) ncol)
10484 (insert "\n")
10485 (if ingroup (insert " "))
10486 (setq cnt 0)))))
10487 (setq ntable (nreverse ntable))
10488 (insert "\n")
10489 (goto-char (point-min))
10490 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
10491 (setq rtn
10492 (catch 'exit
10493 (while t
10494 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [C-c]: multi%s"
10495 (if groups " [!] no groups" ""))
10496 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10497 (cond
10498 ((= c ?\r) (throw 'exit t))
10499 ((= c ?!)
10500 (setq groups nil)
10501 (goto-char (point-min))
10502 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10503 ((= c ?\C-c)
10504 (org-fast-tag-show-exit
10505 (setq exit-after-next (not exit-after-next))))
10506 ((or (= c ?\C-g)
10507 (and (= c ?q) (not (rassoc c ntable))))
10508 (org-detach-overlay org-tags-overlay)
10509 (setq quit-flag t))
10510 ((= c ?\ )
10511 (setq current nil)
10512 (if exit-after-next (setq exit-after-next 'now)))
10513 ((= c ?\t)
10514 (condition-case nil
10515 (setq tg (completing-read
10516 "Tag: "
10517 (or buffer-tags
10518 (with-current-buffer buf
10519 (org-get-buffer-tags)))))
10520 (quit (setq tg "")))
10521 (when (string-match "\\S-" tg)
10522 (add-to-list 'buffer-tags (list tg))
10523 (if (member tg current)
10524 (setq current (delete tg current))
10525 (push tg current)))
10526 (if exit-after-next (setq exit-after-next 'now)))
10527 ((setq e (rassoc c ntable) tg (car e))
10528 (if (member tg current)
10529 (setq current (delete tg current))
10530 (loop for g in groups do
10531 (if (member tg g)
10532 (mapcar (lambda (x)
10533 (setq current (delete x current)))
10534 g)))
10535 (push tg current))
10536 (if exit-after-next (setq exit-after-next 'now))))
10538 ;; Create a sorted list
10539 (setq current
10540 (sort current
10541 (lambda (a b)
10542 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10543 (if (eq exit-after-next 'now) (throw 'exit t))
10544 (goto-char (point-min))
10545 (beginning-of-line 2)
10546 (delete-region (point) (point-at-eol))
10547 (org-fast-tag-insert "Current" current c-face)
10548 (org-set-current-tags-overlay current ov-prefix)
10549 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
10550 (setq tg (match-string 1))
10551 (add-text-properties (match-beginning 1) (match-end 1)
10552 (list 'face
10553 (cond
10554 ((member tg current) c-face)
10555 ((member tg inherited) i-face)
10556 (t nil)))))
10557 (goto-char (point-min)))))
10558 (org-detach-overlay org-tags-overlay)
10559 (if rtn
10560 (mapconcat 'identity current ":")
10561 nil))))
10563 (defun org-get-tags ()
10564 "Get the TAGS string in the current headline."
10565 (unless (org-on-heading-p t)
10566 (error "Not on a heading"))
10567 (save-excursion
10568 (beginning-of-line 1)
10569 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
10570 (org-match-string-no-properties 1)
10571 "")))
10573 (defun org-get-buffer-tags ()
10574 "Get a table of all tags used in the buffer, for completion."
10575 (let (tags)
10576 (save-excursion
10577 (goto-char (point-min))
10578 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
10579 (mapc (lambda (x) (add-to-list 'tags x))
10580 (org-split-string (org-match-string-no-properties 1) ":"))))
10581 (mapcar 'list tags)))
10583 ;;;; Link Stuff
10585 (defvar org-create-file-search-functions nil
10586 "List of functions to construct the right search string for a file link.
10587 These functions are called in turn with point at the location to
10588 which the link should point.
10590 A function in the hook should first test if it would like to
10591 handle this file type, for example by checking the major-mode or
10592 the file extension. If it decides not to handle this file, it
10593 should just return nil to give other functions a chance. If it
10594 does handle the file, it must return the search string to be used
10595 when following the link. The search string will be part of the
10596 file link, given after a double colon, and `org-open-at-point'
10597 will automatically search for it. If special measures must be
10598 taken to make the search successful, another function should be
10599 added to the companion hook `org-execute-file-search-functions',
10600 which see.
10602 A function in this hook may also use `setq' to set the variable
10603 `description' to provide a suggestion for the descriptive text to
10604 be used for this link when it gets inserted into an Org-mode
10605 buffer with \\[org-insert-link].")
10607 (defvar org-execute-file-search-functions nil
10608 "List of functions to execute a file search triggered by a link.
10610 Functions added to this hook must accept a single argument, the
10611 search string that was part of the file link, the part after the
10612 double colon. The function must first check if it would like to
10613 handle this search, for example by checking the major-mode or the
10614 file extension. If it decides not to handle this search, it
10615 should just return nil to give other functions a chance. If it
10616 does handle the search, it must return a non-nil value to keep
10617 other functions from trying.
10619 Each function can access the current prefix argument through the
10620 variable `current-prefix-argument'. Note that a single prefix is
10621 used to force opening a link in Emacs, so it may be good to only
10622 use a numeric or double prefix to guide the search function.
10624 In case this is needed, a function in this hook can also restore
10625 the window configuration before `org-open-at-point' was called using:
10627 (set-window-configuration org-window-config-before-follow-link)")
10629 (defun org-find-file-at-mouse (ev)
10630 "Open file link or URL at mouse."
10631 (interactive "e")
10632 (mouse-set-point ev)
10633 (org-open-at-point 'in-emacs))
10635 (defun org-open-at-mouse (ev)
10636 "Open file link or URL at mouse."
10637 (interactive "e")
10638 (mouse-set-point ev)
10639 (org-open-at-point))
10641 (defvar org-window-config-before-follow-link nil
10642 "The window configuration before following a link.
10643 This is saved in case the need arises to restore it.")
10645 ;; FIXME: IN-EMACS is used for many purposes, maybe rename this argument???
10646 (defun org-open-at-point (&optional in-emacs)
10647 "Open link at or after point.
10648 If there is no link at point, this function will search forward up to
10649 the end of the current subtree.
10650 Normally, files will be opened by an appropriate application. If the
10651 optional argument IN-EMACS is non-nil, Emacs will visit the file."
10652 (interactive "P")
10653 (setq org-window-config-before-follow-link (current-window-configuration))
10654 (org-remove-occur-highlights nil nil t)
10655 (if (org-at-timestamp-p t)
10656 (org-follow-timestamp-link)
10657 (let (type path link line search (pos (point)))
10658 (catch 'match
10659 (save-excursion
10660 (skip-chars-forward "^]\n\r")
10661 (when (and (re-search-backward "\\[\\[" nil t)
10662 (looking-at org-bracket-link-regexp)
10663 (<= (match-beginning 0) pos)
10664 (>= (match-end 0) pos))
10665 (setq link (org-link-unescape (org-match-string-no-properties 1)))
10666 (while (string-match " *\n *" link)
10667 (setq link (replace-match " " t t link)))
10668 (setq link (org-link-expand-abbrev link))
10669 (if (string-match org-link-re-with-space2 link)
10670 (setq type (match-string 1 link)
10671 path (match-string 2 link))
10672 (setq type "thisfile"
10673 path link))
10674 (throw 'match t)))
10676 (when (get-text-property (point) 'org-linked-text)
10677 (setq type "thisfile"
10678 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10679 (1+ (point)) (point))
10680 path (buffer-substring
10681 (previous-single-property-change pos 'org-linked-text)
10682 (next-single-property-change pos 'org-linked-text)))
10683 (throw 'match t))
10685 (save-excursion
10686 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
10687 (if (equal (char-before) ?<) (backward-char 1))
10688 (when (or (looking-at org-angle-link-re)
10689 (looking-at org-plain-link-re)
10690 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
10691 (re-search-forward org-plain-link-re (point-at-eol) t))
10692 (<= (match-beginning 0) pos)
10693 (>= (match-end 0) pos)))
10694 (setq type (match-string 1)
10695 path (match-string 2))
10696 (throw 'match t)))
10697 (save-excursion
10698 (skip-chars-backward "^ \t\n\r")
10699 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
10700 (setq type "tags"
10701 path (match-string 1))
10702 (while (string-match ":" path)
10703 (setq path (replace-match "+" t t path)))
10704 (throw 'match t)))
10705 (save-excursion
10706 (skip-chars-backward "a-zA-Z_")
10707 (when (and (memq 'camel org-activate-links)
10708 (looking-at org-camel-regexp))
10709 (setq type "camel" path (match-string 0))
10710 (if (equal (char-before) ?*)
10711 (setq path (concat "*" path))))
10712 (throw 'match t)))
10713 (unless path
10714 (error "No link found"))
10715 ;; Remove any trailing spaces in path
10716 (if (string-match " +\\'" path)
10717 (setq path (replace-match "" t t path)))
10719 (cond
10721 ((equal type "mailto")
10722 (let ((cmd (car org-link-mailto-program))
10723 (args (cdr org-link-mailto-program)) args1
10724 (address path) (subject "") a)
10725 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10726 (setq address (match-string 1 path)
10727 subject (org-link-escape (match-string 2 path))))
10728 (while args
10729 (cond
10730 ((not (stringp (car args))) (push (pop args) args1))
10731 (t (setq a (pop args))
10732 (if (string-match "%a" a)
10733 (setq a (replace-match address t t a)))
10734 (if (string-match "%s" a)
10735 (setq a (replace-match subject t t a)))
10736 (push a args1))))
10737 (apply cmd (nreverse args1))))
10739 ((member type '("http" "https" "ftp" "news"))
10740 (browse-url (concat type ":" path)))
10742 ((string= type "tags")
10743 (org-tags-view in-emacs path))
10744 ((or (string= type "camel")
10745 (string= type "thisfile"))
10746 (if in-emacs
10747 (switch-to-buffer-other-window
10748 (org-get-buffer-for-internal-link (current-buffer)))
10749 (org-mark-ring-push))
10750 (org-link-search
10751 path
10752 (cond ((equal in-emacs '(4)) 'occur)
10753 ((equal in-emacs '(16)) 'org-occur)
10754 (t nil))))
10756 ((string= type "file")
10757 (if (string-match "::\\([0-9]+\\)\\'" path)
10758 (setq line (string-to-number (match-string 1 path))
10759 path (substring path 0 (match-beginning 0)))
10760 (if (string-match "::\\(.+\\)\\'" path)
10761 (setq search (match-string 1 path)
10762 path (substring path 0 (match-beginning 0)))))
10763 (org-open-file path in-emacs line search))
10765 ((string= type "news")
10766 (org-follow-gnus-link path))
10768 ((string= type "bbdb")
10769 (org-follow-bbdb-link path))
10771 ((string= type "info")
10772 (org-follow-info-link path))
10774 ((string= type "gnus")
10775 (let (group article)
10776 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10777 (error "Error in Gnus link"))
10778 (setq group (match-string 1 path)
10779 article (match-string 3 path))
10780 (org-follow-gnus-link group article)))
10782 ((string= type "vm")
10783 (let (folder article)
10784 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10785 (error "Error in VM link"))
10786 (setq folder (match-string 1 path)
10787 article (match-string 3 path))
10788 ;; in-emacs is the prefix arg, will be interpreted as read-only
10789 (org-follow-vm-link folder article in-emacs)))
10791 ((string= type "wl")
10792 (let (folder article)
10793 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10794 (error "Error in Wanderlust link"))
10795 (setq folder (match-string 1 path)
10796 article (match-string 3 path))
10797 (org-follow-wl-link folder article)))
10799 ((string= type "mhe")
10800 (let (folder article)
10801 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10802 (error "Error in MHE link"))
10803 (setq folder (match-string 1 path)
10804 article (match-string 3 path))
10805 (org-follow-mhe-link folder article)))
10807 ((string= type "rmail")
10808 (let (folder article)
10809 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10810 (error "Error in RMAIL link"))
10811 (setq folder (match-string 1 path)
10812 article (match-string 3 path))
10813 (org-follow-rmail-link folder article)))
10815 ((string= type "shell")
10816 (let ((cmd path))
10817 (while (string-match "@{" cmd) ; FIXME: not needed for [[]] links
10818 (setq cmd (replace-match "<" t t cmd)))
10819 (while (string-match "@}" cmd) ; FIXME: not needed for [[]] links
10820 (setq cmd (replace-match ">" t t cmd)))
10821 (if (or (not org-confirm-shell-link-function)
10822 (funcall org-confirm-shell-link-function
10823 (format "Execute \"%s\" in shell? "
10824 (org-add-props cmd nil
10825 'face 'org-warning))))
10826 (progn
10827 (message "Executing %s" cmd)
10828 (shell-command cmd))
10829 (error "Abort"))))
10831 ((string= type "elisp")
10832 (let ((cmd path))
10833 (if (or (not org-confirm-elisp-link-function)
10834 (funcall org-confirm-elisp-link-function
10835 (format "Execute \"%s\" as elisp? "
10836 (org-add-props cmd nil
10837 'face 'org-warning))))
10838 (message "%s => %s" cmd (eval (read cmd)))
10839 (error "Abort"))))
10842 (browse-url-at-point))))))
10844 (defun org-link-expand-abbrev (link)
10845 "Apply replacements as defined in `org-link-abbrev-alist."
10846 (if (string-match "^\\([a-zA-Z]+\\)\\(::\\(.*\\)\\)?$" link)
10847 (let* ((key (match-string 1 link))
10848 (as (or (assoc key org-link-abbrev-alist-local)
10849 (assoc key org-link-abbrev-alist)))
10850 (tag (and (match-end 2) (match-string 3 link)))
10851 rpl)
10852 (if (not as)
10853 link
10854 (setq rpl (cdr as))
10855 (cond
10856 ((symbolp rpl) (funcall rpl tag))
10857 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
10858 (t (concat rpl tag)))))
10859 link))
10861 (defun org-link-search (s &optional type)
10862 "Search for a link search option.
10863 When S is a CamelCaseWord, search for a target, or for a sentence containing
10864 the words. If S is surrounded by forward slashes, it is interpreted as a
10865 regular expression. In org-mode files, this will create an `org-occur'
10866 sparse tree. In ordinary files, `occur' will be used to list matches.
10867 If the current buffer is in `dired-mode', grep will be used to search
10868 in all files."
10869 (let ((case-fold-search t)
10870 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10871 (pos (point))
10872 (pre "") (post "")
10873 words re0 re1 re2 re3 re4 re5 re2a reall camel)
10874 (cond
10875 ;; First check if there are any special
10876 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10877 ;; Now try the builtin stuff
10878 ((save-excursion
10879 (goto-char (point-min))
10880 (and
10881 (re-search-forward
10882 (concat "<<" (regexp-quote s0) ">>") nil t)
10883 (setq pos (match-beginning 0))))
10884 ;; There is an exact target for this
10885 (goto-char pos))
10886 ((string-match "^/\\(.*\\)/$" s)
10887 ;; A regular expression
10888 (cond
10889 ((org-mode-p)
10890 (org-occur (match-string 1 s)))
10891 ;;((eq major-mode 'dired-mode)
10892 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10893 (t (org-do-occur (match-string 1 s)))))
10894 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
10896 ;; A camel or a normal search string
10897 (when (equal (string-to-char s) ?*)
10898 ;; Anchor on headlines, post may include tags.
10899 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
10900 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
10901 s (substring s 1)))
10902 (remove-text-properties
10903 0 (length s)
10904 '(face nil mouse-face nil keymap nil fontified nil) s)
10905 ;; Make a series of regular expressions to find a match
10906 (setq words
10907 (if camel
10908 (org-camel-to-words s)
10909 (org-split-string s "[ \n\r\t]+"))
10910 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10911 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
10912 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10913 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10914 re1 (concat pre re2 post)
10915 re3 (concat pre re4 post)
10916 re5 (concat pre ".*" re4)
10917 re2 (concat pre re2)
10918 re2a (concat pre re2a)
10919 re4 (concat pre re4)
10920 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10921 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10922 re5 "\\)"
10924 (cond
10925 ((eq type 'org-occur) (org-occur reall))
10926 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10927 (t (goto-char (point-min))
10928 (if (or (org-search-not-link re0 nil t)
10929 (org-search-not-link re1 nil t)
10930 (org-search-not-link re2 nil t)
10931 (org-search-not-link re2a nil t)
10932 (org-search-not-link re3 nil t)
10933 (org-search-not-link re4 nil t)
10934 (org-search-not-link re5 nil t)
10936 (goto-char (match-beginning 1))
10937 (goto-char pos)
10938 (error "No match")))))
10940 ;; Normal string-search
10941 (goto-char (point-min))
10942 (if (search-forward s nil t)
10943 (goto-char (match-beginning 0))
10944 (error "No match"))))
10945 (and (org-mode-p) (org-show-context 'link-search))))
10947 (defun org-search-not-link (&rest args)
10948 "Execute `re-search-forward', but only accept matches that are not a link."
10949 (catch 'exit
10950 (let (p1)
10951 (while (apply 're-search-forward args)
10952 (setq p1 (point))
10953 (if (not (save-match-data
10954 (and (re-search-backward "\\[\\[" nil t)
10955 (looking-at org-bracket-link-regexp)
10956 (<= (match-beginning 0) p1)
10957 (>= (match-end 0) p1))))
10958 (progn (goto-char (match-end 0))
10959 (throw 'exit (point)))
10960 (goto-char (match-end 0)))))))
10962 (defun org-get-buffer-for-internal-link (buffer)
10963 "Return a buffer to be used for displaying the link target of internal links."
10964 (cond
10965 ((not org-display-internal-link-with-indirect-buffer)
10966 buffer)
10967 ((string-match "(Clone)$" (buffer-name buffer))
10968 (message "Buffer is already a clone, not making another one")
10969 ;; we also do not modify visibility in this case
10970 buffer)
10971 (t ; make a new indirect buffer for displaying the link
10972 (let* ((bn (buffer-name buffer))
10973 (ibn (concat bn "(Clone)"))
10974 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10975 (with-current-buffer ib (org-overview))
10976 ib))))
10978 (defun org-do-occur (regexp &optional cleanup)
10979 "Call the Emacs command `occur'.
10980 If CLEANUP is non-nil, remove the printout of the regular expression
10981 in the *Occur* buffer. This is useful if the regex is long and not useful
10982 to read."
10983 (occur regexp)
10984 (when cleanup
10985 (let ((cwin (selected-window)) win beg end)
10986 (when (setq win (get-buffer-window "*Occur*"))
10987 (select-window win))
10988 (goto-char (point-min))
10989 (when (re-search-forward "match[a-z]+" nil t)
10990 (setq beg (match-end 0))
10991 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10992 (setq end (1- (match-beginning 0)))))
10993 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
10994 (goto-char (point-min))
10995 (select-window cwin))))
10997 (defvar org-mark-ring nil
10998 "Mark ring for positions before jumps in Org-mode.")
10999 (defvar org-mark-ring-last-goto nil
11000 "Last position in the mark ring used to go back.")
11001 ;; Fill and close the ring
11002 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11003 (loop for i from 1 to org-mark-ring-length do
11004 (push (make-marker) org-mark-ring))
11005 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11006 org-mark-ring)
11008 (defun org-mark-ring-push (&optional pos buffer)
11009 "Put the current position or POS into the mark ring and rotate it."
11010 (interactive)
11011 (setq pos (or pos (point)))
11012 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11013 (move-marker (car org-mark-ring)
11014 (or pos (point))
11015 (or buffer (current-buffer)))
11016 (message
11017 (substitute-command-keys
11018 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11020 (defun org-mark-ring-goto (&optional n)
11021 "Jump to the previous position in the mark ring.
11022 With prefix arg N, jump back that many stored positions. When
11023 called several times in succession, walk through the entire ring.
11024 Org-mode commands jumping to a different position in the current file,
11025 or to another Org-mode file, automatically push the old position
11026 onto the ring."
11027 (interactive "p")
11028 (let (p m)
11029 (if (eq last-command this-command)
11030 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11031 (setq p org-mark-ring))
11032 (setq org-mark-ring-last-goto p)
11033 (setq m (car p))
11034 (switch-to-buffer (marker-buffer m))
11035 (goto-char m)
11036 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11038 (defun org-camel-to-words (s)
11039 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
11040 (let ((case-fold-search nil)
11041 words)
11042 (while (string-match "[a-z][A-Z]" s)
11043 (push (substring s 0 (1+ (match-beginning 0))) words)
11044 (setq s (substring s (1+ (match-beginning 0)))))
11045 (nreverse (cons s words))))
11047 (defun org-remove-angle-brackets (s)
11048 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11049 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11051 (defun org-add-angle-brackets (s)
11052 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11053 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11056 (defun org-follow-timestamp-link ()
11057 (cond
11058 ((org-at-date-range-p t)
11059 (let ((org-agenda-start-on-weekday)
11060 (t1 (match-string 1))
11061 (t2 (match-string 2)))
11062 (setq t1 (time-to-days (org-time-string-to-time t1))
11063 t2 (time-to-days (org-time-string-to-time t2)))
11064 (org-agenda-list nil t1 (1+ (- t2 t1)))))
11065 ((org-at-timestamp-p t)
11066 (org-agenda-list nil (time-to-days (org-time-string-to-time
11067 (substring (match-string 1) 0 10)))
11069 (t (error "This should not happen"))))
11072 (defun org-follow-bbdb-link (name)
11073 "Follow a BBDB link to NAME."
11074 (require 'bbdb)
11075 (let ((inhibit-redisplay t)
11076 (bbdb-electric-p nil))
11077 (catch 'exit
11078 ;; Exact match on name
11079 (bbdb-name (concat "\\`" name "\\'") nil)
11080 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11081 ;; Exact match on name
11082 (bbdb-company (concat "\\`" name "\\'") nil)
11083 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11084 ;; Partial match on name
11085 (bbdb-name name nil)
11086 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11087 ;; Partial match on company
11088 (bbdb-company name nil)
11089 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11090 ;; General match including network address and notes
11091 (bbdb name nil)
11092 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
11093 (delete-window (get-buffer-window "*BBDB*"))
11094 (error "No matching BBDB record")))))
11097 (defun org-follow-info-link (name)
11098 "Follow an info file & node link to NAME."
11099 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
11100 (string-match "\\(.*\\)" name))
11101 (progn
11102 (require 'info)
11103 (if (match-string 2 name) ; If there isn't a node, choose "Top"
11104 (Info-find-node (match-string 1 name) (match-string 2 name))
11105 (Info-find-node (match-string 1 name) "Top")))
11106 (message (concat "Could not open: " name))))
11108 (defun org-follow-gnus-link (&optional group article)
11109 "Follow a Gnus link to GROUP and ARTICLE."
11110 (require 'gnus)
11111 (funcall (cdr (assq 'gnus org-link-frame-setup)))
11112 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
11113 (if group (gnus-fetch-group group))
11114 (if article
11115 (or (gnus-summary-goto-article article nil 'force)
11116 (if (fboundp 'gnus-summary-insert-cached-articles)
11117 (progn
11118 (gnus-summary-insert-cached-articles)
11119 (gnus-summary-goto-article article nil 'force))
11120 (message "Message could not be found.")))))
11122 (defun org-follow-vm-link (&optional folder article readonly)
11123 "Follow a VM link to FOLDER and ARTICLE."
11124 (require 'vm)
11125 (setq article (org-add-angle-brackets article))
11126 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
11127 ;; ange-ftp or efs or tramp access
11128 (let ((user (or (match-string 1 folder) (user-login-name)))
11129 (host (match-string 2 folder))
11130 (file (match-string 3 folder)))
11131 (cond
11132 ((featurep 'tramp)
11133 ;; use tramp to access the file
11134 (if (featurep 'xemacs)
11135 (setq folder (format "[%s@%s]%s" user host file))
11136 (setq folder (format "/%s@%s:%s" user host file))))
11138 ;; use ange-ftp or efs
11139 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
11140 (setq folder (format "/%s@%s:%s" user host file))))))
11141 (when folder
11142 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
11143 (sit-for 0.1)
11144 (when article
11145 (vm-select-folder-buffer)
11146 (widen)
11147 (let ((case-fold-search t))
11148 (goto-char (point-min))
11149 (if (not (re-search-forward
11150 (concat "^" "message-id: *" (regexp-quote article))))
11151 (error "Could not find the specified message in this folder"))
11152 (vm-isearch-update)
11153 (vm-isearch-narrow)
11154 (vm-beginning-of-message)
11155 (vm-summarize)))))
11157 (defun org-follow-wl-link (folder article)
11158 "Follow a Wanderlust link to FOLDER and ARTICLE."
11159 (setq article (org-add-angle-brackets article))
11160 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
11161 (if article (wl-summary-jump-to-msg-by-message-id article))
11162 (wl-summary-redisplay))
11164 (defun org-follow-rmail-link (folder article)
11165 "Follow an RMAIL link to FOLDER and ARTICLE."
11166 (setq article (org-add-angle-brackets article))
11167 (let (message-number)
11168 (save-excursion
11169 (save-window-excursion
11170 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11171 (setq message-number
11172 (save-restriction
11173 (widen)
11174 (goto-char (point-max))
11175 (if (re-search-backward
11176 (concat "^Message-ID:\\s-+" (regexp-quote
11177 (or article "")))
11178 nil t)
11179 (rmail-what-message))))))
11180 (if message-number
11181 (progn
11182 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11183 (rmail-show-message message-number)
11184 message-number)
11185 (error "Message not found"))))
11187 ;;; mh-e integration based on planner-mode
11188 (defun org-mhe-get-message-real-folder ()
11189 "Return the name of the current message real folder, so if you use
11190 sequences, it will now work."
11191 (save-excursion
11192 (let* ((folder
11193 (if (equal major-mode 'mh-folder-mode)
11194 mh-current-folder
11195 ;; Refer to the show buffer
11196 mh-show-folder-buffer))
11197 (end-index
11198 (if (boundp 'mh-index-folder)
11199 (min (length mh-index-folder) (length folder))))
11201 ;; a simple test on mh-index-data does not work, because
11202 ;; mh-index-data is always nil in a show buffer.
11203 (if (and (boundp 'mh-index-folder)
11204 (string= mh-index-folder (substring folder 0 end-index)))
11205 (if (equal major-mode 'mh-show-mode)
11206 (save-window-excursion
11207 (when (buffer-live-p (get-buffer folder))
11208 (progn
11209 (pop-to-buffer folder)
11210 (org-mhe-get-message-folder-from-index)
11213 (org-mhe-get-message-folder-from-index)
11215 folder
11219 (defun org-mhe-get-message-folder-from-index ()
11220 "Returns the name of the message folder in a index folder buffer."
11221 (save-excursion
11222 (mh-index-previous-folder)
11223 (re-search-forward "^\\(+.*\\)$" nil t)
11224 (message (match-string 1))))
11226 (defun org-mhe-get-message-folder ()
11227 "Return the name of the current message folder. Be careful if you
11228 use sequences."
11229 (save-excursion
11230 (if (equal major-mode 'mh-folder-mode)
11231 mh-current-folder
11232 ;; Refer to the show buffer
11233 mh-show-folder-buffer)))
11235 (defun org-mhe-get-message-num ()
11236 "Return the number of the current message. Be careful if you
11237 use sequences."
11238 (save-excursion
11239 (if (equal major-mode 'mh-folder-mode)
11240 (mh-get-msg-num nil)
11241 ;; Refer to the show buffer
11242 (mh-show-buffer-message-number))))
11244 (defun org-mhe-get-header (header)
11245 "Return a header of the message in folder mode. This will create a
11246 show buffer for the corresponding message. If you have a more clever
11247 idea..."
11248 (let* ((folder (org-mhe-get-message-folder))
11249 (num (org-mhe-get-message-num))
11250 (buffer (get-buffer-create (concat "show-" folder)))
11251 (header-field))
11252 (with-current-buffer buffer
11253 (mh-display-msg num folder)
11254 (if (equal major-mode 'mh-folder-mode)
11255 (mh-header-display)
11256 (mh-show-header-display))
11257 (set-buffer buffer)
11258 (setq header-field (mh-get-header-field header))
11259 (if (equal major-mode 'mh-folder-mode)
11260 (mh-show)
11261 (mh-show-show))
11262 header-field)))
11264 (defun org-follow-mhe-link (folder article)
11265 "Follow an MHE link to FOLDER and ARTICLE.
11266 If ARTICLE is nil FOLDER is shown. If the configuration variable
11267 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
11268 ARTICLE is searched in all folders. Indexed searches (swish++,
11269 namazu, and others supported by MH-E) will always search in all
11270 folders."
11271 (require 'mh-e)
11272 (require 'mh-search)
11273 (require 'mh-utils)
11274 (mh-find-path)
11275 (if (not article)
11276 (mh-visit-folder (mh-normalize-folder-name folder))
11277 (setq article (org-add-angle-brackets article))
11278 (mh-search-choose)
11279 (if (equal mh-searcher 'pick)
11280 (progn
11281 (mh-search folder (list "--message-id" article))
11282 (when (and org-mhe-search-all-folders
11283 (not (org-mhe-get-message-real-folder)))
11284 (kill-this-buffer)
11285 (mh-search "+" (list "--message-id" article))))
11286 (mh-search "+" article))
11287 (if (org-mhe-get-message-real-folder)
11288 (mh-show-msg 1)
11289 (kill-this-buffer)
11290 (error "Message not found"))))
11292 ;;; BibTeX links
11294 ;; Use the custom search meachnism to construct and use search strings for
11295 ;; file links to BibTeX database entries.
11297 (defun org-create-file-search-in-bibtex ()
11298 "Create the search string and description for a BibTeX database entry."
11299 (when (eq major-mode 'bibtex-mode)
11300 ;; yes, we want to construct this search string.
11301 ;; Make a good description for this entry, using names, year and the title
11302 ;; Put it into the `description' variable which is dynamically scoped.
11303 (let ((bibtex-autokey-names 1)
11304 (bibtex-autokey-names-stretch 1)
11305 (bibtex-autokey-name-case-convert-function 'identity)
11306 (bibtex-autokey-name-separator " & ")
11307 (bibtex-autokey-additional-names " et al.")
11308 (bibtex-autokey-year-length 4)
11309 (bibtex-autokey-name-year-separator " ")
11310 (bibtex-autokey-titlewords 3)
11311 (bibtex-autokey-titleword-separator " ")
11312 (bibtex-autokey-titleword-case-convert-function 'identity)
11313 (bibtex-autokey-titleword-length 'infty)
11314 (bibtex-autokey-year-title-separator ": "))
11315 (setq description (bibtex-generate-autokey)))
11316 ;; Now parse the entry, get the key and return it.
11317 (save-excursion
11318 (bibtex-beginning-of-entry)
11319 (cdr (assoc "=key=" (bibtex-parse-entry))))))
11321 (defun org-execute-file-search-in-bibtex (s)
11322 "Find the link search string S as a key for a database entry."
11323 (when (eq major-mode 'bibtex-mode)
11324 ;; Yes, we want to do the search in this file.
11325 ;; We construct a regexp that searches for "@entrytype{" followed by the key
11326 (goto-char (point-min))
11327 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
11328 (regexp-quote s) "[ \t\n]*,") nil t)
11329 (goto-char (match-beginning 0)))
11330 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
11331 ;; Use double prefix to indicate that any web link should be browsed
11332 (let ((b (current-buffer)) (p (point)))
11333 ;; Restore the window configuration because we just use the web link
11334 (set-window-configuration org-window-config-before-follow-link)
11335 (save-excursion (set-buffer b) (goto-char p)
11336 (bibtex-url)))
11337 (recenter 0)) ; Move entry start to beginning of window
11338 ;; return t to indicate that the search is done.
11341 ;; Finally add the functions to the right hooks.
11342 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
11343 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
11345 ;; end of Bibtex link setup
11347 (defun org-upgrade-old-links (&optional query-description)
11348 "Transfer old <...> style links to new [[...]] style links.
11349 With arg query-description, ask at each match for a description text to use
11350 for this link."
11351 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
11352 (save-excursion
11353 (goto-char (point-min))
11354 (let ((re (concat "\\([^[]\\)<\\("
11355 "\\(" (mapconcat 'identity org-link-types "\\|")
11356 "\\):"
11357 "[^" org-non-link-chars "]+\\)>"))
11358 l1 l2 (cnt 0))
11359 (while (re-search-forward re nil t)
11360 (setq cnt (1+ cnt)
11361 l1 (org-match-string-no-properties 2)
11362 l2 (save-match-data (org-link-escape l1)))
11363 (when query-description (setq l1 (read-string "Desc: " l1)))
11364 (if (equal l1 l2)
11365 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
11366 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
11367 (message "%d matches have beed treated" cnt))))
11369 (defun org-open-file (path &optional in-emacs line search)
11370 "Open the file at PATH.
11371 First, this expands any special file name abbreviations. Then the
11372 configuration variable `org-file-apps' is checked if it contains an
11373 entry for this file type, and if yes, the corresponding command is launched.
11374 If no application is found, Emacs simply visits the file.
11375 With optional argument IN-EMACS, Emacs will visit the file.
11376 Optional LINE specifies a line to go to, optional SEARCH a string to
11377 search for. If LINE or SEARCH is given, the file will always be
11378 opened in Emacs.
11379 If the file does not exist, an error is thrown."
11380 (setq in-emacs (or in-emacs line search))
11381 (let* ((file (if (equal path "")
11382 buffer-file-name
11383 (substitute-in-file-name (expand-file-name path))))
11384 (apps (append org-file-apps (org-default-apps)))
11385 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11386 (dirp (if remp nil (file-directory-p file)))
11387 (dfile (downcase file))
11388 (old-buffer (current-buffer))
11389 (old-pos (point))
11390 (old-mode major-mode)
11391 ext cmd)
11392 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11393 (setq ext (match-string 1 dfile))
11394 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11395 (setq ext (match-string 1 dfile))))
11396 (if in-emacs
11397 (setq cmd 'emacs)
11398 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11399 (and dirp (cdr (assoc 'directory apps)))
11400 (cdr (assoc ext apps))
11401 (cdr (assoc t apps)))))
11402 (when (eq cmd 'mailcap)
11403 (require 'mailcap)
11404 (mailcap-parse-mailcaps)
11405 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11406 (command (mailcap-mime-info mime-type)))
11407 (if (stringp command)
11408 (setq cmd command)
11409 (setq cmd 'emacs))))
11410 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
11411 (not (file-exists-p file))
11412 (not org-open-non-existing-files))
11413 (error "No such file: %s" file))
11414 (cond
11415 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11416 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11417 (if (string-match "['\"]%s['\"]" cmd)
11418 (setq cmd (replace-match "%s" t t cmd)))
11419 (setq cmd (format cmd (shell-quote-argument file)))
11420 (save-window-excursion
11421 (shell-command (concat cmd " &"))))
11422 ((or (stringp cmd)
11423 (eq cmd 'emacs))
11424 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
11425 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
11426 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11427 (if line (goto-line line)
11428 (if search (org-link-search search))))
11429 ((consp cmd)
11430 (eval cmd))
11431 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11432 (and (org-mode-p) (eq old-mode 'org-mode)
11433 (or (not (equal old-buffer (current-buffer)))
11434 (not (equal old-pos (point))))
11435 (org-mark-ring-push old-pos old-buffer))))
11437 (defun org-default-apps ()
11438 "Return the default applications for this operating system."
11439 (cond
11440 ((eq system-type 'darwin)
11441 org-file-apps-defaults-macosx)
11442 ((eq system-type 'windows-nt)
11443 org-file-apps-defaults-windowsnt)
11444 (t org-file-apps-defaults-gnu)))
11446 (defun org-expand-file-name (path)
11447 "Replace special path abbreviations and expand the file name."
11448 (expand-file-name path))
11450 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11451 (defun org-file-remote-p (file)
11452 "Test whether FILE specifies a location on a remote system.
11453 Return non-nil if the location is indeed remote.
11455 For example, the filename \"/user@host:/foo\" specifies a location
11456 on the system \"/user@host:\"."
11457 (cond ((fboundp 'file-remote-p)
11458 (file-remote-p file))
11459 ((fboundp 'tramp-handle-file-remote-p)
11460 (tramp-handle-file-remote-p file))
11461 ((and (boundp 'ange-ftp-name-format)
11462 (string-match (car ange-ftp-name-format) file))
11464 (t nil)))
11466 (defvar org-insert-link-history nil
11467 "Minibuffer history for links inserted with `org-insert-link'.")
11469 (defvar org-stored-links nil
11470 "Contains the links stored with `org-store-link'.")
11472 ;;;###autoload
11473 (defun org-store-link (arg)
11474 "\\<org-mode-map>Store an org-link to the current location.
11475 This link can later be inserted into an org-buffer with
11476 \\[org-insert-link].
11477 For some link types, a prefix arg is interpreted:
11478 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11479 For file links, arg negates `org-context-in-file-links'."
11480 (interactive "P")
11481 (let (link cpltxt desc description search txt (pos (point)))
11482 (cond
11484 ((eq major-mode 'bbdb-mode)
11485 (setq cpltxt (concat
11486 "bbdb:"
11487 (or (bbdb-record-name (bbdb-current-record))
11488 (bbdb-record-company (bbdb-current-record))))
11489 link (org-make-link cpltxt)))
11491 ((eq major-mode 'Info-mode)
11492 (setq link (org-make-link "info:"
11493 (file-name-nondirectory Info-current-file)
11494 ":" Info-current-node))
11495 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11496 ":" Info-current-node)))
11498 ((eq major-mode 'calendar-mode)
11499 (let ((cd (calendar-cursor-to-date)))
11500 (setq link
11501 (format-time-string
11502 (car org-time-stamp-formats)
11503 (apply 'encode-time
11504 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11505 nil nil nil))))))
11507 ((or (eq major-mode 'vm-summary-mode)
11508 (eq major-mode 'vm-presentation-mode))
11509 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11510 (vm-follow-summary-cursor)
11511 (save-excursion
11512 (vm-select-folder-buffer)
11513 (let* ((message (car vm-message-pointer))
11514 (folder buffer-file-name)
11515 (subject (vm-su-subject message))
11516 (author (vm-su-full-name message))
11517 (message-id (vm-su-message-id message)))
11518 (setq message-id (org-remove-angle-brackets message-id))
11519 (setq folder (abbreviate-file-name folder))
11520 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11521 folder)
11522 (setq folder (replace-match "" t t folder)))
11523 (setq cpltxt (concat author " on: " subject))
11524 (setq link (org-make-link "vm:" folder "#" message-id)))))
11526 ((eq major-mode 'wl-summary-mode)
11527 (let* ((msgnum (wl-summary-message-number))
11528 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11529 msgnum 'message-id))
11530 (wl-message-entity
11531 (if (fboundp 'elmo-message-entity)
11532 (elmo-message-entity
11533 wl-summary-buffer-elmo-folder msgnum)
11534 (elmo-msgdb-overview-get-entity
11535 msgnum (wl-summary-buffer-msgdb))))
11536 (author (wl-summary-line-from)) ; FIXME: correct?
11537 (subject "???")) ; FIXME:
11538 (setq message-id (org-remove-angle-brackets message-id))
11539 (setq cpltxt (concat author " on: " subject))
11540 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11541 "#" message-id))))
11543 ((or (equal major-mode 'mh-folder-mode)
11544 (equal major-mode 'mh-show-mode))
11545 (let ((from-header (org-mhe-get-header "From:"))
11546 (to-header (org-mhe-get-header "To:"))
11547 (subject (org-mhe-get-header "Subject:")))
11548 (setq cpltxt (concat from-header " on: " subject))
11549 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11550 (org-remove-angle-brackets
11551 (org-mhe-get-header "Message-Id:"))))))
11553 ((eq major-mode 'rmail-mode)
11554 (save-excursion
11555 (save-restriction
11556 (rmail-narrow-to-non-pruned-header)
11557 (let ((folder buffer-file-name)
11558 (message-id (mail-fetch-field "message-id"))
11559 (author (mail-fetch-field "from"))
11560 (subject (mail-fetch-field "subject")))
11561 (setq message-id (org-remove-angle-brackets message-id))
11562 (setq cpltxt (concat author " on: " subject))
11563 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11565 ((eq major-mode 'gnus-group-mode)
11566 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11567 (gnus-group-group-name)) ; version
11568 ((fboundp 'gnus-group-name)
11569 (gnus-group-name))
11570 (t "???"))))
11571 (setq cpltxt (concat
11572 (if (org-xor arg org-usenet-links-prefer-google)
11573 "http://groups.google.com/groups?group="
11574 "gnus:")
11575 group)
11576 link (org-make-link cpltxt))))
11578 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11579 (require 'gnus-sum) ; FIXME: I don't think this is needed, actually
11580 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11581 (gnus-summary-beginning-of-article)
11582 (let* ((group (car gnus-article-current))
11583 (article (cdr gnus-article-current))
11584 (header (gnus-summary-article-header article))
11585 (author (mail-header-from header))
11586 (message-id (mail-header-id header))
11587 (date (mail-header-date header))
11588 (subject (gnus-summary-subject-string)))
11589 (setq cpltxt (concat author " on: " subject))
11590 (if (org-xor arg org-usenet-links-prefer-google)
11591 (setq link
11592 (concat
11593 cpltxt "\n "
11594 (format "http://groups.google.com/groups?as_umsgid=%s"
11595 (org-fixup-message-id-for-http message-id))))
11596 (setq link (org-make-link "gnus:" group
11597 "#" (number-to-string article))))))
11599 ((eq major-mode 'w3-mode)
11600 (setq cpltxt (url-view-url t)
11601 link (org-make-link cpltxt)))
11602 ((eq major-mode 'w3m-mode)
11603 (setq cpltxt (or w3m-current-title w3m-current-url)
11604 link (org-make-link w3m-current-url)))
11606 ((setq search (run-hook-with-args-until-success
11607 'org-create-file-search-functions))
11608 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11609 "::" search))
11610 (setq cpltxt (or description link)))
11612 ((eq major-mode 'image-mode)
11613 (setq cpltxt (concat "file:"
11614 (abbreviate-file-name buffer-file-name))
11615 link (org-make-link cpltxt)))
11617 ((eq major-mode 'dired-mode)
11618 ;; link to the file in the current line
11619 (setq cpltxt (concat "file:"
11620 (abbreviate-file-name
11621 (expand-file-name
11622 (dired-get-filename nil t))))
11623 link (org-make-link cpltxt)))
11625 ((and buffer-file-name (org-mode-p))
11626 ;; Just link to current headline
11627 (setq cpltxt (concat "file:"
11628 (abbreviate-file-name buffer-file-name)))
11629 ;; Add a context search string
11630 (when (org-xor org-context-in-file-links arg)
11631 ;; Check if we are on a target
11632 (if (save-excursion
11633 (skip-chars-forward "^>\n\r")
11634 (and (re-search-backward "<<" nil t)
11635 (looking-at "<<\\(.*?\\)>>")
11636 (<= (match-beginning 0) pos)
11637 (>= (match-end 0) pos)))
11638 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11639 (setq txt (cond
11640 ((org-on-heading-p) nil)
11641 ((org-region-active-p)
11642 (buffer-substring (region-beginning) (region-end)))
11643 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11644 (when (or (null txt) (string-match "\\S-" txt))
11645 (setq cpltxt
11646 (concat cpltxt "::"
11647 (if org-file-link-context-use-camel-case
11648 (org-make-org-heading-camel txt)
11649 (org-make-org-heading-search-string txt)))
11650 desc "NONE"))))
11651 (if (string-match "::\\'" cpltxt)
11652 (setq cpltxt (substring cpltxt 0 -2)))
11653 (setq link (org-make-link cpltxt)))
11655 (buffer-file-name
11656 ;; Just link to this file here.
11657 (setq cpltxt (concat "file:"
11658 (abbreviate-file-name buffer-file-name)))
11659 ;; Add a context string
11660 (when (org-xor org-context-in-file-links arg)
11661 (setq txt (if (org-region-active-p)
11662 (buffer-substring (region-beginning) (region-end))
11663 (buffer-substring (point-at-bol) (point-at-eol))))
11664 ;; Only use search option if there is some text.
11665 (when (string-match "\\S-" txt)
11666 (setq cpltxt
11667 (concat cpltxt "::"
11668 (if org-file-link-context-use-camel-case
11669 (org-make-org-heading-camel txt)
11670 (org-make-org-heading-search-string txt)))
11671 desc "NONE")))
11672 (setq link (org-make-link cpltxt)))
11674 ((interactive-p)
11675 (error "Cannot link to a buffer which is not visiting a file"))
11677 (t (setq link nil)))
11679 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11680 (setq link (or link cpltxt)
11681 desc (or desc cpltxt))
11682 (if (equal desc "NONE") (setq desc nil))
11684 (if (and (interactive-p) link)
11685 (progn
11686 (setq org-stored-links
11687 (cons (list cpltxt link desc) org-stored-links))
11688 (message "Stored: %s" (or cpltxt link)))
11689 (org-make-link-string link desc))))
11691 (defun org-make-org-heading-search-string (&optional string heading)
11692 "Make search string for STRING or current headline."
11693 (interactive)
11694 (let ((s (or string (org-get-heading))))
11695 (unless (and string (not heading))
11696 ;; We are using a headline, clean up garbage in there.
11697 (if (string-match org-todo-regexp s)
11698 (setq s (replace-match "" t t s)))
11699 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
11700 (setq s (replace-match "" t t s)))
11701 (setq s (org-trim s))
11702 (if (string-match (concat "^\\(" org-quote-string "\\|"
11703 org-comment-string "\\)") s)
11704 (setq s (replace-match "" t t s)))
11705 (while (string-match org-ts-regexp s)
11706 (setq s (replace-match "" t t s))))
11707 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11708 (setq s (replace-match " " t t s)))
11709 (or string (setq s (concat "*" s))) ; Add * for headlines
11710 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11712 (defun org-make-org-heading-camel (&optional string heading)
11713 "Make a CamelCase string for STRING or the current headline."
11714 (interactive)
11715 (let ((s (or string (org-get-heading))))
11716 (unless (and string (not heading))
11717 ;; We are using a headline, clean up garbage in there.
11718 (if (string-match org-todo-regexp s)
11719 (setq s (replace-match "" t t s)))
11720 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
11721 (setq s (replace-match "" t t s)))
11722 (setq s (org-trim s))
11723 (if (string-match (concat "^\\(" org-quote-string "\\|"
11724 org-comment-string "\\)") s)
11725 (setq s (replace-match "" t t s)))
11726 (while (string-match org-ts-regexp s)
11727 (setq s (replace-match "" t t s))))
11728 (while (string-match "[^a-zA-Z_ \t]+" s)
11729 (setq s (replace-match " " t t s)))
11730 (or string (setq s (concat "*" s))) ; Add * for headlines
11731 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
11733 (defun org-make-link (&rest strings)
11734 "Concatenate STRINGS, format resulting string with `org-link-format'."
11735 (format org-link-format (apply 'concat strings)))
11737 (defun org-make-link-string (link &optional description)
11738 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11739 (if (eq org-link-style 'plain)
11740 (if (equal description link)
11741 link
11742 (concat description "\n" link))
11743 (when (stringp description)
11744 ;; Remove brackets from the description, they are fatal.
11745 (while (string-match "\\[\\|\\]" description)
11746 (setq description (replace-match "" t t description))))
11747 (when (equal (org-link-escape link) description)
11748 ;; No description needed, it is identical
11749 (setq description nil))
11750 (when (and (not description)
11751 (not (equal link (org-link-escape link))))
11752 (setq description link))
11753 (concat "[[" (org-link-escape link) "]"
11754 (if description (concat "[" description "]") "")
11755 "]")))
11757 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
11758 "Association list of escapes for some characters problematic in links.")
11760 (defun org-link-escape (text)
11761 "Escape charaters in TEXT that are problematic for links."
11762 (when text
11763 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
11764 org-link-escape-chars "\\|")))
11765 (while (string-match re text)
11766 (setq text
11767 (replace-match
11768 (cdr (assoc (match-string 0 text) org-link-escape-chars))
11769 t t text)))
11770 text)))
11772 (defun org-link-unescape (text)
11773 "Reverse the action of `org-link-escape'."
11774 (when text
11775 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11776 org-link-escape-chars "\\|")))
11777 (while (string-match re text)
11778 (setq text
11779 (replace-match
11780 (car (rassoc (match-string 0 text) org-link-escape-chars))
11781 t t text)))
11782 text)))
11784 (defun org-xor (a b)
11785 "Exclusive or."
11786 (if a (not b) b))
11788 (defun org-get-header (header)
11789 "Find a header field in the current buffer."
11790 (save-excursion
11791 (goto-char (point-min))
11792 (let ((case-fold-search t) s)
11793 (cond
11794 ((eq header 'from)
11795 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11796 (setq s (match-string 1)))
11797 (while (string-match "\"" s)
11798 (setq s (replace-match "" t t s)))
11799 (if (string-match "[<(].*" s)
11800 (setq s (replace-match "" t t s))))
11801 ((eq header 'message-id)
11802 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11803 (setq s (match-string 1))))
11804 ((eq header 'subject)
11805 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11806 (setq s (match-string 1)))))
11807 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11808 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11809 s)))
11812 (defun org-fixup-message-id-for-http (s)
11813 "Replace special characters in a message id, so it can be used in an http query."
11814 (while (string-match "<" s)
11815 (setq s (replace-match "%3C" t t s)))
11816 (while (string-match ">" s)
11817 (setq s (replace-match "%3E" t t s)))
11818 (while (string-match "@" s)
11819 (setq s (replace-match "%40" t t s)))
11822 (defun org-insert-link (&optional complete-file)
11823 "Insert a link. At the prompt, enter the link.
11825 Completion can be used to select a link previously stored with
11826 `org-store-link'. When the empty string is entered (i.e. if you just
11827 press RET at the prompt), the link defaults to the most recently
11828 stored link. As SPC triggers completion in the minibuffer, you need to
11829 use M-SPC or C-q SPC to force the insertion of a space character.
11831 You will also be prompted for a description, and if one is given, it will
11832 be displayed in the buffer instead of the link.
11834 If there is already a link at point, this command will allow you to edit link
11835 and description parts.
11837 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11838 selected using completion. The path to the file will be relative to
11839 the current directory if the file is in the current directory or a
11840 subdirectory. Otherwise, the link will be the absolute path as
11841 completed in the minibuffer (i.e. normally ~/path/to/file).
11843 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11844 is in the current directory or below.
11845 With three \\[universal-argument] prefixes, negate the meaning of
11846 `org-keep-stored-link-after-insertion'."
11847 (interactive "P")
11848 (let (link desc entry remove file (pos (point)))
11849 (cond
11850 ((save-excursion
11851 (skip-chars-forward "^]\n\r")
11852 (and (re-search-backward "\\[\\[" nil t)
11853 (looking-at org-bracket-link-regexp)
11854 (<= (match-beginning 0) pos)
11855 (>= (match-end 0) pos)))
11856 ;; We do have a link at point, and we are going to edit it.
11857 (setq remove (list (match-beginning 0) (match-end 0)))
11858 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11859 (setq link (read-string "Link: "
11860 (org-link-unescape
11861 (org-match-string-no-properties 1)))))
11862 ((equal complete-file '(4))
11863 ;; Completing read for file names.
11864 (setq file (read-file-name "File: "))
11865 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11866 (pwd1 (file-name-as-directory (abbreviate-file-name
11867 (expand-file-name ".")))))
11868 (cond
11869 ((equal complete-file '(16))
11870 (setq link (org-make-link
11871 "file:"
11872 (abbreviate-file-name (expand-file-name file)))))
11873 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11874 (setq link (org-make-link "file:" (match-string 1 file))))
11875 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11876 (expand-file-name file))
11877 (setq link (org-make-link
11878 "file:" (match-string 1 (expand-file-name file)))))
11879 (t (setq link (org-make-link "file:" file))))))
11881 ;; Read link, with completion for stored links.
11882 (setq link (org-completing-read
11883 "Link: " org-stored-links nil nil nil
11884 org-insert-link-history
11885 (or (car (car org-stored-links)))))
11886 (setq entry (assoc link org-stored-links))
11887 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11888 (not org-keep-stored-link-after-insertion))
11889 (setq org-stored-links (delq (assoc link org-stored-links)
11890 org-stored-links)))
11891 (setq link (if entry (nth 1 entry) link)
11892 desc (or desc (nth 2 entry)))))
11894 (if (string-match org-plain-link-re link)
11895 ;; URL-like link, normalize the use of angular brackets.
11896 (setq link (org-make-link (org-remove-angle-brackets link))))
11898 ;; Check if we are linking to the current file with a search option
11899 ;; If yes, simplify the link by using only the search option.
11900 (when (and buffer-file-name
11901 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11902 (let* ((path (match-string 1 link))
11903 (case-fold-search nil)
11904 (search (match-string 2 link)))
11905 (save-match-data
11906 (if (equal (file-truename buffer-file-name) (file-truename path))
11907 ;; We are linking to this same file, with a search option
11908 (setq link search)))))
11910 ;; Check if we can/should use a relative path. If yes, simplify the link
11911 (when (string-match "\\<file:\\(.*\\)" link)
11912 (let* ((path (match-string 1 link))
11913 (case-fold-search nil))
11914 (cond
11915 ((eq org-link-file-path-type 'absolute)
11916 (setq path (abbreviate-file-name (expand-file-name path))))
11917 ((eq org-link-file-path-type 'noabbrev)
11918 (setq path (expand-file-name path)))
11919 ((eq org-link-file-path-type 'relative)
11920 (setq path (file-relative-name path)))
11922 (save-match-data
11923 (if (string-match (concat "^" (regexp-quote
11924 (file-name-as-directory
11925 (expand-file-name "."))))
11926 (expand-file-name path))
11927 ;; We are linking a file with relative path name.
11928 (setq path (substring (expand-file-name path)
11929 (match-end 0)))))))
11930 (setq link (concat "file:" path))))
11932 (setq desc (read-string "Description: " desc))
11933 (unless (string-match "\\S-" desc) (setq desc nil))
11934 (if remove (apply 'delete-region remove))
11935 (insert (org-make-link-string link desc))))
11937 (defun org-completing-read (&rest args)
11938 (let ((minibuffer-local-completion-map
11939 (copy-keymap minibuffer-local-completion-map)))
11940 (define-key minibuffer-local-completion-map " " 'self-insert-command)
11941 (apply 'completing-read args)))
11943 ;;;; Hooks for remember.el
11945 (defvar org-finish-function nil)
11947 ;;;###autoload
11948 (defun org-remember-annotation ()
11949 "Return a link to the current location as an annotation for remember.el.
11950 If you are using Org-mode files as target for data storage with
11951 remember.el, then the annotations should include a link compatible with the
11952 conventions in Org-mode. This function returns such a link."
11953 (org-store-link nil))
11955 (defconst org-remember-help
11956 "Select a destination location for the note.
11957 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
11958 RET at beg-of-buf -> Append to file as level 2 headline
11959 RET on headline -> Store as sublevel entry to current headline
11960 <left>/<right> -> before/after current headline, same headings level")
11962 ;;;###autoload
11963 (defun org-remember-apply-template ()
11964 "Initialize *remember* buffer with template, invoke `org-mode'.
11965 This function should be placed into `remember-mode-hook' and in fact requires
11966 to be run from that hook to fucntion properly."
11967 (if org-remember-templates
11969 (let* ((entry (if (= (length org-remember-templates) 1)
11970 (cdar org-remember-templates)
11971 (message "Select template: %s"
11972 (mapconcat
11973 (lambda (x) (char-to-string (car x)))
11974 org-remember-templates " "))
11975 (cdr (assoc (read-char-exclusive) org-remember-templates))))
11976 (tpl (car entry))
11977 (file (if (consp (cdr entry)) (nth 1 entry)))
11978 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
11979 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
11980 (v-u (concat "[" (substring v-t 1 -1) "]"))
11981 (v-U (concat "[" (substring v-T 1 -1) "]"))
11982 (v-a annotation) ; defined in `remember-mode'
11983 (v-i initial) ; defined in `remember-mode'
11984 (v-n user-full-name)
11986 (unless tpl (setq tpl "") (message "No template") (ding))
11987 (insert tpl) (goto-char (point-min))
11988 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
11989 (when (and initial (equal (match-string 0) "%i"))
11990 (save-match-data
11991 (let* ((lead (buffer-substring
11992 (point-at-bol) (match-beginning 0))))
11993 (setq v-i (mapconcat 'identity
11994 (org-split-string initial "\n")
11995 (concat "\n" lead))))))
11996 (replace-match
11997 (or (eval (intern (concat "v-" (match-string 1)))) "")
11998 t t))
11999 (let ((org-startup-folded nil)
12000 (org-startup-with-deadline-check nil))
12001 (org-mode))
12002 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
12003 (org-set-local 'org-default-notes-file file))
12004 (goto-char (point-min))
12005 (if (re-search-forward "%\\?" nil t) (replace-match "")))
12006 (let ((org-startup-folded nil)
12007 (org-startup-with-deadline-check nil))
12008 (org-mode)))
12009 (org-set-local 'org-finish-function 'remember-buffer))
12011 ;;;###autoload
12012 (defun org-remember-handler ()
12013 "Store stuff from remember.el into an org file.
12014 First prompts for an org file. If the user just presses return, the value
12015 of `org-default-notes-file' is used.
12016 Then the command offers the headings tree of the selected file in order to
12017 file the text at a specific location.
12018 You can either immediately press RET to get the note appended to the
12019 file, or you can use vertical cursor motion and visibility cycling (TAB) to
12020 find a better place. Then press RET or <left> or <right> in insert the note.
12022 Key Cursor position Note gets inserted
12023 -----------------------------------------------------------------------------
12024 RET buffer-start as level 2 heading at end of file
12025 RET on headline as sublevel of the heading at cursor
12026 RET no heading at cursor position, level taken from context.
12027 Or use prefix arg to specify level manually.
12028 <left> on headline as same level, before current heading
12029 <right> on headline as same level, after current heading
12031 So the fastest way to store the note is to press RET RET to append it to
12032 the default file. This way your current train of thought is not
12033 interrupted, in accordance with the principles of remember.el. But with
12034 little extra effort, you can push it directly to the correct location.
12036 Before being stored away, the function ensures that the text has a
12037 headline, i.e. a first line that starts with a \"*\". If not, a headline
12038 is constructed from the current date and some additional data.
12040 If the variable `org-adapt-indentation' is non-nil, the entire text is
12041 also indented so that it starts in the same column as the headline
12042 \(i.e. after the stars).
12044 See also the variable `org-reverse-note-order'."
12045 (catch 'quit
12046 (let* ((txt (buffer-substring (point-min) (point-max)))
12047 (fastp current-prefix-arg)
12048 (file (if fastp org-default-notes-file (org-get-org-file)))
12049 (visiting (find-buffer-visiting file))
12050 (org-startup-with-deadline-check nil)
12051 (org-startup-folded nil)
12052 (org-startup-align-all-tables nil)
12053 spos level indent reversed)
12054 ;; Modify text so that it becomes a nice subtree which can be inserted
12055 ;; into an org tree.
12056 (let* ((lines (split-string txt "\n"))
12057 first)
12058 ;; remove empty lines at the beginning
12059 (while (and lines (string-match "^[ \t]*\n" (car lines)))
12060 (setq lines (cdr lines)))
12061 (setq first (car lines) lines (cdr lines))
12062 (if (string-match "^\\*+" first)
12063 ;; Is already a headline
12064 (setq indent nil)
12065 ;; We need to add a headline: Use time and first buffer line
12066 (setq lines (cons first lines)
12067 first (concat "* " (current-time-string)
12068 " (" (remember-buffer-desc) ")")
12069 indent " "))
12070 (if (and org-adapt-indentation indent)
12071 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
12072 (setq txt (concat first "\n"
12073 (mapconcat 'identity lines "\n"))))
12074 ;; Find the file
12075 (if (not visiting)
12076 (find-file-noselect file))
12077 (with-current-buffer (get-file-buffer file)
12078 (save-excursion (and (goto-char (point-min))
12079 (not (re-search-forward "^\\* " nil t))
12080 (insert "\n* Notes\n")))
12081 (setq reversed (org-notes-order-reversed-p))
12082 (save-excursion
12083 (save-restriction
12084 (widen)
12085 ;; Ask the User for a location
12086 (setq spos (if fastp 1 (org-get-location
12087 (current-buffer)
12088 org-remember-help)))
12089 (if (not spos) (throw 'quit nil)) ; return nil to show we did
12090 ; not handle this note
12091 (goto-char spos)
12092 (cond ((and (bobp) (not reversed))
12093 ;; Put it at the end, as level 2
12094 (save-restriction
12095 (widen)
12096 (goto-char (point-max))
12097 (if (not (bolp)) (newline))
12098 (org-paste-subtree 2 txt)))
12099 ((and (bobp) reversed)
12100 ;; Put it at the start, as level 1
12101 (save-restriction
12102 (widen)
12103 (goto-char (point-min))
12104 (re-search-forward "^\\*" nil t)
12105 (beginning-of-line 1)
12106 (org-paste-subtree 1 txt)))
12107 ((and (org-on-heading-p nil) (not current-prefix-arg))
12108 ;; Put it below this entry, at the beg/end of the subtree
12109 (org-back-to-heading)
12110 (setq level (funcall outline-level))
12111 (if reversed
12112 (outline-end-of-heading)
12113 (outline-end-of-subtree))
12114 (if (not (bolp)) (newline))
12115 (beginning-of-line 1)
12116 (org-paste-subtree (org-get-legal-level level 1) txt))
12118 ;; Put it right there, with automatic level determined by
12119 ;; org-paste-subtree or from prefix arg
12120 (org-paste-subtree current-prefix-arg txt)))
12121 (when remember-save-after-remembering
12122 (save-buffer)
12123 (if (not visiting) (kill-buffer (current-buffer)))))))))
12124 t) ;; return t to indicate that we took care of this note.
12126 (defun org-get-org-file ()
12127 "Read a filename, with default directory `org-directory'."
12128 (let ((default (or org-default-notes-file remember-data-file)))
12129 (read-file-name (format "File name [%s]: " default)
12130 (file-name-as-directory org-directory)
12131 default)))
12133 (defun org-notes-order-reversed-p ()
12134 "Check if the current file should receive notes in reversed order."
12135 (cond
12136 ((not org-reverse-note-order) nil)
12137 ((eq t org-reverse-note-order) t)
12138 ((not (listp org-reverse-note-order)) nil)
12139 (t (catch 'exit
12140 (let ((all org-reverse-note-order)
12141 entry)
12142 (while (setq entry (pop all))
12143 (if (string-match (car entry) buffer-file-name)
12144 (throw 'exit (cdr entry))))
12145 nil)))))
12147 ;;;; Tables
12149 ;; Watch out: Here we are talking about two different kind of tables.
12150 ;; Most of the code is for the tables created with the Org-mode table editor.
12151 ;; Sometimes, we talk about tables created and edited with the table.el
12152 ;; Emacs package. We call the former org-type tables, and the latter
12153 ;; table.el-type tables.
12156 (defun org-before-change-function (beg end)
12157 "Every change indicates that a table might need an update."
12158 (setq org-table-may-need-update t))
12160 (defconst org-table-line-regexp "^[ \t]*|"
12161 "Detects an org-type table line.")
12162 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
12163 "Detects an org-type table line.")
12164 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
12165 "Detects a table line marked for automatic recalculation.")
12166 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
12167 "Detects a table line marked for automatic recalculation.")
12168 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
12169 "Detects a table line marked for automatic recalculation.")
12170 (defconst org-table-hline-regexp "^[ \t]*|-"
12171 "Detects an org-type table hline.")
12172 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
12173 "Detects a table-type table hline.")
12174 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
12175 "Detects an org-type or table-type table.")
12176 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
12177 "Searching from within a table (any type) this finds the first line
12178 outside the table.")
12179 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
12180 "Searching from within a table (any type) this finds the first line
12181 outside the table.")
12183 (defun org-table-create-with-table.el ()
12184 "Use the table.el package to insert a new table.
12185 If there is already a table at point, convert between Org-mode tables
12186 and table.el tables."
12187 (interactive)
12188 (require 'table)
12189 (cond
12190 ((org-at-table.el-p)
12191 (if (y-or-n-p "Convert table to Org-mode table? ")
12192 (org-table-convert)))
12193 ((org-at-table-p)
12194 (if (y-or-n-p "Convert table to table.el table? ")
12195 (org-table-convert)))
12196 (t (call-interactively 'table-insert))))
12198 (defun org-table-create-or-convert-from-region (arg)
12199 "Convert region to table, or create an empty table.
12200 If there is an active region, convert it to a table. If there is no such
12201 region, create an empty table."
12202 (interactive "P")
12203 (if (org-region-active-p)
12204 (org-table-convert-region (region-beginning) (region-end) arg)
12205 (org-table-create arg)))
12207 (defun org-table-create (&optional size)
12208 "Query for a size and insert a table skeleton.
12209 SIZE is a string Columns x Rows like for example \"3x2\"."
12210 (interactive "P")
12211 (unless size
12212 (setq size (read-string
12213 (concat "Table size Columns x Rows [e.g. "
12214 org-table-default-size "]: ")
12215 "" nil org-table-default-size)))
12217 (let* ((pos (point))
12218 (indent (make-string (current-column) ?\ ))
12219 (split (org-split-string size " *x *"))
12220 (rows (string-to-number (nth 1 split)))
12221 (columns (string-to-number (car split)))
12222 (line (concat (apply 'concat indent "|" (make-list columns " |"))
12223 "\n")))
12224 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
12225 (point-at-bol) (point)))
12226 (beginning-of-line 1)
12227 (newline))
12228 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
12229 (dotimes (i rows) (insert line))
12230 (goto-char pos)
12231 (if (> rows 1)
12232 ;; Insert a hline after the first row.
12233 (progn
12234 (end-of-line 1)
12235 (insert "\n|-")
12236 (goto-char pos)))
12237 (org-table-align)))
12239 (defun org-table-convert-region (beg0 end0 &optional nspace)
12240 "Convert region to a table.
12241 The region goes from BEG0 to END0, but these borders will be moved
12242 slightly, to make sure a beginning of line in the first line is included.
12243 When NSPACE is non-nil, it indicates the minimum number of spaces that
12244 separate columns (default: just one space)."
12245 (interactive "rP")
12246 (let* ((beg (min beg0 end0))
12247 (end (max beg0 end0))
12248 (tabsep t)
12250 (goto-char beg)
12251 (beginning-of-line 1)
12252 (setq beg (move-marker (make-marker) (point)))
12253 (goto-char end)
12254 (if (bolp) (backward-char 1) (end-of-line 1))
12255 (setq end (move-marker (make-marker) (point)))
12256 ;; Lets see if this is tab-separated material. If every nonempty line
12257 ;; contains a tab, we will assume that it is tab-separated material
12258 (if nspace
12259 (setq tabsep nil)
12260 (goto-char beg)
12261 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
12262 (if nspace (setq tabsep nil))
12263 (if tabsep
12264 (setq re "^\\|\t")
12265 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
12266 (max 1 (prefix-numeric-value nspace)))))
12267 (goto-char beg)
12268 (while (re-search-forward re end t)
12269 (replace-match "| " t t))
12270 (goto-char beg)
12271 (insert " ")
12272 (org-table-align)))
12274 (defun org-table-import (file arg)
12275 "Import FILE as a table.
12276 The file is assumed to be tab-separated. Such files can be produced by most
12277 spreadsheet and database applications. If no tabs (at least one per line)
12278 are found, lines will be split on whitespace into fields."
12279 (interactive "f\nP")
12280 (or (bolp) (newline))
12281 (let ((beg (point))
12282 (pm (point-max)))
12283 (insert-file-contents file)
12284 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
12286 (defun org-table-export ()
12287 "Export table as a tab-separated file.
12288 Such a file can be imported into a spreadsheet program like Excel."
12289 (interactive)
12290 (let* ((beg (org-table-begin))
12291 (end (org-table-end))
12292 (table (buffer-substring beg end))
12293 (file (read-file-name "Export table to: "))
12294 buf)
12295 (unless (or (not (file-exists-p file))
12296 (y-or-n-p (format "Overwrite file %s? " file)))
12297 (error "Abort"))
12298 (with-current-buffer (find-file-noselect file)
12299 (setq buf (current-buffer))
12300 (erase-buffer)
12301 (fundamental-mode)
12302 (insert table)
12303 (goto-char (point-min))
12304 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
12305 (replace-match "" t t)
12306 (end-of-line 1))
12307 (goto-char (point-min))
12308 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
12309 (replace-match "" t t)
12310 (goto-char (min (1+ (point)) (point-max))))
12311 (goto-char (point-min))
12312 (while (re-search-forward "^-[-+]*$" nil t)
12313 (replace-match "")
12314 (if (looking-at "\n")
12315 (delete-char 1)))
12316 (goto-char (point-min))
12317 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
12318 (replace-match "\t" t t))
12319 (save-buffer))
12320 (kill-buffer buf)))
12322 (defvar org-table-aligned-begin-marker (make-marker)
12323 "Marker at the beginning of the table last aligned.
12324 Used to check if cursor still is in that table, to minimize realignment.")
12325 (defvar org-table-aligned-end-marker (make-marker)
12326 "Marker at the end of the table last aligned.
12327 Used to check if cursor still is in that table, to minimize realignment.")
12328 (defvar org-table-last-alignment nil
12329 "List of flags for flushright alignment, from the last re-alignment.
12330 This is being used to correctly align a single field after TAB or RET.")
12331 (defvar org-table-last-column-widths nil
12332 "List of max width of fields in each column.
12333 This is being used to correctly align a single field after TAB or RET.")
12335 (defvar org-last-recalc-line nil)
12336 (defconst org-narrow-column-arrow "=>"
12337 "Used as display property in narrowed table columns.")
12339 (defun org-table-align ()
12340 "Align the table at point by aligning all vertical bars."
12341 (interactive)
12342 (let* (
12343 ;; Limits of table
12344 (beg (org-table-begin))
12345 (end (org-table-end))
12346 ;; Current cursor position
12347 (linepos (org-current-line))
12348 (colpos (org-table-current-column))
12349 (winstart (window-start))
12350 (winstartline (org-current-line (min winstart (1- (point-max)))))
12351 lines (new "") lengths l typenums ty fields maxfields i
12352 column
12353 (indent "") cnt frac
12354 rfmt hfmt
12355 (spaces '(1 . 1))
12356 (sp1 (car spaces))
12357 (sp2 (cdr spaces))
12358 (rfmt1 (concat
12359 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
12360 (hfmt1 (concat
12361 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
12362 emptystrings links dates narrow fmax f1 len c e)
12363 (untabify beg end)
12364 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
12365 ;; Check if we have links or dates
12366 (goto-char beg)
12367 (setq links (re-search-forward org-bracket-link-regexp end t))
12368 (goto-char beg)
12369 (setq dates (and org-display-custom-times
12370 (re-search-forward org-ts-regexp-both end t)))
12371 ;; Make sure the link properties are right
12372 (when links (goto-char beg) (while (org-activate-bracket-links end)))
12373 ;; Make sure the date properties are right
12374 (when dates (goto-char beg) (while (org-activate-dates end)))
12376 ;; Check if we are narrowing any columns
12377 (goto-char beg)
12378 (setq narrow (and org-format-transports-properties-p
12379 (re-search-forward "<[0-9]+>" end t)))
12380 ;; Get the rows
12381 (setq lines (org-split-string
12382 (buffer-substring beg end) "\n"))
12383 ;; Store the indentation of the first line
12384 (if (string-match "^ *" (car lines))
12385 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
12386 ;; Mark the hlines by setting the corresponding element to nil
12387 ;; At the same time, we remove trailing space.
12388 (setq lines (mapcar (lambda (l)
12389 (if (string-match "^ *|-" l)
12391 (if (string-match "[ \t]+$" l)
12392 (substring l 0 (match-beginning 0))
12393 l)))
12394 lines))
12395 ;; Get the data fields by splitting the lines.
12396 (setq fields (mapcar
12397 (lambda (l)
12398 (org-split-string l " *| *"))
12399 (delq nil (copy-sequence lines))))
12400 ;; How many fields in the longest line?
12401 (condition-case nil
12402 (setq maxfields (apply 'max (mapcar 'length fields)))
12403 (error
12404 (kill-region beg end)
12405 (org-table-create org-table-default-size)
12406 (error "Empty table - created default table")))
12407 ;; A list of empty strings to fill any short rows on output
12408 (setq emptystrings (make-list maxfields ""))
12409 ;; Check for special formatting.
12410 (setq i -1)
12411 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
12412 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
12413 ;; Check if there is an explicit width specified
12414 (when (and org-table-limit-column-width narrow)
12415 (setq c column fmax nil)
12416 (while c
12417 (setq e (pop c))
12418 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
12419 (setq fmax (string-to-number (match-string 1 e)) c nil)))
12420 ;; Find fields that are wider than fmax, and shorten them
12421 (when fmax
12422 (loop for xx in column do
12423 (when (and (stringp xx)
12424 (> (org-string-width xx) fmax))
12425 (org-add-props xx nil
12426 'help-echo
12427 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
12428 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
12429 (unless (> f1 1)
12430 (error "Cannot narrow field starting with wide link \"%s\""
12431 (match-string 0 xx)))
12432 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
12433 (add-text-properties (- f1 2) f1
12434 (list 'display org-narrow-column-arrow)
12435 xx)))))
12436 ;; Get the maximum width for each column
12437 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
12438 ;; Get the fraction of numbers, to decide about alignment of the column
12439 (setq cnt 0 frac 0.0)
12440 (loop for x in column do
12441 (if (equal x "")
12443 (setq frac ( / (+ (* frac cnt)
12444 (if (string-match org-table-number-regexp x) 1 0))
12445 (setq cnt (1+ cnt))))))
12446 (push (>= frac org-table-number-fraction) typenums))
12447 (setq lengths (nreverse lengths) typenums (nreverse typenums))
12449 ;; Store the alignment of this table, for later editing of single fields
12450 (setq org-table-last-alignment typenums
12451 org-table-last-column-widths lengths)
12453 ;; With invisible characters, `format' does not get the field width right
12454 ;; So we need to make these fields wide by hand.
12455 (when links
12456 (loop for i from 0 upto (1- maxfields) do
12457 (setq len (nth i lengths))
12458 (loop for j from 0 upto (1- (length fields)) do
12459 (setq c (nthcdr i (car (nthcdr j fields))))
12460 (if (and (stringp (car c))
12461 (string-match org-bracket-link-regexp (car c))
12462 (< (org-string-width (car c)) len))
12463 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
12465 ;; Compute the formats needed for output of the table
12466 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
12467 (while (setq l (pop lengths))
12468 (setq ty (if (pop typenums) "" "-")) ; number types flushright
12469 (setq rfmt (concat rfmt (format rfmt1 ty l))
12470 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
12471 (setq rfmt (concat rfmt "\n")
12472 hfmt (concat (substring hfmt 0 -1) "|\n"))
12474 (setq new (mapconcat
12475 (lambda (l)
12476 (if l (apply 'format rfmt
12477 (append (pop fields) emptystrings))
12478 hfmt))
12479 lines ""))
12480 ;; Replace the old one
12481 (delete-region beg end)
12482 (move-marker end nil)
12483 (move-marker org-table-aligned-begin-marker (point))
12484 (insert new)
12485 (move-marker org-table-aligned-end-marker (point))
12486 (when (and orgtbl-mode (not (org-mode-p)))
12487 (goto-char org-table-aligned-begin-marker)
12488 (while (org-hide-wide-columns org-table-aligned-end-marker)))
12489 ;; Try to move to the old location
12490 (goto-line winstartline)
12491 (setq winstart (point-at-bol))
12492 (goto-line linepos)
12493 (set-window-start (selected-window) winstart 'noforce)
12494 (org-table-goto-column colpos)
12495 (setq org-table-may-need-update nil)
12498 (defun org-string-width (s)
12499 "Compute width of string, ignoring invisible characters.
12500 This ignores character with invisibility property `org-link', and also
12501 characters with property `org-cwidth', because these will become invisible
12502 upon the next fontification round."
12503 (let (b l)
12504 (when (or (eq t buffer-invisibility-spec)
12505 (assq 'org-link buffer-invisibility-spec))
12506 (while (setq b (text-property-any 0 (length s)
12507 'invisible 'org-link s))
12508 (setq s (concat (substring s 0 b)
12509 (substring s (or (next-single-property-change
12510 b 'invisible s) (length s)))))))
12511 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12512 (setq s (concat (substring s 0 b)
12513 (substring s (or (next-single-property-change
12514 b 'org-cwidth s) (length s))))))
12515 (setq l (string-width s) b -1)
12516 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12517 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12520 (defun org-table-begin (&optional table-type)
12521 "Find the beginning of the table and return its position.
12522 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
12523 (save-excursion
12524 (if (not (re-search-backward
12525 (if table-type org-table-any-border-regexp
12526 org-table-border-regexp)
12527 nil t))
12528 (progn (goto-char (point-min)) (point))
12529 (goto-char (match-beginning 0))
12530 (beginning-of-line 2)
12531 (point))))
12533 (defun org-table-end (&optional table-type)
12534 "Find the end of the table and return its position.
12535 With argument TABLE-TYPE, go to the end of a table.el-type table."
12536 (save-excursion
12537 (if (not (re-search-forward
12538 (if table-type org-table-any-border-regexp
12539 org-table-border-regexp)
12540 nil t))
12541 (goto-char (point-max))
12542 (goto-char (match-beginning 0)))
12543 (point-marker)))
12545 (defun org-table-justify-field-maybe (&optional new)
12546 "Justify the current field, text to left, number to right.
12547 Optional argument NEW may specify text to replace the current field content."
12548 (cond
12549 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
12550 ((org-at-table-hline-p))
12551 ((and (not new)
12552 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
12553 (current-buffer)))
12554 (< (point) org-table-aligned-begin-marker)
12555 (>= (point) org-table-aligned-end-marker)))
12556 ;; This is not the same table, force a full re-align
12557 (setq org-table-may-need-update t))
12558 (t ;; realign the current field, based on previous full realign
12559 (let* ((pos (point)) s
12560 (col (org-table-current-column))
12561 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
12562 l f n o e)
12563 (when (> col 0)
12564 (skip-chars-backward "^|\n")
12565 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
12566 (progn
12567 (setq s (match-string 1)
12568 o (match-string 0)
12569 l (max 1 (- (match-end 0) (match-beginning 0) 3))
12570 e (not (= (match-beginning 2) (match-end 2))))
12571 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
12572 l (if e "|" (setq org-table-may-need-update t) ""))
12573 n (format f s))
12574 (if new
12575 (if (<= (length new) l) ;; FIXME: length -> str-width?
12576 (setq n (format f new))
12577 (setq n (concat new "|") org-table-may-need-update t)))
12578 (or (equal n o)
12579 (let (org-table-may-need-update)
12580 (replace-match n))))
12581 (setq org-table-may-need-update t))
12582 (goto-char pos))))))
12584 (defun org-table-next-field ()
12585 "Go to the next field in the current table, creating new lines as needed.
12586 Before doing so, re-align the table if necessary."
12587 (interactive)
12588 (org-table-maybe-eval-formula)
12589 (org-table-maybe-recalculate-line)
12590 (if (and org-table-automatic-realign
12591 org-table-may-need-update)
12592 (org-table-align))
12593 (let ((end (org-table-end)))
12594 (if (org-at-table-hline-p)
12595 (end-of-line 1))
12596 (condition-case nil
12597 (progn
12598 (re-search-forward "|" end)
12599 (if (looking-at "[ \t]*$")
12600 (re-search-forward "|" end))
12601 (if (and (looking-at "-")
12602 org-table-tab-jumps-over-hlines
12603 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
12604 (goto-char (match-beginning 1)))
12605 (if (looking-at "-")
12606 (progn
12607 (beginning-of-line 0)
12608 (org-table-insert-row 'below))
12609 (if (looking-at " ") (forward-char 1))))
12610 (error
12611 (org-table-insert-row 'below)))))
12613 (defun org-table-previous-field ()
12614 "Go to the previous field in the table.
12615 Before doing so, re-align the table if necessary."
12616 (interactive)
12617 (org-table-justify-field-maybe)
12618 (org-table-maybe-recalculate-line)
12619 (if (and org-table-automatic-realign
12620 org-table-may-need-update)
12621 (org-table-align))
12622 (if (org-at-table-hline-p)
12623 (end-of-line 1))
12624 (re-search-backward "|" (org-table-begin))
12625 (re-search-backward "|" (org-table-begin))
12626 (while (looking-at "|\\(-\\|[ \t]*$\\)")
12627 (re-search-backward "|" (org-table-begin)))
12628 (if (looking-at "| ?")
12629 (goto-char (match-end 0))))
12631 (defun org-table-next-row ()
12632 "Go to the next row (same column) in the current table.
12633 Before doing so, re-align the table if necessary."
12634 (interactive)
12635 (org-table-maybe-eval-formula)
12636 (org-table-maybe-recalculate-line)
12637 (if (or (looking-at "[ \t]*$")
12638 (save-excursion (skip-chars-backward " \t") (bolp)))
12639 (newline)
12640 (if (and org-table-automatic-realign
12641 org-table-may-need-update)
12642 (org-table-align))
12643 (let ((col (org-table-current-column)))
12644 (beginning-of-line 2)
12645 (if (or (not (org-at-table-p))
12646 (org-at-table-hline-p))
12647 (progn
12648 (beginning-of-line 0)
12649 (org-table-insert-row 'below)))
12650 (org-table-goto-column col)
12651 (skip-chars-backward "^|\n\r")
12652 (if (looking-at " ") (forward-char 1)))))
12654 (defun org-table-copy-down (n)
12655 "Copy a field down in the current column.
12656 If the field at the cursor is empty, copy into it the content of the nearest
12657 non-empty field above. With argument N, use the Nth non-empty field.
12658 If the current field is not empty, it is copied down to the next row, and
12659 the cursor is moved with it. Therefore, repeating this command causes the
12660 column to be filled row-by-row.
12661 If the variable `org-table-copy-increment' is non-nil and the field is an
12662 integer, it will be incremented while copying."
12663 (interactive "p")
12664 (let* ((colpos (org-table-current-column))
12665 (field (org-table-get-field))
12666 (non-empty (string-match "[^ \t]" field))
12667 (beg (org-table-begin))
12668 txt)
12669 (org-table-check-inside-data-field)
12670 (if non-empty
12671 (progn
12672 (setq txt (org-trim field))
12673 (org-table-next-row)
12674 (org-table-blank-field))
12675 (save-excursion
12676 (setq txt
12677 (catch 'exit
12678 (while (progn (beginning-of-line 1)
12679 (re-search-backward org-table-dataline-regexp
12680 beg t))
12681 (org-table-goto-column colpos t)
12682 (if (and (looking-at
12683 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
12684 (= (setq n (1- n)) 0))
12685 (throw 'exit (match-string 1))))))))
12686 (if txt
12687 (progn
12688 (if (and org-table-copy-increment
12689 (string-match "^[0-9]+$" txt))
12690 (setq txt (format "%d" (+ (string-to-number txt) 1))))
12691 (insert txt)
12692 (org-table-maybe-recalculate-line)
12693 (org-table-align))
12694 (error "No non-empty field found"))))
12696 (defun org-table-check-inside-data-field ()
12697 "Is point inside a table data field?
12698 I.e. not on a hline or before the first or after the last column?
12699 This actually throws an error, so it aborts the current command."
12700 (if (or (not (org-at-table-p))
12701 (= (org-table-current-column) 0)
12702 (org-at-table-hline-p)
12703 (looking-at "[ \t]*$"))
12704 (error "Not in table data field")))
12706 (defvar org-table-clip nil
12707 "Clipboard for table regions.")
12709 (defun org-table-blank-field ()
12710 "Blank the current table field or active region."
12711 (interactive)
12712 (org-table-check-inside-data-field)
12713 (if (and (interactive-p) (org-region-active-p))
12714 (let (org-table-clip)
12715 (org-table-cut-region (region-beginning) (region-end)))
12716 (skip-chars-backward "^|")
12717 (backward-char 1)
12718 (if (looking-at "|[^|\n]+")
12719 (let* ((pos (match-beginning 0))
12720 (match (match-string 0))
12721 (len (org-string-width match)))
12722 (replace-match (concat "|" (make-string (1- len) ?\ )))
12723 (goto-char (+ 2 pos))
12724 (substring match 1)))))
12726 (defun org-table-get-field (&optional n replace)
12727 "Return the value of the field in column N of current row.
12728 N defaults to current field.
12729 If REPLACE is a string, replace field with this value. The return value
12730 is always the old value."
12731 (and n (org-table-goto-column n))
12732 (skip-chars-backward "^|\n")
12733 (backward-char 1)
12734 (if (looking-at "|[^|\r\n]*")
12735 (let* ((pos (match-beginning 0))
12736 (val (buffer-substring (1+ pos) (match-end 0))))
12737 (if replace
12738 (replace-match (concat "|" replace)))
12739 (goto-char (min (point-at-eol) (+ 2 pos)))
12740 val)
12741 (forward-char 1) ""))
12743 (defun org-table-current-column ()
12744 "Find out which column we are in.
12745 When called interactively, column is also displayed in echo area."
12746 (interactive)
12747 (if (interactive-p) (org-table-check-inside-data-field))
12748 (save-excursion
12749 (let ((cnt 0) (pos (point)))
12750 (beginning-of-line 1)
12751 (while (search-forward "|" pos t)
12752 (setq cnt (1+ cnt)))
12753 (if (interactive-p) (message "This is table column %d" cnt))
12754 cnt)))
12756 (defun org-table-goto-column (n &optional on-delim force)
12757 "Move the cursor to the Nth column in the current table line.
12758 With optional argument ON-DELIM, stop with point before the left delimiter
12759 of the field.
12760 If there are less than N fields, just go to after the last delimiter.
12761 However, when FORCE is non-nil, create new columns if necessary."
12762 (interactive "p")
12763 (let ((pos (point-at-eol)))
12764 (beginning-of-line 1)
12765 (when (> n 0)
12766 (while (and (> (setq n (1- n)) -1)
12767 (or (search-forward "|" pos t)
12768 (and force
12769 (progn (end-of-line 1)
12770 (skip-chars-backward "^|")
12771 (insert " | "))))))
12772 ; (backward-char 2) t)))))
12773 (when (and force (not (looking-at ".*|")))
12774 (save-excursion (end-of-line 1) (insert " | ")))
12775 (if on-delim
12776 (backward-char 1)
12777 (if (looking-at " ") (forward-char 1))))))
12779 (defun org-at-table-p (&optional table-type)
12780 "Return t if the cursor is inside an org-type table.
12781 If TABLE-TYPE is non-nil, also check for table.el-type tables."
12782 (if org-enable-table-editor
12783 (save-excursion
12784 (beginning-of-line 1)
12785 (looking-at (if table-type org-table-any-line-regexp
12786 org-table-line-regexp)))
12787 nil))
12789 (defun org-at-table.el-p ()
12790 "Return t if and only if we are at a table.el table."
12791 (and (org-at-table-p 'any)
12792 (save-excursion
12793 (goto-char (org-table-begin 'any))
12794 (looking-at org-table1-hline-regexp))))
12796 (defun org-table-recognize-table.el ()
12797 "If there is a table.el table nearby, recognize it and move into it."
12798 (if org-table-tab-recognizes-table.el
12799 (if (org-at-table.el-p)
12800 (progn
12801 (beginning-of-line 1)
12802 (if (looking-at org-table-dataline-regexp)
12804 (if (looking-at org-table1-hline-regexp)
12805 (progn
12806 (beginning-of-line 2)
12807 (if (looking-at org-table-any-border-regexp)
12808 (beginning-of-line -1)))))
12809 (if (re-search-forward "|" (org-table-end t) t)
12810 (progn
12811 (require 'table)
12812 (if (table--at-cell-p (point))
12814 (message "recognizing table.el table...")
12815 (table-recognize-table)
12816 (message "recognizing table.el table...done")))
12817 (error "This should not happen..."))
12819 nil)
12820 nil))
12822 (defun org-at-table-hline-p ()
12823 "Return t if the cursor is inside a hline in a table."
12824 (if org-enable-table-editor
12825 (save-excursion
12826 (beginning-of-line 1)
12827 (looking-at org-table-hline-regexp))
12828 nil))
12830 (defun org-table-insert-column ()
12831 "Insert a new column into the table."
12832 (interactive)
12833 (if (not (org-at-table-p))
12834 (error "Not at a table"))
12835 (org-table-find-dataline)
12836 (let* ((col (max 1 (org-table-current-column)))
12837 (beg (org-table-begin))
12838 (end (org-table-end))
12839 ;; Current cursor position
12840 (linepos (org-current-line))
12841 (colpos col))
12842 (goto-char beg)
12843 (while (< (point) end)
12844 (if (org-at-table-hline-p)
12846 (org-table-goto-column col t)
12847 (insert "| "))
12848 (beginning-of-line 2))
12849 (move-marker end nil)
12850 (goto-line linepos)
12851 (org-table-goto-column colpos)
12852 (org-table-align)
12853 (org-table-modify-formulas 'insert col)))
12855 (defun org-table-find-dataline ()
12856 "Find a dataline in the current table, which is needed for column commands."
12857 (if (and (org-at-table-p)
12858 (not (org-at-table-hline-p)))
12860 (let ((col (current-column))
12861 (end (org-table-end)))
12862 (move-to-column col)
12863 (while (and (< (point) end)
12864 (or (not (= (current-column) col))
12865 (org-at-table-hline-p)))
12866 (beginning-of-line 2)
12867 (move-to-column col))
12868 (if (and (org-at-table-p)
12869 (not (org-at-table-hline-p)))
12871 (error
12872 "Please position cursor in a data line for column operations")))))
12874 (defun org-table-delete-column ()
12875 "Delete a column from the table."
12876 (interactive)
12877 (if (not (org-at-table-p))
12878 (error "Not at a table"))
12879 (org-table-find-dataline)
12880 (org-table-check-inside-data-field)
12881 (let* ((col (org-table-current-column))
12882 (beg (org-table-begin))
12883 (end (org-table-end))
12884 ;; Current cursor position
12885 (linepos (org-current-line))
12886 (colpos col))
12887 (goto-char beg)
12888 (while (< (point) end)
12889 (if (org-at-table-hline-p)
12891 (org-table-goto-column col t)
12892 (and (looking-at "|[^|\n]+|")
12893 (replace-match "|")))
12894 (beginning-of-line 2))
12895 (move-marker end nil)
12896 (goto-line linepos)
12897 (org-table-goto-column colpos)
12898 (org-table-align)
12899 (org-table-modify-formulas 'remove col)))
12901 (defun org-table-move-column-right ()
12902 "Move column to the right."
12903 (interactive)
12904 (org-table-move-column nil))
12905 (defun org-table-move-column-left ()
12906 "Move column to the left."
12907 (interactive)
12908 (org-table-move-column 'left))
12910 (defun org-table-move-column (&optional left)
12911 "Move the current column to the right. With arg LEFT, move to the left."
12912 (interactive "P")
12913 (if (not (org-at-table-p))
12914 (error "Not at a table"))
12915 (org-table-find-dataline)
12916 (org-table-check-inside-data-field)
12917 (let* ((col (org-table-current-column))
12918 (col1 (if left (1- col) col))
12919 (beg (org-table-begin))
12920 (end (org-table-end))
12921 ;; Current cursor position
12922 (linepos (org-current-line))
12923 (colpos (if left (1- col) (1+ col))))
12924 (if (and left (= col 1))
12925 (error "Cannot move column further left"))
12926 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
12927 (error "Cannot move column further right"))
12928 (goto-char beg)
12929 (while (< (point) end)
12930 (if (org-at-table-hline-p)
12932 (org-table-goto-column col1 t)
12933 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
12934 (replace-match "|\\2|\\1|")))
12935 (beginning-of-line 2))
12936 (move-marker end nil)
12937 (goto-line linepos)
12938 (org-table-goto-column colpos)
12939 (org-table-align)
12940 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
12942 (defun org-table-move-row-down ()
12943 "Move table row down."
12944 (interactive)
12945 (org-table-move-row nil))
12946 (defun org-table-move-row-up ()
12947 "Move table row up."
12948 (interactive)
12949 (org-table-move-row 'up))
12951 (defun org-table-move-row (&optional up)
12952 "Move the current table line down. With arg UP, move it up."
12953 (interactive "P")
12954 (let ((col (current-column))
12955 (pos (point))
12956 (tonew (if up 0 2))
12957 txt)
12958 (beginning-of-line tonew)
12959 (if (not (org-at-table-p))
12960 (progn
12961 (goto-char pos)
12962 (error "Cannot move row further")))
12963 (goto-char pos)
12964 (beginning-of-line 1)
12965 (setq pos (point))
12966 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
12967 (delete-region (point) (1+ (point-at-eol)))
12968 (beginning-of-line tonew)
12969 (insert txt)
12970 (beginning-of-line 0)
12971 (move-to-column col)))
12973 (defun org-table-insert-row (&optional arg)
12974 "Insert a new row above the current line into the table.
12975 With prefix ARG, insert below the current line."
12976 (interactive "P")
12977 (if (not (org-at-table-p))
12978 (error "Not at a table"))
12979 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
12980 (new (org-table-clean-line line)))
12981 ;; Fix the first field if necessary
12982 (if (string-match "^[ \t]*| *[#$] *|" line)
12983 (setq new (replace-match (match-string 0 line) t t new)))
12984 (beginning-of-line (if arg 2 1))
12985 (let (org-table-may-need-update) (insert-before-markers new "\n"))
12986 (beginning-of-line 0)
12987 (re-search-forward "| ?" (point-at-eol) t)
12988 (and org-table-may-need-update (org-table-align))))
12990 (defun org-table-insert-hline (&optional arg)
12991 "Insert a horizontal-line below the current line into the table.
12992 With prefix ARG, insert above the current line."
12993 (interactive "P")
12994 (if (not (org-at-table-p))
12995 (error "Not at a table"))
12996 (let ((line (org-table-clean-line
12997 (buffer-substring (point-at-bol) (point-at-eol))))
12998 (col (current-column)))
12999 (while (string-match "|\\( +\\)|" line)
13000 (setq line (replace-match
13001 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
13002 ?-) "|") t t line)))
13003 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
13004 (beginning-of-line (if arg 1 2))
13005 (insert line "\n")
13006 (beginning-of-line (if arg 1 -1))
13007 (move-to-column col)))
13009 (defun org-table-clean-line (s)
13010 "Convert a table line S into a string with only \"|\" and space.
13011 In particular, this does handle wide and invisible characters."
13012 (if (string-match "^[ \t]*|-" s)
13013 ;; It's a hline, just map the characters
13014 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
13015 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
13016 (setq s (replace-match
13017 (concat "|" (make-string (org-string-width (match-string 1 s))
13018 ?\ ) "|")
13019 t t s)))
13022 (defun org-table-kill-row ()
13023 "Delete the current row or horizontal line from the table."
13024 (interactive)
13025 (if (not (org-at-table-p))
13026 (error "Not at a table"))
13027 (let ((col (current-column)))
13028 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
13029 (if (not (org-at-table-p)) (beginning-of-line 0))
13030 (move-to-column col)))
13032 (defun org-table-sort-lines (with-case &optional sorting-type)
13033 "Sort table lines according to the column at point.
13035 The position of point indicates the column to be used for
13036 sorting, and the range of lines is the range between the nearest
13037 horizontal separator lines, or the entire table of no such lines
13038 exist. If point is before the first column, you will be prompted
13039 for the sorting column. If there is an active region, the mark
13040 specifies the first line and the sorting column, while point
13041 should be in the last line to be included into the sorting.
13043 The command then prompts for the sorting type which can be
13044 alphabetically, numerically, or by time (as given in a time stamp
13045 in the field). Sorting in reverse order is also possible.
13047 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
13049 If SORTING-TYPE is specified when this function is called from a Lisp
13050 program, no prompting will take place. SORTING-TYPE must be a character,
13051 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
13052 should be done in reverse order."
13053 (interactive "P")
13054 (let* ((thisline (org-current-line))
13055 (thiscol (org-table-current-column))
13056 beg end bcol ecol tend tbeg column lns pos)
13057 (when (equal thiscol 0)
13058 (if (interactive-p)
13059 (setq thiscol
13060 (string-to-number
13061 (read-string "Use column N for sorting: ")))
13062 (setq thiscol 1))
13063 (org-table-goto-column thiscol))
13064 (org-table-check-inside-data-field)
13065 (if (org-region-active-p)
13066 (progn
13067 (setq beg (region-beginning) end (region-end))
13068 (goto-char beg)
13069 (setq column (org-table-current-column)
13070 beg (point-at-bol))
13071 (goto-char end)
13072 (setq end (point-at-bol 2)))
13073 (setq column (org-table-current-column)
13074 pos (point)
13075 tbeg (org-table-begin)
13076 tend (org-table-end))
13077 (if (re-search-backward org-table-hline-regexp tbeg t)
13078 (setq beg (point-at-bol 2))
13079 (goto-char tbeg)
13080 (setq beg (point-at-bol 1)))
13081 (goto-char pos)
13082 (if (re-search-forward org-table-hline-regexp tend t)
13083 (setq beg (point-at-bol 0))
13084 (goto-char tend)
13085 (setq end (point-at-bol))))
13086 (setq beg (move-marker (make-marker) beg)
13087 end (move-marker (make-marker) end))
13088 (untabify beg end)
13089 (goto-char beg)
13090 (org-table-goto-column column)
13091 (skip-chars-backward "^|")
13092 (setq bcol (current-column))
13093 (org-table-goto-column (1+ column))
13094 (skip-chars-backward "^|")
13095 (setq ecol (1- (current-column)))
13096 (org-table-goto-column column)
13097 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
13098 (org-split-string (buffer-substring beg end) "\n")))
13099 (setq lns (org-do-sort lns "Table" with-case sorting-type))
13100 (delete-region beg end)
13101 (move-marker beg nil)
13102 (move-marker end nil)
13103 (insert (mapconcat 'cdr lns "\n") "\n")
13104 (goto-line thisline)
13105 (org-table-goto-column thiscol)
13106 (message "%d lines sorted, based on column %d" (length lns) column)))
13108 (defun org-table-cut-region (beg end)
13109 "Copy region in table to the clipboard and blank all relevant fields."
13110 (interactive "r")
13111 (org-table-copy-region beg end 'cut))
13113 (defun org-table-copy-region (beg end &optional cut)
13114 "Copy rectangular region in table to clipboard.
13115 A special clipboard is used which can only be accessed
13116 with `org-table-paste-rectangle'."
13117 (interactive "rP")
13118 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
13119 region cols
13120 (rpl (if cut " " nil)))
13121 (goto-char beg)
13122 (org-table-check-inside-data-field)
13123 (setq l01 (count-lines (point-min) (point))
13124 c01 (org-table-current-column))
13125 (goto-char end)
13126 (org-table-check-inside-data-field)
13127 (setq l02 (count-lines (point-min) (point))
13128 c02 (org-table-current-column))
13129 (setq l1 (min l01 l02) l2 (max l01 l02)
13130 c1 (min c01 c02) c2 (max c01 c02))
13131 (catch 'exit
13132 (while t
13133 (catch 'nextline
13134 (if (> l1 l2) (throw 'exit t))
13135 (goto-line l1)
13136 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
13137 (setq cols nil ic1 c1 ic2 c2)
13138 (while (< ic1 (1+ ic2))
13139 (push (org-table-get-field ic1 rpl) cols)
13140 (setq ic1 (1+ ic1)))
13141 (push (nreverse cols) region)
13142 (setq l1 (1+ l1)))))
13143 (setq org-table-clip (nreverse region))
13144 (if cut (org-table-align))
13145 org-table-clip))
13147 (defun org-table-paste-rectangle ()
13148 "Paste a rectangular region into a table.
13149 The upper right corner ends up in the current field. All involved fields
13150 will be overwritten. If the rectangle does not fit into the present table,
13151 the table is enlarged as needed. The process ignores horizontal separator
13152 lines."
13153 (interactive)
13154 (unless (and org-table-clip (listp org-table-clip))
13155 (error "First cut/copy a region to paste!"))
13156 (org-table-check-inside-data-field)
13157 (let* ((clip org-table-clip)
13158 (line (count-lines (point-min) (point)))
13159 (col (org-table-current-column))
13160 (org-enable-table-editor t)
13161 (org-table-automatic-realign nil)
13162 c cols field)
13163 (while (setq cols (pop clip))
13164 (while (org-at-table-hline-p) (beginning-of-line 2))
13165 (if (not (org-at-table-p))
13166 (progn (end-of-line 0) (org-table-next-field)))
13167 (setq c col)
13168 (while (setq field (pop cols))
13169 (org-table-goto-column c nil 'force)
13170 (org-table-get-field nil field)
13171 (setq c (1+ c)))
13172 (beginning-of-line 2))
13173 (goto-line line)
13174 (org-table-goto-column col)
13175 (org-table-align)))
13177 (defun org-table-convert ()
13178 "Convert from `org-mode' table to table.el and back.
13179 Obviously, this only works within limits. When an Org-mode table is
13180 converted to table.el, all horizontal separator lines get lost, because
13181 table.el uses these as cell boundaries and has no notion of horizontal lines.
13182 A table.el table can be converted to an Org-mode table only if it does not
13183 do row or column spanning. Multiline cells will become multiple cells.
13184 Beware, Org-mode does not test if the table can be successfully converted - it
13185 blindly applies a recipe that works for simple tables."
13186 (interactive)
13187 (require 'table)
13188 (if (org-at-table.el-p)
13189 ;; convert to Org-mode table
13190 (let ((beg (move-marker (make-marker) (org-table-begin t)))
13191 (end (move-marker (make-marker) (org-table-end t))))
13192 (table-unrecognize-region beg end)
13193 (goto-char beg)
13194 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
13195 (replace-match ""))
13196 (goto-char beg))
13197 (if (org-at-table-p)
13198 ;; convert to table.el table
13199 (let ((beg (move-marker (make-marker) (org-table-begin)))
13200 (end (move-marker (make-marker) (org-table-end))))
13201 ;; first, get rid of all horizontal lines
13202 (goto-char beg)
13203 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
13204 (replace-match ""))
13205 ;; insert a hline before first
13206 (goto-char beg)
13207 (org-table-insert-hline 'above)
13208 (beginning-of-line -1)
13209 ;; insert a hline after each line
13210 (while (progn (beginning-of-line 3) (< (point) end))
13211 (org-table-insert-hline))
13212 (goto-char beg)
13213 (setq end (move-marker end (org-table-end)))
13214 ;; replace "+" at beginning and ending of hlines
13215 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
13216 (replace-match "\\1+-"))
13217 (goto-char beg)
13218 (while (re-search-forward "-|[ \t]*$" end t)
13219 (replace-match "-+"))
13220 (goto-char beg)))))
13222 (defun org-table-wrap-region (arg)
13223 "Wrap several fields in a column like a paragraph.
13224 This is useful if you'd like to spread the contents of a field over several
13225 lines, in order to keep the table compact.
13227 If there is an active region, and both point and mark are in the same column,
13228 the text in the column is wrapped to minimum width for the given number of
13229 lines. Generally, this makes the table more compact. A prefix ARG may be
13230 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
13231 formats the selected text to two lines. If the region was longer than two
13232 lines, the remaining lines remain empty. A negative prefix argument reduces
13233 the current number of lines by that amount. The wrapped text is pasted back
13234 into the table. If you formatted it to more lines than it was before, fields
13235 further down in the table get overwritten - so you might need to make space in
13236 the table first.
13238 If there is no region, the current field is split at the cursor position and
13239 the text fragment to the right of the cursor is prepended to the field one
13240 line down.
13242 If there is no region, but you specify a prefix ARG, the current field gets
13243 blank, and the content is appended to the field above."
13244 (interactive "P")
13245 (org-table-check-inside-data-field)
13246 (if (org-region-active-p)
13247 ;; There is a region: fill as a paragraph
13248 (let ((beg (region-beginning))
13249 nlines)
13250 (org-table-cut-region (region-beginning) (region-end))
13251 (if (> (length (car org-table-clip)) 1)
13252 (error "Region must be limited to single column"))
13253 (setq nlines (if arg
13254 (if (< arg 1)
13255 (+ (length org-table-clip) arg)
13256 arg)
13257 (length org-table-clip)))
13258 (setq org-table-clip
13259 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
13260 nil nlines)))
13261 (goto-char beg)
13262 (org-table-paste-rectangle))
13263 ;; No region, split the current field at point
13264 (if arg
13265 ;; combine with field above
13266 (let ((s (org-table-blank-field))
13267 (col (org-table-current-column)))
13268 (beginning-of-line 0)
13269 (while (org-at-table-hline-p) (beginning-of-line 0))
13270 (org-table-goto-column col)
13271 (skip-chars-forward "^|")
13272 (skip-chars-backward " ")
13273 (insert " " (org-trim s))
13274 (org-table-align))
13275 ;; split field
13276 (when (looking-at "\\([^|]+\\)+|")
13277 (let ((s (match-string 1)))
13278 (replace-match " |")
13279 (goto-char (match-beginning 0))
13280 (org-table-next-row)
13281 (insert (org-trim s) " ")
13282 (org-table-align))))))
13284 (defvar org-field-marker nil)
13286 (defun org-table-edit-field (arg)
13287 "Edit table field in a different window.
13288 This is mainly useful for fields that contain hidden parts.
13289 When called with a \\[universal-argument] prefix, just make the full field visible so that
13290 it can be edited in place."
13291 (interactive "P")
13292 (if arg
13293 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
13294 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
13295 (remove-text-properties b e '(org-cwidth t invisible t
13296 display t intangible t))
13297 (if (and (boundp 'font-lock-mode) font-lock-mode)
13298 (font-lock-fontify-block)))
13299 (let ((pos (move-marker (make-marker) (point)))
13300 (field (org-table-get-field))
13301 (cw (current-window-configuration))
13303 (switch-to-buffer-other-window "*Org tmp*")
13304 (erase-buffer)
13305 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
13306 (org-mode)
13307 (goto-char (setq p (point-max)))
13308 (insert (org-trim field))
13309 (remove-text-properties p (point-max)
13310 '(invisible t org-cwidth t display t
13311 intangible t))
13312 (goto-char p)
13313 (org-set-local 'org-finish-function
13314 'org-table-finish-edit-field)
13315 (org-set-local 'org-window-configuration cw)
13316 (org-set-local 'org-field-marker pos)
13317 (message "Edit and finish with C-c C-c"))))
13319 (defun org-table-finish-edit-field ()
13320 "Finish editing a table data field.
13321 Remove all newline characters, insert the result into the table, realign
13322 the table and kill the editing buffer."
13323 (let ((pos org-field-marker)
13324 (cw org-window-configuration)
13325 (cb (current-buffer))
13326 text)
13327 (goto-char (point-min))
13328 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
13329 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
13330 (replace-match " "))
13331 (setq text (org-trim (buffer-string)))
13332 (set-window-configuration cw)
13333 (kill-buffer cb)
13334 (select-window (get-buffer-window (marker-buffer pos)))
13335 (goto-char pos)
13336 (move-marker pos nil)
13337 (org-table-check-inside-data-field)
13338 (org-table-get-field nil text)
13339 (org-table-align)
13340 (message "New field value inserted")))
13342 (defun org-trim (s)
13343 "Remove whitespace at beginning and end of string."
13344 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
13345 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
13348 (defun org-wrap (string &optional width lines)
13349 "Wrap string to either a number of lines, or a width in characters.
13350 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13351 that costs. If there is a word longer than WIDTH, the text is actually
13352 wrapped to the length of that word.
13353 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13354 many lines, whatever width that takes.
13355 The return value is a list of lines, without newlines at the end."
13356 (let* ((words (org-split-string string "[ \t\n]+"))
13357 (maxword (apply 'max (mapcar 'org-string-width words)))
13358 w ll)
13359 (cond (width
13360 (org-do-wrap words (max maxword width)))
13361 (lines
13362 (setq w maxword)
13363 (setq ll (org-do-wrap words maxword))
13364 (if (<= (length ll) lines)
13366 (setq ll words)
13367 (while (> (length ll) lines)
13368 (setq w (1+ w))
13369 (setq ll (org-do-wrap words w)))
13370 ll))
13371 (t (error "Cannot wrap this")))))
13374 (defun org-do-wrap (words width)
13375 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13376 (let (lines line)
13377 (while words
13378 (setq line (pop words))
13379 (while (and words (< (+ (length line) (length (car words))) width))
13380 (setq line (concat line " " (pop words))))
13381 (setq lines (push line lines)))
13382 (nreverse lines)))
13384 (defun org-split-string (string &optional separators)
13385 "Splits STRING into substrings at SEPARATORS.
13386 No empty strings are returned if there are matches at the beginning
13387 and end of string."
13388 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13389 (start 0)
13390 notfirst
13391 (list nil))
13392 (while (and (string-match rexp string
13393 (if (and notfirst
13394 (= start (match-beginning 0))
13395 (< start (length string)))
13396 (1+ start) start))
13397 (< (match-beginning 0) (length string)))
13398 (setq notfirst t)
13399 (or (eq (match-beginning 0) 0)
13400 (and (eq (match-beginning 0) (match-end 0))
13401 (eq (match-beginning 0) start))
13402 (setq list
13403 (cons (substring string start (match-beginning 0))
13404 list)))
13405 (setq start (match-end 0)))
13406 (or (eq start (length string))
13407 (setq list
13408 (cons (substring string start)
13409 list)))
13410 (nreverse list)))
13412 (defun org-table-map-tables (function)
13413 "Apply FUNCTION to the start of all tables in the buffer."
13414 (save-excursion
13415 (save-restriction
13416 (widen)
13417 (goto-char (point-min))
13418 (while (re-search-forward org-table-any-line-regexp nil t)
13419 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
13420 (beginning-of-line 1)
13421 (if (looking-at org-table-line-regexp)
13422 (save-excursion (funcall function)))
13423 (re-search-forward org-table-any-border-regexp nil 1))))
13424 (message "Mapping tables: done"))
13426 (defun org-table-sum (&optional beg end nlast)
13427 "Sum numbers in region of current table column.
13428 The result will be displayed in the echo area, and will be available
13429 as kill to be inserted with \\[yank].
13431 If there is an active region, it is interpreted as a rectangle and all
13432 numbers in that rectangle will be summed. If there is no active
13433 region and point is located in a table column, sum all numbers in that
13434 column.
13436 If at least one number looks like a time HH:MM or HH:MM:SS, all other
13437 numbers are assumed to be times as well (in decimal hours) and the
13438 numbers are added as such.
13440 If NLAST is a number, only the NLAST fields will actually be summed."
13441 (interactive)
13442 (save-excursion
13443 (let (col (timecnt 0) diff h m s org-table-clip)
13444 (cond
13445 ((and beg end)) ; beg and end given explicitly
13446 ((org-region-active-p)
13447 (setq beg (region-beginning) end (region-end)))
13449 (setq col (org-table-current-column))
13450 (goto-char (org-table-begin))
13451 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
13452 (error "No table data"))
13453 (org-table-goto-column col)
13454 ;not needed? (skip-chars-backward "^|")
13455 (setq beg (point))
13456 (goto-char (org-table-end))
13457 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
13458 (error "No table data"))
13459 (org-table-goto-column col)
13460 ;not needed? (skip-chars-forward "^|")
13461 (setq end (point))))
13462 (let* ((items (apply 'append (org-table-copy-region beg end)))
13463 (items1 (cond ((not nlast) items)
13464 ((>= nlast (length items)) items)
13465 (t (setq items (reverse items))
13466 (setcdr (nthcdr (1- nlast) items) nil)
13467 (nreverse items))))
13468 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
13469 items1)))
13470 (res (apply '+ numbers))
13471 (sres (if (= timecnt 0)
13472 (format "%g" res)
13473 (setq diff (* 3600 res)
13474 h (floor (/ diff 3600)) diff (mod diff 3600)
13475 m (floor (/ diff 60)) diff (mod diff 60)
13476 s diff)
13477 (format "%d:%02d:%02d" h m s))))
13478 (kill-new sres)
13479 (if (interactive-p)
13480 (message "%s"
13481 (substitute-command-keys
13482 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
13483 (length numbers) sres))))
13484 sres))))
13486 (defun org-table-get-number-for-summing (s)
13487 (let (n)
13488 (if (string-match "^ *|? *" s)
13489 (setq s (replace-match "" nil nil s)))
13490 (if (string-match " *|? *$" s)
13491 (setq s (replace-match "" nil nil s)))
13492 (setq n (string-to-number s))
13493 (cond
13494 ((and (string-match "0" s)
13495 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
13496 ((string-match "\\`[ \t]+\\'" s) nil)
13497 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
13498 (let ((h (string-to-number (or (match-string 1 s) "0")))
13499 (m (string-to-number (or (match-string 2 s) "0")))
13500 (s (string-to-number (or (match-string 4 s) "0"))))
13501 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
13502 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
13503 ((equal n 0) nil)
13504 (t n))))
13506 (defun org-table-get-vertical-vector (desc &optional tbeg col)
13507 "Get a calc vector from a column, accorting to descriptor DESC.
13508 Optional arguments TBEG and COL can give the beginning of the table and
13509 the current column, to avoid unnecessary parsing."
13510 (save-excursion
13511 (or tbeg (setq tbeg (org-table-begin)))
13512 (or col (setq col (org-table-current-column)))
13513 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
13514 (cond
13515 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
13516 (setq n1 (- (match-end 1) (match-beginning 1)))
13517 (if (match-beginning 3)
13518 (setq n2 (- (match-end 2) (match-beginning 3))))
13519 (setq n (if n2 (max n1 n2) n1))
13520 (setq n1 (if n2 (min n1 n2)))
13521 (setq nn n)
13522 (while (and (> nn 0)
13523 (re-search-backward org-table-hline-regexp tbeg t))
13524 (push (org-current-line) hline-list)
13525 (setq nn (1- nn)))
13526 (setq hline-list (nreverse hline-list))
13527 (goto-line (nth (1- n) hline-list))
13528 (when (re-search-forward org-table-dataline-regexp)
13529 (org-table-goto-column col)
13530 (setq beg (point)))
13531 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
13532 (when (re-search-backward org-table-dataline-regexp)
13533 (org-table-goto-column col)
13534 (setq end (point)))
13535 (setq l (apply 'append (org-table-copy-region beg end)))
13536 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
13537 (if (equal x "") "0" x))
13538 l ",") "]"))
13539 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
13540 (setq n1 (string-to-number (match-string 1 desc))
13541 n2 (string-to-number (match-string 2 desc)))
13542 (beginning-of-line 1)
13543 (save-excursion
13544 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
13545 (org-table-goto-column col)
13546 (setq beg (point))))
13547 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
13548 (org-table-goto-column col)
13549 (setq end (point)))
13550 (setq l (apply 'append (org-table-copy-region beg end)))
13551 (concat "[" (mapconcat
13552 (lambda (x) (setq x (org-trim x))
13553 (if (equal x "") "0" x))
13554 l ",") "]"))
13555 ((string-match "\\([0-9]+\\)" desc)
13556 (beginning-of-line 1)
13557 (when (re-search-backward org-table-dataline-regexp tbeg t
13558 (string-to-number (match-string 0 desc)))
13559 (org-table-goto-column col)
13560 (org-trim (org-table-get-field))))))))
13562 (defvar org-table-formula-history nil)
13564 (defvar org-table-column-names nil
13565 "Alist with column names, derived from the `!' line.")
13566 (defvar org-table-column-name-regexp nil
13567 "Regular expression matching the current column names.")
13568 (defvar org-table-local-parameters nil
13569 "Alist with parameter names, derived from the `$' line.")
13570 (defvar org-table-named-field-locations nil
13571 "Alist with locations of named fields.")
13573 (defun org-table-get-formula (&optional equation named)
13574 "Read a formula from the minibuffer, offer stored formula as default."
13575 (let* ((name (car (rassoc (list (org-current-line)
13576 (org-table-current-column))
13577 org-table-named-field-locations)))
13578 (scol (if named
13579 (if name name
13580 (error "Not in a named field"))
13581 (int-to-string (org-table-current-column))))
13582 (dummy (and name (not named)
13583 (not (y-or-n-p "Replace named-field formula with column equation? " ))
13584 (error "Abort")))
13585 (org-table-may-need-update nil)
13586 (stored-list (org-table-get-stored-formulas))
13587 (stored (cdr (assoc scol stored-list)))
13588 (eq (cond
13589 ((and stored equation (string-match "^ *=? *$" equation))
13590 stored)
13591 ((stringp equation)
13592 equation)
13593 (t (read-string
13594 (format "%s formula $%s=" (if named "Field" "Column") scol)
13595 (or stored "") 'org-table-formula-history
13596 ;stored
13597 ))))
13598 mustsave)
13599 (when (not (string-match "\\S-" eq))
13600 ;; remove formula
13601 (setq stored-list (delq (assoc scol stored-list) stored-list))
13602 (org-table-store-formulas stored-list)
13603 (error "Formula removed"))
13604 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
13605 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
13606 (if (and name (not named))
13607 ;; We set the column equation, delete the named one.
13608 (setq stored-list (delq (assoc name stored-list) stored-list)
13609 mustsave t))
13610 (if stored
13611 (setcdr (assoc scol stored-list) eq)
13612 (setq stored-list (cons (cons scol eq) stored-list)))
13613 (if (or mustsave (not (equal stored eq)))
13614 (org-table-store-formulas stored-list))
13615 eq))
13617 (defun org-table-store-formulas (alist)
13618 "Store the list of formulas below the current table."
13619 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
13620 (save-excursion
13621 (goto-char (org-table-end))
13622 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
13623 (delete-region (point) (match-end 0)))
13624 (insert "#+TBLFM: "
13625 (mapconcat (lambda (x)
13626 (concat "$" (car x) "=" (cdr x)))
13627 alist "::")
13628 "\n")))
13630 (defun org-table-get-stored-formulas ()
13631 "Return an alist with the stored formulas directly after current table."
13632 (interactive)
13633 (let (scol eq eq-alist strings string seen)
13634 (save-excursion
13635 (goto-char (org-table-end))
13636 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
13637 (setq strings (org-split-string (match-string 2) " *:: *"))
13638 (while (setq string (pop strings))
13639 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
13640 (setq scol (match-string 1 string)
13641 eq (match-string 2 string)
13642 eq-alist (cons (cons scol eq) eq-alist))
13643 (if (member scol seen)
13644 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
13645 (push scol seen))))))
13646 (nreverse eq-alist)))
13648 (defun org-table-modify-formulas (action &rest columns)
13649 "Modify the formulas stored below the current table.
13650 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
13651 expected, for the other actions only a single column number is needed."
13652 (let ((list (org-table-get-stored-formulas))
13653 (nmax (length (org-split-string
13654 (buffer-substring (point-at-bol) (point-at-eol))
13655 "|")))
13656 col col1 col2 scol si sc1 sc2)
13657 (cond
13658 ((null list)) ; No action needed if there are no stored formulas
13659 ((eq action 'remove)
13660 (setq col (car columns)
13661 scol (int-to-string col))
13662 (org-table-replace-in-formulas list scol "INVALID")
13663 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
13664 (loop for i from (1+ col) upto nmax by 1 do
13665 (setq si (int-to-string i))
13666 (org-table-replace-in-formulas list si (int-to-string (1- i)))
13667 (if (assoc si list) (setcar (assoc si list)
13668 (int-to-string (1- i))))))
13669 ((eq action 'insert)
13670 (setq col (car columns))
13671 (loop for i from nmax downto col by 1 do
13672 (setq si (int-to-string i))
13673 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
13674 (if (assoc si list) (setcar (assoc si list)
13675 (int-to-string (1+ i))))))
13676 ((eq action 'swap)
13677 (setq col1 (car columns) col2 (nth 1 columns)
13678 sc1 (int-to-string col1) sc2 (int-to-string col2))
13679 ;; Hopefully, ZqZtZ will never be a name in a table
13680 (org-table-replace-in-formulas list sc1 "ZqZtZ")
13681 (org-table-replace-in-formulas list sc2 sc1)
13682 (org-table-replace-in-formulas list "ZqZtZ" sc2)
13683 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
13684 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
13685 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
13686 (t (error "Invalid action in `org-table-modify-formulas'")))
13687 (if list (org-table-store-formulas list))))
13689 (defun org-table-replace-in-formulas (list s1 s2)
13690 (let (elt re s)
13691 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
13692 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
13693 re (concat (regexp-quote s1) "\\>"))
13694 (while (setq elt (pop list))
13695 (setq s (cdr elt))
13696 (while (string-match re s)
13697 (setq s (replace-match s2 t t s)))
13698 (setcdr elt s))))
13700 (defun org-table-get-specials ()
13701 "Get the column names and local parameters for this table."
13702 (save-excursion
13703 (let ((beg (org-table-begin)) (end (org-table-end))
13704 names name fields fields1 field cnt c v line col)
13705 (setq org-table-column-names nil
13706 org-table-local-parameters nil
13707 org-table-named-field-locations nil)
13708 (goto-char beg)
13709 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
13710 (setq names (org-split-string (match-string 1) " *| *")
13711 cnt 1)
13712 (while (setq name (pop names))
13713 (setq cnt (1+ cnt))
13714 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
13715 (push (cons name (int-to-string cnt)) org-table-column-names))))
13716 (setq org-table-column-names (nreverse org-table-column-names))
13717 (setq org-table-column-name-regexp
13718 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
13719 (goto-char beg)
13720 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
13721 (setq fields (org-split-string (match-string 1) " *| *"))
13722 (while (setq field (pop fields))
13723 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
13724 (push (cons (match-string 1 field) (match-string 2 field))
13725 org-table-local-parameters))))
13726 (goto-char beg)
13727 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
13728 (setq c (match-string 1)
13729 fields (org-split-string (match-string 2) " *| *"))
13730 (save-excursion
13731 (beginning-of-line (if (equal c "_") 2 0))
13732 (setq line (org-current-line) col 1)
13733 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
13734 (setq fields1 (org-split-string (match-string 1) " *| *"))))
13735 (while (and fields1 (setq field (pop fields)))
13736 (setq v (pop fields1) col (1+ col))
13737 (when (and (stringp field) (stringp v)
13738 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
13739 (push (cons field v) org-table-local-parameters)
13740 (push (list field line col) org-table-named-field-locations)))))))
13742 (defun org-this-word ()
13743 ;; Get the current word
13744 (save-excursion
13745 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
13746 (end (progn (skip-chars-forward "^ \t\n") (point))))
13747 (buffer-substring-no-properties beg end))))
13749 (defun org-table-maybe-eval-formula ()
13750 "Check if the current field starts with \"=\" or \":=\".
13751 If yes, store the formula and apply it."
13752 ;; We already know we are in a table. Get field will only return a formula
13753 ;; when appropriate. It might return a separator line, but no problem.
13754 (when org-table-formula-evaluate-inline
13755 (let* ((field (org-trim (or (org-table-get-field) "")))
13756 named eq)
13757 (when (string-match "^:?=\\(.*\\)" field)
13758 (setq named (equal (string-to-char field) ?:)
13759 eq (match-string 1 field))
13760 (if (fboundp 'calc-eval)
13761 (org-table-eval-formula (if named '(4) nil) eq))))))
13763 (defvar org-recalc-commands nil
13764 "List of commands triggering the recalculation of a line.
13765 Will be filled automatically during use.")
13767 (defvar org-recalc-marks
13768 '((" " . "Unmarked: no special line, no automatic recalculation")
13769 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
13770 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
13771 ("!" . "Column name definition line. Reference in formula as $name.")
13772 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
13773 ("_" . "Names for values in row below this one.")
13774 ("^" . "Names for values in row above this one.")))
13776 (defun org-table-rotate-recalc-marks (&optional newchar)
13777 "Rotate the recalculation mark in the first column.
13778 If in any row, the first field is not consistent with a mark,
13779 insert a new column for the markers.
13780 When there is an active region, change all the lines in the region,
13781 after prompting for the marking character.
13782 After each change, a message will be displayed indicating the meaning
13783 of the new mark."
13784 (interactive)
13785 (unless (org-at-table-p) (error "Not at a table"))
13786 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
13787 (beg (org-table-begin))
13788 (end (org-table-end))
13789 (l (org-current-line))
13790 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
13791 (l2 (if (org-region-active-p) (org-current-line (region-end))))
13792 (have-col
13793 (save-excursion
13794 (goto-char beg)
13795 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
13796 (col (org-table-current-column))
13797 (forcenew (car (assoc newchar org-recalc-marks)))
13798 epos new)
13799 (when l1
13800 (message "Change region to what mark? Type # * ! $ or SPC: ")
13801 (setq newchar (char-to-string (read-char-exclusive))
13802 forcenew (car (assoc newchar org-recalc-marks))))
13803 (if (and newchar (not forcenew))
13804 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
13805 newchar))
13806 (if l1 (goto-line l1))
13807 (save-excursion
13808 (beginning-of-line 1)
13809 (unless (looking-at org-table-dataline-regexp)
13810 (error "Not at a table data line")))
13811 (unless have-col
13812 (org-table-goto-column 1)
13813 (org-table-insert-column)
13814 (org-table-goto-column (1+ col)))
13815 (setq epos (point-at-eol))
13816 (save-excursion
13817 (beginning-of-line 1)
13818 (org-table-get-field
13819 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
13820 (concat " "
13821 (setq new (or forcenew
13822 (cadr (member (match-string 1) marks))))
13823 " ")
13824 " # ")))
13825 (if (and l1 l2)
13826 (progn
13827 (goto-line l1)
13828 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
13829 (and (looking-at org-table-dataline-regexp)
13830 (org-table-get-field 1 (concat " " new " "))))
13831 (goto-line l1)))
13832 (if (not (= epos (point-at-eol))) (org-table-align))
13833 (goto-line l)
13834 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
13836 (defun org-table-maybe-recalculate-line ()
13837 "Recompute the current line if marked for it, and if we haven't just done it."
13838 (interactive)
13839 (and org-table-allow-automatic-line-recalculation
13840 (not (and (memq last-command org-recalc-commands)
13841 (equal org-last-recalc-line (org-current-line))))
13842 (save-excursion (beginning-of-line 1)
13843 (looking-at org-table-auto-recalculate-regexp))
13844 (fboundp 'calc-eval)
13845 (org-table-recalculate) t))
13847 (defvar org-table-formula-debug nil
13848 "Non-nil means, debug table formulas.
13849 When nil, simply write \"#ERROR\" in corrupted fields.")
13851 (defvar modes)
13852 (defsubst org-set-calc-mode (var &optional value)
13853 (if (stringp var)
13854 (setq var (assoc var '(("D" calc-angle-mode deg)
13855 ("R" calc-angle-mode rad)
13856 ("F" calc-prefer-frac t)
13857 ("S" calc-symbolic-mode t)))
13858 value (nth 2 var) var (nth 1 var)))
13859 (if (memq var modes)
13860 (setcar (cdr (memq var modes)) value)
13861 (cons var (cons value modes)))
13862 modes)
13864 (defun org-table-eval-formula (&optional arg equation
13865 suppress-align suppress-const
13866 suppress-store)
13867 "Replace the table field value at the cursor by the result of a calculation.
13869 This function makes use of Dave Gillespie's Calc package, in my view the
13870 most exciting program ever written for GNU Emacs. So you need to have Calc
13871 installed in order to use this function.
13873 In a table, this command replaces the value in the current field with the
13874 result of a formula. It also installs the formula as the \"current\" column
13875 formula, by storing it in a special line below the table. When called
13876 with a `C-u' prefix, the current field must ba a named field, and the
13877 formula is installed as valid in only this specific field.
13879 When called, the command first prompts for a formula, which is read in
13880 the minibuffer. Previously entered formulas are available through the
13881 history list, and the last used formula is offered as a default.
13882 These stored formulas are adapted correctly when moving, inserting, or
13883 deleting columns with the corresponding commands.
13885 The formula can be any algebraic expression understood by the Calc package.
13886 For details, see the Org-mode manual.
13888 This function can also be called from Lisp programs and offers
13889 additional arguments: EQUATION can be the formula to apply. If this
13890 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
13891 used to speed-up recursive calls by by-passing unnecessary aligns.
13892 SUPPRESS-CONST suppresses the interpretation of constants in the
13893 formula, assuming that this has been done already outside the function.
13894 SUPPRESS-STORE means the formula should not be stored, either because
13895 it is already stored, or because it is a modified equation that should
13896 not overwrite the stored one."
13897 (interactive "P")
13898 (require 'calc)
13899 (org-table-check-inside-data-field)
13900 (org-table-get-specials)
13901 (let* (fields
13902 (ndown (if (integerp arg) arg 1))
13903 (org-table-automatic-realign nil)
13904 (case-fold-search nil)
13905 (down (> ndown 1))
13906 (formula (if (and equation suppress-store)
13907 equation
13908 (org-table-get-formula equation (equal arg '(4)))))
13909 (n0 (org-table-current-column))
13910 (modes (copy-sequence org-calc-default-modes))
13911 n form fmt x ev orig c lispp)
13912 ;; Parse the format string. Since we have a lot of modes, this is
13913 ;; a lot of work. However, I think calc still uses most of the time.
13914 (if (string-match ";" formula)
13915 (let ((tmp (org-split-string formula ";")))
13916 (setq formula (car tmp)
13917 fmt (concat (cdr (assoc "%" org-table-local-parameters))
13918 (nth 1 tmp)))
13919 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
13920 (setq c (string-to-char (match-string 1 fmt))
13921 n (string-to-number (match-string 2 fmt)))
13922 (if (= c ?p)
13923 (setq modes (org-set-calc-mode 'calc-internal-prec n))
13924 (setq modes (org-set-calc-mode
13925 'calc-float-format
13926 (list (cdr (assoc c '((?n . float) (?f . fix)
13927 (?s . sci) (?e . eng))))
13928 n))))
13929 (setq fmt (replace-match "" t t fmt)))
13930 (while (string-match "[DRFS]" fmt)
13931 (setq modes (org-set-calc-mode (match-string 0 fmt)))
13932 (setq fmt (replace-match "" t t fmt)))
13933 (unless (string-match "\\S-" fmt)
13934 (setq fmt nil))))
13935 (if (and (not suppress-const) org-table-formula-use-constants)
13936 (setq formula (org-table-formula-substitute-names formula)))
13937 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
13938 (while (> ndown 0)
13939 (setq fields (org-split-string
13940 (buffer-substring
13941 (point-at-bol) (point-at-eol)) " *| *"))
13942 (if org-table-formula-numbers-only
13943 (setq fields (mapcar
13944 (lambda (x) (number-to-string (string-to-number x)))
13945 fields)))
13946 (setq ndown (1- ndown))
13947 (setq form (copy-sequence formula)
13948 lispp (equal (substring form 0 2) "'("))
13949 ;; Insert the references to fields in same row
13950 (while (string-match "\\$\\([0-9]+\\)?" form)
13951 (setq n (if (match-beginning 1)
13952 (string-to-number (match-string 1 form))
13954 x (nth (1- n) fields))
13955 (unless x (error "Invalid field specifier \"%s\""
13956 (match-string 0 form)))
13957 (if (equal x "") (setq x "0"))
13958 (setq form (replace-match
13959 (if lispp x (concat "(" x ")"))
13960 t t form)))
13961 ;; Insert ranges in current column
13962 (while (string-match "\\&[-I0-9]+" form)
13963 (setq form (replace-match
13964 (save-match-data
13965 (org-table-get-vertical-vector (match-string 0 form)
13966 nil n0))
13967 t t form)))
13968 (if lispp
13969 (setq ev (eval (eval (read form)))
13970 ev (if (numberp ev) (number-to-string ev) ev))
13971 (setq ev (calc-eval (cons form modes)
13972 (if org-table-formula-numbers-only 'num))))
13974 (when org-table-formula-debug
13975 (with-output-to-temp-buffer "*Help*"
13976 (princ (format "Substitution history of formula
13977 Orig: %s
13978 $xyz-> %s
13979 $1-> %s\n" orig formula form))
13980 (if (listp ev)
13981 (princ (format " %s^\nError: %s"
13982 (make-string (car ev) ?\-) (nth 1 ev)))
13983 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
13984 ev (or fmt "NONE")
13985 (if fmt (format fmt (string-to-number ev)) ev)))))
13986 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
13987 (unless (and (interactive-p) (not ndown))
13988 (unless (let (inhibit-redisplay)
13989 (y-or-n-p "Debugging Formula. Continue to next? "))
13990 (org-table-align)
13991 (error "Abort"))
13992 (delete-window (get-buffer-window "*Help*"))
13993 (message "")))
13994 (if (listp ev) (setq fmt nil ev "#ERROR"))
13995 (org-table-justify-field-maybe
13996 (if fmt (format fmt (string-to-number ev)) ev))
13997 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
13998 (call-interactively 'org-return)
13999 (setq ndown 0)))
14000 (and down (org-table-maybe-recalculate-line))
14001 (or suppress-align (and org-table-may-need-update
14002 (org-table-align)))))
14004 (defun org-table-recalculate (&optional all noalign)
14005 "Recalculate the current table line by applying all stored formulas.
14006 With prefix arg ALL, do this for all lines in the table."
14007 (interactive "P")
14008 (or (memq this-command org-recalc-commands)
14009 (setq org-recalc-commands (cons this-command org-recalc-commands)))
14010 (unless (org-at-table-p) (error "Not at a table"))
14011 (org-table-get-specials)
14012 (let* ((eqlist (sort (org-table-get-stored-formulas)
14013 (lambda (a b) (string< (car a) (car b)))))
14014 (inhibit-redisplay t)
14015 (line-re org-table-dataline-regexp)
14016 (thisline (org-current-line))
14017 (thiscol (org-table-current-column))
14018 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
14019 ;; Insert constants in all formulas
14020 (setq eqlist
14021 (mapcar (lambda (x)
14022 (setcdr x (org-table-formula-substitute-names (cdr x)))
14024 eqlist))
14025 ;; Split the equation list
14026 (while (setq eq (pop eqlist))
14027 (if (<= (string-to-char (car eq)) ?9)
14028 (push eq eqlnum)
14029 (push eq eqlname)))
14030 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
14031 (if all
14032 (progn
14033 (setq end (move-marker (make-marker) (1+ (org-table-end))))
14034 (goto-char (setq beg (org-table-begin)))
14035 (if (re-search-forward org-table-calculate-mark-regexp end t)
14036 ;; This is a table with marked lines, only compute selected lines
14037 (setq line-re org-table-recalculate-regexp)
14038 ;; Move forward to the first non-header line
14039 (if (and (re-search-forward org-table-dataline-regexp end t)
14040 (re-search-forward org-table-hline-regexp end t)
14041 (re-search-forward org-table-dataline-regexp end t))
14042 (setq beg (match-beginning 0))
14043 nil))) ;; just leave beg where it is
14044 (setq beg (point-at-bol)
14045 end (move-marker (make-marker) (1+ (point-at-eol)))))
14046 (goto-char beg)
14047 (and all (message "Re-applying formulas to full table..."))
14048 (while (re-search-forward line-re end t)
14049 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
14050 ;; Unprotected line, recalculate
14051 (and all (message "Re-applying formulas to full table...(line %d)"
14052 (setq cnt (1+ cnt))))
14053 (setq org-last-recalc-line (org-current-line))
14054 (setq eql eqlnum)
14055 (while (setq entry (pop eql))
14056 (goto-line org-last-recalc-line)
14057 (org-table-goto-column (string-to-number (car entry)) nil 'force)
14058 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
14059 (goto-line thisline)
14060 (org-table-goto-column thiscol)
14061 (or noalign (and org-table-may-need-update (org-table-align))
14062 (and all (message "Re-applying formulas to %d lines...done" cnt)))
14063 ;; Now do the names fields
14064 (while (setq eq (pop eqlname))
14065 (setq name (car eq)
14066 a (assoc name org-table-named-field-locations))
14067 (when a
14068 (message "Re-applying formula to named field: %s" name)
14069 (goto-line (nth 1 a))
14070 (org-table-goto-column (nth 2 a))
14071 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
14072 ;; back to initial position
14073 (goto-line thisline)
14074 (org-table-goto-column thiscol)
14075 (or noalign (and org-table-may-need-update (org-table-align))
14076 (and all (message "Re-applying formulas...done")))))
14078 (defun org-table-formula-substitute-names (f)
14079 "Replace $const with values in string F."
14080 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
14081 ;; First, check for column names
14082 (while (setq start (string-match org-table-column-name-regexp f start))
14083 (setq start (1+ start))
14084 (setq a (assoc (match-string 1 f) org-table-column-names))
14085 (setq f (replace-match (concat "$" (cdr a)) t t f)))
14086 ;; Expand ranges to vectors
14087 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
14088 (setq n1 (string-to-number (match-string 1 f))
14089 n2 (string-to-number (match-string 2 f))
14090 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
14091 s (concat "[($" (number-to-string (1- nn1)) ")"))
14092 (loop for i from nn1 upto nn2 do
14093 (setq s (concat s ",($" (int-to-string i) ")")))
14094 (setq s (concat s "]"))
14095 (if (< n2 n1) (setq s (concat "rev(" s ")")))
14096 (setq f (replace-match s t t f)))
14097 ;; Parameters and constants
14098 (setq start 0)
14099 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
14100 (setq start (1+ start))
14101 (if (setq a (save-match-data
14102 (org-table-get-constant (match-string 1 f))))
14103 (setq f (replace-match (concat "(" a ")") t t f))))
14104 (if org-table-formula-debug
14105 (put-text-property 0 (length f) :orig-formula f1 f))
14108 (defun org-table-get-constant (const)
14109 "Find the value for a parameter or constant in a formula.
14110 Parameters get priority."
14111 (or (cdr (assoc const org-table-local-parameters))
14112 (cdr (assoc const org-table-formula-constants))
14113 (and (fboundp 'constants-get) (constants-get const))
14114 "#UNDEFINED_NAME"))
14116 (defvar org-edit-formulas-map (make-sparse-keymap))
14117 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
14118 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
14119 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
14121 (defvar org-pos)
14123 (defun org-table-edit-formulas ()
14124 "Edit the formulas of the current table in a separate buffer."
14125 (interactive)
14126 (unless (org-at-table-p)
14127 (error "Not at a table"))
14128 (org-table-get-specials)
14129 (let ((eql (org-table-get-stored-formulas))
14130 (pos (move-marker (make-marker) (point)))
14131 (wc (current-window-configuration))
14132 entry loc s)
14133 (switch-to-buffer-other-window "*Edit Formulas*")
14134 (erase-buffer)
14135 (fundamental-mode)
14136 (org-set-local 'org-pos pos)
14137 (org-set-local 'org-window-configuration wc)
14138 (use-local-map org-edit-formulas-map)
14139 (setq s "# Edit formulas and finish with `C-c C-c'.
14140 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
14141 # Use `C-c ?' to get information about $name at point.
14142 # To cancel editing, press `C-c C-q'.\n")
14143 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
14144 (insert s)
14145 (while (setq entry (pop eql))
14146 (when (setq loc (assoc (car entry) org-table-named-field-locations))
14147 (setq s (format "# Named formula, referring to column %d in line %d\n"
14148 (nth 2 loc) (nth 1 loc)))
14149 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
14150 (insert s))
14151 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
14152 (remove-text-properties 0 (length s) '(face nil) s)
14153 (insert s))
14154 (goto-char (point-min))
14155 (message "Edit formulas and finish with `C-c C-c'.")))
14157 (defun org-show-variable ()
14158 "Show the location/value of the $ expression at point."
14159 (interactive)
14160 (let (var (pos org-pos) (win (selected-window)) e)
14161 (save-excursion
14162 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
14163 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
14164 (setq var (match-string 1))
14165 (error "No variable at point")))
14166 (cond
14167 ((setq e (assoc var org-table-named-field-locations))
14168 (switch-to-buffer-other-window (marker-buffer pos))
14169 (goto-line (nth 1 e))
14170 (org-table-goto-column (nth 2 e))
14171 (select-window win)
14172 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
14173 ((setq e (assoc var org-table-column-names))
14174 (switch-to-buffer-other-window (marker-buffer pos))
14175 (goto-char pos)
14176 (goto-char (org-table-begin))
14177 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
14178 (org-table-end) t)
14179 (progn
14180 (goto-char (match-beginning 1))
14181 (message "Named column (column %s)" (cdr e)))
14182 (error "Column name not found"))
14183 (select-window win))
14184 ((string-match "^[0-9]$" var)
14185 ;; column number
14186 (switch-to-buffer-other-window (marker-buffer pos))
14187 (goto-char pos)
14188 (goto-char (org-table-begin))
14189 (recenter 1)
14190 (if (re-search-forward org-table-dataline-regexp
14191 (org-table-end) t)
14192 (progn
14193 (goto-char (match-beginning 0))
14194 (org-table-goto-column (string-to-number var))
14195 (message "Column %s" var))
14196 (error "Column name not found"))
14197 (select-window win))
14198 ((setq e (assoc var org-table-local-parameters))
14199 (switch-to-buffer-other-window (marker-buffer pos))
14200 (goto-char pos)
14201 (goto-char (org-table-begin))
14202 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
14203 (progn
14204 (goto-char (match-beginning 1))
14205 (message "Local parameter."))
14206 (error "Parameter not found"))
14207 (select-window win))
14209 (cond
14210 ((setq e (assoc var org-table-formula-constants))
14211 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
14212 ((setq e (and (fboundp 'constants-get) (constants-get var)))
14213 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
14214 (t (error "Undefined name $%s" var)))))))
14216 (defun org-finish-edit-formulas (&optional arg)
14217 "Parse the buffer for formula definitions and install them.
14218 With prefix ARG, apply the new formulas to the table."
14219 (interactive "P")
14220 (let ((pos org-pos) eql)
14221 (goto-char (point-min))
14222 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
14223 (push (cons (match-string 1) (match-string 2)) eql))
14224 (set-window-configuration org-window-configuration)
14225 (select-window (get-buffer-window (marker-buffer pos)))
14226 (goto-char pos)
14227 (unless (org-at-table-p)
14228 (error "Lost table position - cannot install formulae"))
14229 (org-table-store-formulas eql)
14230 (move-marker pos nil)
14231 (kill-buffer "*Edit Formulas*")
14232 (if arg
14233 (org-table-recalculate 'all)
14234 (message "New formulas installed - press C-u C-c C-c to apply."))))
14236 (defun org-abort-edit-formulas ()
14237 "Abort editing formulas, without installing the changes."
14238 (interactive)
14239 (let ((pos org-pos))
14240 (set-window-configuration org-window-configuration)
14241 (select-window (get-buffer-window (marker-buffer pos)))
14242 (goto-char pos)
14243 (message "Formula editing aborted without installing changes")))
14245 ;;;; The orgtbl minor mode
14247 ;; Define a minor mode which can be used in other modes in order to
14248 ;; integrate the org-mode table editor.
14250 ;; This is really a hack, because the org-mode table editor uses several
14251 ;; keys which normally belong to the major mode, for example the TAB and
14252 ;; RET keys. Here is how it works: The minor mode defines all the keys
14253 ;; necessary to operate the table editor, but wraps the commands into a
14254 ;; function which tests if the cursor is currently inside a table. If that
14255 ;; is the case, the table editor command is executed. However, when any of
14256 ;; those keys is used outside a table, the function uses `key-binding' to
14257 ;; look up if the key has an associated command in another currently active
14258 ;; keymap (minor modes, major mode, global), and executes that command.
14259 ;; There might be problems if any of the keys used by the table editor is
14260 ;; otherwise used as a prefix key.
14262 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
14263 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
14264 ;; addresses this by checking explicitly for both bindings.
14266 ;; The optimized version (see variable `orgtbl-optimized') takes over
14267 ;; all keys which are bound to `self-insert-command' in the *global map*.
14268 ;; Some modes bind other commands to simple characters, for example
14269 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
14270 ;; active, this binding is ignored inside tables and replaced with a
14271 ;; modified self-insert.
14273 (defvar orgtbl-mode nil
14274 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
14275 table editor in arbitrary modes.")
14276 (make-variable-buffer-local 'orgtbl-mode)
14278 (defvar orgtbl-mode-map (make-keymap)
14279 "Keymap for `orgtbl-mode'.")
14281 ;;;###autoload
14282 (defun turn-on-orgtbl ()
14283 "Unconditionally turn on `orgtbl-mode'."
14284 (orgtbl-mode 1))
14286 ;;;###autoload
14287 (defun orgtbl-mode (&optional arg)
14288 "The `org-mode' table editor as a minor mode for use in other modes."
14289 (interactive)
14290 (if (org-mode-p)
14291 ;; Exit without error, in case some hook functions calls this
14292 ;; by accident in org-mode.
14293 (message "Orgtbl-mode is not useful in org-mode, command ignored")
14294 (setq orgtbl-mode
14295 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
14296 (if orgtbl-mode
14297 (progn
14298 (and (orgtbl-setup) (defun orgtbl-setup () nil))
14299 ;; Make sure we are first in minor-mode-map-alist
14300 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
14301 (and c (setq minor-mode-map-alist
14302 (cons c (delq c minor-mode-map-alist)))))
14303 (org-set-local (quote org-table-may-need-update) t)
14304 (org-add-hook 'before-change-functions 'org-before-change-function
14305 nil 'local)
14306 (org-set-local 'org-old-auto-fill-inhibit-regexp
14307 auto-fill-inhibit-regexp)
14308 (org-set-local 'auto-fill-inhibit-regexp
14309 (if auto-fill-inhibit-regexp
14310 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
14311 "[ \t]*|"))
14312 (org-add-to-invisibility-spec '(org-cwidth))
14313 (easy-menu-add orgtbl-mode-menu)
14314 (run-hooks 'orgtbl-mode-hook))
14315 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
14316 (org-cleanup-narrow-column-properties)
14317 (org-remove-from-invisibility-spec '(org-cwidth))
14318 (remove-hook 'before-change-functions 'org-before-change-function t)
14319 (easy-menu-remove orgtbl-mode-menu)
14320 (force-mode-line-update 'all))))
14322 (defun org-cleanup-narrow-column-properties ()
14323 "Remove all properties related to narrow-column invisibility."
14324 (let ((s 1))
14325 (while (setq s (text-property-any s (point-max)
14326 'display org-narrow-column-arrow))
14327 (remove-text-properties s (1+ s) '(display t)))
14328 (setq s 1)
14329 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
14330 (remove-text-properties s (1+ s) '(org-cwidth t)))
14331 (setq s 1)
14332 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
14333 (remove-text-properties s (1+ s) '(invisible t)))))
14335 ;; Install it as a minor mode.
14336 (put 'orgtbl-mode :included t)
14337 (put 'orgtbl-mode :menu-tag "Org Table Mode")
14338 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
14340 (defun orgtbl-make-binding (fun n &rest keys)
14341 "Create a function for binding in the table minor mode.
14342 FUN is the command to call inside a table. N is used to create a unique
14343 command name. KEYS are keys that should be checked in for a command
14344 to execute outside of tables."
14345 (eval
14346 (list 'defun
14347 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
14348 '(arg)
14349 (concat "In tables, run `" (symbol-name fun) "'.\n"
14350 "Outside of tables, run the binding of `"
14351 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
14352 "'.")
14353 '(interactive "p")
14354 (list 'if
14355 '(org-at-table-p)
14356 (list 'call-interactively (list 'quote fun))
14357 (list 'let '(orgtbl-mode)
14358 (list 'call-interactively
14359 (append '(or)
14360 (mapcar (lambda (k)
14361 (list 'key-binding k))
14362 keys)
14363 '('orgtbl-error))))))))
14365 (defun orgtbl-error ()
14366 "Error when there is no default binding for a table key."
14367 (interactive)
14368 (error "This key is has no function outside tables"))
14370 (defun orgtbl-setup ()
14371 "Setup orgtbl keymaps."
14372 (let ((nfunc 0)
14373 (bindings
14374 (list
14375 '([(meta shift left)] org-table-delete-column)
14376 '([(meta left)] org-table-move-column-left)
14377 '([(meta right)] org-table-move-column-right)
14378 '([(meta shift right)] org-table-insert-column)
14379 '([(meta shift up)] org-table-kill-row)
14380 '([(meta shift down)] org-table-insert-row)
14381 '([(meta up)] org-table-move-row-up)
14382 '([(meta down)] org-table-move-row-down)
14383 '("\C-c\C-w" org-table-cut-region)
14384 '("\C-c\M-w" org-table-copy-region)
14385 '("\C-c\C-y" org-table-paste-rectangle)
14386 '("\C-c-" org-table-insert-hline)
14387 ; '([(shift tab)] org-table-previous-field)
14388 '("\C-m" org-table-next-row)
14389 (list (org-key 'S-return) 'org-table-copy-down)
14390 '([(meta return)] org-table-wrap-region)
14391 '("\C-c\C-q" org-table-wrap-region)
14392 '("\C-c?" org-table-current-column)
14393 '("\C-c " org-table-blank-field)
14394 '("\C-c+" org-table-sum)
14395 '("\C-c=" org-table-eval-formula)
14396 '("\C-c'" org-table-edit-formulas)
14397 '("\C-c`" org-table-edit-field)
14398 '("\C-c*" org-table-recalculate)
14399 '("\C-c|" org-table-create-or-convert-from-region)
14400 '("\C-c^" org-table-sort-lines)
14401 '([(control ?#)] org-table-rotate-recalc-marks)))
14402 elt key fun cmd)
14403 (while (setq elt (pop bindings))
14404 (setq nfunc (1+ nfunc))
14405 (setq key (car elt)
14406 fun (nth 1 elt)
14407 cmd (orgtbl-make-binding fun nfunc key))
14408 (define-key orgtbl-mode-map key cmd))
14409 ;; Special treatment needed for TAB and RET
14410 (define-key orgtbl-mode-map [(return)]
14411 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
14412 (define-key orgtbl-mode-map "\C-m"
14413 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
14414 (define-key orgtbl-mode-map [(tab)]
14415 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
14416 (define-key orgtbl-mode-map "\C-i"
14417 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
14418 (define-key orgtbl-mode-map "\C-i"
14419 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
14420 (define-key orgtbl-mode-map "\C-c\C-c"
14421 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
14422 (when orgtbl-optimized
14423 ;; If the user wants maximum table support, we need to hijack
14424 ;; some standard editing functions
14425 (org-remap orgtbl-mode-map
14426 'self-insert-command 'orgtbl-self-insert-command
14427 'delete-char 'org-delete-char
14428 'delete-backward-char 'org-delete-backward-char)
14429 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
14430 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
14431 '("OrgTbl"
14432 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
14433 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
14434 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
14435 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
14436 "--"
14437 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
14438 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
14439 ["Copy Field from Above"
14440 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
14441 "--"
14442 ("Column"
14443 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
14444 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
14445 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
14446 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
14447 "--"
14448 ["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])
14449 ("Row"
14450 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
14451 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
14452 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
14453 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
14454 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
14455 "--"
14456 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
14457 ("Rectangle"
14458 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
14459 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
14460 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
14461 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
14462 "--"
14463 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
14464 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14465 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
14466 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
14467 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
14468 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
14469 ["Sum Column/Rectangle" org-table-sum
14470 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
14471 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
14472 ["Debug Formulas"
14473 (setq org-table-formula-debug (not org-table-formula-debug))
14474 :style toggle :selected org-table-formula-debug]
14478 (defun orgtbl-tab (arg)
14479 "Justification and field motion for `orgtbl-mode'."
14480 (interactive "P")
14481 (if arg (org-table-edit-field t)
14482 (org-table-justify-field-maybe)
14483 (org-table-next-field)))
14485 (defun orgtbl-ret ()
14486 "Justification and field motion for `orgtbl-mode'."
14487 (interactive)
14488 (org-table-justify-field-maybe)
14489 (org-table-next-row))
14491 (defun orgtbl-self-insert-command (N)
14492 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14493 If the cursor is in a table looking at whitespace, the whitespace is
14494 overwritten, and the table is not marked as requiring realignment."
14495 (interactive "p")
14496 (if (and (org-at-table-p)
14498 (and org-table-auto-blank-field
14499 (member last-command
14500 '(orgtbl-hijacker-command-100
14501 orgtbl-hijacker-command-101
14502 orgtbl-hijacker-command-102
14503 orgtbl-hijacker-command-103
14504 orgtbl-hijacker-command-104
14505 orgtbl-hijacker-command-105))
14506 (org-table-blank-field))
14508 (eq N 1)
14509 (looking-at "[^|\n]* +|"))
14510 (let (org-table-may-need-update)
14511 (goto-char (1- (match-end 0)))
14512 (delete-backward-char 1)
14513 (goto-char (match-beginning 0))
14514 (self-insert-command N))
14515 (setq org-table-may-need-update t)
14516 (let (orgtbl-mode)
14517 (call-interactively (key-binding (vector last-input-event))))))
14519 (defun org-force-self-insert (N)
14520 "Needed to enforce self-insert under remapping."
14521 (interactive "p")
14522 (self-insert-command N))
14524 ;;;; Exporting
14526 (defconst org-level-max 20)
14528 (defvar org-export-html-preamble nil
14529 "Preamble, to be inserted just after <body>. Set by publishing functions.")
14530 (defvar org-export-html-postamble nil
14531 "Preamble, to be inserted just before </body>. Set by publishing functions.")
14532 (defvar org-export-html-auto-preamble t
14533 "Should default preamble be inserted? Set by publishing functions.")
14534 (defvar org-export-html-auto-postamble t
14535 "Should default postamble be inserted? Set by publishing functions.")
14537 (defconst org-export-plist-vars
14538 '((:language . org-export-default-language)
14539 (:customtime . org-display-custom-times)
14540 (:headline-levels . org-export-headline-levels)
14541 (:section-numbers . org-export-with-section-numbers)
14542 (:table-of-contents . org-export-with-toc)
14543 (:archived-trees . org-export-with-archived-trees)
14544 (:emphasize . org-export-with-emphasize)
14545 (:sub-superscript . org-export-with-sub-superscripts)
14546 (:TeX-macros . org-export-with-TeX-macros)
14547 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
14548 (:fixed-width . org-export-with-fixed-width)
14549 (:timestamps . org-export-with-timestamps)
14550 (:tables . org-export-with-tables)
14551 (:table-auto-headline . org-export-highlight-first-table-line)
14552 (:style . org-export-html-style)
14553 (:convert-org-links . org-export-html-link-org-files-as-html)
14554 (:inline-images . org-export-html-inline-images)
14555 (:expand-quoted-html . org-export-html-expand)
14556 (:timestamp . org-export-html-with-timestamp)
14557 (:publishing-directory . org-export-publishing-directory)
14558 (:preamble . org-export-html-preamble)
14559 (:postamble . org-export-html-postamble)
14560 (:auto-preamble . org-export-html-auto-preamble)
14561 (:auto-postamble . org-export-html-auto-postamble)
14562 (:author . user-full-name)
14563 (:email . user-mail-address)))
14565 (defun org-default-export-plist ()
14566 "Return the property list with default settings for the export variables."
14567 (let ((l org-export-plist-vars) rtn e)
14568 (while (setq e (pop l))
14569 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
14570 rtn))
14572 (defun org-infile-export-plist ()
14573 "Return the property list with file-local settings for export."
14574 (save-excursion
14575 (goto-char 0)
14576 (let ((re (org-make-options-regexp
14577 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
14578 p key val text options)
14579 (while (re-search-forward re nil t)
14580 (setq key (org-match-string-no-properties 1)
14581 val (org-match-string-no-properties 2))
14582 (cond
14583 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
14584 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
14585 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
14586 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
14587 ((string-equal key "TEXT")
14588 (setq text (if text (concat text "\n" val) val)))
14589 ((string-equal key "OPTIONS") (setq options val))))
14590 (setq p (plist-put p :text text))
14591 (when options
14592 (let ((op '(("H" . :headline-levels)
14593 ("num" . :section-numbers)
14594 ("toc" . :table-of-contents)
14595 ("\\n" . :preserve-breaks)
14596 ("@" . :expand-quoted-html)
14597 (":" . :fixed-width)
14598 ("|" . :tables)
14599 ("^" . :sub-superscript)
14600 ("*" . :emphasize)
14601 ("TeX" . :TeX-macros)
14602 ("LaTeX" . :LaTeX-fragments)))
14604 (while (setq o (pop op))
14605 (if (string-match (concat (regexp-quote (car o))
14606 ":\\([^ \t\n\r;,.]*\\)")
14607 options)
14608 (setq p (plist-put p (cdr o)
14609 (car (read-from-string
14610 (match-string 1 options)))))))))
14611 p)))
14613 (defun org-combine-plists (&rest plists)
14614 "Create a single property list from all plists in PLISTS.
14615 The process starts by copying the last list, and then setting properties
14616 from the other lists. Settings in the first list are the most significant
14617 ones and overrule settings in the other lists."
14618 (let ((rtn (copy-sequence (pop plists)))
14619 p v ls)
14620 (while plists
14621 (setq ls (pop plists))
14622 (while ls
14623 (setq p (pop ls) v (pop ls))
14624 (setq rtn (plist-put rtn p v))))
14625 rtn))
14627 (defun org-export-directory (type plist)
14628 (let* ((val (plist-get plist :publishing-directory))
14629 (dir (if (listp val)
14630 (or (cdr (assoc type val)) ".")
14631 val)))
14632 dir))
14634 (defun org-export-find-first-heading-line (list)
14635 "Remove all lines from LIST which are before the first headline."
14636 (let ((orig-list list)
14637 (re (concat "^" outline-regexp)))
14638 (while (and list
14639 (not (string-match re (car list))))
14640 (pop list))
14641 (or list orig-list)))
14643 (defun org-skip-comments (lines)
14644 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
14645 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
14646 (re2 "^\\(\\*+\\)[ \t\n\r]")
14647 rtn line level)
14648 (while (setq line (pop lines))
14649 (cond
14650 ((and (string-match re1 line)
14651 (setq level (- (match-end 1) (match-beginning 1))))
14652 ;; Beginning of a COMMENT subtree. Skip it.
14653 (while (and (setq line (pop lines))
14654 (or (not (string-match re2 line))
14655 (> (- (match-end 1) (match-beginning 1)) level))))
14656 (setq lines (cons line lines)))
14657 ((string-match "^#" line)
14658 ;; an ordinary comment line
14660 ((and org-export-table-remove-special-lines
14661 (string-match "^[ \t]*|" line)
14662 (or (string-match "^[ \t]*| *[!_^] *|" line)
14663 (and (string-match "| *<[0-9]+> *|" line)
14664 (not (string-match "| *[^ <|]" line)))))
14665 ;; a special table line that should be removed
14667 (t (setq rtn (cons line rtn)))))
14668 (nreverse rtn)))
14670 (defun org-export (&optional arg)
14671 (interactive)
14672 (let ((help "[t] insert the export option template
14673 \[v] limit export to visible part of outline tree
14675 \[a] export as ASCII
14676 \[h] export as HTML
14677 \[b] export as HTML and browse immediately
14678 \[x] export as XOXO
14680 \[i] export current file as iCalendar file
14681 \[I] export all agenda files as iCalendar files
14682 \[c] export agenda files into combined iCalendar file
14684 \[F] publish current file
14685 \[P] publish current project
14686 \[X] publish... (project will be prompted for)
14687 \[A] publish all projects")
14688 (cmds
14689 '((?t . org-insert-export-options-template)
14690 (?v . org-export-visible)
14691 (?a . org-export-as-ascii)
14692 (?h . org-export-as-html)
14693 (?b . org-export-as-html-and-open)
14694 (?x . org-export-as-xoxo)
14695 (?i . org-export-icalendar-this-file)
14696 (?I . org-export-icalendar-all-agenda-files)
14697 (?c . org-export-icalendar-combine-agenda-files)
14698 (?F . org-publish-current-file)
14699 (?P . org-publish-current-project)
14700 (?X . org-publish)
14701 (?A . org-publish-all)))
14702 r1 r2 ass)
14703 (save-window-excursion
14704 (delete-other-windows)
14705 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
14706 (princ help))
14707 (message "Select command: ")
14708 (setq r1 (read-char-exclusive)))
14709 (setq r2 (if (< r1 27) (+ r1 96) r1))
14710 (if (setq ass (assq r2 cmds))
14711 (call-interactively (cdr ass))
14712 (error "No command associated with key %c" r1))))
14714 ;;; ASCII
14716 (defconst org-html-entities
14717 '(("nbsp")
14718 ("iexcl")
14719 ("cent")
14720 ("pound")
14721 ("curren")
14722 ("yen")
14723 ("brvbar")
14724 ("sect")
14725 ("uml")
14726 ("copy")
14727 ("ordf")
14728 ("laquo")
14729 ("not")
14730 ("shy")
14731 ("reg")
14732 ("macr")
14733 ("deg")
14734 ("plusmn")
14735 ("sup2")
14736 ("sup3")
14737 ("acute")
14738 ("micro")
14739 ("para")
14740 ("middot")
14741 ("odot"."o")
14742 ("star"."*")
14743 ("cedil")
14744 ("sup1")
14745 ("ordm")
14746 ("raquo")
14747 ("frac14")
14748 ("frac12")
14749 ("frac34")
14750 ("iquest")
14751 ("Agrave")
14752 ("Aacute")
14753 ("Acirc")
14754 ("Atilde")
14755 ("Auml")
14756 ("Aring") ("AA"."&Aring;")
14757 ("AElig")
14758 ("Ccedil")
14759 ("Egrave")
14760 ("Eacute")
14761 ("Ecirc")
14762 ("Euml")
14763 ("Igrave")
14764 ("Iacute")
14765 ("Icirc")
14766 ("Iuml")
14767 ("ETH")
14768 ("Ntilde")
14769 ("Ograve")
14770 ("Oacute")
14771 ("Ocirc")
14772 ("Otilde")
14773 ("Ouml")
14774 ("times")
14775 ("Oslash")
14776 ("Ugrave")
14777 ("Uacute")
14778 ("Ucirc")
14779 ("Uuml")
14780 ("Yacute")
14781 ("THORN")
14782 ("szlig")
14783 ("agrave")
14784 ("aacute")
14785 ("acirc")
14786 ("atilde")
14787 ("auml")
14788 ("aring")
14789 ("aelig")
14790 ("ccedil")
14791 ("egrave")
14792 ("eacute")
14793 ("ecirc")
14794 ("euml")
14795 ("igrave")
14796 ("iacute")
14797 ("icirc")
14798 ("iuml")
14799 ("eth")
14800 ("ntilde")
14801 ("ograve")
14802 ("oacute")
14803 ("ocirc")
14804 ("otilde")
14805 ("ouml")
14806 ("divide")
14807 ("oslash")
14808 ("ugrave")
14809 ("uacute")
14810 ("ucirc")
14811 ("uuml")
14812 ("yacute")
14813 ("thorn")
14814 ("yuml")
14815 ("fnof")
14816 ("Alpha")
14817 ("Beta")
14818 ("Gamma")
14819 ("Delta")
14820 ("Epsilon")
14821 ("Zeta")
14822 ("Eta")
14823 ("Theta")
14824 ("Iota")
14825 ("Kappa")
14826 ("Lambda")
14827 ("Mu")
14828 ("Nu")
14829 ("Xi")
14830 ("Omicron")
14831 ("Pi")
14832 ("Rho")
14833 ("Sigma")
14834 ("Tau")
14835 ("Upsilon")
14836 ("Phi")
14837 ("Chi")
14838 ("Psi")
14839 ("Omega")
14840 ("alpha")
14841 ("beta")
14842 ("gamma")
14843 ("delta")
14844 ("epsilon")
14845 ("varepsilon"."&epsilon;")
14846 ("zeta")
14847 ("eta")
14848 ("theta")
14849 ("iota")
14850 ("kappa")
14851 ("lambda")
14852 ("mu")
14853 ("nu")
14854 ("xi")
14855 ("omicron")
14856 ("pi")
14857 ("rho")
14858 ("sigmaf") ("varsigma"."&sigmaf;")
14859 ("sigma")
14860 ("tau")
14861 ("upsilon")
14862 ("phi")
14863 ("chi")
14864 ("psi")
14865 ("omega")
14866 ("thetasym") ("vartheta"."&thetasym;")
14867 ("upsih")
14868 ("piv")
14869 ("bull") ("bullet"."&bull;")
14870 ("hellip") ("dots"."&hellip;")
14871 ("prime")
14872 ("Prime")
14873 ("oline")
14874 ("frasl")
14875 ("weierp")
14876 ("image")
14877 ("real")
14878 ("trade")
14879 ("alefsym")
14880 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
14881 ("uarr") ("uparrow"."&uarr;")
14882 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
14883 ("darr")("downarrow"."&darr;")
14884 ("harr") ("leftrightarrow"."&harr;")
14885 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
14886 ("lArr") ("Leftarrow"."&lArr;")
14887 ("uArr") ("Uparrow"."&uArr;")
14888 ("rArr") ("Rightarrow"."&rArr;")
14889 ("dArr") ("Downarrow"."&dArr;")
14890 ("hArr") ("Leftrightarrow"."&hArr;")
14891 ("forall")
14892 ("part") ("partial"."&part;")
14893 ("exist") ("exists"."&exist;")
14894 ("empty") ("emptyset"."&empty;")
14895 ("nabla")
14896 ("isin") ("in"."&isin;")
14897 ("notin")
14898 ("ni")
14899 ("prod")
14900 ("sum")
14901 ("minus")
14902 ("lowast") ("ast"."&lowast;")
14903 ("radic")
14904 ("prop") ("proptp"."&prop;")
14905 ("infin") ("infty"."&infin;")
14906 ("ang") ("angle"."&ang;")
14907 ("and") ("vee"."&and;")
14908 ("or") ("wedge"."&or;")
14909 ("cap")
14910 ("cup")
14911 ("int")
14912 ("there4")
14913 ("sim")
14914 ("cong") ("simeq"."&cong;")
14915 ("asymp")("approx"."&asymp;")
14916 ("ne") ("neq"."&ne;")
14917 ("equiv")
14918 ("le")
14919 ("ge")
14920 ("sub") ("subset"."&sub;")
14921 ("sup") ("supset"."&sup;")
14922 ("nsub")
14923 ("sube")
14924 ("supe")
14925 ("oplus")
14926 ("otimes")
14927 ("perp")
14928 ("sdot") ("cdot"."&sdot;")
14929 ("lceil")
14930 ("rceil")
14931 ("lfloor")
14932 ("rfloor")
14933 ("lang")
14934 ("rang")
14935 ("loz") ("Diamond"."&loz;")
14936 ("spades") ("spadesuit"."&spades;")
14937 ("clubs") ("clubsuit"."&clubs;")
14938 ("hearts") ("diamondsuit"."&hearts;")
14939 ("diams") ("diamondsuit"."&diams;")
14940 ("quot")
14941 ("amp")
14942 ("lt")
14943 ("gt")
14944 ("OElig")
14945 ("oelig")
14946 ("Scaron")
14947 ("scaron")
14948 ("Yuml")
14949 ("circ")
14950 ("tilde")
14951 ("ensp")
14952 ("emsp")
14953 ("thinsp")
14954 ("zwnj")
14955 ("zwj")
14956 ("lrm")
14957 ("rlm")
14958 ("ndash")
14959 ("mdash")
14960 ("lsquo")
14961 ("rsquo")
14962 ("sbquo")
14963 ("ldquo")
14964 ("rdquo")
14965 ("bdquo")
14966 ("dagger")
14967 ("Dagger")
14968 ("permil")
14969 ("lsaquo")
14970 ("rsaquo")
14971 ("euro")
14973 ("arccos"."arccos")
14974 ("arcsin"."arcsin")
14975 ("arctan"."arctan")
14976 ("arg"."arg")
14977 ("cos"."cos")
14978 ("cosh"."cosh")
14979 ("cot"."cot")
14980 ("coth"."coth")
14981 ("csc"."csc")
14982 ("deg"."deg")
14983 ("det"."det")
14984 ("dim"."dim")
14985 ("exp"."exp")
14986 ("gcd"."gcd")
14987 ("hom"."hom")
14988 ("inf"."inf")
14989 ("ker"."ker")
14990 ("lg"."lg")
14991 ("lim"."lim")
14992 ("liminf"."liminf")
14993 ("limsup"."limsup")
14994 ("ln"."ln")
14995 ("log"."log")
14996 ("max"."max")
14997 ("min"."min")
14998 ("Pr"."Pr")
14999 ("sec"."sec")
15000 ("sin"."sin")
15001 ("sinh"."sinh")
15002 ("sup"."sup")
15003 ("tan"."tan")
15004 ("tanh"."tanh")
15006 "Entities for TeX->HTML translation.
15007 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
15008 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
15009 In that case, \"\\ent\" will be translated to \"&other;\".
15010 The list contains HTML entities for Latin-1, Greek and other symbols.
15011 It is supplemented by a number of commonly used TeX macros with appropriate
15012 translations. There is currently no way for users to extend this.")
15014 (defun org-cleaned-string-for-export (string &rest parameters)
15015 "Cleanup a buffer substring so that links can be created safely."
15016 (interactive)
15017 (let* ((re-radio (and org-target-link-regexp
15018 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
15019 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
15020 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
15021 (re-archive (concat ":" org-archive-tag ":"))
15022 rtn)
15023 (save-excursion
15024 (set-buffer (get-buffer-create " org-mode-tmp"))
15025 (erase-buffer)
15026 (insert string)
15027 (let ((org-inhibit-startup t)) (org-mode))
15028 (untabify (point-min) (point-max))
15030 ;; Get rid of archived trees
15031 (when (not (eq org-export-with-archived-trees t))
15032 (goto-char (point-min))
15033 (while (re-search-forward re-archive nil t)
15034 (if (not (org-on-heading-p))
15035 (org-end-of-subtree t)
15036 (beginning-of-line 1)
15037 (delete-region
15038 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
15039 (org-end-of-subtree t)))))
15041 ;; Find targets in comments and move them out of comments,
15042 ;; but mark them as targets that should be invisible
15043 (goto-char (point-min))
15044 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
15045 (replace-match "\\1(INVISIBLE)"))
15047 ;; Remove comments
15048 (goto-char (point-min))
15049 (while (re-search-forward "^#.*\n?" nil t)
15050 (replace-match ""))
15052 ;; Find matches for radio targets and turn them into internal links
15053 (goto-char (point-min))
15054 (when re-radio
15055 (while (re-search-forward re-radio nil t)
15056 (replace-match "\\1[[\\2]]")))
15058 ;; Find all links that contain a newline and put them into a single line
15059 (goto-char (point-min))
15060 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
15061 (replace-match "\\1 \\3")
15062 (goto-char (match-beginning 0)))
15064 ;; Convert LaTeX fragments to images
15065 (when (memq :LaTeX-fragments parameters)
15066 (org-format-latex
15067 (concat "ltxpng/" (file-name-sans-extension
15068 (file-name-nondirectory
15069 org-current-export-file)))
15070 org-current-export-dir nil "Creating LaTeX image %s"))
15071 (message "Exporting...")
15073 ;; Normalize links: Convert angle and plain links into bracket links
15074 ;; Expand link abbreviations
15075 (goto-char (point-min))
15076 (while (re-search-forward re-plain-link nil t)
15077 (replace-match
15078 (concat
15079 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
15080 t t))
15081 (goto-char (point-min))
15082 (while (re-search-forward re-angle-link nil t)
15083 (replace-match
15084 (concat
15085 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
15086 t t))
15087 (goto-char (point-min))
15088 (while (re-search-forward org-bracket-link-regexp nil t)
15089 (replace-match
15090 (concat "[[" (save-match-data
15091 (org-link-expand-abbrev (match-string 1)))
15093 (if (match-end 3)
15094 (match-string 2)
15095 (concat "[" (match-string 1) "]"))
15096 "]")
15097 t t))
15099 ;; Find multiline emphasis and put them into single line
15100 (when (memq :emph-multiline parameters)
15101 (goto-char (point-min))
15102 (while (re-search-forward org-emph-re nil t)
15103 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
15104 (goto-char (1- (match-end 0)))))
15106 (setq rtn (buffer-string)))
15107 (kill-buffer " org-mode-tmp")
15108 rtn))
15110 (defun org-solidify-link-text (s &optional alist)
15111 "Take link text and make a safe target out of it."
15112 (save-match-data
15113 (let* ((rtn
15114 (mapconcat
15115 'identity
15116 (org-split-string s "[ \t\r\n]+") "--"))
15117 (a (assoc rtn alist)))
15118 (or (cdr a) rtn))))
15120 (defun org-convert-to-odd-levels ()
15121 "Convert an org-mode file with all levels allowed to one with odd levels.
15122 This will leave level 1 alone, convert level 2 to level 3, level 3 to
15123 level 5 etc."
15124 (interactive)
15125 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
15126 (let ((org-odd-levels-only nil) n)
15127 (save-excursion
15128 (goto-char (point-min))
15129 (while (re-search-forward "^\\*\\*+" nil t)
15130 (setq n (1- (length (match-string 0))))
15131 (while (>= (setq n (1- n)) 0)
15132 (org-demote))
15133 (end-of-line 1))))))
15136 (defun org-convert-to-oddeven-levels ()
15137 "Convert an org-mode file with only odd levels to one with odd and even levels.
15138 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
15139 section with an even level, conversion would destroy the structure of the file. An error
15140 is signaled in this case."
15141 (interactive)
15142 (goto-char (point-min))
15143 ;; First check if there are no even levels
15144 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
15145 (org-show-context t)
15146 (error "Not all levels are odd in this file. Conversion not possible."))
15147 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
15148 (let ((org-odd-levels-only nil) n)
15149 (save-excursion
15150 (goto-char (point-min))
15151 (while (re-search-forward "^\\*\\*+" nil t)
15152 (setq n (/ (length (match-string 0)) 2))
15153 (while (>= (setq n (1- n)) 0)
15154 (org-promote))
15155 (end-of-line 1))))))
15157 (defun org-tr-level (n)
15158 "Make N odd if required."
15159 (if org-odd-levels-only (1+ (/ n 2)) n))
15161 (defvar org-last-level nil) ; dynamically scoped variable
15162 (defvar org-ascii-current-indentation nil) ; For communication
15164 (defun org-export-as-ascii (arg)
15165 "Export the outline as a pretty ASCII file.
15166 If there is an active region, export only the region.
15167 The prefix ARG specifies how many levels of the outline should become
15168 underlined headlines. The default is 3."
15169 (interactive "P")
15170 (setq-default org-todo-line-regexp org-todo-line-regexp)
15171 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
15172 (org-infile-export-plist)))
15173 (region
15174 (buffer-substring
15175 (if (org-region-active-p) (region-beginning) (point-min))
15176 (if (org-region-active-p) (region-end) (point-max))))
15177 (custom-times org-display-custom-times)
15178 (lines (org-export-find-first-heading-line
15179 (org-skip-comments
15180 (org-split-string
15181 (org-cleaned-string-for-export region)
15182 "[\r\n]"))))
15183 (org-ascii-current-indentation '(0 . 0))
15184 (org-startup-with-deadline-check nil)
15185 (level 0) line txt
15186 (umax nil)
15187 (case-fold-search nil)
15188 (filename (concat (file-name-as-directory
15189 (org-export-directory :ascii opt-plist))
15190 (file-name-sans-extension
15191 (file-name-nondirectory buffer-file-name))
15192 ".txt"))
15193 (buffer (find-file-noselect filename))
15194 (levels-open (make-vector org-level-max nil))
15195 (odd org-odd-levels-only)
15196 (date (format-time-string "%Y/%m/%d" (current-time)))
15197 (time (format-time-string "%X" (org-current-time)))
15198 (author (plist-get opt-plist :author))
15199 (title (or (plist-get opt-plist :title)
15200 (file-name-sans-extension
15201 (file-name-nondirectory buffer-file-name))))
15202 (email (plist-get opt-plist :email))
15203 (language (plist-get opt-plist :language))
15204 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
15205 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
15206 (text nil)
15207 (todo nil)
15208 (lang-words nil))
15210 (setq org-last-level 1)
15211 (org-init-section-numbers)
15213 (find-file-noselect filename)
15215 (setq lang-words (or (assoc language org-export-language-setup)
15216 (assoc "en" org-export-language-setup)))
15217 (if org-export-ascii-show-new-buffer
15218 (switch-to-buffer-other-window buffer)
15219 (set-buffer buffer))
15220 (erase-buffer)
15221 (fundamental-mode)
15222 ;; create local variables for all options, to make sure all called
15223 ;; functions get the correct information
15224 (mapcar (lambda (x)
15225 (set (make-local-variable (cdr x))
15226 (plist-get opt-plist (car x))))
15227 org-export-plist-vars)
15228 (org-set-local 'org-odd-levels-only odd)
15229 (setq umax (if arg (prefix-numeric-value arg)
15230 org-export-headline-levels))
15232 ;; File header
15233 (if title (org-insert-centered title ?=))
15234 (insert "\n")
15235 (if (or author email)
15236 (insert (concat (nth 1 lang-words) ": " (or author "")
15237 (if email (concat " <" email ">") "")
15238 "\n")))
15239 (if (and date time)
15240 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
15241 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
15243 (insert "\n\n")
15245 (if org-export-with-toc
15246 (progn
15247 (insert (nth 3 lang-words) "\n"
15248 (make-string (length (nth 3 lang-words)) ?=) "\n")
15249 (mapcar '(lambda (line)
15250 (if (string-match org-todo-line-regexp
15251 line)
15252 ;; This is a headline
15253 (progn
15254 (setq level (- (match-end 1) (match-beginning 1))
15255 level (org-tr-level level)
15256 txt (match-string 3 line)
15257 todo
15258 (or (and org-export-mark-todo-in-toc
15259 (match-beginning 2)
15260 (not (equal (match-string 2 line)
15261 org-done-string)))
15262 ; TODO, not DONE
15263 (and org-export-mark-todo-in-toc
15264 (= level umax)
15265 (org-search-todo-below
15266 line lines level))))
15267 (setq txt (org-html-expand-for-ascii txt))
15269 (if (and (memq org-export-with-tags '(not-in-toc nil))
15270 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
15271 (setq txt (replace-match "" t t txt)))
15272 (if (string-match quote-re0 txt)
15273 (setq txt (replace-match "" t t txt)))
15275 (if org-export-with-section-numbers
15276 (setq txt (concat (org-section-number level)
15277 " " txt)))
15278 (if (<= level umax)
15279 (progn
15280 (insert
15281 (make-string (* (1- level) 4) ?\ )
15282 (format (if todo "%s (*)\n" "%s\n") txt))
15283 (setq org-last-level level))
15284 ))))
15285 lines)))
15287 (org-init-section-numbers)
15288 (while (setq line (pop lines))
15289 ;; Remove the quoted HTML tags.
15290 (setq line (org-html-expand-for-ascii line))
15291 ;; Remove targets
15292 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
15293 (setq line (replace-match "" t t line)))
15294 ;; Replace internal links
15295 (while (string-match org-bracket-link-regexp line)
15296 (setq line (replace-match
15297 (if (match-end 3) "[\\3]" "[\\1]")
15298 t nil line)))
15299 (when custom-times
15300 (setq line (org-translate-time line)))
15301 (cond
15302 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
15303 ;; a Headline
15304 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
15305 txt (match-string 2 line))
15306 (org-ascii-level-start level txt umax lines))
15308 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
15309 (normal-mode)
15310 (save-buffer)
15311 ;; remove display and invisible chars
15312 (let (beg end)
15313 (goto-char (point-min))
15314 (while (setq beg (next-single-property-change (point) 'display))
15315 (setq end (next-single-property-change beg 'display))
15316 (delete-region beg end)
15317 (goto-char beg)
15318 (insert "=>"))
15319 (goto-char (point-min))
15320 (while (setq beg (next-single-property-change (point) 'org-cwidth))
15321 (setq end (next-single-property-change beg 'org-cwidth))
15322 (delete-region beg end)
15323 (goto-char beg)))
15324 (goto-char (point-min))))
15326 (defun org-search-todo-below (line lines level)
15327 "Search the subtree below LINE for any TODO entries."
15328 (let ((rest (cdr (memq line lines)))
15329 (re org-todo-line-regexp)
15330 line lv todo)
15331 (catch 'exit
15332 (while (setq line (pop rest))
15333 (if (string-match re line)
15334 (progn
15335 (setq lv (- (match-end 1) (match-beginning 1))
15336 todo (and (match-beginning 2)
15337 (not (equal (match-string 2 line)
15338 org-done-string))))
15339 ; TODO, not DONE
15340 (if (<= lv level) (throw 'exit nil))
15341 (if todo (throw 'exit t))))))))
15343 (defun org-html-expand-for-ascii (line)
15344 "Handle quoted HTML for ASCII export."
15345 (if org-export-html-expand
15346 (while (string-match "@<[^<>\n]*>" line)
15347 ;; We just remove the tags for now.
15348 (setq line (replace-match "" nil nil line))))
15349 line)
15351 (defun org-insert-centered (s &optional underline)
15352 "Insert the string S centered and underline it with character UNDERLINE."
15353 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
15354 (insert (make-string ind ?\ ) s "\n")
15355 (if underline
15356 (insert (make-string ind ?\ )
15357 (make-string (string-width s) underline)
15358 "\n"))))
15360 (defun org-ascii-level-start (level title umax &optional lines)
15361 "Insert a new level in ASCII export."
15362 (let (char (n (- level umax 1)) (ind 0))
15363 (if (> level umax)
15364 (progn
15365 (insert (make-string (* 2 n) ?\ )
15366 (char-to-string (nth (% n (length org-export-ascii-bullets))
15367 org-export-ascii-bullets))
15368 " " title "\n")
15369 ;; find the indentation of the next non-empty line
15370 (catch 'stop
15371 (while lines
15372 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
15373 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
15374 (throw 'stop (setq ind (org-get-indentation (car lines)))))
15375 (pop lines)))
15376 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
15377 (if (or (not (equal (char-before) ?\n))
15378 (not (equal (char-before (1- (point))) ?\n)))
15379 (insert "\n"))
15380 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
15381 (unless org-export-with-tags
15382 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
15383 (setq title (replace-match "" t t title))))
15384 (if org-export-with-section-numbers
15385 (setq title (concat (org-section-number level) " " title)))
15386 (insert title "\n" (make-string (string-width title) char) "\n")
15387 (setq org-ascii-current-indentation '(0 . 0)))))
15389 (defun org-export-visible (type arg)
15390 "Create a copy of the visible part of the current buffer, and export it.
15391 The copy is created in a temporary buffer and removed after use.
15392 TYPE is the final key (as a string) that also select the export command in
15393 the `C-c C-e' export dispatcher.
15394 As a special case, if the you type SPC at the prompt, the temporary
15395 org-mode file will not be removed but presented to you so that you can
15396 continue to use it. The prefix arg ARG is passed through to the exporting
15397 command."
15398 (interactive
15399 (list (progn
15400 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
15401 (read-char-exclusive))
15402 current-prefix-arg))
15403 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
15404 (error "Invalid export key"))
15405 (let* ((binding (cdr (assoc type
15406 '((?a . org-export-as-ascii)
15407 (?\C-a . org-export-as-ascii)
15408 (?b . org-export-as-html-and-open)
15409 (?\C-b . org-export-as-html-and-open)
15410 (?h . org-export-as-html)
15411 (?x . org-export-as-xoxo)))))
15412 (keepp (equal type ?\ ))
15413 (file buffer-file-name)
15414 (buffer (get-buffer-create "*Org Export Visible*"))
15415 s e)
15416 (with-current-buffer buffer (erase-buffer))
15417 (save-excursion
15418 (setq s (goto-char (point-min)))
15419 (while (not (= (point) (point-max)))
15420 (goto-char (org-find-invisible))
15421 (append-to-buffer buffer s (point))
15422 (setq s (goto-char (org-find-visible))))
15423 (goto-char (point-min))
15424 (unless keepp
15425 ;; Copy all comment lines to the end, to make sure #+ settings are
15426 ;; still available for the second export step. Kind of a hack, but
15427 ;; does do the trick.
15428 (if (looking-at "#[^\r\n]*")
15429 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
15430 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
15431 (append-to-buffer buffer (1+ (match-beginning 0))
15432 (min (point-max) (1+ (match-end 0))))))
15433 (set-buffer buffer)
15434 (let ((buffer-file-name file)
15435 (org-inhibit-startup t))
15436 (org-mode)
15437 (show-all)
15438 (unless keepp (funcall binding arg))))
15439 (if (not keepp)
15440 (kill-buffer buffer)
15441 (switch-to-buffer-other-window buffer)
15442 (goto-char (point-min)))))
15444 (defun org-find-visible ()
15445 (let ((s (point)))
15446 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
15447 (get-char-property s 'invisible)))
15449 (defun org-find-invisible ()
15450 (let ((s (point)))
15451 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
15452 (not (get-char-property s 'invisible))))
15455 ;;; HTML
15457 (defun org-get-current-options ()
15458 "Return a string with current options as keyword options.
15459 Does include HTML export options as well as TODO and CATEGORY stuff."
15460 (format
15461 "#+TITLE: %s
15462 #+AUTHOR: %s
15463 #+EMAIL: %s
15464 #+LANGUAGE: %s
15465 #+TEXT: Some descriptive text to be emitted. Several lines OK.
15466 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
15467 #+CATEGORY: %s
15468 #+SEQ_TODO: %s
15469 #+TYP_TODO: %s
15470 #+STARTUP: %s %s %s %s %s %s
15471 #+TAGS: %s
15472 #+ARCHIVE: %s
15473 #+LINK: %s
15475 (buffer-name) (user-full-name) user-mail-address org-export-default-language
15476 org-export-headline-levels
15477 org-export-with-section-numbers
15478 org-export-with-toc
15479 org-export-preserve-breaks
15480 org-export-html-expand
15481 org-export-with-fixed-width
15482 org-export-with-tables
15483 org-export-with-sub-superscripts
15484 org-export-with-emphasize
15485 org-export-with-TeX-macros
15486 org-export-with-LaTeX-fragments
15487 (file-name-nondirectory buffer-file-name)
15488 (if (equal org-todo-interpretation 'sequence)
15489 (mapconcat 'identity org-todo-keywords " ")
15490 "TODO FEEDBACK VERIFY DONE")
15491 (if (equal org-todo-interpretation 'type)
15492 (mapconcat 'identity org-todo-keywords " ")
15493 "Me Jason Marie DONE")
15494 (cdr (assoc org-startup-folded
15495 '((nil . "showall") (t . "overview") (content . "content"))))
15496 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
15497 (if org-odd-levels-only "odd" "oddeven")
15498 (if org-hide-leading-stars "hidestars" "showstars")
15499 (if org-startup-align-all-tables "align" "noalign")
15500 (if org-log-done "logging" "nologging")
15501 (or (mapconcat (lambda (x)
15502 (cond
15503 ((equal '(:startgroup) x) "{")
15504 ((equal '(:endgroup) x) "}")
15505 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
15506 (t (car x))))
15507 (or org-tag-alist (org-get-buffer-tags)) " ") "")
15508 org-archive-location
15509 "org file:~/org/%s.org"
15512 (defun org-insert-export-options-template ()
15513 "Insert into the buffer a template with information for exporting."
15514 (interactive)
15515 (if (not (bolp)) (newline))
15516 (let ((s (org-get-current-options)))
15517 (and (string-match "#\\+CATEGORY" s)
15518 (setq s (substring s 0 (match-beginning 0))))
15519 (insert s)))
15521 (defun org-toggle-fixed-width-section (arg)
15522 "Toggle the fixed-width export.
15523 If there is no active region, the QUOTE keyword at the current headline is
15524 inserted or removed. When present, it causes the text between this headline
15525 and the next to be exported as fixed-width text, and unmodified.
15526 If there is an active region, this command adds or removes a colon as the
15527 first character of this line. If the first character of a line is a colon,
15528 this line is also exported in fixed-width font."
15529 (interactive "P")
15530 (let* ((cc 0)
15531 (regionp (org-region-active-p))
15532 (beg (if regionp (region-beginning) (point)))
15533 (end (if regionp (region-end)))
15534 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15535 (re "[ \t]*\\(:\\)")
15536 off)
15537 (if regionp
15538 (save-excursion
15539 (goto-char beg)
15540 (setq cc (current-column))
15541 (beginning-of-line 1)
15542 (setq off (looking-at re))
15543 (while (> nlines 0)
15544 (setq nlines (1- nlines))
15545 (beginning-of-line 1)
15546 (cond
15547 (arg
15548 (move-to-column cc t)
15549 (insert ":\n")
15550 (forward-line -1))
15551 ((and off (looking-at re))
15552 (replace-match "" t t nil 1))
15553 ((not off) (move-to-column cc t) (insert ":")))
15554 (forward-line 1)))
15555 (save-excursion
15556 (org-back-to-heading)
15557 (if (looking-at (concat outline-regexp
15558 "\\( +\\<" org-quote-string "\\>\\)"))
15559 (replace-match "" t t nil 1)
15560 (if (looking-at outline-regexp)
15561 (progn
15562 (goto-char (match-end 0))
15563 (insert " " org-quote-string))))))))
15565 (defun org-export-as-html-and-open (arg)
15566 "Export the outline as HTML and immediately open it with a browser.
15567 If there is an active region, export only the region.
15568 The prefix ARG specifies how many levels of the outline should become
15569 headlines. The default is 3. Lower levels will become bulleted lists."
15570 (interactive "P")
15571 (org-export-as-html arg 'hidden)
15572 (org-open-file buffer-file-name))
15574 (defun org-export-as-html-batch ()
15575 "Call `org-export-as-html', may be used in batch processing as
15576 emacs --batch
15577 --load=$HOME/lib/emacs/org.el
15578 --eval \"(setq org-export-headline-levels 2)\"
15579 --visit=MyFile --funcall org-export-as-html-batch"
15580 (org-export-as-html org-export-headline-levels 'hidden))
15582 (defun org-export-as-html (arg &optional hidden ext-plist)
15583 "Export the outline as a pretty HTML file.
15584 If there is an active region, export only the region.
15585 The prefix ARG specifies how many levels of the outline should become
15586 headlines. The default is 3. Lower levels will become bulleted lists.
15587 When HIDDEN is non-nil, don't display the HTML buffer.
15588 EXT-PLIST is a property list with external parameters overriding
15589 org-mode's default settings, but still inferior to file-local settings."
15590 (interactive "P")
15591 (message "Exporting...")
15592 (setq-default org-todo-line-regexp org-todo-line-regexp)
15593 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
15594 (setq-default org-done-string org-done-string)
15595 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
15596 ext-plist
15597 (org-infile-export-plist)))
15599 (style (plist-get opt-plist :style))
15600 (link-validate (plist-get opt-plist :link-validation-function))
15601 valid
15602 (odd org-odd-levels-only)
15603 (region-p (org-region-active-p))
15604 (region
15605 (buffer-substring
15606 (if region-p (region-beginning) (point-min))
15607 (if region-p (region-end) (point-max))))
15608 ;; The following two are dynamically scoped into other
15609 ;; routines below.
15610 (org-current-export-dir (org-export-directory :html opt-plist))
15611 (org-current-export-file buffer-file-name)
15612 (all_lines
15613 (org-skip-comments (org-split-string
15614 (org-cleaned-string-for-export
15615 region :emph-multiline
15616 (if (plist-get opt-plist :LaTeX-fragments)
15617 :LaTeX-fragments))
15618 "[\r\n]")))
15619 (lines (org-export-find-first-heading-line all_lines))
15620 (level 0) (line "") (origline "") txt todo
15621 (umax nil)
15622 (filename (concat (file-name-as-directory
15623 (org-export-directory :html opt-plist))
15624 (file-name-sans-extension
15625 (file-name-nondirectory buffer-file-name))
15626 ".html"))
15627 (current-dir (file-name-directory buffer-file-name))
15628 (buffer (find-file-noselect filename))
15629 (levels-open (make-vector org-level-max nil))
15630 (date (format-time-string "%Y/%m/%d" (current-time)))
15631 (time (format-time-string "%X" (org-current-time)))
15632 (author (plist-get opt-plist :author))
15633 (title (or (plist-get opt-plist :title)
15634 (file-name-sans-extension
15635 (file-name-nondirectory buffer-file-name))))
15636 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
15637 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
15638 (inquote nil)
15639 (infixed nil)
15640 (in-local-list nil)
15641 (local-list-num nil)
15642 (local-list-indent nil)
15643 (llt org-plain-list-ordered-item-terminator)
15644 (email (plist-get opt-plist :email))
15645 (language (plist-get opt-plist :language))
15646 (text (plist-get opt-plist :text))
15647 (lang-words nil)
15648 (target-alist nil) tg
15649 (head-count 0) cnt
15650 (start 0)
15651 (coding-system (and (boundp 'buffer-file-coding-system)
15652 buffer-file-coding-system))
15653 (coding-system-for-write coding-system)
15654 (save-buffer-coding-system coding-system)
15655 (charset (and coding-system
15656 (fboundp 'coding-system-get)
15657 (coding-system-get coding-system 'mime-charset)))
15658 table-open type
15659 table-buffer table-orig-buffer
15660 ind start-is-num starter
15661 rpl path desc descp desc1 desc2 link
15663 (message "Exporting...")
15665 (setq org-last-level 1)
15666 (org-init-section-numbers)
15668 ;; Get the language-dependent settings
15669 (setq lang-words (or (assoc language org-export-language-setup)
15670 (assoc "en" org-export-language-setup)))
15672 ;; Switch to the output buffer
15673 (if (or hidden (not org-export-html-show-new-buffer))
15674 (set-buffer buffer)
15675 (switch-to-buffer-other-window buffer))
15676 (erase-buffer)
15677 (fundamental-mode)
15678 (let ((case-fold-search nil)
15679 (org-odd-levels-only odd))
15680 ;; create local variables for all options, to make sure all called
15681 ;; functions get the correct information
15682 (mapcar (lambda (x)
15683 (set (make-local-variable (cdr x))
15684 (plist-get opt-plist (car x))))
15685 org-export-plist-vars)
15686 (setq umax (if arg (prefix-numeric-value arg)
15687 org-export-headline-levels))
15689 ;; File header
15690 (insert (format
15691 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
15692 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
15693 <html xmlns=\"http://www.w3.org/1999/xhtml\"
15694 lang=\"%s\" xml:lang=\"%s\">
15695 <head>
15696 <title>%s</title>
15697 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
15698 <meta name=\"generator\" content=\"Org-mode\"/>
15699 <meta name=\"generated\" content=\"%s %s\"/>
15700 <meta name=\"author\" content=\"%s\"/>
15702 </head><body>
15704 language language (org-html-expand title) (or charset "iso-8859-1")
15705 date time author style))
15708 (insert (or (plist-get opt-plist :preamble) ""))
15710 (when (plist-get opt-plist :auto-preamble)
15711 (if title (insert (format org-export-html-title-format
15712 (org-html-expand title))))
15713 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
15715 (if org-export-with-toc
15716 (progn
15717 (insert (format "<h%d>%s</h%d>\n"
15718 org-export-html-toplevel-hlevel
15719 (nth 3 lang-words)
15720 org-export-html-toplevel-hlevel))
15721 (insert "<ul>\n<li>")
15722 (setq lines
15723 (mapcar '(lambda (line)
15724 (if (string-match org-todo-line-regexp line)
15725 ;; This is a headline
15726 (progn
15727 (setq level (- (match-end 1) (match-beginning 1))
15728 level (org-tr-level level)
15729 txt (save-match-data
15730 (org-html-expand
15731 (org-export-cleanup-toc-line
15732 (match-string 3 line))))
15733 todo
15734 (or (and org-export-mark-todo-in-toc
15735 (match-beginning 2)
15736 (not (equal (match-string 2 line)
15737 org-done-string)))
15738 ; TODO, not DONE
15739 (and org-export-mark-todo-in-toc
15740 (= level umax)
15741 (org-search-todo-below
15742 line lines level))))
15743 (if (and (memq org-export-with-tags '(not-in-toc nil))
15744 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
15745 (setq txt (replace-match "" t t txt)))
15746 (if (string-match quote-re0 txt)
15747 (setq txt (replace-match "" t t txt)))
15748 (if org-export-with-section-numbers
15749 (setq txt (concat (org-section-number level)
15750 " " txt)))
15751 (if (<= level umax)
15752 (progn
15753 (setq head-count (+ head-count 1))
15754 (if (> level org-last-level)
15755 (progn
15756 (setq cnt (- level org-last-level))
15757 (while (>= (setq cnt (1- cnt)) 0)
15758 (insert "\n<ul>\n<li>"))
15759 (insert "\n")))
15760 (if (< level org-last-level)
15761 (progn
15762 (setq cnt (- org-last-level level))
15763 (while (>= (setq cnt (1- cnt)) 0)
15764 (insert "</li>\n</ul>"))
15765 (insert "\n")))
15766 ;; Check for targets
15767 (while (string-match org-target-regexp line)
15768 (setq tg (match-string 1 line)
15769 line (replace-match
15770 (concat "@<span class=\"target\">" tg "@</span> ")
15771 t t line))
15772 (push (cons (org-solidify-link-text tg)
15773 (format "sec-%d" head-count))
15774 target-alist))
15775 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
15776 (setq txt (replace-match "" t t txt)))
15777 (insert
15778 (format
15779 (if todo
15780 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
15781 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
15782 head-count txt))
15784 (setq org-last-level level))
15786 line)
15787 lines))
15788 (while (> org-last-level 0)
15789 (setq org-last-level (1- org-last-level))
15790 (insert "</li>\n</ul>\n"))
15792 (setq head-count 0)
15793 (org-init-section-numbers)
15795 (while (setq line (pop lines) origline line)
15796 (catch 'nextline
15798 ;; end of quote section?
15799 (when (and inquote (string-match "^\\*+" line))
15800 (insert "</pre>\n")
15801 (setq inquote nil))
15802 ;; inside a quote section?
15803 (when inquote
15804 (insert (org-html-protect line) "\n")
15805 (throw 'nextline nil))
15807 ;; verbatim lines
15808 (when (and org-export-with-fixed-width
15809 (string-match "^[ \t]*:\\(.*\\)" line))
15810 (when (not infixed)
15811 (setq infixed t)
15812 (insert "<pre>\n"))
15813 (insert (org-html-protect (match-string 1 line)) "\n")
15814 (when (and lines
15815 (not (string-match "^[ \t]*\\(:.*\\)"
15816 (car lines))))
15817 (setq infixed nil)
15818 (insert "</pre>\n"))
15819 (throw 'nextline nil))
15822 ;; make targets to anchors
15823 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
15824 (cond
15825 ((match-end 2)
15826 (setq line (replace-match
15827 (concat "@<a name=\""
15828 (org-solidify-link-text (match-string 1 line))
15829 "\">\\nbsp@</a>")
15830 t t line)))
15831 ((and org-export-with-toc (equal (string-to-char line) ?*))
15832 (setq line (replace-match
15833 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
15834 ; (concat "@<i>" (match-string 1 line) "@</i> ")
15835 t t line)))
15837 (setq line (replace-match
15838 (concat "@<a name=\""
15839 (org-solidify-link-text (match-string 1 line))
15840 "\" class=\"target\">" (match-string 1 line) "@</a> ")
15841 t t line)))))
15843 (setq line (org-html-handle-time-stamps line))
15845 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
15846 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
15847 ;; Also handle sub_superscripts and checkboxes
15848 (setq line (org-html-expand line))
15850 ;; Format the links
15851 (setq start 0)
15852 (while (string-match org-bracket-link-analytic-regexp line start)
15853 (setq start (match-beginning 0))
15854 (setq type (if (match-end 2) (match-string 2 line) "internal"))
15855 (setq path (match-string 3 line))
15856 (setq desc1 (if (match-end 5) (match-string 5 line))
15857 desc2 (if (match-end 2) (concat type ":" path) path)
15858 descp (and desc1 (not (equal desc1 desc2)))
15859 desc (or desc1 desc2))
15860 ;; FIXME: do we need to unescape here somewhere?
15861 (cond
15862 ((equal type "internal")
15863 (setq rpl
15864 (concat
15865 "<a href=\"#"
15866 (org-solidify-link-text path target-alist)
15867 "\">" desc "</a>")))
15868 ((member type '("http" "https" "ftp" "mailto" "news"))
15869 ;; standard URL
15870 (setq link (concat type ":" path))
15871 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
15872 ((string= type "file")
15873 ;; FILE link
15874 (let* ((filename path)
15875 (abs-p (file-name-absolute-p filename))
15876 thefile file-is-image-p search)
15877 (save-match-data
15878 (if (string-match "::\\(.*\\)" filename)
15879 (setq search (match-string 1 filename)
15880 filename (replace-match "" t nil filename)))
15881 (setq valid
15882 (if (functionp link-validate)
15883 (funcall link-validate filename current-dir)
15885 (setq file-is-image-p
15886 (string-match (org-image-file-name-regexp) filename))
15887 (setq thefile (if abs-p (expand-file-name filename) filename))
15888 (when (and org-export-html-link-org-files-as-html
15889 (string-match "\\.org$" thefile))
15890 (setq thefile (concat (substring thefile 0
15891 (match-beginning 0))
15892 ".html"))
15893 (if (and search
15894 ;; make sure this is can be used as target search
15895 (not (string-match "^[0-9]*$" search))
15896 (not (string-match "^\\*" search))
15897 (not (string-match "^/.*/$" search)))
15898 (setq thefile (concat thefile "#"
15899 (org-solidify-link-text
15900 (org-link-unescape search)))))
15901 (when (string-match "^file:" desc)
15902 (setq desc (replace-match "" t t desc))
15903 (if (string-match "\\.org$" desc)
15904 (setq desc (replace-match "" t t desc))))))
15905 (setq rpl (if (and file-is-image-p
15906 (or (eq t org-export-html-inline-images)
15907 (and org-export-html-inline-images
15908 (not descp))))
15909 (concat "<img src=\"" thefile "\"/>")
15910 (concat "<a href=\"" thefile "\">" desc "</a>")))
15911 (if (not valid) (setq rpl desc))))
15912 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
15913 (setq rpl (concat "<i>&lt;" type ":"
15914 (save-match-data (org-link-unescape path))
15915 "&gt;</i>"))))
15916 (setq line (replace-match rpl t t line)
15917 start (+ start (length rpl))))
15918 ;; TODO items
15919 (if (and (string-match org-todo-line-regexp line)
15920 (match-beginning 2))
15921 (if (equal (match-string 2 line) org-done-string)
15922 (setq line (replace-match
15923 "<span class=\"done\">\\2</span>"
15924 t nil line 2))
15925 (setq line (replace-match "<span class=\"todo\">\\2</span>"
15926 t nil line 2))))
15928 (cond
15929 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
15930 ;; This is a headline
15931 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
15932 txt (match-string 2 line))
15933 (if (string-match quote-re0 txt)
15934 (setq txt (replace-match "" t t txt)))
15935 (if (<= level umax) (setq head-count (+ head-count 1)))
15936 (when in-local-list
15937 ;; Close any local lists before inserting a new header line
15938 (while local-list-num
15939 (org-close-li)
15940 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
15941 (pop local-list-num))
15942 (setq local-list-indent nil
15943 in-local-list nil))
15944 (org-html-level-start level txt umax
15945 (and org-export-with-toc (<= level umax))
15946 head-count)
15947 ;; QUOTES
15948 (when (string-match quote-re line)
15949 (insert "<pre>")
15950 (setq inquote t)))
15952 ((and org-export-with-tables
15953 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
15954 (if (not table-open)
15955 ;; New table starts
15956 (setq table-open t table-buffer nil table-orig-buffer nil))
15957 ;; Accumulate lines
15958 (setq table-buffer (cons line table-buffer)
15959 table-orig-buffer (cons origline table-orig-buffer))
15960 (when (or (not lines)
15961 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
15962 (car lines))))
15963 (setq table-open nil
15964 table-buffer (nreverse table-buffer)
15965 table-orig-buffer (nreverse table-orig-buffer))
15966 (org-close-par-maybe)
15967 (insert (org-format-table-html table-buffer table-orig-buffer))))
15969 ;; Normal lines
15970 (when (string-match
15971 (cond
15972 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
15973 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
15974 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
15975 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
15976 line)
15977 (setq ind (org-get-string-indentation line)
15978 start-is-num (match-beginning 4)
15979 starter (if (match-beginning 2)
15980 (substring (match-string 2 line) 0 -1))
15981 line (substring line (match-beginning 5)))
15982 (unless (string-match "[^ \t]" line)
15983 ;; empty line. Pretend indentation is large.
15984 (setq ind (1+ (or (car local-list-indent) 1))))
15985 (while (and in-local-list
15986 (or (and (= ind (car local-list-indent))
15987 (not starter))
15988 (< ind (car local-list-indent))))
15989 (org-close-li)
15990 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
15991 (pop local-list-num) (pop local-list-indent)
15992 (setq in-local-list local-list-indent))
15993 (cond
15994 ((and starter
15995 (or (not in-local-list)
15996 (> ind (car local-list-indent))))
15997 ;; Start new (level of ) list
15998 (org-close-par-maybe)
15999 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
16000 (push start-is-num local-list-num)
16001 (push ind local-list-indent)
16002 (setq in-local-list t))
16003 (starter
16004 ;; continue current list
16005 (org-close-li)
16006 (insert "<li>\n")))
16007 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
16008 (setq line
16009 (replace-match
16010 (if (equal (match-string 1 line) "X")
16011 "<b>[X]</b>"
16012 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
16013 t t line))))
16015 ;; Empty lines start a new paragraph. If hand-formatted lists
16016 ;; are not fully interpreted, lines starting with "-", "+", "*"
16017 ;; also start a new paragraph.
16018 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
16020 ;; Check if the line break needs to be conserved
16021 (cond
16022 ((string-match "\\\\\\\\[ \t]*$" line)
16023 (setq line (replace-match "<br/>" t t line)))
16024 (org-export-preserve-breaks
16025 (setq line (concat line "<br/>"))))
16027 (insert line "\n")))))
16029 ;; Properly close all local lists and other lists
16030 (when inquote (insert "</pre>\n"))
16031 (when in-local-list
16032 ;; Close any local lists before inserting a new header line
16033 (while local-list-num
16034 (org-close-li)
16035 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
16036 (pop local-list-num))
16037 (setq local-list-indent nil
16038 in-local-list nil))
16039 (org-html-level-start 1 nil umax
16040 (and org-export-with-toc (<= level umax))
16041 head-count)
16043 (when (plist-get opt-plist :auto-postamble)
16044 (when author
16045 (insert "<p class=\"author\"> "
16046 (nth 1 lang-words) ": " author "\n")
16047 (when email
16048 (insert "<a href=\"mailto:" email "\">&lt;"
16049 email "&gt;</a>\n"))
16050 (insert "</p>\n"))
16051 (when (and date time)
16052 (insert "<p class=\"date\"> "
16053 (nth 2 lang-words) ": "
16054 date " " time "</p>\n")))
16056 (if org-export-html-with-timestamp
16057 (insert org-export-html-html-helper-timestamp))
16058 (insert (or (plist-get opt-plist :postamble) ""))
16059 (insert "</body>\n</html>\n")
16060 (normal-mode)
16061 ;; remove empty paragraphs and lists
16062 (goto-char (point-min))
16063 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
16064 (replace-match ""))
16065 (goto-char (point-min))
16066 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
16067 (replace-match ""))
16068 (save-buffer)
16069 (goto-char (point-min))
16070 (message "Exporting... done"))))
16073 (defun org-format-table-html (lines olines)
16074 "Find out which HTML converter to use and return the HTML code."
16075 (if (string-match "^[ \t]*|" (car lines))
16076 ;; A normal org table
16077 (org-format-org-table-html lines)
16078 ;; Table made by table.el - test for spanning
16079 (let* ((hlines (delq nil (mapcar
16080 (lambda (x)
16081 (if (string-match "^[ \t]*\\+-" x) x
16082 nil))
16083 lines)))
16084 (first (car hlines))
16085 (ll (and (string-match "\\S-+" first)
16086 (match-string 0 first)))
16087 (re (concat "^[ \t]*" (regexp-quote ll)))
16088 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
16089 hlines))))
16090 (if (and (not spanning)
16091 (not org-export-prefer-native-exporter-for-tables))
16092 ;; We can use my own converter with HTML conversions
16093 (org-format-table-table-html lines)
16094 ;; Need to use the code generator in table.el, with the original text.
16095 (org-format-table-table-html-using-table-generate-source olines)))))
16097 (defun org-format-org-table-html (lines)
16098 "Format a table into HTML."
16099 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
16100 (setq lines (nreverse lines))
16101 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
16102 (setq lines (nreverse lines))
16103 (when org-export-table-remove-special-lines
16104 ;; Check if the table has a marking column. If yes remove the
16105 ;; column and the special lines
16106 (let* ((special
16107 (not
16108 (memq nil
16109 (mapcar
16110 (lambda (x)
16111 (or (string-match "^[ \t]*|-" x)
16112 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
16113 lines)))))
16114 (if special
16115 (setq lines
16116 (delq nil
16117 (mapcar
16118 (lambda (x)
16119 (if (string-match "^[ \t]*| *[!_^] *|" x)
16120 nil ; ignore this line
16121 (and (or (string-match "^[ \t]*|-+\\+" x)
16122 (string-match "^[ \t]*|[^|]*|" x))
16123 (replace-match "|" t t x))))
16124 lines))))))
16126 (let ((head (and org-export-highlight-first-table-line
16127 (delq nil (mapcar
16128 (lambda (x) (string-match "^[ \t]*|-" x))
16129 (cdr lines)))))
16130 line fields html)
16131 (setq html (concat org-export-html-table-tag "\n"))
16132 (while (setq line (pop lines))
16133 (catch 'next-line
16134 (if (string-match "^[ \t]*|-" line)
16135 (progn
16136 (setq head nil) ;; head ends here, first time around
16137 ;; ignore this line
16138 (throw 'next-line t)))
16139 ;; Break the line into fields
16140 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
16141 (setq html (concat
16142 html
16143 "<tr>"
16144 (mapconcat (lambda (x)
16145 (if head
16146 (concat "<th>" x "</th>")
16147 (concat "<td>" x "</td>")))
16148 fields "")
16149 "</tr>\n"))))
16150 (setq html (concat html "</table>\n"))
16151 html))
16153 (defun org-fake-empty-table-line (line)
16154 "Replace everything except \"|\" with spaces."
16155 (let ((i (length line))
16156 (newstr (copy-sequence line)))
16157 (while (> i 0)
16158 (setq i (1- i))
16159 (if (not (eq (aref newstr i) ?|))
16160 (aset newstr i ?\ )))
16161 newstr))
16163 (defun org-format-table-table-html (lines)
16164 "Format a table generated by table.el into HTML.
16165 This conversion does *not* use `table-generate-source' from table.el.
16166 This has the advantage that Org-mode's HTML conversions can be used.
16167 But it has the disadvantage, that no cell- or row-spanning is allowed."
16168 (let (line field-buffer
16169 (head org-export-highlight-first-table-line)
16170 fields html empty)
16171 (setq html (concat org-export-html-table-tag "\n"))
16172 (while (setq line (pop lines))
16173 (setq empty "&nbsp;")
16174 (catch 'next-line
16175 (if (string-match "^[ \t]*\\+-" line)
16176 (progn
16177 (if field-buffer
16178 (progn
16179 (setq html (concat
16180 html
16181 "<tr>"
16182 (mapconcat
16183 (lambda (x)
16184 (if (equal x "") (setq x empty))
16185 (if head
16186 (concat "<th>" x "</th>\n")
16187 (concat "<td>" x "</td>\n")))
16188 field-buffer "\n")
16189 "</tr>\n"))
16190 (setq head nil)
16191 (setq field-buffer nil)))
16192 ;; Ignore this line
16193 (throw 'next-line t)))
16194 ;; Break the line into fields and store the fields
16195 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
16196 (if field-buffer
16197 (setq field-buffer (mapcar
16198 (lambda (x)
16199 (concat x "<br/>" (pop fields)))
16200 field-buffer))
16201 (setq field-buffer fields))))
16202 (setq html (concat html "</table>\n"))
16203 html))
16205 (defun org-format-table-table-html-using-table-generate-source (lines)
16206 "Format a table into html, using `table-generate-source' from table.el.
16207 This has the advantage that cell- or row-spanning is allowed.
16208 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
16209 (require 'table)
16210 (with-current-buffer (get-buffer-create " org-tmp1 ")
16211 (erase-buffer)
16212 (insert (mapconcat 'identity lines "\n"))
16213 (goto-char (point-min))
16214 (if (not (re-search-forward "|[^+]" nil t))
16215 (error "Error processing table"))
16216 (table-recognize-table)
16217 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
16218 (table-generate-source 'html " org-tmp2 ")
16219 (set-buffer " org-tmp2 ")
16220 (buffer-substring (point-min) (point-max))))
16222 (defun org-html-handle-time-stamps (s)
16223 "Format time stamps in string S, or remove them."
16224 (catch 'exit
16225 (let (r b)
16226 (while (string-match org-maybe-keyword-time-regexp s)
16227 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
16228 ;; never export CLOCK
16229 (throw 'exit ""))
16230 (or b (setq b (substring s 0 (match-beginning 0))))
16231 (if (not org-export-with-timestamps)
16232 (setq r (concat r (substring s 0 (match-beginning 0)))
16233 s (substring s (match-end 0)))
16234 (setq r (concat
16235 r (substring s 0 (match-beginning 0))
16236 (if (match-end 1)
16237 (format "@<span class=\"timestamp-kwd\">%s @</span>"
16238 (match-string 1 s)))
16239 (format " @<span class=\"timestamp\">%s@</span>"
16240 (substring
16241 (org-translate-time (match-string 3 s)) 1 -1)))
16242 s (substring s (match-end 0)))))
16243 ;; Line break if line started and ended with time stamp stuff
16244 (if (not r)
16246 (setq r (concat r s))
16247 (unless (string-match "\\S-" (concat b s))
16248 (setq r (concat r "@<br/>")))
16249 r))))
16251 (defun org-html-protect (s)
16252 ;; convert & to &amp;, < to &lt; and > to &gt;
16253 (let ((start 0))
16254 (while (string-match "&" s start)
16255 (setq s (replace-match "&amp;" t t s)
16256 start (1+ (match-beginning 0))))
16257 (while (string-match "<" s)
16258 (setq s (replace-match "&lt;" t t s)))
16259 (while (string-match ">" s)
16260 (setq s (replace-match "&gt;" t t s))))
16263 (defun org-export-cleanup-toc-line (s)
16264 "Remove tags and time staps from lines going into the toc."
16265 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
16266 (setq s (replace-match "" t t s)))
16267 (when org-export-remove-timestamps-from-toc
16268 (while (string-match org-maybe-keyword-time-regexp s)
16269 (setq s (replace-match "" t t s))))
16272 (defun org-html-expand (string)
16273 "Prepare STRING for HTML export. Applies all active conversions.
16274 If there are links in the string, don't modify these."
16275 (let* (m s l res)
16276 (while (setq m (string-match org-bracket-link-regexp string))
16277 (setq s (substring string 0 m)
16278 l (match-string 0 string)
16279 string (substring string (match-end 0)))
16280 (push (org-html-do-expand s) res)
16281 (push l res))
16282 (push (org-html-do-expand string) res)
16283 (apply 'concat (nreverse res))))
16285 (defun org-html-do-expand (s)
16286 "Apply all active conversions to translate special ASCII to HTML."
16287 (setq s (org-html-protect s))
16288 (if org-export-html-expand
16289 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
16290 (setq s (replace-match "<\\1>" t nil s))))
16291 (if org-export-with-emphasize
16292 (setq s (org-export-html-convert-emphasize s)))
16293 (if org-export-with-sub-superscripts
16294 (setq s (org-export-html-convert-sub-super s)))
16295 (if org-export-with-TeX-macros
16296 (let ((start 0) wd ass)
16297 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
16298 (setq wd (match-string 1 s))
16299 (if (setq ass (assoc wd org-html-entities))
16300 (setq s (replace-match (or (cdr ass)
16301 (concat "&" (car ass) ";"))
16302 t t s))
16303 (setq start (+ start (length wd)))))))
16306 (defun org-create-multibrace-regexp (left right n)
16307 "Create a regular expression which will match a balanced sexp.
16308 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
16309 as single character strings.
16310 The regexp returned will match the entire expression including the
16311 delimiters. It will also define a single group which contains the
16312 match except for the outermost delimiters. The maximum depth of
16313 stacked delimiters is N. Escaping delimiters is not possible."
16314 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
16315 (or "\\|")
16316 (re nothing)
16317 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
16318 (while (> n 1)
16319 (setq n (1- n)
16320 re (concat re or next)
16321 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
16322 (concat left "\\(" re "\\)" right)))
16324 (defvar org-match-substring-regexp
16325 (concat
16326 "\\([^\\]\\)\\([_^]\\)\\("
16327 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
16328 "\\|"
16329 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
16330 "\\|"
16331 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
16332 "The regular expression matching a sub- or superscript.")
16334 (defun org-export-html-convert-sub-super (string)
16335 "Convert sub- and superscripts in STRING to HTML."
16336 (let (key c)
16337 (while (string-match org-match-substring-regexp string)
16338 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
16339 (setq c (or (match-string 8 string)
16340 (match-string 6 string)
16341 (match-string 5 string)))
16342 (setq string (replace-match
16343 (concat (match-string 1 string)
16344 "<" key ">" c "</" key ">")
16345 t t string)))
16346 (while (string-match "\\\\\\([_^]\\)" string)
16347 (setq string (replace-match (match-string 1 string) t t string))))
16348 string)
16350 (defun org-export-html-convert-emphasize (string)
16351 "Apply emphasis."
16352 (while (string-match org-emph-re string)
16353 (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)))
16354 string)
16356 (defvar org-par-open nil)
16357 (defun org-open-par ()
16358 "Insert <p>, but first close previous paragraph if any."
16359 (org-close-par-maybe)
16360 (insert "\n<p>")
16361 (setq org-par-open t))
16362 (defun org-close-par-maybe ()
16363 "Close paragraph if there is one open."
16364 (when org-par-open
16365 (insert "</p>")
16366 (setq org-par-open nil)))
16367 (defun org-close-li ()
16368 "Close <li> if necessary."
16369 (org-close-par-maybe)
16370 (insert "</li>\n"))
16371 ; (when (save-excursion
16372 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
16373 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
16374 ; (insert "</li>"))))
16376 (defun org-html-level-start (level title umax with-toc head-count)
16377 "Insert a new level in HTML export.
16378 When TITLE is nil, just close all open levels."
16379 (org-close-par-maybe)
16380 (let ((l (1+ (max level umax))))
16381 (while (<= l org-level-max)
16382 (if (aref levels-open (1- l))
16383 (progn
16384 (org-html-level-close l)
16385 (aset levels-open (1- l) nil)))
16386 (setq l (1+ l)))
16387 (when title
16388 ;; If title is nil, this means this function is called to close
16389 ;; all levels, so the rest is done only if title is given
16390 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
16391 (setq title (replace-match
16392 (if org-export-with-tags
16393 (save-match-data
16394 (concat
16395 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
16396 (mapconcat 'identity (org-split-string
16397 (match-string 1 title) ":")
16398 "&nbsp;")
16399 "</span>"))
16401 t t title)))
16402 (if (> level umax)
16403 (progn
16404 (if (aref levels-open (1- level))
16405 (progn
16406 (org-close-li)
16407 (insert "<li>" title "<br/>\n"))
16408 (aset levels-open (1- level) t)
16409 (org-close-par-maybe)
16410 (insert "<ul>\n<li>" title "<br/>\n")))
16411 (if org-export-with-section-numbers
16412 (setq title (concat (org-section-number level) " " title)))
16413 (setq level (+ level org-export-html-toplevel-hlevel -1))
16414 (if with-toc
16415 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
16416 level head-count title level))
16417 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
16418 (org-open-par)))))
16420 (defun org-html-level-close (&rest args)
16421 "Terminate one level in HTML export."
16422 (org-close-li)
16423 (insert "</ul>"))
16425 ;; Variable holding the vector with section numbers
16426 (defvar org-section-numbers (make-vector org-level-max 0))
16428 (defun org-init-section-numbers ()
16429 "Initialize the vector for the section numbers."
16430 (let* ((level -1)
16431 (numbers (nreverse (org-split-string "" "\\.")))
16432 (depth (1- (length org-section-numbers)))
16433 (i depth) number-string)
16434 (while (>= i 0)
16435 (if (> i level)
16436 (aset org-section-numbers i 0)
16437 (setq number-string (or (car numbers) "0"))
16438 (if (string-match "\\`[A-Z]\\'" number-string)
16439 (aset org-section-numbers i
16440 (- (string-to-char number-string) ?A -1))
16441 (aset org-section-numbers i (string-to-number number-string)))
16442 (pop numbers))
16443 (setq i (1- i)))))
16445 (defun org-section-number (&optional level)
16446 "Return a string with the current section number.
16447 When LEVEL is non-nil, increase section numbers on that level."
16448 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
16449 (when level
16450 (when (> level -1)
16451 (aset org-section-numbers
16452 level (1+ (aref org-section-numbers level))))
16453 (setq idx (1+ level))
16454 (while (<= idx depth)
16455 (if (not (= idx 1))
16456 (aset org-section-numbers idx 0))
16457 (setq idx (1+ idx))))
16458 (setq idx 0)
16459 (while (<= idx depth)
16460 (setq n (aref org-section-numbers idx))
16461 (setq string (concat string (if (not (string= string "")) "." "")
16462 (int-to-string n)))
16463 (setq idx (1+ idx)))
16464 (save-match-data
16465 (if (string-match "\\`\\([@0]\\.\\)+" string)
16466 (setq string (replace-match "" t nil string)))
16467 (if (string-match "\\(\\.0\\)+\\'" string)
16468 (setq string (replace-match "" t nil string))))
16469 string))
16472 ;;;###autoload
16473 (defun org-export-icalendar-this-file ()
16474 "Export current file as an iCalendar file.
16475 The iCalendar file will be located in the same directory as the Org-mode
16476 file, but with extension `.ics'."
16477 (interactive)
16478 (org-export-icalendar nil buffer-file-name))
16480 (defun org-export-as-xoxo-insert-into (buffer &rest output)
16481 (with-current-buffer buffer
16482 (apply 'insert output)))
16483 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
16485 (defun org-export-as-xoxo (&optional buffer)
16486 "Export the org buffer as XOXO.
16487 The XOXO buffer is named *xoxo-<source buffer name>*"
16488 (interactive (list (current-buffer)))
16489 ;; A quickie abstraction
16491 ;; Output everything as XOXO
16492 (with-current-buffer (get-buffer buffer)
16493 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
16494 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
16495 (org-infile-export-plist)))
16496 (filename (concat (file-name-as-directory
16497 (org-export-directory :xoxo opt-plist))
16498 (file-name-sans-extension
16499 (file-name-nondirectory buffer-file-name))
16500 ".html"))
16501 (out (find-file-noselect filename))
16502 (last-level 1)
16503 (hanging-li nil))
16504 ;; Check the output buffer is empty.
16505 (with-current-buffer out (erase-buffer))
16506 ;; Kick off the output
16507 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
16508 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
16509 (let* ((hd (match-string-no-properties 1))
16510 (level (length hd))
16511 (text (concat
16512 (match-string-no-properties 2)
16513 (save-excursion
16514 (goto-char (match-end 0))
16515 (let ((str ""))
16516 (catch 'loop
16517 (while 't
16518 (forward-line)
16519 (if (looking-at "^[ \t]\\(.*\\)")
16520 (setq str (concat str (match-string-no-properties 1)))
16521 (throw 'loop str)))))))))
16523 ;; Handle level rendering
16524 (cond
16525 ((> level last-level)
16526 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
16528 ((< level last-level)
16529 (dotimes (- (- last-level level) 1)
16530 (if hanging-li
16531 (org-export-as-xoxo-insert-into out "</li>\n"))
16532 (org-export-as-xoxo-insert-into out "</ol>\n"))
16533 (when hanging-li
16534 (org-export-as-xoxo-insert-into out "</li>\n")
16535 (setq hanging-li nil)))
16537 ((equal level last-level)
16538 (if hanging-li
16539 (org-export-as-xoxo-insert-into out "</li>\n")))
16542 (setq last-level level)
16544 ;; And output the new li
16545 (setq hanging-li 't)
16546 (if (equal ?+ (elt text 0))
16547 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
16548 (org-export-as-xoxo-insert-into out "<li>" text))))
16550 ;; Finally finish off the ol
16551 (dotimes (- last-level 1)
16552 (if hanging-li
16553 (org-export-as-xoxo-insert-into out "</li>\n"))
16554 (org-export-as-xoxo-insert-into out "</ol>\n"))
16556 ;; Finish the buffer off and clean it up.
16557 (switch-to-buffer-other-window out)
16558 (indent-region (point-min) (point-max) nil)
16559 (save-buffer)
16560 (goto-char (point-min))
16563 ;;;###autoload
16564 (defun org-export-icalendar-all-agenda-files ()
16565 "Export all files in `org-agenda-files' to iCalendar .ics files.
16566 Each iCalendar file will be located in the same directory as the Org-mode
16567 file, but with extension `.ics'."
16568 (interactive)
16569 (apply 'org-export-icalendar nil (org-agenda-files t)))
16571 ;;;###autoload
16572 (defun org-export-icalendar-combine-agenda-files ()
16573 "Export all files in `org-agenda-files' to a single combined iCalendar file.
16574 The file is stored under the name `org-combined-agenda-icalendar-file'."
16575 (interactive)
16576 (apply 'org-export-icalendar t (org-agenda-files t)))
16578 (defun org-export-icalendar (combine &rest files)
16579 "Create iCalendar files for all elements of FILES.
16580 If COMBINE is non-nil, combine all calendar entries into a single large
16581 file and store it under the name `org-combined-agenda-icalendar-file'."
16582 (save-excursion
16583 (let* ((dir (org-export-directory
16584 :ical (list :publishing-directory
16585 org-export-publishing-directory)))
16586 file ical-file ical-buffer category started org-agenda-new-buffers)
16588 (when combine
16589 (setq ical-file
16590 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
16591 org-combined-agenda-icalendar-file
16592 (expand-file-name org-combined-agenda-icalendar-file dir))
16593 ical-buffer (org-get-agenda-file-buffer ical-file))
16594 (set-buffer ical-buffer) (erase-buffer))
16595 (while (setq file (pop files))
16596 (catch 'nextfile
16597 (org-check-agenda-file file)
16598 (set-buffer (org-get-agenda-file-buffer file))
16599 (unless combine
16600 (setq ical-file (concat (file-name-as-directory dir)
16601 (file-name-sans-extension
16602 (file-name-nondirectory buffer-file-name))
16603 ".ics"))
16604 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
16605 (with-current-buffer ical-buffer (erase-buffer)))
16606 (setq category (or org-category
16607 (file-name-sans-extension
16608 (file-name-nondirectory buffer-file-name))))
16609 (if (symbolp category) (setq category (symbol-name category)))
16610 (let ((standard-output ical-buffer))
16611 (if combine
16612 (and (not started) (setq started t)
16613 (org-start-icalendar-file org-icalendar-combined-name))
16614 (org-start-icalendar-file category))
16615 (org-print-icalendar-entries combine category)
16616 (when (or (and combine (not files)) (not combine))
16617 (org-finish-icalendar-file)
16618 (set-buffer ical-buffer)
16619 (save-buffer)
16620 (run-hooks 'org-after-save-iCalendar-file-hook)))))
16621 (org-release-buffers org-agenda-new-buffers))))
16623 (defvar org-after-save-iCalendar-file-hook nil
16624 "Hook run after an iCalendar file has been saved.
16625 The iCalendar buffer is still current when this hook is run.
16626 A good way to use this is to tell a desktop calenndar application to re-read
16627 the iCalendar file.")
16629 (defun org-print-icalendar-entries (&optional combine category)
16630 "Print iCalendar entries for the current Org-mode file to `standard-output'.
16631 When COMBINE is non nil, add the category to each line."
16632 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
16633 (dts (org-ical-ts-to-string
16634 (format-time-string (cdr org-time-stamp-formats) (current-time))
16635 "DTSTART"))
16636 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
16637 (save-excursion
16638 (goto-char (point-min))
16639 (while (re-search-forward org-ts-regexp nil t)
16640 (setq pos (match-beginning 0)
16641 ts (match-string 0)
16642 inc t
16643 hd (org-get-heading))
16644 (if (looking-at re2)
16645 (progn
16646 (goto-char (match-end 0))
16647 (setq ts2 (match-string 1) inc nil))
16648 (setq ts2 ts
16649 tmp (buffer-substring (max (point-min)
16650 (- pos org-ds-keyword-length))
16651 pos)
16652 deadlinep (string-match org-deadline-regexp tmp)
16653 scheduledp (string-match org-scheduled-regexp tmp)
16654 ;; donep (org-entry-is-done-p)
16656 (if (or (string-match org-tr-regexp hd)
16657 (string-match org-ts-regexp hd))
16658 (setq hd (replace-match "" t t hd)))
16659 (if combine
16660 (setq hd (concat hd " (category " category ")")))
16661 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
16662 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
16663 (princ (format "BEGIN:VEVENT
16666 SUMMARY:%s
16667 END:VEVENT\n"
16668 (org-ical-ts-to-string ts "DTSTART")
16669 (org-ical-ts-to-string ts2 "DTEND" inc)
16670 hd)))
16671 (when org-icalendar-include-todo
16672 (goto-char (point-min))
16673 (while (re-search-forward org-todo-line-regexp nil t)
16674 (setq state (match-string 1))
16675 (unless (equal state org-done-string)
16676 (setq hd (match-string 3))
16677 (if (string-match org-priority-regexp hd)
16678 (setq pri (string-to-char (match-string 2 hd))
16679 hd (concat (substring hd 0 (match-beginning 1))
16680 (substring hd (- (match-end 1)))))
16681 (setq pri org-default-priority))
16682 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
16683 (- org-lowest-priority ?A))))))
16685 (princ (format "BEGIN:VTODO
16687 SUMMARY:%s
16688 SEQUENCE:1
16689 PRIORITY:%d
16690 END:VTODO\n"
16691 dts hd pri))))))))
16693 (defun org-start-icalendar-file (name)
16694 "Start an iCalendar file by inserting the header."
16695 (let ((user user-full-name)
16696 (name (or name "unknown"))
16697 (timezone (cadr (current-time-zone))))
16698 (princ
16699 (format "BEGIN:VCALENDAR
16700 VERSION:2.0
16701 X-WR-CALNAME:%s
16702 PRODID:-//%s//Emacs with Org-mode//EN
16703 X-WR-TIMEZONE:%s
16704 CALSCALE:GREGORIAN\n" name user timezone))))
16706 (defun org-finish-icalendar-file ()
16707 "Finish an iCalendar file by inserting the END statement."
16708 (princ "END:VCALENDAR\n"))
16710 (defun org-ical-ts-to-string (s keyword &optional inc)
16711 "Take a time string S and convert it to iCalendar format.
16712 KEYWORD is added in front, to make a complete line like DTSTART....
16713 When INC is non-nil, increase the hour by two (if time string contains
16714 a time), or the day by one (if it does not contain a time)."
16715 (let ((t1 (org-parse-time-string s 'nodefault))
16716 t2 fmt have-time time)
16717 (if (and (car t1) (nth 1 t1) (nth 2 t1))
16718 (setq t2 t1 have-time t)
16719 (setq t2 (org-parse-time-string s)))
16720 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
16721 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
16722 (when inc
16723 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
16724 (setq time (encode-time s mi h d m y)))
16725 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
16726 (concat keyword (format-time-string fmt time))))
16728 ;;;; LaTeX stuff
16730 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16731 "Keymap for the minor `org-cdlatex-mode'.")
16733 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16734 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16735 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16736 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16737 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16739 (defvar org-cdlatex-texmathp-advice-is-done nil
16740 "Flag remembering if we have applied the advice to texmathp already.")
16742 (define-minor-mode org-cdlatex-mode
16743 "Toggle the minor `org-cdlatex-mode'.
16744 This mode supports entering LaTeX environment and math in LaTeX fragments
16745 in Org-mode.
16746 \\{org-cdlatex-mode-map}"
16747 nil " OCDL" nil
16748 (when org-cdlatex-mode (require 'cdlatex))
16749 (unless org-cdlatex-texmathp-advice-is-done
16750 (setq org-cdlatex-texmathp-advice-is-done t)
16751 (defadvice texmathp (around org-math-always-on activate)
16752 "Always return t in org-mode buffers.
16753 This is because we want to insert math symbols without dollars even outside
16754 the LaTeX math segments. If Orgmode thinks that point is actually inside
16755 en embedded LaTeX fragement, let texmathp do its job.
16756 \\[org-cdlatex-mode-map]"
16757 (interactive)
16758 (let (p)
16759 (cond
16760 ((not (org-mode-p)) ad-do-it)
16761 ((eq this-command 'cdlatex-math-symbol)
16762 (setq ad-return-value t
16763 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16765 (let ((p (org-inside-LaTeX-fragment-p)))
16766 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16767 (setq ad-return-value t
16768 texmathp-why '("Org-mode embedded math" . 0))
16769 (if p ad-do-it)))))))))
16771 (defun turn-on-org-cdlatex ()
16772 "Unconditionally turn on `org-cdlatex-mode'."
16773 (org-cdlatex-mode 1))
16775 (defun org-inside-LaTeX-fragment-p ()
16776 "Test if point is inside a LaTeX fragment.
16777 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16778 sequence appearing also before point.
16779 Even though the matchers for math are configurable, this function assumes
16780 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16781 delimiters are skipped when they have been removed by customization.
16782 The return value is nil, or a cons cell with the delimiter and
16783 and the position of this delimiter.
16785 This function does a reasonably good job, but can locally be fooled by
16786 for example currency specifications. For example it will assume being in
16787 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16788 fragments that are properly closed, but during editing, we have to live
16789 with the uncertainty caused by missing closing delimiters. This function
16790 looks only before point, not after."
16791 (catch 'exit
16792 (let ((pos (point))
16793 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16794 (lim (progn
16795 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16796 (point)))
16797 dd-on str (start 0) m re)
16798 (goto-char pos)
16799 (when dodollar
16800 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16801 re (nth 1 (assoc "$" org-latex-regexps)))
16802 (while (string-match re str start)
16803 (cond
16804 ((= (match-end 0) (length str))
16805 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
16806 ((= (match-end 0) (- (length str) 5))
16807 (throw 'exit nil))
16808 (t (setq start (match-end 0))))))
16809 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16810 (goto-char pos)
16811 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16812 (and (match-beginning 2) (throw 'exit nil))
16813 ;; count $$
16814 (while (re-search-backward "\\$\\$" lim t)
16815 (setq dd-on (not dd-on)))
16816 (goto-char pos)
16817 (if dd-on (cons "$$" m))))))
16820 (defun org-try-cdlatex-tab ()
16821 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16822 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16823 - inside a LaTeX fragment, or
16824 - after the first word in a line, where an abbreviation expansion could
16825 insert a LaTeX environment."
16826 (when org-cdlatex-mode
16827 (cond
16828 ((save-excursion
16829 (skip-chars-backward "a-zA-Z0-9*")
16830 (skip-chars-backward " \t")
16831 (bolp))
16832 (cdlatex-tab) t)
16833 ((org-inside-LaTeX-fragment-p)
16834 (cdlatex-tab) t)
16835 (t nil))))
16837 (defun org-cdlatex-underscore-caret (&optional arg)
16838 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16839 Revert to the normal definition outside of these fragments."
16840 (interactive "P")
16841 (if (org-inside-LaTeX-fragment-p)
16842 (call-interactively 'cdlatex-sub-superscript)
16843 (let (org-cdlatex-mode)
16844 (call-interactively (key-binding (vector last-input-event))))))
16846 (defun org-cdlatex-math-modify (&optional arg)
16847 "Execute `cdlatex-math-modify' in LaTeX fragments.
16848 Revert to the normal definition outside of these fragments."
16849 (interactive "P")
16850 (if (org-inside-LaTeX-fragment-p)
16851 (call-interactively 'cdlatex-math-modify)
16852 (let (org-cdlatex-mode)
16853 (call-interactively (key-binding (vector last-input-event))))))
16855 (defvar org-latex-fragment-image-overlays nil
16856 "List of overlays carrying the images of latex fragments.")
16857 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16859 (defun org-remove-latex-fragment-image-overlays ()
16860 "Remove all overlays with LaTeX fragment images in current buffer."
16861 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
16862 (setq org-latex-fragment-image-overlays nil))
16864 (defun org-preview-latex-fragment (&optional subtree)
16865 "Preview the LaTeX fragment at point, or all locally or globally.
16866 If the cursor is in a LaTeX fragment, create the image and overlay
16867 it over the source code. If there is no fragment at point, display
16868 all fragments in the current text, from one headline to the next. With
16869 prefix SUBTREE, display all fragments in the current subtree. With a
16870 double prefix `C-u C-u', or when the cursor is before the first headline,
16871 display all fragments in the buffer.
16872 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16873 (interactive "P")
16874 (org-remove-latex-fragment-image-overlays)
16875 (save-excursion
16876 (save-restriction
16877 (let (beg end at msg)
16878 (cond
16879 ((or (equal subtree '(16))
16880 (not (save-excursion
16881 (re-search-backward (concat "^" outline-regexp) nil t))))
16882 (setq beg (point-min) end (point-max)
16883 msg "Creating images for buffer...%s"))
16884 ((equal subtree '(4))
16885 (org-back-to-heading)
16886 (setq beg (point) end (org-end-of-subtree t)
16887 msg "Creating images for subtree...%s"))
16889 (if (setq at (org-inside-LaTeX-fragment-p))
16890 (goto-char (max (point-min) (- (cdr at) 2)))
16891 (org-back-to-heading))
16892 (setq beg (point) end (progn (outline-next-heading) (point))
16893 msg (if at "Creating image...%s"
16894 "Creating images for entry...%s"))))
16895 (message msg "")
16896 (narrow-to-region beg end)
16897 (org-format-latex
16898 (concat "ltxpng/" (file-name-sans-extension
16899 (file-name-nondirectory
16900 buffer-file-name)))
16901 default-directory 'overlays msg at)
16902 (message msg "done. Use `C-c C-c' to remove images.")))))
16904 (defvar org-latex-regexps
16905 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16906 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16907 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16908 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
16909 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16910 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
16911 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
16912 "Regular expressions for matching embedded LaTeX.")
16914 (defun org-format-latex (prefix &optional dir overlays msg at)
16915 "Replace LaTeX fragments with links to an image, and produce images."
16916 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16917 (let* ((prefixnodir (file-name-nondirectory prefix))
16918 (absprefix (expand-file-name prefix dir))
16919 (todir (file-name-directory absprefix))
16920 (opt org-format-latex-options)
16921 (matchers (plist-get opt :matchers))
16922 (re-list org-latex-regexps)
16923 (cnt 0) txt link beg end re e oldfiles
16924 m n block linkfile movefile ov)
16925 ;; Make sure the directory exists
16926 (or (file-directory-p todir) (make-directory todir))
16927 ;; Check if there are old images files with this prefix, and remove them
16928 (setq oldfiles (directory-files
16929 todir 'full
16930 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
16931 (while oldfiles (delete-file (pop oldfiles)))
16932 ;; Check the different regular expressions
16933 (while (setq e (pop re-list))
16934 (setq m (car e) re (nth 1 e) n (nth 2 e)
16935 block (if (nth 3 e) "\n\n" ""))
16936 (when (member m matchers)
16937 (goto-char (point-min))
16938 (while (re-search-forward re nil t)
16939 (when (or (not at) (equal (cdr at) (match-beginning n)))
16940 (setq txt (match-string n)
16941 beg (match-beginning n) end (match-end n)
16942 cnt (1+ cnt)
16943 linkfile (format "%s_%04d.png" prefix cnt)
16944 movefile (format "%s_%04d.png" absprefix cnt)
16945 link (concat block "[[file:" linkfile "]]" block))
16946 (if msg (message msg cnt))
16947 (goto-char beg)
16948 (org-create-formula-image
16949 txt movefile opt)
16950 (if overlays
16951 (progn
16952 (setq ov (org-make-overlay beg end))
16953 (if (featurep 'xemacs)
16954 (progn
16955 (org-overlay-put ov 'invisible t)
16956 (org-overlay-put
16957 ov 'end-glyph
16958 (make-glyph (vector 'png :file movefile))))
16959 (org-overlay-put
16960 ov 'display
16961 (list 'image :type 'png :file movefile :ascent 'center)))
16962 (push ov org-latex-fragment-image-overlays)
16963 (goto-char end))
16964 (delete-region beg end)
16965 (insert link))))))))
16967 ;; This function borrows from Ganesh Swami's latex2png.el
16968 (defun org-create-formula-image (string tofile options)
16969 (let* ((tmpdir (if (featurep 'xemacs)
16970 (temp-directory)
16971 temporary-file-directory))
16972 (texfilebase (make-temp-name
16973 (expand-file-name "orgtex" tmpdir)))
16975 ;(texfilebase (make-temp-file "orgtex"))
16976 ; (dummy (delete-file texfilebase))
16977 (texfile (concat texfilebase ".tex"))
16978 (dvifile (concat texfilebase ".dvi"))
16979 (pngfile (concat texfilebase ".png"))
16980 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
16981 (fg (or (plist-get options :foreground) "Black"))
16982 (bg (or (plist-get options :background) "Transparent")))
16983 (with-temp-file texfile
16984 (insert "\\documentclass{article}
16985 \\usepackage{fullpage}
16986 \\usepackage{amssymb}
16987 \\usepackage[usenames]{color}
16988 \\usepackage{amsmath}
16989 \\usepackage{latexsym}
16990 \\usepackage[mathscr]{eucal}
16991 \\pagestyle{empty}
16992 \\begin{document}\n" string "\n\\end{document}\n"))
16993 (let ((dir default-directory))
16994 (condition-case nil
16995 (progn
16996 (cd tmpdir)
16997 (call-process "latex" nil nil nil texfile))
16998 (error nil))
16999 (cd dir))
17000 (if (not (file-exists-p dvifile))
17001 (progn (message "Failed to create dvi file from %s" texfile) nil)
17002 (call-process "dvipng" nil nil nil
17003 "-E" "-fg" fg "-bg" bg
17004 "-x" scale "-y" scale "-T" "tight"
17005 "-o" pngfile
17006 dvifile)
17007 (if (not (file-exists-p pngfile))
17008 (progn (message "Failed to create png file from %s" texfile) nil)
17009 ;; Use the requested file name and clean up
17010 (copy-file pngfile tofile 'replace)
17011 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17012 (delete-file (concat texfilebase e)))
17013 pngfile))))
17015 ;;;; Key bindings
17017 ;; - Bindings in Org-mode map are currently
17018 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
17019 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
17020 ;; e (?) useful from outline-mode
17021 ;; i k @ expendable from outline-mode
17022 ;; 0123456789 % & ()_{} " ` free
17024 ;; Make `C-c C-x' a prefix key
17025 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
17027 ;; TAB key with modifiers
17028 (define-key org-mode-map "\C-i" 'org-cycle)
17029 (define-key org-mode-map [(tab)] 'org-cycle)
17030 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
17031 (define-key org-mode-map [(meta tab)] 'org-complete)
17032 (define-key org-mode-map "\M-\C-i" 'org-complete)
17033 ;; The following line is necessary under Suse GNU/Linux
17034 (unless (featurep 'xemacs)
17035 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
17036 (define-key org-mode-map [(shift tab)] 'org-shifttab)
17038 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
17039 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17040 (define-key org-mode-map [(meta return)] 'org-meta-return)
17042 ;; Cursor keys with modifiers
17043 (define-key org-mode-map [(meta left)] 'org-metaleft)
17044 (define-key org-mode-map [(meta right)] 'org-metaright)
17045 (define-key org-mode-map [(meta up)] 'org-metaup)
17046 (define-key org-mode-map [(meta down)] 'org-metadown)
17048 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17049 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
17050 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
17051 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
17053 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
17054 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
17055 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
17056 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
17058 ;;; Extra keys for tty access.
17059 ;; We only set them when really needed because otherwise the
17060 ;; menus don't show the simple keys
17062 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17063 (not window-system))
17064 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17065 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17066 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return)
17067 (define-key org-mode-map [?\e (return)] 'org-meta-return)
17068 (define-key org-mode-map [?\e (left)] 'org-metaleft)
17069 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft)
17070 (define-key org-mode-map [?\e (right)] 'org-metaright)
17071 (define-key org-mode-map "\C-c\C-xr" 'org-metaright)
17072 (define-key org-mode-map [?\e (up)] 'org-metaup)
17073 (define-key org-mode-map "\C-c\C-xu" 'org-metaup)
17074 (define-key org-mode-map [?\e (down)] 'org-metadown)
17075 (define-key org-mode-map "\C-c\C-xd" 'org-metadown)
17076 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17077 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17078 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17079 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17080 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
17081 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
17082 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
17083 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright))
17085 ;; All the other keys
17087 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17088 (define-key org-mode-map "\C-c\C-r" 'org-reveal)
17089 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
17090 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
17091 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
17092 (define-key org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17093 (define-key org-mode-map "\C-c\C-j" 'org-goto)
17094 (define-key org-mode-map "\C-c\C-t" 'org-todo)
17095 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
17096 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
17097 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
17098 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
17099 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
17100 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
17101 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
17102 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
17103 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
17104 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
17105 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
17106 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
17107 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
17108 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
17109 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17110 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17111 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17112 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17113 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
17114 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
17115 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17116 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
17117 (define-key org-mode-map "\C-c]" 'org-remove-file)
17118 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
17119 (define-key org-mode-map "\C-c^" 'org-sort)
17120 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17121 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
17122 (define-key org-mode-map "\C-m" 'org-return)
17123 (define-key org-mode-map "\C-c?" 'org-table-current-column)
17124 (define-key org-mode-map "\C-c " 'org-table-blank-field)
17125 (define-key org-mode-map "\C-c+" 'org-table-sum)
17126 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
17127 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
17128 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
17129 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17130 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
17131 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17132 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
17133 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
17134 (define-key org-mode-map "\C-c\C-e" 'org-export)
17135 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17137 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
17138 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17139 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17140 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17142 (define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17143 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17144 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17145 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17146 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17147 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17148 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17149 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17150 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17152 (when (featurep 'xemacs)
17153 (define-key org-mode-map 'button3 'popup-mode-menu))
17155 (defsubst org-table-p () (org-at-table-p))
17157 (defun org-self-insert-command (N)
17158 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17159 If the cursor is in a table looking at whitespace, the whitespace is
17160 overwritten, and the table is not marked as requiring realignment."
17161 (interactive "p")
17162 (if (and (org-table-p)
17163 (progn
17164 ;; check if we blank the field, and if that triggers align
17165 (and org-table-auto-blank-field
17166 (member last-command
17167 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
17168 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17169 ;; got extra space, this field does not determine column width
17170 (let (org-table-may-need-update) (org-table-blank-field))
17171 ;; no extra space, this field may determine column width
17172 (org-table-blank-field)))
17174 (eq N 1)
17175 (looking-at "[^|\n]* |"))
17176 (let (org-table-may-need-update)
17177 (goto-char (1- (match-end 0)))
17178 (delete-backward-char 1)
17179 (goto-char (match-beginning 0))
17180 (self-insert-command N))
17181 (setq org-table-may-need-update t)
17182 (self-insert-command N)))
17184 (defun org-delete-backward-char (N)
17185 "Like `delete-backward-char', insert whitespace at field end in tables.
17186 When deleting backwards, in tables this function will insert whitespace in
17187 front of the next \"|\" separator, to keep the table aligned. The table will
17188 still be marked for re-alignment if the field did fill the entire column,
17189 because, in this case the deletion might narrow the column."
17190 (interactive "p")
17191 (if (and (org-table-p)
17192 (eq N 1)
17193 (string-match "|" (buffer-substring (point-at-bol) (point)))
17194 (looking-at ".*?|"))
17195 (let ((pos (point))
17196 (noalign (looking-at "[^|\n\r]* |"))
17197 (c org-table-may-need-update))
17198 (backward-delete-char N)
17199 (skip-chars-forward "^|")
17200 (insert " ")
17201 (goto-char (1- pos))
17202 ;; noalign: if there were two spaces at the end, this field
17203 ;; does not determine the width of the column.
17204 (if noalign (setq org-table-may-need-update c)))
17205 (backward-delete-char N)))
17207 (defun org-delete-char (N)
17208 "Like `delete-char', but insert whitespace at field end in tables.
17209 When deleting characters, in tables this function will insert whitespace in
17210 front of the next \"|\" separator, to keep the table aligned. The table will
17211 still be marked for re-alignment if the field did fill the entire column,
17212 because, in this case the deletion might narrow the column."
17213 (interactive "p")
17214 (if (and (org-table-p)
17215 (not (bolp))
17216 (not (= (char-after) ?|))
17217 (eq N 1))
17218 (if (looking-at ".*?|")
17219 (let ((pos (point))
17220 (noalign (looking-at "[^|\n\r]* |"))
17221 (c org-table-may-need-update))
17222 (replace-match (concat
17223 (substring (match-string 0) 1 -1)
17224 " |"))
17225 (goto-char pos)
17226 ;; noalign: if there were two spaces at the end, this field
17227 ;; does not determine the width of the column.
17228 (if noalign (setq org-table-may-need-update c)))
17229 (delete-char N))
17230 (delete-char N)))
17232 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17233 (put 'org-self-insert-command 'delete-selection t)
17234 (put 'orgtbl-self-insert-command 'delete-selection t)
17235 (put 'org-delete-char 'delete-selection 'supersede)
17236 (put 'org-delete-backward-char 'delete-selection 'supersede)
17238 ;; How to do this: Measure non-white length of current string
17239 ;; If equal to column width, we should realign.
17241 (defun org-remap (map &rest commands)
17242 "In MAP, remap the functions given in COMMANDS.
17243 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17244 (let (new old)
17245 (while commands
17246 (setq old (pop commands) new (pop commands))
17247 (if (fboundp 'command-remapping)
17248 (define-key map (vector 'remap old) new)
17249 (substitute-key-definition old new map global-map)))))
17251 (when (eq org-enable-table-editor 'optimized)
17252 ;; If the user wants maximum table support, we need to hijack
17253 ;; some standard editing functions
17254 (org-remap org-mode-map
17255 'self-insert-command 'org-self-insert-command
17256 'delete-char 'org-delete-char
17257 'delete-backward-char 'org-delete-backward-char)
17258 (define-key org-mode-map "|" 'org-force-self-insert))
17260 (defun org-shiftcursor-error ()
17261 "Throw an error because Shift-Cursor command was applied in wrong context."
17262 (error "This command is active in special context like tables, headlines or timestamps"))
17264 (defun org-shifttab (&optional arg)
17265 "Global visibility cycling or move to previous table field.
17266 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17267 on context.
17268 See the individual commands for more information."
17269 (interactive "P")
17270 (cond
17271 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17272 (t (call-interactively 'org-global-cycle))))
17274 (defun org-shiftmetaleft ()
17275 "Promote subtree or delete table column.
17276 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
17277 See the individual commands for more information."
17278 (interactive)
17279 (cond
17280 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17281 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17282 ((org-at-item-p) (call-interactively 'org-outdent-item))
17283 (t (org-shiftcursor-error))))
17285 (defun org-shiftmetaright ()
17286 "Demote subtree or insert table column.
17287 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
17288 See the individual commands for more information."
17289 (interactive)
17290 (cond
17291 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17292 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17293 ((org-at-item-p) (call-interactively 'org-indent-item))
17294 (t (org-shiftcursor-error))))
17296 (defun org-shiftmetaup (&optional arg)
17297 "Move subtree up or kill table row.
17298 Calls `org-move-subtree-up' or `org-table-kill-row' or
17299 `org-move-item-up' depending on context. See the individual commands
17300 for more information."
17301 (interactive "P")
17302 (cond
17303 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17304 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17305 ((org-at-item-p) (call-interactively 'org-move-item-up))
17306 (t (org-shiftcursor-error))))
17307 (defun org-shiftmetadown (&optional arg)
17308 "Move subtree down or insert table row.
17309 Calls `org-move-subtree-down' or `org-table-insert-row' or
17310 `org-move-item-down', depending on context. See the individual
17311 commands for more information."
17312 (interactive "P")
17313 (cond
17314 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17315 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17316 ((org-at-item-p) (call-interactively 'org-move-item-down))
17317 (t (org-shiftcursor-error))))
17319 (defun org-metaleft (&optional arg)
17320 "Promote heading or move table column to left.
17321 Calls `org-do-promote' or `org-table-move-column', depending on context.
17322 With no specific context, calls the Emacs default `backward-word'.
17323 See the individual commands for more information."
17324 (interactive "P")
17325 (cond
17326 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17327 ((or (org-on-heading-p) (org-region-active-p))
17328 (call-interactively 'org-do-promote))
17329 ((org-at-item-p) (call-interactively 'org-outdent-item))
17330 (t (call-interactively 'backward-word))))
17332 (defun org-metaright (&optional arg)
17333 "Demote subtree or move table column to right.
17334 Calls `org-do-demote' or `org-table-move-column', depending on context.
17335 With no specific context, calls the Emacs default `forward-word'.
17336 See the individual commands for more information."
17337 (interactive "P")
17338 (cond
17339 ((org-at-table-p) (call-interactively 'org-table-move-column))
17340 ((or (org-on-heading-p) (org-region-active-p))
17341 (call-interactively 'org-do-demote))
17342 ((org-at-item-p) (call-interactively 'org-indent-item))
17343 (t (call-interactively 'forward-word))))
17345 (defun org-metaup (&optional arg)
17346 "Move subtree up or move table row up.
17347 Calls `org-move-subtree-up' or `org-table-move-row' or
17348 `org-move-item-up', depending on context. See the individual commands
17349 for more information."
17350 (interactive "P")
17351 (cond
17352 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17353 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17354 ((org-at-item-p) (call-interactively 'org-move-item-up))
17355 (t (org-shiftcursor-error))))
17357 (defun org-metadown (&optional arg)
17358 "Move subtree down or move table row down.
17359 Calls `org-move-subtree-down' or `org-table-move-row' or
17360 `org-move-item-down', depending on context. See the individual
17361 commands for more information."
17362 (interactive "P")
17363 (cond
17364 ((org-at-table-p) (call-interactively 'org-table-move-row))
17365 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17366 ((org-at-item-p) (call-interactively 'org-move-item-down))
17367 (t (org-shiftcursor-error))))
17369 (defun org-shiftup (&optional arg)
17370 "Increase item in timestamp or increase priority of current headline.
17371 Calls `org-timestamp-up' or `org-priority-up', depending on context.
17372 See the individual commands for more information."
17373 (interactive "P")
17374 (cond
17375 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
17376 ((org-on-heading-p) (call-interactively 'org-priority-up))
17377 ((org-at-item-p) (call-interactively 'org-previous-item))
17378 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
17380 (defun org-shiftdown (&optional arg)
17381 "Decrease item in timestamp or decrease priority of current headline.
17382 Calls `org-timestamp-down' or `org-priority-down', depending on context.
17383 See the individual commands for more information."
17384 (interactive "P")
17385 (cond
17386 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
17387 ((org-on-heading-p) (call-interactively 'org-priority-down))
17388 (t (call-interactively 'org-next-item))))
17390 (defun org-shiftright ()
17391 "Next TODO keyword or timestamp one day later, depending on context."
17392 (interactive)
17393 (cond
17394 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17395 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
17396 (t (org-shiftcursor-error))))
17398 (defun org-shiftleft ()
17399 "Previous TODO keyword or timestamp one day earlier, depending on context."
17400 (interactive)
17401 (cond
17402 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17403 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
17404 (t (org-shiftcursor-error))))
17406 (defun org-copy-special ()
17407 "Copy region in table or copy current subtree.
17408 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17409 See the individual commands for more information."
17410 (interactive)
17411 (call-interactively
17412 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17414 (defun org-cut-special ()
17415 "Cut region in table or cut current subtree.
17416 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17417 See the individual commands for more information."
17418 (interactive)
17419 (call-interactively
17420 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17422 (defun org-paste-special (arg)
17423 "Paste rectangular region into table, or past subtree relative to level.
17424 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17425 See the individual commands for more information."
17426 (interactive "P")
17427 (if (org-at-table-p)
17428 (org-table-paste-rectangle)
17429 (org-paste-subtree arg)))
17431 (defun org-ctrl-c-ctrl-c (&optional arg)
17432 "Set tags in headline, or update according to changed information at point.
17434 This command does many different things, depending on context:
17436 - If the cursor is in a headline, prompt for tags and insert them
17437 into the current line, aligned to `org-tags-column'. When called
17438 with prefix arg, realign all tags in the current buffer.
17440 - If the cursor is in one of the special #+KEYWORD lines, this
17441 triggers scanning the buffer for these lines and updating the
17442 information.
17444 - If the cursor is inside a table, realign the table. This command
17445 works even if the automatic table editor has been turned off.
17447 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17448 the entire table.
17450 - If the cursor is inside a table created by the table.el package,
17451 activate that table.
17453 - If the current buffer is a remember buffer, close note and file it.
17454 with a prefix argument, file it without further interaction to the default
17455 location.
17457 - If the cursor is on a <<<target>>>, update radio targets and corresponding
17458 links in this buffer.
17460 - If the cursor is on a numbered item in a plain list, renumber the
17461 ordered list."
17462 (interactive "P")
17463 (let ((org-enable-table-editor t))
17464 (cond
17465 ((or org-clock-overlays
17466 org-occur-highlights
17467 org-latex-fragment-image-overlays)
17468 (org-remove-clock-overlays)
17469 (org-remove-occur-highlights)
17470 (org-remove-latex-fragment-image-overlays)
17471 (message "Temporary highlights/overlays removed from current buffer"))
17472 ((and (local-variable-p 'org-finish-function (current-buffer))
17473 (fboundp org-finish-function))
17474 (funcall org-finish-function))
17475 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17476 ((org-on-heading-p) (call-interactively 'org-set-tags))
17477 ((org-at-table.el-p)
17478 (require 'table)
17479 (beginning-of-line 1)
17480 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
17481 (call-interactively 'table-recognize-table))
17482 ((org-at-table-p)
17483 (org-table-maybe-eval-formula)
17484 (if arg
17485 (call-interactively 'org-table-recalculate)
17486 (org-table-maybe-recalculate-line))
17487 (call-interactively 'org-table-align))
17488 ((org-at-item-checkbox-p)
17489 (call-interactively 'org-toggle-checkbox))
17490 ((org-at-item-p)
17491 (call-interactively 'org-renumber-ordered-list))
17492 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
17493 (cond
17494 ((equal (match-string 1) "TBLFM")
17495 ;; Recalculate the table before this line
17496 (save-excursion
17497 (beginning-of-line 1)
17498 (skip-chars-backward " \r\n\t")
17499 (if (org-at-table-p)
17500 (org-call-with-arg 'org-table-recalculate t))))
17502 (call-interactively 'org-mode-restart))))
17503 (t (error "C-c C-c can do nothing useful at this location.")))))
17505 (defun org-mode-restart ()
17506 "Restart Org-mode, to scan again for special lines.
17507 Also updates the keyword regular expressions."
17508 (interactive)
17509 (let ((org-inhibit-startup t)) (org-mode))
17510 (message "Org-mode restarted to refresh keyword and special line setup"))
17512 (defun org-return ()
17513 "Goto next table row or insert a newline.
17514 Calls `org-table-next-row' or `newline', depending on context.
17515 See the individual commands for more information."
17516 (interactive)
17517 (cond
17518 ((org-at-table-p)
17519 (org-table-justify-field-maybe)
17520 (call-interactively 'org-table-next-row))
17521 (t (newline))))
17523 (defun org-meta-return (&optional arg)
17524 "Insert a new heading or wrap a region in a table.
17525 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17526 See the individual commands for more information."
17527 (interactive "P")
17528 (cond
17529 ((org-at-table-p)
17530 (call-interactively 'org-table-wrap-region))
17531 (t (call-interactively 'org-insert-heading))))
17533 ;;; Menu entries
17535 ;; Define the Org-mode menus
17536 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17537 '("Tbl"
17538 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
17539 ["Next Field" org-cycle (org-at-table-p)]
17540 ["Previous Field" org-shifttab (org-at-table-p)]
17541 ["Next Row" org-return (org-at-table-p)]
17542 "--"
17543 ["Blank Field" org-table-blank-field (org-at-table-p)]
17544 ["Edit Field" org-table-edit-field (org-at-table-p)]
17545 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17546 "--"
17547 ("Column"
17548 ["Move Column Left" org-metaleft (org-at-table-p)]
17549 ["Move Column Right" org-metaright (org-at-table-p)]
17550 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17551 ["Insert Column" org-shiftmetaright (org-at-table-p)]
17552 "--"
17553 ["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])
17554 ("Row"
17555 ["Move Row Up" org-metaup (org-at-table-p)]
17556 ["Move Row Down" org-metadown (org-at-table-p)]
17557 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17558 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17559 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17560 "--"
17561 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
17562 ("Rectangle"
17563 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17564 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17565 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17566 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17567 "--"
17568 ("Calculate"
17569 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17570 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17571 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
17572 "--"
17573 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17574 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17575 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17576 "--"
17577 ["Sum Column/Rectangle" org-table-sum
17578 (or (org-at-table-p) (org-region-active-p))]
17579 ["Which Column?" org-table-current-column (org-at-table-p)])
17580 ["Debug Formulas"
17581 (setq org-table-formula-debug (not org-table-formula-debug))
17582 :style toggle :selected org-table-formula-debug]
17583 "--"
17584 ["Create" org-table-create (and (not (org-at-table-p))
17585 org-enable-table-editor)]
17586 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17587 ["Import from File" org-table-import (not (org-at-table-p))]
17588 ["Export to File" org-table-export (org-at-table-p)]
17589 "--"
17590 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17592 (easy-menu-define org-org-menu org-mode-map "Org menu"
17593 '("Org"
17594 ("Show/Hide"
17595 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
17596 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
17597 ["Sparse Tree" org-occur t]
17598 ["Reveal Context" org-reveal t]
17599 ["Show All" show-all t]
17600 "--"
17601 ["Subtree to indirect buffer" 'org-tree-to-indirect-buffer t])
17602 "--"
17603 ["New Heading" org-insert-heading t]
17604 ("Navigate Headings"
17605 ["Up" outline-up-heading t]
17606 ["Next" outline-next-visible-heading t]
17607 ["Previous" outline-previous-visible-heading t]
17608 ["Next Same Level" outline-forward-same-level t]
17609 ["Previous Same Level" outline-backward-same-level t]
17610 "--"
17611 ["Jump" org-goto t])
17612 ("Edit Structure"
17613 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17614 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17615 "--"
17616 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17617 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17618 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17619 "--"
17620 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17621 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17622 ["Demote Heading" org-metaright (not (org-at-table-p))]
17623 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17624 "--"
17625 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17626 "--"
17627 ["Convert to odd levels" org-convert-to-odd-levels t]
17628 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17629 ("Archive"
17630 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17631 ["Check and Tag Children" (org-toggle-archive-tag (4))
17632 :active t :keys "C-u C-c C-x C-a"]
17633 ["Sparse trees open ARCHIVE trees"
17634 (setq org-sparse-tree-open-archived-trees
17635 (not org-sparse-tree-open-archived-trees))
17636 :style toggle :selected org-sparse-tree-open-archived-trees]
17637 ["Cycling opens ARCHIVE trees"
17638 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
17639 :style toggle :selected org-cycle-open-archived-trees]
17640 ["Agenda includes ARCHIVE trees"
17641 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
17642 :style toggle :selected (not org-agenda-skip-archived-trees)]
17643 "--"
17644 ["Move Subtree to Archive" org-archive-subtree t]
17645 ["Check and Move Children" (org-archive-subtree '(4))
17646 :active t :keys "C-u C-c $"])
17647 "--"
17648 ("TODO Lists"
17649 ["TODO/DONE/-" org-todo t]
17650 ("Select keyword"
17651 ["Next keyword" org-shiftright (org-on-heading-p)]
17652 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17653 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
17654 ["Show TODO Tree" org-show-todo-tree t]
17655 ["Global TODO list" org-todo-list t]
17656 "--"
17657 ["Set Priority" org-priority t]
17658 ["Priority Up" org-shiftup t]
17659 ["Priority Down" org-shiftdown t]
17660 "--"
17661 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
17662 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
17663 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
17664 ; (or (org-on-heading-p) (org-at-item-p))]
17665 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
17666 ; (or (org-on-heading-p) (org-at-item-p))]
17667 ; ["Update Statistics" org-update-checkbox-count t]
17669 ("Dates and Scheduling"
17670 ["Timestamp" org-time-stamp t]
17671 ["Timestamp (inactive)" org-time-stamp-inactive t]
17672 ("Change Date"
17673 ["1 Day Later" org-shiftright t]
17674 ["1 Day Earlier" org-shiftleft t]
17675 ["1 ... Later" org-shiftup t]
17676 ["1 ... Earlier" org-shiftdown t])
17677 ["Compute Time Range" org-evaluate-time-range t]
17678 ["Schedule Item" org-schedule t]
17679 ["Deadline" org-deadline t]
17680 "--"
17681 ["Custom time format" org-toggle-time-stamp-overlays
17682 :style radio :selected org-display-custom-times]
17683 "--"
17684 ["Goto Calendar" org-goto-calendar t]
17685 ["Date from Calendar" org-date-from-calendar t])
17686 ("Logging work"
17687 ["Clock in" org-clock-in t]
17688 ["Clock out" org-clock-out t]
17689 ["Clock cancel" org-clock-cancel t]
17690 ["Display times" org-clock-display t]
17691 ["Create clock table" org-clock-report t]
17692 "--"
17693 ["Record DONE time"
17694 (progn (setq org-log-done (not org-log-done))
17695 (message "Switching to %s will %s record a timestamp"
17696 org-done-string
17697 (if org-log-done "automatically" "not")))
17698 :style toggle :selected org-log-done])
17699 "--"
17700 ["Agenda Command..." org-agenda t]
17701 ("File List for Agenda")
17702 ("Special views current file"
17703 ["TODO Tree" org-show-todo-tree t]
17704 ["Check Deadlines" org-check-deadlines t]
17705 ["Timeline" org-timeline t]
17706 ["Tags Tree" org-tags-sparse-tree t])
17707 "--"
17708 ("Hyperlinks"
17709 ["Store Link (Global)" org-store-link t]
17710 ["Insert Link" org-insert-link t]
17711 ["Follow Link" org-open-at-point t]
17712 "--"
17713 ["Descriptive Links"
17714 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17715 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
17716 ["Literal Links"
17717 (progn
17718 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17719 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
17720 "--"
17721 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
17722 (save-excursion (goto-char (point-min))
17723 (re-search-forward "<[a-z]+:" nil t))])
17724 "--"
17725 ["Export/Publish..." org-export t]
17726 ("LaTeX"
17727 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
17728 :selected org-cdlatex-mode]
17729 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
17730 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
17731 ["Modify math symbol" org-cdlatex-math-modify
17732 (org-inside-LaTeX-fragment-p)]
17733 ["Export LaTeX fragments as images"
17734 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
17735 :style toggle :selected org-export-with-LaTeX-fragments])
17736 "--"
17737 ("Documentation"
17738 ["Show Version" org-version t]
17739 ["Info Documentation" org-info t])
17740 ("Customize"
17741 ["Browse Org Group" org-customize t]
17742 "--"
17743 ["Expand This Menu" org-create-customize-menu
17744 (fboundp 'customize-menu-create)])
17745 "--"
17746 ["Refresh setup" org-mode-restart t]
17749 (defun org-info (&optional node)
17750 "Read documentation for Org-mode in the info system.
17751 With optional NODE, go directly to that node."
17752 (interactive)
17753 (require 'info)
17754 (Info-goto-node (format "(org)%s" (or node ""))))
17756 (defun org-install-agenda-files-menu ()
17757 (let ((bl (buffer-list)))
17758 (save-excursion
17759 (while bl
17760 (set-buffer (pop bl))
17761 (if (org-mode-p) (setq bl nil)))
17762 (when (org-mode-p)
17763 (easy-menu-change
17764 '("Org") "File List for Agenda"
17765 (append
17766 (list
17767 ["Edit File List" (org-edit-agenda-file-list) t]
17768 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17769 ["Remove Current File from List" org-remove-file t]
17770 ["Cycle through agenda files" org-cycle-agenda-files t]
17771 "--")
17772 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17774 ;;;; Documentation
17776 (defun org-customize ()
17777 "Call the customize function with org as argument."
17778 (interactive)
17779 (customize-browse 'org))
17781 (defun org-create-customize-menu ()
17782 "Create a full customization menu for Org-mode, insert it into the menu."
17783 (interactive)
17784 (if (fboundp 'customize-menu-create)
17785 (progn
17786 (easy-menu-change
17787 '("Org") "Customize"
17788 `(["Browse Org group" org-customize t]
17789 "--"
17790 ,(customize-menu-create 'org)
17791 ["Set" Custom-set t]
17792 ["Save" Custom-save t]
17793 ["Reset to Current" Custom-reset-current t]
17794 ["Reset to Saved" Custom-reset-saved t]
17795 ["Reset to Standard Settings" Custom-reset-standard t]))
17796 (message "\"Org\"-menu now contains full customization menu"))
17797 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17799 ;;;; Miscellaneous stuff
17801 (defun org-context ()
17802 "Return a list of contexts of the current cursor position.
17803 If several contexts apply, all are returned.
17804 Each context entry is a list with a symbol naming the context, and
17805 two positions indicating start and end of the context. Possible
17806 contexts are:
17808 :headline anywhere in a headline
17809 :headline-stars on the leading stars in a headline
17810 :todo-keyword on a TODO keyword (including DONE) in a headline
17811 :tags on the TAGS in a headline
17812 :priority on the priority cookie in a headline
17813 :item on the first line of a plain list item
17814 :item-bullet on the bullet/number of a plain list item
17815 :checkbox on the checkbox in a plain list item
17816 :table in an org-mode table
17817 :table-special on a special filed in a table
17818 :table-table in a table.el table
17819 :link on a hyperline
17820 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17821 :target on a <<target>>
17822 :radio-target on a <<<radio-target>>>
17823 :latex-fragment on a LaTeX fragment
17824 :latex-preview on a LaTeX fragment with overlayed preview image
17826 This function expects the position to be visible because it uses font-lock
17827 faces as a help to recognize the following contexts: :table-special, :link,
17828 and :keyword."
17829 (let* ((f (get-text-property (point) 'face))
17830 (faces (if (listp f) f (list f)))
17831 (p (point)) clist o)
17832 ;; First the large context
17833 (cond
17834 ((org-on-heading-p)
17835 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17836 (when (progn
17837 (beginning-of-line 1)
17838 (looking-at org-todo-line-tags-regexp))
17839 (push (org-point-in-group p 1 :headline-stars) clist)
17840 (push (org-point-in-group p 2 :todo-keyword) clist)
17841 (push (org-point-in-group p 4 :tags) clist))
17842 (goto-char p)
17843 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
17844 (if (looking-at "\\[#[A-Z]\\]")
17845 (push (org-point-in-group p 0 :priority) clist)))
17847 ((org-at-item-p)
17848 (push (org-point-in-group p 2 :item-bullet) clist)
17849 (push (list :item (point-at-bol)
17850 (save-excursion (org-end-of-item) (point)))
17851 clist)
17852 (and (org-at-item-checkbox-p)
17853 (push (org-point-in-group p 0 :checkbox) clist)))
17855 ((org-at-table-p)
17856 (push (list :table (org-table-begin) (org-table-end)) clist)
17857 (if (memq 'org-formula faces)
17858 (push (list :table-special
17859 (previous-single-property-change p 'face)
17860 (next-single-property-change p 'face)) clist)))
17861 ((org-at-table-p 'any)
17862 (push (list :table-table) clist)))
17863 (goto-char p)
17865 ;; Now the small context
17866 (cond
17867 ((org-at-timestamp-p)
17868 (push (org-point-in-group p 0 :timestamp) clist))
17869 ((memq 'org-link faces)
17870 (push (list :link
17871 (previous-single-property-change p 'face)
17872 (next-single-property-change p 'face)) clist))
17873 ((memq 'org-special-keyword faces)
17874 (push (list :keyword
17875 (previous-single-property-change p 'face)
17876 (next-single-property-change p 'face)) clist))
17877 ((org-on-target-p)
17878 (push (org-point-in-group p 0 :target) clist)
17879 (goto-char (1- (match-beginning 0)))
17880 (if (looking-at org-radio-target-regexp)
17881 (push (org-point-in-group p 0 :radio-target) clist))
17882 (goto-char p))
17883 ((setq o (car (delq nil
17884 (mapcar
17885 (lambda (x)
17886 (if (memq x org-latex-fragment-image-overlays) x))
17887 (org-overlays-at (point))))))
17888 (push (list :latex-fragment
17889 (org-overlay-start o) (org-overlay-end o)) clist)
17890 (push (list :latex-preview
17891 (org-overlay-start o) (org-overlay-end o)) clist))
17892 ((org-inside-LaTeX-fragment-p)
17893 ;; FIXME: positions wrong.
17894 (push (list :latex-fragment (point) (point)) clist)))
17896 (setq clist (nreverse (delq nil clist)))
17897 clist))
17899 (defun org-point-in-group (point group &optional context)
17900 "Check if POINT is in match-group GROUP.
17901 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17902 match. If the match group does ot exist or point is not inside it,
17903 return nil."
17904 (and (match-beginning group)
17905 (>= point (match-beginning group))
17906 (<= point (match-end group))
17907 (if context
17908 (list context (match-beginning group) (match-end group))
17909 t)))
17911 (defun org-move-line-down (arg)
17912 "Move the current line down. With prefix argument, move it past ARG lines."
17913 (interactive "p")
17914 (let ((col (current-column))
17915 beg end pos)
17916 (beginning-of-line 1) (setq beg (point))
17917 (beginning-of-line 2) (setq end (point))
17918 (beginning-of-line (+ 1 arg))
17919 (setq pos (move-marker (make-marker) (point)))
17920 (insert (delete-and-extract-region beg end))
17921 (goto-char pos)
17922 (move-to-column col)))
17924 (defun org-move-line-up (arg)
17925 "Move the current line up. With prefix argument, move it past ARG lines."
17926 (interactive "p")
17927 (let ((col (current-column))
17928 beg end pos)
17929 (beginning-of-line 1) (setq beg (point))
17930 (beginning-of-line 2) (setq end (point))
17931 (beginning-of-line (- arg))
17932 (setq pos (move-marker (make-marker) (point)))
17933 (insert (delete-and-extract-region beg end))
17934 (goto-char pos)
17935 (move-to-column col)))
17937 (defun org-replace-escapes (string table)
17938 ;; FIXME: document and make safer
17939 (let (e)
17940 (while (setq e (pop table))
17941 (while (string-match (car e) string)
17942 (setq string (replace-match (cdr e) t t string))))
17943 string))
17945 ;;;; Paragraph filling stuff.
17946 ;; We want this to be just right, so use the full arsenal.
17948 (defun org-set-autofill-regexps ()
17949 (interactive)
17950 ;; In the paragraph separator we include headlines, because filling
17951 ;; text in a line directly attached to a headline would otherwise
17952 ;; fill the headline as well.
17953 (org-set-local 'comment-start-skip "^#+[ \t]*")
17954 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
17955 ;; The paragraph starter includes hand-formatted lists.
17956 (org-set-local 'paragraph-start
17957 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
17958 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17959 ;; But only if the user has not turned off tables or fixed-width regions
17960 (org-set-local
17961 'auto-fill-inhibit-regexp
17962 (concat "\\*\\|#\\+"
17963 "\\|[ \t]*" org-keyword-time-regexp
17964 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17965 (concat
17966 "\\|[ \t]*["
17967 (if org-enable-table-editor "|" "")
17968 (if org-enable-fixed-width-editor ":" "")
17969 "]"))))
17970 ;; We use our own fill-paragraph function, to make sure that tables
17971 ;; and fixed-width regions are not wrapped. That function will pass
17972 ;; through to `fill-paragraph' when appropriate.
17973 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17974 ; Adaptive filling: To get full control, first make sure that
17975 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17976 (org-set-local 'adaptive-fill-regexp "\000")
17977 (org-set-local 'adaptive-fill-function
17978 'org-adaptive-fill-function))
17980 (defun org-fill-paragraph (&optional justify)
17981 "Re-align a table, pass through to fill-paragraph if no table."
17982 (let ((table-p (org-at-table-p))
17983 (table.el-p (org-at-table.el-p)))
17984 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
17985 (table.el-p t) ; skip table.el tables
17986 (table-p (org-table-align) t) ; align org-mode tables
17987 (t nil)))) ; call paragraph-fill
17989 ;; For reference, this is the default value of adaptive-fill-regexp
17990 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17992 (defun org-adaptive-fill-function ()
17993 "Return a fill prefix for org-mode files.
17994 In particular, this makes sure hanging paragraphs for hand-formatted lists
17995 work correctly."
17996 (cond ((looking-at "#[ \t]+")
17997 (match-string 0))
17998 ((looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
17999 (make-string (- (match-end 0) (match-beginning 0)) ?\ ))
18000 (t nil)))
18002 ;; Functions needed for Emacs/XEmacs region compatibility
18004 (defun org-add-hook (hook function &optional append local)
18005 "Add-hook, compatible with both Emacsen."
18006 (if (and local (featurep 'xemacs))
18007 (add-local-hook hook function append)
18008 (add-hook hook function append local)))
18010 (defun org-region-active-p ()
18011 "Is `transient-mark-mode' on and the region active?
18012 Works on both Emacs and XEmacs."
18013 (if org-ignore-region
18015 (if (featurep 'xemacs)
18016 (and zmacs-regions (region-active-p))
18017 (and transient-mark-mode mark-active))))
18019 (defun org-add-to-invisibility-spec (arg)
18020 "Add elements to `buffer-invisibility-spec'.
18021 See documentation for `buffer-invisibility-spec' for the kind of elements
18022 that can be added."
18023 (cond
18024 ((fboundp 'add-to-invisibility-spec)
18025 (add-to-invisibility-spec arg))
18026 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
18027 (setq buffer-invisibility-spec (list arg)))
18029 (setq buffer-invisibility-spec
18030 (cons arg buffer-invisibility-spec)))))
18032 (defun org-remove-from-invisibility-spec (arg)
18033 "Remove elements from `buffer-invisibility-spec'."
18034 (if (fboundp 'remove-from-invisibility-spec)
18035 (remove-from-invisibility-spec arg)
18036 (if (consp buffer-invisibility-spec)
18037 (setq buffer-invisibility-spec
18038 (delete arg buffer-invisibility-spec)))))
18040 (defun org-in-invisibility-spec-p (arg)
18041 "Is ARG a member of `buffer-invisibility-spec'?"
18042 (if (consp buffer-invisibility-spec)
18043 (member arg buffer-invisibility-spec)
18044 nil))
18046 (defun org-image-file-name-regexp ()
18047 "Return regexp matching the file names of images."
18048 (if (fboundp 'image-file-name-regexp)
18049 (image-file-name-regexp)
18050 (let ((image-file-name-extensions
18051 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18052 "xbm" "xpm" "pbm" "pgm" "ppm")))
18053 (concat "\\."
18054 (regexp-opt (nconc (mapcar 'upcase
18055 image-file-name-extensions)
18056 image-file-name-extensions)
18058 "\\'"))))
18060 ;;;; Functions extending outline functionality
18062 ;; C-a should go to the beginning of a *visible* line, also in the
18063 ;; new outline.el. I guess this should be patched into Emacs?
18064 (defun org-beginning-of-line ()
18065 "Go to the beginning of the current line. If that is invisible, continue
18066 to a visible line beginning. This makes the function of C-a more intuitive."
18067 (interactive)
18068 (beginning-of-line 1)
18069 (if (bobp)
18071 (backward-char 1)
18072 (if (org-invisible-p)
18073 (while (and (not (bobp)) (org-invisible-p))
18074 (backward-char 1)
18075 (beginning-of-line 1))
18076 (forward-char 1))))
18078 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18080 (defun org-invisible-p ()
18081 "Check if point is at a character currently not visible."
18082 ;; Early versions of noutline don't have `outline-invisible-p'.
18083 (if (fboundp 'outline-invisible-p)
18084 (outline-invisible-p)
18085 (get-char-property (point) 'invisible)))
18087 (defun org-invisible-p2 ()
18088 "Check if point is at a character currently not visible."
18089 (save-excursion
18090 (if (and (eolp) (not (bobp))) (backward-char 1))
18091 ;; Early versions of noutline don't have `outline-invisible-p'.
18092 (if (fboundp 'outline-invisible-p)
18093 (outline-invisible-p)
18094 (get-char-property (point) 'invisible))))
18096 (defalias 'org-back-to-heading 'outline-back-to-heading)
18097 (defalias 'org-on-heading-p 'outline-on-heading-p)
18099 (defun org-on-target-p ()
18100 (let ((pos (point)))
18101 (save-excursion
18102 (skip-chars-forward "<")
18103 (and (re-search-backward "<<" nil t)
18104 (or (looking-at org-radio-target-regexp)
18105 (looking-at org-target-regexp))
18106 (<= (match-beginning 0) pos)
18107 (>= (1+ (match-end 0)) pos)))))
18109 (defun org-up-heading-all (arg)
18110 "Move to the heading line of which the present line is a subheading.
18111 This function considers both visible and invisible heading lines.
18112 With argument, move up ARG levels."
18113 (if (fboundp 'outline-up-heading-all)
18114 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18115 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18117 (defun org-goto-sibling (&optional previous)
18118 "Goto the next sibling, even if it is invisible.
18119 When PREVIOUS is set, go to the previous sibling instead. Returns t
18120 when a sibling was found. When none is found, return nil and don't
18121 move point."
18122 (let ((fun (if previous 're-search-backward 're-search-forward))
18123 (pos (point))
18124 (re (concat "^" outline-regexp))
18125 level l)
18126 (org-back-to-heading t)
18127 (setq level (funcall outline-level))
18128 (catch 'exit
18129 (or previous (forward-char 1))
18130 (while (funcall fun re nil t)
18131 (setq l (funcall outline-level))
18132 (when (< l level) (goto-char pos) (throw 'exit nil))
18133 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18134 (goto-char pos)
18135 nil)))
18137 (defun org-show-hidden-entry ()
18138 "Show an entry where even the heading is hidden."
18139 (save-excursion
18140 (org-show-entry)))
18142 (defun org-flag-heading (flag &optional entry)
18143 "Flag the current heading. FLAG non-nil means make invisible.
18144 When ENTRY is non-nil, show the entire entry."
18145 (save-excursion
18146 (org-back-to-heading t)
18147 ;; Check if we should show the entire entry
18148 (if entry
18149 (progn
18150 (org-show-entry)
18151 (save-excursion
18152 (and (outline-next-heading)
18153 (org-flag-heading nil))))
18154 (outline-flag-region (max 1 (1- (point)))
18155 (save-excursion (outline-end-of-heading) (point))
18156 flag))))
18158 (defun org-end-of-subtree (&optional invisible-OK)
18159 ;; This is an exact copy of the original function, but it uses
18160 ;; `org-back-to-heading', to make it work also in invisible
18161 ;; trees. And is uses an invisible-OK argument.
18162 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18163 (org-back-to-heading invisible-OK)
18164 (let ((first t)
18165 (level (funcall outline-level)))
18166 (while (and (not (eobp))
18167 (or first (> (funcall outline-level) level)))
18168 (setq first nil)
18169 (outline-next-heading))
18170 (if (memq (preceding-char) '(?\n ?\^M))
18171 (progn
18172 ;; Go to end of line before heading
18173 (forward-char -1)
18174 (if (memq (preceding-char) '(?\n ?\^M))
18175 ;; leave blank line before heading
18176 (forward-char -1)))))
18177 (point))
18179 (defun org-show-subtree ()
18180 "Show everything after this heading at deeper levels."
18181 (outline-flag-region
18182 (point)
18183 (save-excursion
18184 (outline-end-of-subtree) (outline-next-heading) (point))
18185 nil))
18187 (defun org-show-entry ()
18188 "Show the body directly following this heading.
18189 Show the heading too, if it is currently invisible."
18190 (interactive)
18191 (save-excursion
18192 (org-back-to-heading t)
18193 (outline-flag-region
18194 (max 1 (1- (point)))
18195 (save-excursion
18196 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
18197 (or (match-beginning 1) (point-max)))
18198 nil)))
18200 (defun org-make-options-regexp (kwds)
18201 "Make a regular expression for keyword lines."
18202 (concat
18204 "#?[ \t]*\\+\\("
18205 (mapconcat 'regexp-quote kwds "\\|")
18206 "\\):[ \t]*"
18207 "\\(.+\\)"))
18209 ;;;; Repair problems with some other packages
18211 ;; Make `bookmark-jump' show the jump location if it was hidden.
18212 (eval-after-load "bookmark"
18213 '(if (boundp 'bookmark-after-jump-hook)
18214 ;; We can use the hook
18215 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18216 ;; Hook not available, use advice
18217 (defadvice bookmark-jump (after org-make-visible activate)
18218 "Make the position visible."
18219 (org-bookmark-jump-unhide))))
18221 (defun org-bookmark-jump-unhide ()
18222 "Unhide the current position, to show the bookmark location."
18223 (and (org-mode-p)
18224 (or (org-invisible-p)
18225 (save-excursion (goto-char (max (point-min) (1- (point))))
18226 (org-invisible-p)))
18227 (org-show-context 'bookmark-jump)))
18229 ;; Make session.el ignore our circular variable
18230 (eval-after-load "session"
18231 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18233 ;;;; Experimental code
18237 ;;;; Finish up
18239 (provide 'org)
18241 (run-hooks 'org-load-hook)
18243 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18244 ;;; org.el ends here