Release 4.53
[org-mode/org-mode-NeilSmithlineMods.git] / org.el
blob3c0c21a6bc08dee32ebd784c3b34720e43e13dd2
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.53
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.53
65 ;; - Custom time formats can be overlayed over time stamps.
66 ;; - New option `org-agenda-todo-ignore-deadlines'.
67 ;; - Work-around for flyspell bug (CVS Emacs has this fixed in flyspell.el).
68 ;; - Work-around for session.el proglem with circular data structures.
69 ;; - Bug fixes.
71 ;; Version 4.52
72 ;; - TAG matches can also specify conditions on TODO keywords.
73 ;; - The fast tag interface allows setting tags that are not in the
74 ;; predefined list.
75 ;; - Bug fixes.
77 ;; Version 4.51
78 ;; - Link abbreviations (manual section 4.5).
79 ;; - More control over how agenda is displayed. See the new variables
80 ;; `org-agenda-window-setup', `org-agenda-restore-windows-after-quit'.
81 ;; - Bug fixes.
82 ;;
83 ;; Version 4.50
84 ;; - Closing a TODO item can record an additional note.
85 ;; See variables `org-log-done' and `org-log-note-headings'.
86 ;; - Inserting headlines and bullets can leave an extra blank line.
87 ;; See variable `org-blank-before-new-entry'. (Ed Hirgelt patch)
88 ;; - [[bracket links]] in the agenda are active just as in org-mode buffers.
89 ;; - C-c C-o on a date range displays the agenda for exactly this range.
90 ;; - The default for `org-cycle-include-plain-lists' is back to nil.
91 ;; - Calls to `org-occur' can be stacked by using a prefix argument.
92 ;; - The options `org-show-hierarchy-above' and `org-show-following-heading'
93 ;; now always default to `t', but can be customized differently for
94 ;; different types of sparse trees or jump commands.
95 ;; - Bug fixes.
97 ;; Version 4.49
98 ;; - Agenda views can be made in batch mode from the command line.
99 ;; - `org-store-link' does the right thing in dired-mode.
100 ;; - File links can contain environment variables.
101 ;; - Full Emacs 21 compatibility has been restored.
102 ;; - Bug fixes.
104 ;; Version 4.47
105 ;; - Custom commands may produce an agenda which contains several blocks,
106 ;; each block created by a different agenda command.
107 ;; - Agenda commands can be restricted to the current file, region, subtree.
108 ;; - The timeline command must now be called through the agenda
109 ;; dispatcher (C-c a L). `C-c C-r' no longer works.
110 ;; - Agenda items can be sorted by tag. The *last* tag is used for this.
111 ;; - The prefix and the sorting strategy for agenda items can depend
112 ;; upon the agenda type.
113 ;; - The handling of `mailto:' links can be customized, see the new
114 ;; variable `org-link-mailto-program'.
115 ;; - `mailto' links can specify a subject after a double colon,
116 ;; like [[mailto:carsten@orgmode.org::Org-mode is buggy]].
117 ;; - In the #+STARTUP line, M-TAB completes valid keywords.
118 ;; - In the #+TAGS: line, M-TAB after ":" inserts all currently used tags.
119 ;; - Again full Emacs 21 support: Checkboxes and publishing are fixed.
120 ;; - More minor bug fixes.
122 ;; Version 4.45
123 ;; - Checkbox lists can show statistics about checked items.
124 ;; - C-TAB will cycle the visibility of archived subtrees.
125 ;;; - Documentation about checkboxes has been moved to chapter 5.
126 ;; - Bux fixes.
128 ;; Version 4.44
129 ;; - Clock table can be done for a limited time interval.
130 ;; - Obsolete support for the old outline mode has been removed.
131 ;; - Bug fixes and code cleaning.
133 ;; Version 4.43
134 ;; - Bug fixes
135 ;; - `s' key in the agenda saves all org-mode buffers.
137 ;; Version 4.41
138 ;; - Shift-curser keys can modify inactive time stamps (inactive time
139 ;; stamps are the ones in [...] brackets.
140 ;; - Toggle all checkboxes in a region/below a headline.
141 ;; - Bug fixes.
143 ;;; Code:
145 (eval-when-compile
146 (require 'cl)
147 (require 'calendar))
148 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
149 ;; the file noutline.el being loaded.
150 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
151 ;; We require noutline, which might be provided in outline.el
152 (require 'outline) (require 'noutline)
153 ;; Other stuff we need.
154 (require 'time-date)
155 (require 'easymenu)
157 ;;; Customization variables
159 (defvar org-version "4.53"
160 "The version number of the file org.el.")
161 (defun org-version ()
162 (interactive)
163 (message "Org-mode version %s" org-version))
165 ;; Compatibility constants
166 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
167 (defconst org-format-transports-properties-p
168 (let ((x "a"))
169 (add-text-properties 0 1 '(test t) x)
170 (get-text-property 0 'test (format "%s" x)))
171 "Does format transport text properties?")
173 (defgroup org nil
174 "Outline-based notes management and organizer."
175 :tag "Org"
176 :group 'outlines
177 :group 'hypermedia
178 :group 'calendar)
180 (defgroup org-startup nil
181 "Options concerning startup of Org-mode."
182 :tag "Org Startup"
183 :group 'org)
185 (defcustom org-startup-folded t
186 "Non-nil means, entering Org-mode will switch to OVERVIEW.
187 This can also be configured on a per-file basis by adding one of
188 the following lines anywhere in the buffer:
190 #+STARTUP: fold
191 #+STARTUP: nofold
192 #+STARTUP: content"
193 :group 'org-startup
194 :type '(choice
195 (const :tag "nofold: show all" nil)
196 (const :tag "fold: overview" t)
197 (const :tag "content: all headlines" content)))
199 (defcustom org-startup-truncated t
200 "Non-nil means, entering Org-mode will set `truncate-lines'.
201 This is useful since some lines containing links can be very long and
202 uninteresting. Also tables look terrible when wrapped."
203 :group 'org-startup
204 :type 'boolean)
206 (defcustom org-startup-align-all-tables nil
207 "Non-nil means, align all tables when visiting a file.
208 This is useful when the column width in tables is forced with <N> cookies
209 in table fields. Such tables will look correct only after the first re-align.
210 This can also be configured on a per-file basis by adding one of
211 the following lines anywhere in the buffer:
212 #+STARTUP: align
213 #+STARTUP: noalign"
214 :group 'org-startup
215 :type 'boolean)
217 (defcustom org-startup-with-deadline-check nil
218 "Non-nil means, entering Org-mode will run the deadline check.
219 This means, if you start editing an org file, you will get an
220 immediate reminder of any due deadlines.
221 This can also be configured on a per-file basis by adding one of
222 the following lines anywhere in the buffer:
223 #+STARTUP: dlcheck
224 #+STARTUP: nodlcheck"
225 :group 'org-startup
226 :type 'boolean)
228 (defcustom org-insert-mode-line-in-empty-file nil
229 "Non-nil means insert the first line setting Org-mode in empty files.
230 When the function `org-mode' is called interactively in an empty file, this
231 normally means that the file name does not automatically trigger Org-mode.
232 To ensure that the file will always be in Org-mode in the future, a
233 line enforcing Org-mode will be inserted into the buffer, if this option
234 has been set."
235 :group 'org-startup
236 :type 'boolean)
238 (defcustom org-CUA-compatible nil
239 "Non-nil means use alternative key bindings for S-<cursor movement>.
240 Org-mode used S-<cursor movement> for changing timestamps and priorities.
241 S-<cursor movement> is also used for example by `CUA-mode' to select text.
242 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
243 alternative bindings. Setting this variable to t will replace the following
244 keys both in Org-mode and in the Org-agenda buffer.
246 S-RET -> C-S-RET
247 S-up -> M-p
248 S-down -> M-n
249 S-left -> M--
250 S-right -> M-+
252 If you do not like the alternative keys, take a look at the variable
253 `org-disputed-keys'.
255 This option is only relevant at load-time of Org-mode. Changing it requires
256 a restart of Emacs to become effective."
257 :group 'org-startup
258 :type 'boolean)
260 (defvar org-disputed-keys
261 '((S-up [(shift up)] [(meta ?p)])
262 (S-down [(shift down)] [(meta ?n)])
263 (S-left [(shift left)] [(meta ?-)])
264 (S-right [(shift right)] [(meta ?+)])
265 (S-return [(shift return)] [(control shift return)]))
266 "Keys for which Org-mode and other modes compete.
267 This is an alist, cars are symbols for lookup, 1st element is the default key,
268 second element will be used when `org-CUA-compatible' is t.")
270 (defun org-key (key)
271 "Select a key according to `org-CUA-compatible'."
272 (nth (if org-CUA-compatible 2 1)
273 (or (assq key org-disputed-keys)
274 (error "Invalid Key %s in `org-key'" key))))
276 (defcustom org-ellipsis nil
277 "The ellipsis to use in the Org-mode outline.
278 When nil, just use the standard three dots. When a string, use that instead,
279 and just in Org-mode (which will then use its own display table).
280 Changing this requires executing `M-x org-mode' in a buffer to become
281 effective."
282 :group 'org-startup
283 :type '(choice (const :tag "Default" nil)
284 (string :tag "String" :value "...#")))
286 (defvar org-display-table nil
287 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
289 (defgroup org-keywords nil
290 "Keywords in Org-mode."
291 :tag "Org Keywords"
292 :group 'org)
294 (defcustom org-deadline-string "DEADLINE:"
295 "String to mark deadline entries.
296 A deadline is this string, followed by a time stamp. Should be a word,
297 terminated by a colon. You can insert a schedule keyword and
298 a timestamp with \\[org-deadline].
299 Changes become only effective after restarting Emacs."
300 :group 'org-keywords
301 :type 'string)
303 (defcustom org-scheduled-string "SCHEDULED:"
304 "String to mark scheduled TODO entries.
305 A schedule is this string, followed by a time stamp. Should be a word,
306 terminated by a colon. You can insert a schedule keyword and
307 a timestamp with \\[org-schedule].
308 Changes become only effective after restarting Emacs."
309 :group 'org-keywords
310 :type 'string)
312 (defcustom org-closed-string "CLOSED:"
313 "String used as the prefix for timestamps logging closing a TODO entry."
314 :group 'org-keywords
315 :type 'string)
317 (defcustom org-clock-string "CLOCK:"
318 "String used as prefix for timestamps clocking work hours on an item."
319 :group 'org-keywords
320 :type 'string)
322 (defcustom org-comment-string "COMMENT"
323 "Entries starting with this keyword will never be exported.
324 An entry can be toggled between COMMENT and normal with
325 \\[org-toggle-comment].
326 Changes become only effective after restarting Emacs."
327 :group 'org-keywords
328 :type 'string)
330 (defcustom org-quote-string "QUOTE"
331 "Entries starting with this keyword will be exported in fixed-width font.
332 Quoting applies only to the text in the entry following the headline, and does
333 not extend beyond the next headline, even if that is lower level.
334 An entry can be toggled between QUOTE and normal with
335 \\[org-toggle-fixed-width-section]."
336 :group 'org-keywords
337 :type 'string)
339 (defgroup org-structure nil
340 "Options concerning the general structure of Org-mode files."
341 :tag "Org Structure"
342 :group 'org)
344 (defgroup org-cycle nil
345 "Options concerning visibility cycling in Org-mode."
346 :tag "Org Cycle"
347 :group 'org-structure)
349 (defcustom org-cycle-global-at-bob t
350 "Cycle globally if cursor is at beginning of buffer and not at a headline.
351 This makes it possible to do global cycling without having to use S-TAB or
352 C-u TAB. For this special case to work, the first line of the buffer
353 must not be a headline - it may be empty ot some other text. When used in
354 this way, `org-cycle-hook' is disables temporarily, to make sure the
355 cursor stays at the beginning of the buffer.
356 When this option is nil, don't do anything special at the beginning
357 of the buffer."
358 :group 'org-cycle
359 :type 'boolean)
361 (defcustom org-cycle-emulate-tab t
362 "Where should `org-cycle' emulate TAB.
363 nil Never
364 white Only in completely white lines
365 whitestart Only at the beginning of lines, before the first non-white char.
366 t Everywhere except in headlines
367 If TAB is used in a place where it does not emulate TAB, the current subtree
368 visibility is cycled."
369 :group 'org-cycle
370 :type '(choice (const :tag "Never" nil)
371 (const :tag "Only in completely white lines" white)
372 (const :tag "Before first char in a line" whitestart)
373 (const :tag "Everywhere except in headlines" t)
376 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
377 org-optimize-window-after-visibility-change)
378 "Hook that is run after `org-cycle' has changed the buffer visibility.
379 The function(s) in this hook must accept a single argument which indicates
380 the new state that was set by the most recent `org-cycle' command. The
381 argument is a symbol. After a global state change, it can have the values
382 `overview', `content', or `all'. After a local state change, it can have
383 the values `folded', `children', or `subtree'."
384 :group 'org-cycle
385 :type 'hook)
387 (defgroup org-edit-structure nil
388 "Options concerning structure editing in Org-mode."
389 :tag "Org Edit Structure"
390 :group 'org-structure)
392 (defcustom org-odd-levels-only nil
393 "Non-nil means, skip even levels and only use odd levels for the outline.
394 This has the effect that two stars are being added/taken away in
395 promotion/demotion commands. It also influences how levels are
396 handled by the exporters.
397 Changing it requires restart of `font-lock-mode' to become effective
398 for fontification also in regions already fontified.
399 You may also set this on a per-file basis by adding one of the following
400 lines to the buffer:
402 #+STARTUP: odd
403 #+STARTUP: oddeven"
404 :group 'org-edit-structure
405 :group 'org-font-lock
406 :type 'boolean)
408 (defcustom org-adapt-indentation t
409 "Non-nil means, adapt indentation when promoting and demoting.
410 When this is set and the *entire* text in an entry is indented, the
411 indentation is increased by one space in a demotion command, and
412 decreased by one in a promotion command. If any line in the entry
413 body starts at column 0, indentation is not changed at all."
414 :group 'org-edit-structure
415 :type 'boolean)
417 (defcustom org-blank-before-new-entry '((heading . nil)
418 (plain-list-item . nil))
419 "Should `org-insert-heading' leave a blank line before new heading/item?
420 The value is an alist, with `heading' and `plain-list-item' as car,
421 and a boolean flag as cdr."
422 :group 'org-edit-structure
423 :type '(list
424 (cons (const heading) (boolean))
425 (cons (const plain-list-item) (boolean))))
427 (defcustom org-insert-heading-hook nil
428 "Hook being run after inserting a new heading."
429 :group 'org-edit-structure
430 :type 'boolean)
432 (defcustom org-enable-fixed-width-editor t
433 "Non-nil means, lines starting with \":\" are treated as fixed-width.
434 This currently only means, they are never auto-wrapped.
435 When nil, such lines will be treated like ordinary lines.
436 See also the QUOTE keyword."
437 :group 'org-edit-structure
438 :type 'boolean)
440 (defgroup org-sparse-trees nil
441 "Options concerning sparse trees in Org-mode."
442 :tag "Org Sparse Trees"
443 :group 'org-structure)
445 (defcustom org-highlight-sparse-tree-matches t
446 "Non-nil means, highlight all matches that define a sparse tree.
447 The highlights will automatically disappear the next time the buffer is
448 changed by an edit command."
449 :group 'org-sparse-trees
450 :type 'boolean)
452 (defcustom org-remove-highlights-with-change t
453 "Non-nil means, any change to the buffer will remove temporary highlights.
454 Such highlights are created by `org-occur' and `org-clock-display'.
455 When nil, `C-c C-c needs to be used to get rid of the highlights.
456 The highlights created by `org-preview-latex-fragment' always need
457 `C-c C-c' to be removed."
458 :group 'org-sparse-trees
459 :group 'org-time
460 :type 'boolean)
462 (defcustom org-show-hierarchy-above '((default t))
463 "Non-nil means, show full hierarchy when showing a spot in the tree.
464 Turning this off makes sparse trees more compact, but also less clear.
465 Instead of t, this can also be an alist specifying this option for different
466 contexts. Valid contexts are
467 agenda when exposing an entry from the agenda
468 org-goto when using the command `org-goto' on key C-c C-j
469 occur-tree when using the command `org-occur' on key C-c /
470 tags-tree when constructing a sparse tree based on tags matches
471 link-search when exposing search matches associated with a link
472 mark-goto when exposing the jump goal of a mark
473 bookmark-jump when exposing a bookmark location
474 default default for all contexts not set explicitly"
475 :group 'org-sparse-trees
476 :type '(choice
477 (const :tag "Always" t)
478 (const :tag "Never" nil)
479 (repeat :greedy t :tag "Individual contexts"
480 (cons
481 (choice :tag "Context"
482 (const agenda)
483 (const org-goto)
484 (const occur-tree)
485 (const tags-tree)
486 (const link-search)
487 (const mark-goto)
488 (const bookmark-jump)
489 (const default))
490 (boolean)))))
492 (defcustom org-show-following-heading '((default t))
493 "Non-nil means, show heading following match in `org-occur'.
494 When doing an `org-occur' it is useful to show the headline which
495 follows the match, even if they do not match the regexp. This makes it
496 easier to edit directly inside the sparse tree. However, if you use
497 `org-occur' mainly as an overview, the following headlines are
498 unnecessary clutter.
499 Instead of t, this can also be an alist specifying this option for different
500 contexts. See `org-show-hierarchy-above' for valid contexts."
501 :group 'org-sparse-trees
502 :type '(choice
503 (const :tag "Always" t)
504 (const :tag "Never" nil)
505 (repeat :greedy t :tag "Individual contexts"
506 (cons
507 (choice :tag "Context"
508 (const agenda)
509 (const org-goto)
510 (const occur-tree)
511 (const tags-tree)
512 (const link-search)
513 (const mark-goto)
514 (const bookmark-jump)
515 (const default))
516 (boolean)))))
518 (defcustom org-occur-hook '(org-first-headline-recenter)
519 "Hook that is run after `org-occur' has constructed a sparse tree.
520 This can be used to recenter the window to show as much of the structure
521 as possible."
522 :group 'org-sparse-trees
523 :type 'hook)
525 (defgroup org-plain-lists nil
526 "Options concerning plain lists in Org-mode."
527 :tag "Org Plain lists"
528 :group 'org-structure)
530 (defcustom org-cycle-include-plain-lists nil
531 "Non-nil means, include plain lists into visibility cycling.
532 This means that during cycling, plain list items will *temporarily* be
533 interpreted as outline headlines with a level given by 1000+i where i is the
534 indentation of the bullet. In all other operations, plain list items are
535 not seen as headlines. For example, you cannot assign a TODO keyword to
536 such an item."
537 :group 'org-plain-lists
538 :type 'boolean)
540 (defcustom org-plain-list-ordered-item-terminator t
541 "The character that makes a line with leading number an ordered list item.
542 Valid values are ?. and ?\). To get both terminators, use t. While
543 ?. may look nicer, it creates the danger that a line with leading
544 number may be incorrectly interpreted as an item. ?\) therefore is
545 the safe choice."
546 :group 'org-plain-lists
547 :type '(choice (const :tag "dot like in \"2.\"" ?.)
548 (const :tag "paren like in \"2)\"" ?\))
549 (const :tab "both" t)))
551 (defcustom org-auto-renumber-ordered-lists t
552 "Non-nil means, automatically renumber ordered plain lists.
553 Renumbering happens when the sequence have been changed with
554 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
555 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
556 :group 'org-plain-lists
557 :type 'boolean)
559 (defcustom org-provide-checkbox-statistics t
560 "Non-nil means, update checkbox statistics after insert and toggle.
561 When this is set, checkbox statistics is updated each time you either insert
562 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
563 with \\[org-ctrl-c-ctrl-c\\]."
564 :group 'org
565 :type 'boolean)
567 (defgroup org-archive nil
568 "Options concerning archiving in Org-mode."
569 :tag "Org Archive"
570 :group 'org-structure)
572 (defcustom org-archive-tag "ARCHIVE"
573 "The tag that marks a subtree as archived.
574 An archived subtree does not open during visibility cycling, and does
575 not contribute to the agenda listings."
576 :group 'org-archive
577 :group 'org-keywords
578 :type 'string)
580 (defcustom org-agenda-skip-archived-trees t
581 "Non-nil means, the agenda will skip any items located in archived trees.
582 An archived tree is a tree marked with the tag ARCHIVE."
583 :group 'org-archive
584 :group 'org-agenda-display
585 :type 'boolean)
587 (defcustom org-cycle-open-archived-trees nil
588 "Non-nil means, `org-cycle' will open archived trees.
589 An archived tree is a tree marked with the tag ARCHIVE.
590 When nil, archived trees will stay folded. You can still open them with
591 normal outline commands like `show-all', but not with the cycling commands."
592 :group 'org-archive
593 :group 'org-cycle
594 :type 'boolean)
596 (defcustom org-sparse-tree-open-archived-trees nil
597 "Non-nil means sparse tree construction shows matches in archived trees.
598 When nil, matches in these trees are highlighted, but the trees are kept in
599 collapsed state."
600 :group 'org-archive
601 :group 'org-sparse-trees
602 :type 'boolean)
604 (defcustom org-archive-location "%s_archive::"
605 "The location where subtrees should be archived.
606 This string consists of two parts, separated by a double-colon.
608 The first part is a file name - when omitted, archiving happens in the same
609 file. %s will be replaced by the current file name (without directory part).
610 Archiving to a different file is useful to keep archived entries from
611 contributing to the Org-mode Agenda.
613 The part after the double colon is a headline. The archived entries will be
614 filed under that headline. When omitted, the subtrees are simply filed away
615 at the end of the file, as top-level entries.
617 Here are a few examples:
618 \"%s_archive::\"
619 If the current file is Projects.org, archive in file
620 Projects.org_archive, as top-level trees. This is the default.
622 \"::* Archived Tasks\"
623 Archive in the current file, under the top-level headline
624 \"* Archived Tasks\".
626 \"~/org/archive.org::\"
627 Archive in file ~/org/archive.org (absolute path), as top-level trees.
629 \"basement::** Finished Tasks\"
630 Archive in file ./basement (relative path), as level 3 trees
631 below the level 2 heading \"** Finished Tasks\".
633 You may set this option on a per-file basis by adding to the buffer a
634 line like
636 #+ARCHIVE: basement::** Finished Tasks"
637 :group 'org-archive
638 :type 'string)
640 (defcustom org-archive-mark-done t
641 "Non-nil means, mark entries as DONE when they are moved to the archive file."
642 :group 'org-archive
643 :type 'boolean)
645 (defcustom org-archive-stamp-time t
646 "Non-nil means, add a time stamp to entries moved to an archive file.
647 The time stamp will be added directly after the TODO state keyword in the
648 first line, so it is probably best to use this in combinations with
649 `org-archive-mark-done'."
650 :group 'org-archive
651 :type 'boolean)
653 (defgroup org-table nil
654 "Options concerning tables in Org-mode."
655 :tag "Org Table"
656 :group 'org)
658 (defcustom org-enable-table-editor 'optimized
659 "Non-nil means, lines starting with \"|\" are handled by the table editor.
660 When nil, such lines will be treated like ordinary lines.
662 When equal to the symbol `optimized', the table editor will be optimized to
663 do the following:
664 - Automatic overwrite mode in front of whitespace in table fields.
665 This makes the structure of the table stay in tact as long as the edited
666 field does not exceed the column width.
667 - Minimize the number of realigns. Normally, the table is aligned each time
668 TAB or RET are pressed to move to another field. With optimization this
669 happens only if changes to a field might have changed the column width.
670 Optimization requires replacing the functions `self-insert-command',
671 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
672 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
673 very good at guessing when a re-align will be necessary, but you can always
674 force one with \\[org-ctrl-c-ctrl-c].
676 If you would like to use the optimized version in Org-mode, but the
677 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
679 This variable can be used to turn on and off the table editor during a session,
680 but in order to toggle optimization, a restart is required.
682 See also the variable `org-table-auto-blank-field'."
683 :group 'org-table
684 :type '(choice
685 (const :tag "off" nil)
686 (const :tag "on" t)
687 (const :tag "on, optimized" optimized)))
689 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
690 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
691 In the optimized version, the table editor takes over all simple keys that
692 normally just insert a character. In tables, the characters are inserted
693 in a way to minimize disturbing the table structure (i.e. in overwrite mode
694 for empty fields). Outside tables, the correct binding of the keys is
695 restored.
697 The default for this option is t if the optimized version is also used in
698 Org-mode. See the variable `org-enable-table-editor' for details. Changing
699 this variable requires a restart of Emacs to become effective."
700 :group 'org-table
701 :type 'boolean)
703 (defgroup org-table-settings nil
704 "Settings for tables in Org-mode."
705 :tag "Org Table Settings"
706 :group 'org-table)
708 (defcustom org-table-default-size "5x2"
709 "The default size for newly created tables, Columns x Rows."
710 :group 'org-table-settings
711 :type 'string)
713 (defcustom org-table-number-regexp
714 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)?[0-9a-fA-F]+\\)$"
715 "Regular expression for recognizing numbers in table columns.
716 If a table column contains mostly numbers, it will be aligned to the
717 right. If not, it will be aligned to the left.
719 The default value of this option is a regular expression which allows
720 anything which looks remotely like a number as used in scientific
721 context. For example, all of the following will be considered a
722 number:
723 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
725 Other options offered by the customize interface are more restrictive."
726 :group 'org-table-settings
727 :type '(choice
728 (const :tag "Positive Integers"
729 "^[0-9]+$")
730 (const :tag "Integers"
731 "^[-+]?[0-9]+$")
732 (const :tag "Floating Point Numbers"
733 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
734 (const :tag "Floating Point Number or Integer"
735 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
736 (const :tag "Exponential, Floating point, Integer"
737 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
738 (const :tag "Very General Number-Like, including hex"
739 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)?[0-9a-fA-F]+\\)$")
740 (string :tag "Regexp:")))
742 (defcustom org-table-number-fraction 0.5
743 "Fraction of numbers in a column required to make the column align right.
744 In a column all non-white fields are considered. If at least this
745 fraction of fields is matched by `org-table-number-fraction',
746 alignment to the right border applies."
747 :group 'org-table-settings
748 :type 'number)
750 (defgroup org-table-editing nil
751 "Bahavior of tables during editing in Org-mode."
752 :tag "Org Table Editing"
753 :group 'org-table)
755 (defcustom org-table-automatic-realign t
756 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
757 When nil, aligning is only done with \\[org-table-align], or after column
758 removal/insertion."
759 :group 'org-table-editing
760 :type 'boolean)
762 (defcustom org-table-limit-column-width t ;kw
763 "Non-nil means, allow to limit the width of table columns with <N> fields."
764 :group 'org-table-editing
765 :type 'boolean)
767 (defcustom org-table-auto-blank-field t
768 "Non-nil means, automatically blank table field when starting to type into it.
769 This only happens when typing immediately after a field motion
770 command (TAB, S-TAB or RET).
771 Only relevant when `org-enable-table-editor' is equal to `optimized'."
772 :group 'org-table-editing
773 :type 'boolean)
775 (defcustom org-table-tab-jumps-over-hlines t
776 "Non-nil means, tab in the last column of a table with jump over a hline.
777 If a horizontal separator line is following the current line,
778 `org-table-next-field' can either create a new row before that line, or jump
779 over the line. When this option is nil, a new line will be created before
780 this line."
781 :group 'org-table-editing
782 :type 'boolean)
784 (defcustom org-table-tab-recognizes-table.el t
785 "Non-nil means, TAB will automatically notice a table.el table.
786 When it sees such a table, it moves point into it and - if necessary -
787 calls `table-recognize-table'."
788 :group 'org-table-editing
789 :type 'boolean)
791 (defgroup org-table-calculation nil
792 "Options concerning tables in Org-mode."
793 :tag "Org Table Calculation"
794 :group 'org-table)
796 (defcustom org-table-copy-increment t
797 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
798 :group 'org-table-calculation
799 :type 'boolean)
801 (defcustom org-calc-default-modes
802 '(calc-internal-prec 12
803 calc-float-format (float 5)
804 calc-angle-mode deg
805 calc-prefer-frac nil
806 calc-symbolic-mode nil
807 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
808 calc-display-working-message t
810 "List with Calc mode settings for use in calc-eval for table formulas.
811 The list must contain alternating symbols (Calc modes variables and values).
812 Don't remove any of the default settings, just change the values. Org-mode
813 relies on the variables to be present in the list."
814 :group 'org-table-calculation
815 :type 'plist)
817 (defcustom org-table-formula-evaluate-inline t
818 "Non-nil means, TAB and RET evaluate a formula in current table field.
819 If the current field starts with an equal sign, it is assumed to be a formula
820 which should be evaluated as described in the manual and in the documentation
821 string of the command `org-table-eval-formula'. This feature requires the
822 Emacs calc package.
823 When this variable is nil, formula calculation is only available through
824 the command \\[org-table-eval-formula]."
825 :group 'org-table-calculation
826 :type 'boolean)
829 (defcustom org-table-formula-use-constants t
830 "Non-nil means, interpret constants in formulas in tables.
831 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
832 by the value given in `org-table-formula-constants', or by a value obtained
833 from the `constants.el' package."
834 :group 'org-table-calculation
835 :type 'boolean)
837 (defcustom org-table-formula-constants nil
838 "Alist with constant names and values, for use in table formulas.
839 The car of each element is a name of a constant, without the `$' before it.
840 The cdr is the value as a string. For example, if you'd like to use the
841 speed of light in a formula, you would configure
843 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
845 and then use it in an equation like `$1*$c'."
846 :group 'org-table-calculation
847 :type '(repeat
848 (cons (string :tag "name")
849 (string :tag "value"))))
851 (defcustom org-table-formula-numbers-only nil
852 "Non-nil means, calculate only with numbers in table formulas.
853 Then all input fields will be converted to a number, and the result
854 must also be a number. When nil, calc's full potential is available
855 in table calculations, including symbolics etc."
856 :group 'org-table-calculation
857 :type 'boolean)
859 (defcustom org-table-allow-automatic-line-recalculation t
860 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
861 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
862 :group 'org-table-calculation
863 :type 'boolean)
865 (defgroup org-link nil
866 "Options concerning links in Org-mode."
867 :tag "Org Link"
868 :group 'org)
870 (defvar org-link-abbrev-alist-local nil
871 "buffer-local version of `org-link-abbrev-alist', which see.
872 The value of this is taken from the #+LINK lines.")
873 (make-variable-buffer-local 'org-link-abbrev-alist-local)
875 (defcustom org-link-abbrev-alist nil
876 "Alist of link abbreviations.
877 The car of each element is a string, to be replaced at the start of a link.
878 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
879 links in Org-mode buffers can have an optional tag after a double colon, e.g.
881 [[linkkey::tag][description]]
883 If REPLACE is a string, the tag will simply be appended to create the link.
884 If the string contains \"%s\", the tag will be inserted there. REPLACE may
885 also be a function that will be called with the tag as the only argument to
886 create the link. See the manual for examples."
887 :group 'org-link
888 :type 'alist)
890 (defcustom org-descriptive-links t
891 "Non-nil means, hide link part and only show description of bracket links.
892 Bracket links are like [[link][descritpion]]. This variable sets the initial
893 state in new org-mode buffers. The setting can then be toggled on a
894 per-buffer basis from the Org->Hyperlinks menu."
895 :group 'org-link
896 :type 'boolean)
898 (defcustom org-link-style 'bracket
899 "The style of links to be inserted with \\[org-insert-link].
900 Possible values are:
901 bracket [[link][description]]. This is recommended
902 plain Description \\n link. The old way, no longer recommended."
903 :group 'org-link
904 :type '(choice
905 (const :tag "Bracket (recommended)" bracket)
906 (const :tag "Plain (no longer recommended)" plain)))
908 (defcustom org-link-format "%s"
909 "Default format for external, URL-like linkes in the buffer.
910 This is a format string for printf, %s will be replaced by the link text.
911 The recommended value is just \"%s\", since links will be protected by
912 enclosing them in double brackets. If you prefer plain links (see variable
913 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
914 additional URL: prefix, so the format would be \"<URL:%s>\"."
915 :group 'org-link
916 :type '(choice
917 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
918 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
919 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
920 (string :tag "Other" :value "<%s>")))
922 (defcustom org-link-file-path-type 'adaptive
923 "How the path name in file links should be stored.
924 Valid values are:
926 relative relative to the current directory, i.e. the directory of the file
927 into which the link is being inserted.
928 absolute absolute path, if possible with ~ for home directory.
929 noabbrev absolute path, no abbreviation of home directory.
930 adaptive Use relative path for files in the current directory and sub-
931 directories of it. For other files, use an absolute path."
932 :group 'org-link
933 :type '(choice
934 (const relative)
935 (const absolute)
936 (const noabbrev)
937 (const adaptive)))
939 (defcustom org-activate-links '(bracket angle plain radio tag date)
940 "Types of links that should be activated in Org-mode files.
941 This is a list of symbols, each leading to the activation of a certain link
942 type. In principle, it does not hurt to turn on most link types - there may
943 be a small gain when turning off unused link types. The types are:
945 bracket The recommended [[link][description]] or [[link]] links with hiding.
946 angular Links in angular brackes that may contain whitespace like
947 <bbdb:Carsten Dominik>.
948 plain Plain links in normal text, no whitespace, like http://google.com.
949 radio Text that is matched by a radio target, see manual for details.
950 tag Tag settings in a headline (link to tag search).
951 date Time stamps (link to calendar).
952 camel CamelCase words defining text searches.
954 Changing this variable requires a restart of Emacs to become effective."
955 :group 'org-link
956 :type '(set (const :tag "Double bracket links (new style)" bracket)
957 (const :tag "Angular bracket links (old style)" angular)
958 (const :tag "plain text links" plain)
959 (const :tag "Radio target matches" radio)
960 (const :tag "Tags" tag)
961 (const :tag "Timestamps" date)
962 (const :tag "CamelCase words" camel)))
964 (defgroup org-link-store nil
965 "Options concerning storing links in Org-mode"
966 :tag "Org Store Link"
967 :group 'org-link)
969 (defcustom org-context-in-file-links t
970 "Non-nil means, file links from `org-store-link' contain context.
971 A search string will be added to the file name with :: as separator and
972 used to find the context when the link is activated by the command
973 `org-open-at-point'.
974 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
975 negates this setting for the duration of the command."
976 :group 'org-link-store
977 :type 'boolean)
979 (defcustom org-file-link-context-use-camel-case nil
980 "Non-nil means, use CamelCase to store a search context in a file link.
981 When nil, the search string simply consists of the words of the string.
982 CamelCase is deprecated, and support for it may be dropped in the future."
983 :group 'org-link-store
984 :type 'boolean)
986 (defcustom org-keep-stored-link-after-insertion nil
987 "Non-nil means, keep link in list for entire session.
989 The command `org-store-link' adds a link pointing to the current
990 location to an internal list. These links accumulate during a session.
991 The command `org-insert-link' can be used to insert links into any
992 Org-mode file (offering completion for all stored links). When this
993 option is nil, every link which has been inserted once using \\[org-insert-link]
994 will be removed from the list, to make completing the unused links
995 more efficient."
996 :group 'org-link-store
997 :type 'boolean)
999 (defcustom org-usenet-links-prefer-google nil
1000 "Non-nil means, `org-store-link' will create web links to Google groups.
1001 When nil, Gnus will be used for such links.
1002 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1003 negates this setting for the duration of the command."
1004 :group 'org-link-store
1005 :type 'boolean)
1007 (defgroup org-link-follow nil
1008 "Options concerning following links in Org-mode"
1009 :tag "Org Follow Link"
1010 :group 'org-link)
1012 (defcustom org-tab-follows-link nil
1013 "Non-nil means, on links TAB will follow the link.
1014 Needs to be set before org.el is loaded."
1015 :group 'org-link-follow
1016 :type 'boolean)
1018 (defcustom org-return-follows-link nil
1019 "Non-nil means, on links RET will follow the link.
1020 Needs to be set before org.el is loaded."
1021 :group 'org-link-follow
1022 :type 'boolean)
1024 (defcustom org-mouse-1-follows-link t
1025 "Non-nil means, mouse-1 on a link will follow the link.
1026 A longer mouse click will still set point. Does not wortk on XEmacs.
1027 Needs to be set before org.el is loaded."
1028 :group 'org-link-follow
1029 :type 'boolean)
1031 (defcustom org-mark-ring-length 4
1032 "Number of different positions to be recorded in the ring
1033 Changing this requires a restart of Emacs to work correctly."
1034 :group 'org-link-follow
1035 :type 'interger)
1037 (defcustom org-link-frame-setup
1038 '((vm . vm-visit-folder-other-frame)
1039 (gnus . gnus-other-frame)
1040 (file . find-file-other-window))
1041 "Setup the frame configuration for following links.
1042 When following a link with Emacs, it may often be useful to display
1043 this link in another window or frame. This variable can be used to
1044 set this up for the different types of links.
1045 For VM, use any of
1046 `vm-visit-folder'
1047 `vm-visit-folder-other-frame'
1048 For Gnus, use any of
1049 `gnus'
1050 `gnus-other-frame'
1051 For FILE, use any of
1052 `find-file'
1053 `find-file-other-window'
1054 `find-file-other-frame'
1055 For the calendar, use the variable `calendar-setup'.
1056 For BBDB, it is currently only possible to display the matches in
1057 another window."
1058 :group 'org-link-follow
1059 :type '(list
1060 (cons (const vm)
1061 (choice
1062 (const vm-visit-folder)
1063 (const vm-visit-folder-other-window)
1064 (const vm-visit-folder-other-frame)))
1065 (cons (const gnus)
1066 (choice
1067 (const gnus)
1068 (const gnus-other-frame)))
1069 (cons (const file)
1070 (choice
1071 (const find-file)
1072 (const find-file-other-window)
1073 (const find-file-other-frame)))))
1075 (defcustom org-display-internal-link-with-indirect-buffer nil
1076 "Non-nil means, use indirect buffer to display infile links.
1077 Activating internal links (from one location in a file to another location
1078 in the same file) normally just jumps to the location. When the link is
1079 activated with a C-u prefix (or with mouse-3), the link is displayed in
1080 another window. When this option is set, the other window actually displays
1081 an indirect buffer clone of the current buffer, to avoid any visibility
1082 changes to the current buffer."
1083 :group 'org-link-follow
1084 :type 'boolean)
1087 (defcustom org-open-non-existing-files nil
1088 "Non-nil means, `org-open-file' will open non-existing file.
1089 When nil, an error will be generated."
1090 :group 'org-link-follow
1091 :type 'boolean)
1093 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1094 "Function and arguments to call for following mailto links.
1095 This is a list with the first element being a lisp function, and the
1096 remaining elements being arguments to the function. In string arguments,
1097 %a will be replaced by the address, and %s will be replaced by the subject
1098 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1099 :group 'org-link-follow
1100 :type '(choice
1101 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1102 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1103 (const :tag "message-mail" (message-mail "%a" "%s"))
1104 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1106 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1107 "Non-nil means, ask for confirmation before executing shell links.
1108 Shell links can be dangerous, just thing about a link
1110 [[shell:rm -rf ~/*][Google Search]]
1112 This link would show up in your Org-mode document as \"Google Search\"
1113 but really it would remove your entire home directory.
1114 Therefore I *definitely* advise against setting this variable to nil.
1115 Just change it to `y-or-n-p' of you want to confirm with a single key press
1116 rather than having to type \"yes\"."
1117 :group 'org-link-follow
1118 :type '(choice
1119 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1120 (const :tag "with y-or-n (faster)" y-or-n-p)
1121 (const :tag "no confirmation (dangerous)" nil)))
1123 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1124 "Non-nil means, ask for confirmation before executing elisp links.
1125 Elisp links can be dangerous, just think about a link
1127 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1129 This link would show up in your Org-mode document as \"Google Search\"
1130 but really it would remove your entire home directory.
1131 Therefore I *definitely* advise against setting this variable to nil.
1132 Just change it to `y-or-n-p' of you want to confirm with a single key press
1133 rather than having to type \"yes\"."
1134 :group 'org-link-follow
1135 :type '(choice
1136 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1137 (const :tag "with y-or-n (faster)" y-or-n-p)
1138 (const :tag "no confirmation (dangerous)" nil)))
1140 (defconst org-file-apps-defaults-gnu
1141 '((remote . emacs)
1142 (t . mailcap))
1143 "Default file applications on a UNIX or GNU/Linux system.
1144 See `org-file-apps'.")
1146 (defconst org-file-apps-defaults-macosx
1147 '((remote . emacs)
1148 (t . "open %s")
1149 ("ps" . "gv %s")
1150 ("ps.gz" . "gv %s")
1151 ("eps" . "gv %s")
1152 ("eps.gz" . "gv %s")
1153 ("dvi" . "xdvi %s")
1154 ("fig" . "xfig %s"))
1155 "Default file applications on a MacOS X system.
1156 The system \"open\" is known as a default, but we use X11 applications
1157 for some files for which the OS does not have a good default.
1158 See `org-file-apps'.")
1160 (defconst org-file-apps-defaults-windowsnt
1161 (list
1162 '(remote . emacs)
1163 (cons t
1164 (list (if (featurep 'xemacs)
1165 'mswindows-shell-execute
1166 'w32-shell-execute)
1167 "open" 'file)))
1168 "Default file applications on a Windows NT system.
1169 The system \"open\" is used for most files.
1170 See `org-file-apps'.")
1172 (defcustom org-file-apps
1174 ("txt" . emacs)
1175 ("tex" . emacs)
1176 ("ltx" . emacs)
1177 ("org" . emacs)
1178 ("el" . emacs)
1179 ("bib" . emacs)
1181 "External applications for opening `file:path' items in a document.
1182 Org-mode uses system defaults for different file types, but
1183 you can use this variable to set the application for a given file
1184 extension. The entries in this list are cons cells where the car identifies
1185 files and the cdr the corresponding command. Possible values for the
1186 file identifier are
1187 \"ext\" A string identifying an extension
1188 `directory' Matches a directory
1189 `remote' Matches a remote file, accessible through tramp or efs.
1190 Remote files most likely should be visited through emacs
1191 because external applications cannot handle such paths.
1192 t Default for all remaining files
1194 Possible values for the command are:
1195 `emacs' The file will be visited by the current Emacs process.
1196 `default' Use the default application for this file type.
1197 string A command to be executed by a shell; %s will be replaced
1198 by the path to the file.
1199 sexp A Lisp form which will be evaluated. The file path will
1200 be available in the Lisp variable `file'.
1201 For more examples, see the system specific constants
1202 `org-file-apps-defaults-macosx'
1203 `org-file-apps-defaults-windowsnt'
1204 `org-file-apps-defaults-gnu'."
1205 :group 'org-link-follow
1206 :type '(repeat
1207 (cons (choice :value ""
1208 (string :tag "Extension")
1209 (const :tag "Default for unrecognized files" t)
1210 (const :tag "Remote file" remote)
1211 (const :tag "Links to a directory" directory))
1212 (choice :value ""
1213 (const :tag "Visit with Emacs" emacs)
1214 (const :tag "Use system default" default)
1215 (string :tag "Command")
1216 (sexp :tag "Lisp form")))))
1218 (defcustom org-mhe-search-all-folders nil
1219 "Non-nil means, that the search for the mh-message will be extended to
1220 all folders if the message cannot be found in the folder given in the link.
1221 Searching all folders is very effective with one of the search engines
1222 supported by MH-E, but will be slow with pick."
1223 :group 'org-link-follow
1224 :type 'boolean)
1226 (defgroup org-remember nil
1227 "Options concerning interaction with remember.el."
1228 :tag "Org Remember"
1229 :group 'org)
1231 (defcustom org-directory "~/org"
1232 "Directory with org files.
1233 This directory will be used as default to prompt for org files.
1234 Used by the hooks for remember.el."
1235 :group 'org-remember
1236 :type 'directory)
1238 (defcustom org-default-notes-file "~/.notes"
1239 "Default target for storing notes.
1240 Used by the hooks for remember.el. This can be a string, or nil to mean
1241 the value of `remember-data-file'."
1242 :group 'org-remember
1243 :type '(choice
1244 (const :tag "Default from remember-data-file" nil)
1245 file))
1247 (defcustom org-remember-templates nil
1248 "Templates for the creation of remember buffers.
1249 When nil, just let remember make the buffer.
1250 When not nil, this is a list of 3-element lists. In each entry, the first
1251 element is a character, a unique key to select this template.
1252 The second element is the template. The third element is optional and can
1253 specify a destination file for remember items created with this template.
1254 The default file is given by `org-default-notes-file'.
1256 The template specifies the structure of the remember buffer. It should have
1257 a first line starting with a star, to act as the org-mode headline.
1258 Furthermore, the following %-escapes will be replaced with content:
1259 %t time stamp, date only
1260 %T time stamp with date and time
1261 %u inactive time stamp, date only
1262 %U inactive time stamp with date and time
1263 %n user name
1264 %a annotation, normally the link created with org-store-link
1265 %i initial content, the region when remember is called with C-u.
1266 If %i is indented, the entire inserted text will be indented as well.
1267 %? This will be removed, and the cursor placed at this position."
1268 :group 'org-remember
1269 :type '(repeat :tag "enabled"
1270 (list :value (?a "\n" nil)
1271 (character :tag "Selection Key")
1272 (string :tag "Template")
1273 (file :tag "Destination file (optional)"))))
1275 (defcustom org-reverse-note-order nil
1276 "Non-nil means, store new notes at the beginning of a file or entry.
1277 When nil, new notes will be filed to the end of a file or entry."
1278 :group 'org-remember
1279 :type '(choice
1280 (const :tag "Reverse always" t)
1281 (const :tag "Reverse never" nil)
1282 (repeat :tag "By file name regexp"
1283 (cons regexp boolean))))
1285 (defgroup org-todo nil
1286 "Options concerning TODO items in Org-mode."
1287 :tag "Org TODO"
1288 :group 'org)
1290 (defcustom org-todo-keywords '("TODO" "DONE")
1291 "List of TODO entry keywords.
1292 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1293 considered to mean that the entry is \"done\". All the other mean that
1294 action is required, and will make the entry show up in todo lists, diaries
1295 etc.
1296 The command \\[org-todo] cycles an entry through these states, and an
1297 additional state where no keyword is present. For details about this
1298 cycling, see also the variable `org-todo-interpretation'
1299 Changes become only effective after restarting Emacs."
1300 :group 'org-todo
1301 :group 'org-keywords
1302 :type '(repeat (string :tag "Keyword")))
1304 (defcustom org-todo-interpretation 'sequence
1305 "Controls how TODO keywords are interpreted.
1306 This variable is only relevant if `org-todo-keywords' contains more than two
1307 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1309 When `sequence', \\[org-todo] will always switch to the next state in the
1310 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1311 to state when executed several times in direct succession. Otherwise, it
1312 switches directly to DONE from any state.
1313 See the manual for more information."
1314 :group 'org-todo
1315 :group 'org-keywords
1316 :type '(choice (const sequence)
1317 (const type)))
1319 (defcustom org-after-todo-state-change-hook nil
1320 "Hook which is run after the state of a TODO item was changed.
1321 The new state (a string with a TODO keyword, or nil) is available in the
1322 Lisp variable `state'."
1323 :group 'org-todo
1324 :type 'hook)
1326 (defcustom org-log-done nil
1327 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1328 When the state of an entry is changed from nothing to TODO, remove a previous
1329 closing date.
1331 This can also be a list of symbols indicating under which conditions
1332 the time stamp recording the action should be annotated with a short note.
1333 Valid members of this list are
1335 done Offer to record a note when marking entries done
1336 clock-out Offer to record a note when clocking out of an item.
1338 A separate window will then pop up and allow you to type a note.
1339 After finishing with C-c C-c, the note will be added directly after the
1340 timestamp, as a plain list item. See also the variable
1341 `org-log-note-headings'.
1343 Logging can also be configured on a per-file basis by adding one of
1344 the following lines anywhere in the buffer:
1346 #+STARTUP: logging
1347 #+STARTUP: nologging"
1348 ;; FIXME: in-buffer words for notes???????
1349 :group 'org-todo
1350 :type '(choice
1351 (const :tag "off" nil)
1352 (const :tag "on" t)
1353 (set :tag "on, with notes" :greedy t :value (done)
1354 (const done) (const clock-out))))
1356 (defcustom org-log-note-headings '((done . "CLOSING NOTE") (clock-out . ""))
1357 "Headings for notes added when clocking out or closing TODO items.
1358 The value is an alist, with the car being a sympol indicating the note
1359 context, and the cdr is the heading to be used. The heading may also be the
1360 empty string."
1361 :group 'org-todo
1362 :type '(list :greedy t
1363 (cons (const :tag "Heading when closing an item" done) string)
1364 (cons (const :tag "Heading when clocking out" clock-out) string)))
1366 (defgroup org-priorities nil
1367 "Priorities in Org-mode."
1368 :tag "Org Priorities"
1369 :group 'org-todo)
1371 (defcustom org-default-priority ?B
1372 "The default priority of TODO items.
1373 This is the priority an item get if no explicit priority is given."
1374 :group 'org-priorities
1375 :type 'character)
1377 (defcustom org-lowest-priority ?C
1378 "The lowest priority of TODO items. A character like ?A, ?B etc."
1379 :group 'org-priorities
1380 :type 'character)
1382 (defgroup org-time nil
1383 "Options concerning time stamps and deadlines in Org-mode."
1384 :tag "Org Time"
1385 :group 'org)
1387 (defcustom org-insert-labeled-timestamps-at-point nil
1388 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1389 When nil, these labeled time stamps are forces into the second line of an
1390 entry, just after the headline. When scheduling from the global TODO list,
1391 the time stamp will always be forced into the second line."
1392 :group 'org-time
1393 :type 'boolean)
1395 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1396 "Formats for `format-time-string' which are used for time stamps.
1397 It is not recommended to change this constant.")
1399 (defcustom org-time-stamp-rounding-minutes 0
1400 "Number of minutes to round time stamps to upon insertion.
1401 When zero, insert the time unmodified. Useful rounding numbers
1402 should be factors of 60, so for example 5, 10, 15.
1403 When this is not zero, you can still force an exact time-stamp by using
1404 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1405 :group 'org-time
1406 :type 'integer)
1408 (defcustom org-display-custom-times nil
1409 "Non-nil means, overlay custom formats over all time stamps.
1410 See also `org-time-stamp-custom-formats'.
1411 To turn this on on a per-file basis, insert anywhere in the file:
1412 #+STARTUP: customtime"
1413 :group 'org-time
1414 :set 'set-default
1415 :type 'sexp)
1416 (make-variable-buffer-local 'org-display-custom-times)
1418 (defcustom org-time-stamp-custom-formats
1419 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1420 "Custom formats for time stamps. See `format-time-string' for the syntax.
1421 These are overlayed over the default ISO format if the variable
1422 `org-display-custom-times' is set."
1423 :group 'org-time
1424 :type 'sexp)
1426 (defcustom org-deadline-warning-days 30
1427 "No. of days before expiration during which a deadline becomes active.
1428 This variable governs the display in sparse trees and in the agenda."
1429 :group 'org-time
1430 :type 'number)
1432 (defcustom org-popup-calendar-for-date-prompt t
1433 "Non-nil means, pop up a calendar when prompting for a date.
1434 In the calendar, the date can be selected with mouse-1. However, the
1435 minibuffer will also be active, and you can simply enter the date as well.
1436 When nil, only the minibuffer will be available."
1437 :group 'org-time
1438 :type 'boolean)
1440 (defcustom org-calendar-follow-timestamp-change t
1441 "Non-nil means, make the calendar window follow timestamp changes.
1442 When a timestamp is modified and the calendar window is visible, it will be
1443 moved to the new date."
1444 :group 'org-time
1445 :type 'boolean)
1447 (defgroup org-tags nil
1448 "Options concerning tags in Org-mode."
1449 :tag "Org Tags"
1450 :group 'org)
1452 (defcustom org-tag-alist nil
1453 "List of tags allowed in Org-mode files.
1454 When this list is nil, Org-mode will base TAG input on what is already in the
1455 buffer.
1456 The value of this variable is an alist, the car may be (and should) be a
1457 character that is used to select that tag through the fast-tag-selection
1458 interface. See the manual for details."
1459 :group 'org-tags
1460 :type '(repeat
1461 (choice
1462 (cons (string :tag "Tag name")
1463 (character :tag "Access char"))
1464 (const :tag "Start radio group" (:startgroup))
1465 (const :tag "End radio group" (:endgroup)))))
1467 (defcustom org-use-fast-tag-selection 'auto
1468 "Non-nil means, use fast tag selection scheme.
1469 This is a special interface to select and deselect tags with single keys.
1470 When nil, fast selection is never used.
1471 When the symbol `auto', fast selection is used if and only if selection
1472 characters for tags have been configured, either through the variable
1473 `org-tag-alist' or through a #+TAGS line in the buffer.
1474 When t, fast selection is always used and selection keys are assigned
1475 automatically if necessary."
1476 :group 'org-tags
1477 :type '(choice
1478 (const :tag "Always" t)
1479 (const :tag "Never" nil)
1480 (const :tag "When selection characters are configured" 'auto)))
1482 (defcustom org-tags-column 48
1483 "The column to which tags should be indented in a headline.
1484 If this number is positive, it specifies the column. If it is negative,
1485 it means that the tags should be flushright to that column. For example,
1486 -79 works well for a normal 80 character screen."
1487 :group 'org-tags
1488 :type 'integer)
1490 (defcustom org-auto-align-tags t
1491 "Non-nil means, realign tags after pro/demotion of TODO state change.
1492 These operations change the length of a headline and therefore shift
1493 the tags around. With this options turned on, after each such operation
1494 the tags are again aligned to `org-tags-column'."
1495 :group 'org-tags
1496 :type 'boolean)
1498 (defcustom org-use-tag-inheritance t
1499 "Non-nil means, tags in levels apply also for sublevels.
1500 When nil, only the tags directly given in a specific line apply there.
1501 If you turn off this option, you very likely want to turn on the
1502 companion option `org-tags-match-list-sublevels'."
1503 :group 'org-tags
1504 :type 'boolean)
1506 (defcustom org-tags-match-list-sublevels nil
1507 "Non-nil means list also sublevels of headlines matching tag search.
1508 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1509 the sublevels of a headline matching a tag search often also match
1510 the same search. Listing all of them can create very long lists.
1511 Setting this variable to nil causes subtrees of a match to be skipped.
1512 This option is off by default, because inheritance in on. If you turn
1513 inheritance off, you very likely want to turn this option on.
1515 As a special case, if the tag search is restricted to TODO items, the
1516 value of this variable is ignored and sublevels are always checked, to
1517 make sure all corresponding TODO items find their way into the list."
1518 :group 'org-tags
1519 :type 'boolean)
1521 (defvar org-tags-history nil
1522 "History of minibuffer reads for tags.")
1523 (defvar org-last-tags-completion-table nil
1524 "The last used completion table for tags.")
1526 (defgroup org-agenda nil
1527 "Options concerning agenda display Org-mode."
1528 :tag "Org Agenda"
1529 :group 'org)
1531 (defvar org-category nil
1532 "Variable used by org files to set a category for agenda display.
1533 Such files should use a file variable to set it, for example
1535 -*- mode: org; org-category: \"ELisp\"
1537 or contain a special line
1539 #+CATEGORY: ELisp
1541 If the file does not specify a category, then file's base name
1542 is used instead.")
1543 (make-variable-buffer-local 'org-category)
1545 (defcustom org-agenda-files nil
1546 "The files to be used for agenda display.
1547 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1548 \\[org-remove-file]. You can also use customize to edit the list.
1550 If the value of the variable is not a list but a single file name, then
1551 the list of agenda files is actually stored and maintained in that file, one
1552 agenda file per line."
1553 :group 'org-agenda
1554 :type '(choice
1555 (repeat :tag "List of files" file)
1556 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1558 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1559 "Custom commands for the agenda.
1560 These commands will be offered on the splash screen displayed by the
1561 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1563 (key type match options)
1565 key The key (a single char as a string) to be associated with the command.
1566 type The command type, any of the following symbols:
1567 todo Entries with a specific TODO keyword, in all agenda files.
1568 tags Tags match in all agenda files.
1569 tags-todo Tags match in all agenda files, TODO entries only.
1570 todo-tree Sparse tree of specific TODO keyword in *current* file.
1571 tags-tree Sparse tree with all tags matches in *current* file.
1572 occur-tree Occur sparse tree for *current* file.
1573 match What to search for:
1574 - a single keyword for TODO keyword searches
1575 - a tags match expression for tags searches
1576 - a regular expression for occur searches
1577 options A list of option setttings, similar to that in a let form, so like
1578 this: ((opt1 val1) (opt2 val2) ...)
1580 You can also define a set of commands, to create a composite agenda buffer.
1581 In this case, an entry looks like this:
1583 (key desc (cmd1 cmd2 ...) general-options)
1585 where
1587 desc A description string to be displayed in the dispatcher menu.
1588 cmd An agenda command, similar to the above. However, tree commands
1589 are no allowed, but instead you can get agenda and global todo list.
1590 So valid commands for a set are:
1591 (agenda)
1592 (alltodo)
1593 (todo \"match\" options)
1594 (tags \"match\" options )
1595 (tags-todo \"match\" options)
1597 Each command can carry a list of options, and another set of options can be
1598 given for the whole set of commands. Individual command options take
1599 precedence over the general options."
1600 :group 'org-agenda
1601 :type '(repeat
1602 (choice
1603 (list :tag "Single command"
1604 (string :tag "Key")
1605 (choice
1606 (const :tag "Tags search (all agenda files)" tags)
1607 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1608 (const :tag "TODO keyword search (all agenda files)" todo)
1609 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1610 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1611 (const :tag "Occur tree (current buffer)" occur-tree))
1612 (string :tag "Match")
1613 (repeat :tag "Local options"
1614 (list (variable :tag "Option") (sexp :tag "Value"))))
1615 (list :tag "Command series, all agenda files"
1616 (string :tag "Key")
1617 (string :tag "Description")
1618 (repeat
1619 (choice
1620 (const :tag "Agenda" (agenda))
1621 (const :tag "TODO list" (alltodo))
1622 (list :tag "Tags search"
1623 (const :format "" tags)
1624 (string :tag "Match")
1625 (repeat :tag "Local options"
1626 (list (variable :tag "Option")
1627 (sexp :tag "Value"))))
1629 (list :tag "Tags search, TODO entries only"
1630 (const :format "" tags-todo)
1631 (string :tag "Match")
1632 (repeat :tag "Local options"
1633 (list (variable :tag "Option")
1634 (sexp :tag "Value"))))
1636 (list :tag "TODO keyword search"
1637 (const :format "" todo)
1638 (string :tag "Match")
1639 (repeat :tag "Local options"
1640 (list (variable :tag "Option")
1641 (sexp :tag "Value"))))))
1642 (repeat :tag "General options"
1643 (list (variable :tag "Option")
1644 (sexp :tag "Value")))))))
1646 (defcustom org-agenda-todo-list-sublevels t
1647 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1648 When nil, the sublevels of a TODO entry are not checked, resulting in
1649 potentially much shorter TODO lists."
1650 :group 'org-agenda
1651 :group 'org-todo
1652 :type 'boolean)
1654 (defcustom org-agenda-todo-ignore-scheduled nil
1655 "Non-nil means, don't show scheduled entries in the global todo list.
1656 The idea behind this is that by scheduling it, you have already taken care
1657 of this item."
1658 :group 'org-agenda
1659 :group 'org-todo
1660 :type 'boolean)
1662 (defcustom org-agenda-todo-ignore-deadlines nil
1663 "Non-nil means, don't show near deadline entries in the global todo list.
1664 Near means closer than `org-deadline-warning-days' days.
1665 The idea behind this is that such items will appear in the agenda anyway."
1666 :group 'org-agenda
1667 :group 'org-todo
1668 :type 'boolean)
1671 (defcustom org-timeline-show-empty-dates 3
1672 "Non-nil means, `org-timeline' also shows dates without an entry.
1673 When nil, only the days which actually have entries are shown.
1674 When t, all days between the first and the last date are shown.
1675 When an integer, show also empty dates, but if there is a gap of more than
1676 N days, just insert a special line indicating the size of the gap."
1677 :group 'org-agenda
1678 :type '(choice
1679 (const :tag "None" nil)
1680 (const :tag "All" t)
1681 (number :tag "at most")))
1683 (defcustom org-agenda-include-all-todo nil
1684 "Set means weekly/daily agenda will always contain all TODO entries.
1685 The TODO entries will be listed at the top of the agenda, before
1686 the entries for specific days."
1687 :group 'org-agenda
1688 :type 'boolean)
1690 (defcustom org-agenda-include-diary nil
1691 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1692 :group 'org-agenda
1693 :type 'boolean)
1695 (defcustom org-calendar-to-agenda-key [?c]
1696 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1697 The command `org-calendar-goto-agenda' will be bound to this key. The
1698 default is the character `c' because then `c' can be used to switch back and
1699 forth between agenda and calendar."
1700 :group 'org-agenda
1701 :type 'sexp)
1703 (defgroup org-agenda-setup nil
1704 "Options concerning setting up the Agenda window in Org Mode."
1705 :tag "Org Agenda Window Setup"
1706 :group 'org-agenda)
1708 (defcustom org-agenda-window-setup 'reorganize-frame
1709 "How the agenda buffer should be displayed.
1710 Possible values for this option are:
1712 current-window Show agenda in the current window, keeping all other windows.
1713 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1714 other-window Use `switch-to-buffer-other-window' to display agenda.
1715 reorganize-frame Show only two windows on the current frame, the current
1716 window and the agenda. Also, if the option
1717 `org-fit-agenda-window' is set, resize the agenda window to
1718 try to show as much as possible of the buffer content.
1719 See also the variable `org-agenda-restore-windows-after-quit'."
1720 :group 'org-agenda-setup
1721 :type '(choice
1722 (const current-window)
1723 (const other-frame)
1724 (const other-window)
1725 (const reorganize-frame)))
1727 (defcustom org-agenda-restore-windows-after-quit nil
1728 "Non-nil means, restore window configuration open exiting agenda.
1729 Before the window configuration is changed for displaying the agenda,
1730 the current status is recorded. When the agenda is exited with
1731 `q' or `x' and this option is set, the old state is restored. If
1732 `org-agenda-window-setup' is `other-frame', the value of this
1733 option will be ignored.."
1734 :group 'org-agenda-setup
1735 :type 'boolean)
1737 ;; FIXME: I think this variable could be removed.
1738 (defcustom org-select-agenda-window t
1739 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1740 When nil, cursor will remain in the current window."
1741 :group 'org-agenda-setup
1742 :type 'boolean)
1744 ;; FIXME: I think this variable could be removed.
1745 (defcustom org-fit-agenda-window t
1746 "Non-nil means, change window size of agenda to fit content.
1747 This is only effective if `org-agenda-window-setup' is `reorganize-frame'."
1748 :group 'org-agenda-setup
1749 :type 'boolean)
1751 (defcustom org-finalize-agenda-hook nil
1752 "Hook run just before displaying an agenda buffer."
1753 :group 'org-agenda-setup
1754 :type 'hook)
1756 (defcustom org-agenda-mouse-1-follows-link nil
1757 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1758 A longer mouse click will still set point. Does not wortk on XEmacs.
1759 Needs to be set before org.el is loaded."
1760 :group 'org-agenda-setup
1761 :type 'boolean)
1763 (defcustom org-agenda-start-with-follow-mode nil
1764 "The initial value of follwo-mode in a newly created agenda window."
1765 :group 'org-agenda-setup
1766 :type 'boolean)
1768 (defgroup org-agenda-display nil
1769 "Options concerning what to display initially in Agenda."
1770 :tag "Org Agenda Display"
1771 :group 'org-agenda)
1773 (defcustom org-agenda-show-all-dates t
1774 "Non-nil means, `org-agenda' shows every day in the selected range.
1775 When nil, only the days which actually have entries are shown."
1776 :group 'org-agenda-display
1777 :type 'boolean)
1779 (defcustom org-agenda-start-on-weekday 1
1780 "Non-nil means, start the overview always on the specified weekday.
1781 0 denotes Sunday, 1 denotes Monday etc.
1782 When nil, always start on the current day."
1783 :group 'org-agenda-display
1784 :type '(choice (const :tag "Today" nil)
1785 (number :tag "Weekday No.")))
1787 (defcustom org-agenda-ndays 7
1788 "Number of days to include in overview display.
1789 Should be 1 or 7."
1790 :group 'org-agenda-display
1791 :type 'number)
1793 (defcustom org-agenda-use-time-grid t
1794 "Non-nil means, show a time grid in the agenda schedule.
1795 A time grid is a set of lines for specific times (like every two hours between
1796 8:00 and 20:00). The items scheduled for a day at specific times are
1797 sorted in between these lines.
1798 For details about when the grid will be shown, and what it will look like, see
1799 the variable `org-agenda-time-grid'."
1800 :group 'org-agenda-display
1801 :type 'boolean)
1803 (defcustom org-agenda-time-grid
1804 '((daily today require-timed)
1805 "----------------"
1806 (800 1000 1200 1400 1600 1800 2000))
1808 "The settings for time grid for agenda display.
1809 This is a list of three items. The first item is again a list. It contains
1810 symbols specifying conditions when the grid should be displayed:
1812 daily if the agenda shows a single day
1813 weekly if the agenda shows an entire week
1814 today show grid on current date, independent of daily/weekly display
1815 require-timed show grid only if at least one item has a time specification
1817 The second item is a string which will be places behing the grid time.
1819 The third item is a list of integers, indicating the times that should have
1820 a grid line."
1821 :group 'org-agenda-display
1822 :type
1823 '(list
1824 (set :greedy t :tag "Grid Display Options"
1825 (const :tag "Show grid in single day agenda display" daily)
1826 (const :tag "Show grid in weekly agenda display" weekly)
1827 (const :tag "Always show grid for today" today)
1828 (const :tag "Show grid only if any timed entries are present"
1829 require-timed)
1830 (const :tag "Skip grid times already present in an entry"
1831 remove-match))
1832 (string :tag "Grid String")
1833 (repeat :tag "Grid Times" (integer :tag "Time"))))
1835 (let ((sorting-choice
1836 '(choice
1837 (const time-up) (const time-down)
1838 (const category-keep) (const category-up) (const category-down)
1839 (const tag-down) (const tag-up)
1840 (const priority-up) (const priority-down))))
1842 (defcustom org-agenda-sorting-strategy
1843 '((agenda time-up category-keep priority-down)
1844 (todo category-keep priority-down)
1845 (tags category-keep))
1846 "Sorting structure for the agenda items of a single day.
1847 This is a list of symbols which will be used in sequence to determine
1848 if an entry should be listed before another entry. The following
1849 symbols are recognized:
1851 time-up Put entries with time-of-day indications first, early first
1852 time-down Put entries with time-of-day indications first, late first
1853 category-keep Keep the default order of categories, corresponding to the
1854 sequence in `org-agenda-files'.
1855 category-up Sort alphabetically by category, A-Z.
1856 category-down Sort alphabetically by category, Z-A.
1857 tag-up Sort alphabetically by last tag, A-Z.
1858 tag-down Sort alphabetically by last tag, Z-A.
1859 priority-up Sort numerically by priority, high priority last.
1860 priority-down Sort numerically by priority, high priority first.
1862 The different possibilities will be tried in sequence, and testing stops
1863 if one comparison returns a \"not-equal\". For example, the default
1864 '(time-up category-keep priority-down)
1865 means: Pull out all entries having a specified time of day and sort them,
1866 in order to make a time schedule for the current day the first thing in the
1867 agenda listing for the day. Of the entries without a time indication, keep
1868 the grouped in categories, don't sort the categories, but keep them in
1869 the sequence given in `org-agenda-files'. Within each category sort by
1870 priority.
1872 Leaving out `category-keep' would mean that items will be sorted across
1873 categories by priority."
1874 :group 'org-agenda-display
1875 :type `(choice
1876 (repeat :tag "General" ,sorting-choice)
1877 (list :tag "Individually"
1878 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
1879 (repeat ,sorting-choice))
1880 (cons (const :tag "Strategy for TODO lists" todo)
1881 (repeat ,sorting-choice))
1882 (cons (const :tag "Strategy for Tags matches" tags)
1883 (repeat ,sorting-choice))))))
1885 (defcustom org-sort-agenda-notime-is-late t
1886 "Non-nil means, items without time are considered late.
1887 This is only relevant for sorting. When t, items which have no explicit
1888 time like 15:30 will be considered as 99:01, i.e. later than any items which
1889 do have a time. When nil, the default time is before 0:00. You can use this
1890 option to decide if the schedule for today should come before or after timeless
1891 agenda entries."
1892 :group 'org-agenda-display
1893 :type 'boolean)
1895 (defgroup org-agenda-prefix nil
1896 "Options concerning the entry prefix in the Org-mode agenda display."
1897 :tag "Org Agenda Prefix"
1898 :group 'org-agenda)
1900 (defcustom org-agenda-prefix-format
1901 '((agenda . " %-12:c%?-12t% s")
1902 (timeline . " % s")
1903 (todo . " %-12:c")
1904 (tags . " %-12:c"))
1905 "Format specifications for the prefix of items in the agenda views.
1906 An alist with four entries, for the different agenda types. The keys to the
1907 sublists are `agenda', `timeline', `todo', and `tags'. The values
1908 are format strings.
1909 This format works similar to a printf format, with the following meaning:
1911 %c the category of the item, \"Diary\" for entries from the diary, or
1912 as given by the CATEGORY keyword or derived from the file name.
1913 %T the *last* tag of the item. Last because inherited tags come
1914 first in the list.
1915 %t the time-of-day specification if one applies to the entry, in the
1916 format HH:MM
1917 %s Scheduling/Deadline information, a short string
1919 All specifiers work basically like the standard `%s' of printf, but may
1920 contain two additional characters: A question mark just after the `%' and
1921 a whitespace/punctuation character just before the final letter.
1923 If the first character after `%' is a question mark, the entire field
1924 will only be included if the corresponding value applies to the
1925 current entry. This is useful for fields which should have fixed
1926 width when present, but zero width when absent. For example,
1927 \"%?-12t\" will result in a 12 character time field if a time of the
1928 day is specified, but will completely disappear in entries which do
1929 not contain a time.
1931 If there is punctuation or whitespace character just before the final
1932 format letter, this character will be appended to the field value if
1933 the value is not empty. For example, the format \"%-12:c\" leads to
1934 \"Diary: \" if the category is \"Diary\". If the category were be
1935 empty, no additional colon would be interted.
1937 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1938 - Indent the line with two space characters
1939 - Give the category in a 12 chars wide field, padded with whitespace on
1940 the right (because of `-'). Append a colon if there is a category
1941 (because of `:').
1942 - If there is a time-of-day, put it into a 12 chars wide field. If no
1943 time, don't put in an empty field, just skip it (because of '?').
1944 - Finally, put the scheduling information and append a whitespace.
1946 As another example, if you don't want the time-of-day of entries in
1947 the prefix, you could use:
1949 (setq org-agenda-prefix-format \" %-11:c% s\")
1951 See also the variables `org-agenda-remove-times-when-in-prefix' and
1952 `org-agenda-remove-tags-when-in-prefix'."
1953 :type '(choice
1954 (string :tag "General format")
1955 (list :greedy t :tag "View dependent"
1956 (cons (const agenda) (string :tag "Format"))
1957 (cons (const timeline) (string :tag "Format"))
1958 (cons (const todo) (string :tag "Format"))
1959 (cons (const tags) (string :tag "Format"))))
1960 :group 'org-agenda-prefix)
1962 (defvar org-prefix-format-compiled nil
1963 "The compiled version of the most recently used prefix format.
1964 See the variable `org-agenda-prefix-format'.")
1966 (defcustom org-agenda-remove-times-when-in-prefix t
1967 "Non-nil means, remove duplicate time specifications in agenda items.
1968 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1969 time-of-day specification in a headline or diary entry is extracted and
1970 placed into the prefix. If this option is non-nil, the original specification
1971 \(a timestamp or -range, or just a plain time(range) specification like
1972 11:30-4pm) will be removed for agenda display. This makes the agenda less
1973 cluttered.
1974 The option can be t or nil. It may also be the symbol `beg', indicating
1975 that the time should only be removed what it is located at the beginning of
1976 the headline/diary entry."
1977 :group 'org-agenda-prefix
1978 :type '(choice
1979 (const :tag "Always" t)
1980 (const :tag "Never" nil)
1981 (const :tag "When at beginning of entry" beg)))
1983 (defcustom org-agenda-remove-tags-when-in-prefix nil
1984 "Non-nil means, remove the tags from the headline copy in the agenda.
1985 When this is the symbol `prefix', only remove tags when
1986 `org-agenda-prefix-format' contains a `%T' specifier."
1987 :group 'org-agenda-prefix
1988 :type '(choice
1989 (const :tag "Always" t)
1990 (const :tag "Never" nil)
1991 (const :tag "When prefix format contains %T" prefix)))
1993 (defcustom org-agenda-align-tags-to-column 65
1994 "Shift tags in agenda items to this column."
1995 :group 'org-agenda-prefix
1996 :type 'integer)
1998 (defgroup org-latex nil
1999 "Options for embedding LaTeX code into Org-mode"
2000 :tag "Org LaTeX"
2001 :group 'org)
2003 (defcustom org-format-latex-options
2004 '(:foreground "Black" :background "Transparent" :scale 1.0
2005 :matchers ("begin" "$" "$$" "\\(" "\\["))
2006 "Options for creating images from LaTeX fragments.
2007 This is a property list with the following properties:
2008 :foreground the foreground color, for example \"Black\".
2009 :background the background color, or \"Transparent\".
2010 :scale a scaling factor for the size of the images
2011 :matchers a list indicating which matchers should be used to
2012 find LaTeX fragments. Valid members of this list are:
2013 \"begin\" find environments
2014 \"$\" find math expressions surrounded by $...$
2015 \"$$\" find math expressions surrounded by $$....$$
2016 \"\\(\" find math expressions surrounded by \\(...\\)
2017 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2018 :group 'org-latex
2019 :type 'plist)
2021 (defgroup org-export nil
2022 "Options for exporting org-listings."
2023 :tag "Org Export"
2024 :group 'org)
2026 (defgroup org-export-general nil
2027 "General options for exporting Org-mode files."
2028 :tag "Org Export General"
2029 :group 'org-export)
2031 (defcustom org-export-publishing-directory "."
2032 "Path to the location where exported files should be located.
2033 This path may be relative to the directory where the Org-mode file lives.
2034 The default is to put them into the same directory as the Org-mode file.
2035 The variable may also be an alist with export types `:html', `:ascii',
2036 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2037 is relative, it is interpreted relative to the directory where the exported
2038 Org-mode files lives."
2039 :group 'org-export-general
2040 :type '(choice
2041 (directory)
2042 (repeat
2043 (cons
2044 (choice :tag "Type"
2045 (const :html) (const :ascii) (const :ical) (const :xoxo))
2046 (directory)))))
2048 (defcustom org-export-language-setup
2049 '(("en" "Author" "Date" "Table of Contents")
2050 ("cs" "Autor" "Datum" "Obsah")
2051 ("da" "Ophavsmand" "Dato" "Indhold")
2052 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2053 ("es" "Autor" "Fecha" "\xccndice")
2054 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2055 ("it" "Autore" "Data" "Indice")
2056 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2057 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2058 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2059 "Terms used in export text, translated to different languages.
2060 Use the variable `org-export-default-language' to set the language,
2061 or use the +OPTION lines for a per-file setting."
2062 :group 'org-export-general
2063 :type '(repeat
2064 (list
2065 (string :tag "HTML language tag")
2066 (string :tag "Author")
2067 (string :tag "Date")
2068 (string :tag "Table of Contents"))))
2070 (defcustom org-export-default-language "en"
2071 "The default language of HTML export, as a string.
2072 This should have an association in `org-export-language-setup'."
2073 :group 'org-export-general
2074 :type 'string)
2076 (defcustom org-export-headline-levels 3
2077 "The last level which is still exported as a headline.
2078 Inferior levels will produce itemize lists when exported.
2079 Note that a numeric prefix argument to an exporter function overrides
2080 this setting.
2082 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2083 :group 'org-export-general
2084 :type 'number)
2086 (defcustom org-export-with-section-numbers t
2087 "Non-nil means, add section numbers to headlines when exporting.
2089 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2090 :group 'org-export-general
2091 :type 'boolean)
2093 (defcustom org-export-with-toc t
2094 "Non-nil means, create a table of contents in exported files.
2095 The TOC contains headlines with levels up to`org-export-headline-levels'.
2097 Headlines which contain any TODO items will be marked with \"(*)\" in
2098 ASCII export, and with red color in HTML output.
2100 In HTML output, the TOC will be clickable.
2102 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
2103 :group 'org-export-general
2104 :type 'boolean)
2106 (defcustom org-export-mark-todo-in-toc nil
2107 "Non-nil means, mark TOC lines that contain any open TODO items."
2108 :group 'org-export-general
2109 :type 'boolean)
2111 (defcustom org-export-preserve-breaks nil
2112 "Non-nil means, preserve all line breaks when exporting.
2113 Normally, in HTML output paragraphs will be reformatted. In ASCII
2114 export, line breaks will always be preserved, regardless of this variable.
2116 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2117 :group 'org-export-general
2118 :type 'boolean)
2120 (defcustom org-export-with-archived-trees 'headline
2121 "Whether subtrees with the ARCHIVE tag should be exported.
2122 This can have three different values
2123 nil Do not export, pretend this tree is not present
2124 t Do export the entire tree
2125 headline Only export the headline, but skip the tree below it."
2126 :group 'org-export-general
2127 :group 'org-archive
2128 :type '(choice
2129 (const :tag "not at all" nil)
2130 (const :tag "headline only" 'headline)
2131 (const :tag "entirely" t)))
2133 (defcustom org-export-with-timestamps t
2134 "Nil means, do not export time stamps and associated keywords."
2135 :group 'org-export-general
2136 :type 'boolean)
2138 (defcustom org-export-remove-timestamps-from-toc t
2139 "Nil means, remove timestamps from the table of contents entries."
2140 :group 'org-export-general
2141 :type 'boolean)
2143 (defcustom org-export-with-tags 'not-in-toc
2144 "Nil means, do not export tags, just remove them from headlines.
2145 If this is the sysmbol `not-in-toc', tags will be removed from table of
2146 contents entries, but still be shown in the headlines of the document."
2147 :group 'org-export-general
2148 :type '(choice
2149 (const :tag "Off" nil)
2150 (const :tag "Not in TOC" not-in-toc)
2151 (const :tag "On" t)))
2153 (defgroup org-export-translation nil
2154 "Options for translating special ascii sequences for the export backends."
2155 :tag "Org Export Translation"
2156 :group 'org-export)
2158 (defcustom org-export-with-emphasize t
2159 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2160 If the export target supports emphasizing text, the word will be
2161 typeset in bold, italic, or underlined, respectively. Works only for
2162 single words, but you can say: I *really* *mean* *this*.
2163 Not all export backends support this.
2165 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2166 :group 'org-export-translation
2167 :type 'boolean)
2169 (defcustom org-export-with-sub-superscripts t
2170 "Non-nil means, interpret \"_\" and \"^\" for export.
2171 When this option is turned on, you can use TeX-like syntax for sub- and
2172 superscripts. Several characters after \"_\" or \"^\" will be
2173 considered as a single item - so grouping with {} is normally not
2174 needed. For example, the following things will be parsed as single
2175 sub- or superscripts.
2177 10^24 or 10^tau several digits will be considered 1 item.
2178 10^-12 or 10^-tau a leading sign with digits or a word
2179 x^2-y^3 will be read as x^2 - y^3, because items are
2180 terminated by almost any nonword/nondigit char.
2181 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2183 Still, ambiguity is possible - so when in doubt use {} to enclose the
2184 sub/superscript.
2185 Not all export backends support this, but HTML does.
2187 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2188 :group 'org-export-translation
2189 :type 'boolean)
2191 (defcustom org-export-with-TeX-macros t
2192 "Non-nil means, interpret simple TeX-like macros when exporting.
2193 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2194 No only real TeX macros will work here, but the standard HTML entities
2195 for math can be used as macro names as well. For a list of supported
2196 names in HTML export, see the constant `org-html-entities'.
2197 Not all export backends support this.
2199 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2200 :group 'org-export-translation
2201 :group 'org-latex
2202 :type 'boolean)
2204 (defcustom org-export-with-LaTeX-fragments nil
2205 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2206 When set, the exporter will find LaTeX environments if the \\begin line is
2207 the first non-white thing on a line. It will also find the math delimiters
2208 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2209 display math.
2211 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2212 :group 'org-export-translation
2213 :group 'org-latex
2214 :type 'boolean)
2216 (defcustom org-export-with-fixed-width t
2217 "Non-nil means, lines starting with \":\" will be in fixed width font.
2218 This can be used to have pre-formatted text, fragments of code etc. For
2219 example:
2220 : ;; Some Lisp examples
2221 : (while (defc cnt)
2222 : (ding))
2223 will be looking just like this in also HTML. See also the QUOTE keyword.
2224 Not all export backends support this.
2226 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2227 :group 'org-export-translation
2228 :type 'boolean)
2230 (defcustom org-match-sexp-depth 3
2231 "Number of stacked braces for sub/superscript matching.
2232 This has to be set before loading org.el to be effective."
2233 :group 'org-export-translation
2234 :type 'integer)
2236 (defgroup org-export-tables nil
2237 "Options for exporting tables in Org-mode."
2238 :tag "Org Export Tables"
2239 :group 'org-export)
2241 (defcustom org-export-with-tables t
2242 "If non-nil, lines starting with \"|\" define a table.
2243 For example:
2245 | Name | Address | Birthday |
2246 |-------------+----------+-----------|
2247 | Arthur Dent | England | 29.2.2100 |
2249 Not all export backends support this.
2251 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2252 :group 'org-export-tables
2253 :type 'boolean)
2255 (defcustom org-export-highlight-first-table-line t
2256 "Non-nil means, highlight the first table line.
2257 In HTML export, this means use <th> instead of <td>.
2258 In tables created with table.el, this applies to the first table line.
2259 In Org-mode tables, all lines before the first horizontal separator
2260 line will be formatted with <th> tags."
2261 :group 'org-export-tables
2262 :type 'boolean)
2264 (defcustom org-export-table-remove-special-lines t
2265 "Remove special lines and marking characters in calculating tables.
2266 This removes the special marking character column from tables that are set
2267 up for spreadsheet calculations. It also removes the entire lines
2268 marked with `!', `_', or `^'. The lines with `$' are kept, because
2269 the values of constants may be useful to have."
2270 :group 'org-export-tables
2271 :type 'boolean)
2273 (defcustom org-export-prefer-native-exporter-for-tables nil
2274 "Non-nil means, always export tables created with table.el natively.
2275 Natively means, use the HTML code generator in table.el.
2276 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2277 the table does not use row- or column-spanning). This has the
2278 advantage, that the automatic HTML conversions for math symbols and
2279 sub/superscripts can be applied. Org-mode's HTML generator is also
2280 much faster."
2281 :group 'org-export-tables
2282 :type 'boolean)
2284 (defgroup org-export-ascii nil
2285 "Options specific for ASCII export of Org-mode files."
2286 :tag "Org Export ASCII"
2287 :group 'org-export)
2289 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2290 "Characters for underlining headings in ASCII export.
2291 In the given sequence, these characters will be used for level 1, 2, ..."
2292 :group 'org-export-ascii
2293 :type '(repeat character))
2295 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2296 "Bullet characters for headlines converted to lists in ASCII export.
2297 The first character is is used for the first lest level generated in this
2298 way, and so on. If there are more levels than characters given here,
2299 the list will be repeated.
2300 Note that plain lists will keep the same bullets as the have in the
2301 Org-mode file."
2302 :group 'org-export-ascii
2303 :type '(repeat character))
2305 (defcustom org-export-ascii-show-new-buffer t
2306 "Non-nil means, popup buffer containing the exported ASCII text.
2307 Otherwise the buffer will just be saved to a file and stay hidden."
2308 :group 'org-export-ascii
2309 :type 'boolean)
2311 (defgroup org-export-xml nil
2312 "Options specific for XML export of Org-mode files."
2313 :tag "Org Export XML"
2314 :group 'org-export)
2316 (defgroup org-export-html nil
2317 "Options specific for HTML export of Org-mode files."
2318 :tag "Org Export HTML"
2319 :group 'org-export)
2321 (defcustom org-export-html-style
2322 "<style type=\"text/css\">
2323 html {
2324 font-family: Times, serif;
2325 font-size: 12pt;
2327 .title { text-align: center; }
2328 .todo { color: red; }
2329 .done { color: green; }
2330 .timestamp { color: grey }
2331 .timestamp-kwd { color: CadetBlue }
2332 .tag { background-color:lightblue; font-weight:normal }
2333 .target { background-color: lavender; }
2334 pre {
2335 border: 1pt solid #AEBDCC;
2336 background-color: #F3F5F7;
2337 padding: 5pt;
2338 font-family: courier, monospace;
2340 table { border-collapse: collapse; }
2341 td, th {
2342 vertical-align: top;
2343 border: 1pt solid #ADB9CC;
2345 </style>"
2346 "The default style specification for exported HTML files.
2347 Since there are different ways of setting style information, this variable
2348 needs to contain the full HTML structure to provide a style, including the
2349 surrounding HTML tags. The style specifications should include definitions
2350 for new classes todo, done, title, and deadline. For example, legal values
2351 would be:
2353 <style type=\"text/css\">
2354 p { font-weight: normal; color: gray; }
2355 h1 { color: black; }
2356 .title { text-align: center; }
2357 .todo, .deadline { color: red; }
2358 .done { color: green; }
2359 </style>
2361 or, if you want to keep the style in a file,
2363 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2365 As the value of this option simply gets inserted into the HTML <head> header,
2366 you can \"misuse\" it to add arbitrary text to the header."
2367 :group 'org-export-html
2368 :type 'string)
2370 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2371 "Format for typesetting the document title in HTML export."
2372 :group 'org-export-html
2373 :type 'string)
2375 (defcustom org-export-html-toplevel-hlevel 2
2376 "The <H> level for level 1 headings in HTML export."
2377 :group 'org-export-html
2378 :type 'string)
2380 (defcustom org-export-html-link-org-files-as-html t
2381 "Non-nil means, make file links to `file.org' point to `file.html'.
2382 When org-mode is exporting an org-mode file to HTML, links to
2383 non-html files are directly put into a href tag in HTML.
2384 However, links to other Org-mode files (recognized by the
2385 extension `.org.) should become links to the corresponding html
2386 file, assuming that the linked org-mode file will also be
2387 converted to HTML.
2388 When nil, the links still point to the plain `.org' file."
2389 :group 'org-export-html
2390 :type 'boolean)
2392 (defcustom org-export-html-inline-images 'maybe
2393 "Non-nil means, inline images into exported HTML pages.
2394 This is done using an <img> tag. When nil, an anchor with href is used to
2395 link to the image. If this option is `maybe', then images in links with
2396 an empty description will be inlined, while images with a description will
2397 be linked only."
2398 :group 'org-export-html
2399 :type '(choice (const :tag "Never" nil)
2400 (const :tag "Always" t)
2401 (const :tag "When there is no description" maybe)))
2403 (defcustom org-export-html-expand t
2404 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2405 When nil, these tags will be exported as plain text and therefore
2406 not be interpreted by a browser.
2408 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2409 :group 'org-export-html
2410 :type 'boolean)
2412 (defcustom org-export-html-table-tag
2413 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2414 "The HTML tag used to start a table.
2415 This must be a <table> tag, but you may change the options like
2416 borders and spacing."
2417 :group 'org-export-html
2418 :type 'string)
2420 (defcustom org-export-html-with-timestamp nil
2421 "If non-nil, write `org-export-html-html-helper-timestamp'
2422 into the exported HTML text. Otherwise, the buffer will just be saved
2423 to a file."
2424 :group 'org-export-html
2425 :type 'boolean)
2427 (defcustom org-export-html-html-helper-timestamp
2428 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2429 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2430 :group 'org-export-html
2431 :type 'string)
2433 (defcustom org-export-html-show-new-buffer nil
2434 "Non-nil means, popup buffer containing the exported html text.
2435 Otherwise, the buffer will just be saved to a file and stay hidden."
2436 :group 'org-export-html
2437 :type 'boolean)
2439 (defgroup org-export-icalendar nil
2440 "Options specific for iCalendar export of Org-mode files."
2441 :tag "Org Export iCalendar"
2442 :group 'org-export)
2444 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2445 "The file name for the iCalendar file covering all agenda files.
2446 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2447 The file name should be absolute."
2448 :group 'org-export-icalendar
2449 :type 'file)
2451 (defcustom org-icalendar-include-todo nil
2452 "Non-nil means, export to iCalendar files should also cover TODO items."
2453 :group 'org-export-icalendar
2454 :type 'boolean)
2456 (defcustom org-icalendar-combined-name "OrgMode"
2457 "Calendar name for the combined iCalendar representing all agenda files."
2458 :group 'org-export-icalendar
2459 :type 'string)
2461 (defgroup org-font-lock nil
2462 "Font-lock settings for highlighting in Org-mode."
2463 :tag "Org Font Lock"
2464 :group 'org)
2466 (defcustom org-level-color-stars-only nil
2467 "Non-nil means fontify only the stars in each headline.
2468 When nil, the entire headline is fontified.
2469 Changing it requires restart of `font-lock-mode' to become effective
2470 also in regions already fontified."
2471 :group 'org-font-lock
2472 :type 'boolean)
2474 (defcustom org-hide-leading-stars nil
2475 "Non-nil means, hide the first N-1 stars in a headline.
2476 This works by using the face `org-hide' for these stars. This
2477 face is white for a light background, and black for a dark
2478 background. You may have to customize the face `org-hide' to
2479 make this work.
2480 Changing it requires restart of `font-lock-mode' to become effective
2481 also in regions already fontified.
2482 You may also set this on a per-file basis by adding one of the following
2483 lines to the buffer:
2485 #+STARTUP: hidestars
2486 #+STARTUP: showstars"
2487 :group 'org-font-lock
2488 :type 'boolean)
2490 (defcustom org-fontify-done-headline nil
2491 "Non-nil means, change the face of a headline if it is marked DONE.
2492 Normally, only the TODO/DONE keyword indicates the state of a headline.
2493 When this is non-nil, the headline after the keyword is set to the
2494 `org-headline-done' as an additional indication."
2495 :group 'org-font-lock
2496 :type 'boolean)
2498 (defcustom org-fontify-emphasized-text t
2499 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2500 Changing this variable requires a restart of Emacs to take effect."
2501 :group 'org-font-lock
2502 :type 'boolean)
2504 (defvar org-emph-re nil
2505 "Regular expression for matching emphasis.")
2506 (defvar org-emphasis-regexp-components) ; defined just below
2507 (defvar org-emphasis-alist) ; defined just below
2508 (defun org-set-emph-re (var val)
2509 "Set variable and compute the emphasis regular expression."
2510 (set var val)
2511 (when (and (boundp 'org-emphasis-alist)
2512 (boundp 'org-emphasis-regexp-components)
2513 org-emphasis-alist org-emphasis-regexp-components)
2514 (let* ((e org-emphasis-regexp-components)
2515 (pre (car e))
2516 (post (nth 1 e))
2517 (border (nth 2 e))
2518 (body (nth 3 e))
2519 (nl (nth 4 e))
2520 (stacked (nth 5 e))
2521 (body1 (concat body "*?"))
2522 (markers (mapconcat 'car org-emphasis-alist "")))
2523 ;; make sure special characters appear at the right position in the class
2524 (if (string-match "\\^" markers)
2525 (setq markers (concat (replace-match "" t t markers) "^")))
2526 (if (string-match "-" markers)
2527 (setq markers (concat (replace-match "" t t markers) "-")))
2528 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2529 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2530 (if (> nl 0)
2531 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2532 (int-to-string nl) "\\}")))
2533 ;; Make the regexp
2534 (setq org-emph-re
2535 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2536 "\\("
2537 "\\([" markers "]\\)"
2538 "\\("
2539 "[^" border markers "]"
2540 body1
2541 "[^" border markers "]"
2542 "\\)"
2543 "\\3\\)"
2544 "\\([" post (if stacked markers) "]\\|$\\)")))))
2546 (defcustom org-emphasis-regexp-components
2547 '(" \t(" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2548 "Components used to build the reqular expression for emphasis.
2549 This is a list with 6 entries. Terminology: In an emphasis string
2550 like \" *strong word* \", we call the initial space PREMATCH, the final
2551 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2552 and \"trong wor\" is the body. The different components in this variable
2553 specify what is allowed/forbidden in each part:
2555 pre Chars allowed as prematch. Beginning of line will be allowed too.
2556 post Chars allowed as postmatch. End of line will be allowed too.
2557 border The chars *forbidden* as border characters. In addition to the
2558 characters given here, all marker characters are forbidden too.
2559 body-regexp A regexp like \".\" to match a body character. Don't use
2560 non-shy groups here, and don't allow newline here.
2561 newline The maximum number of newlines allowed in an emphasis exp.
2562 stacked Non-nil means, allow stacked styles. This works only in HTML
2563 export. When this is set, all marker characters (as given in
2564 `org-emphasis-alist') will be allowed as pre/post, aiding
2565 inside-out matching.
2566 Use customize to modify this, or restart emacs after changing it."
2567 :group 'org-font-lock
2568 :set 'org-set-emph-re
2569 :type '(list
2570 (sexp :tag "Allowed chars in pre ")
2571 (sexp :tag "Allowed chars in post ")
2572 (sexp :tag "Forbidden chars in border ")
2573 (sexp :tag "Regexp for body ")
2574 (integer :tag "number of newlines allowed")
2575 (boolean :tag "Stacking allowed ")))
2577 (defcustom org-emphasis-alist
2578 '(("*" bold "<b>" "</b>")
2579 ("/" italic "<i>" "</i>")
2580 ("_" underline "<u>" "</u>")
2581 ("=" shadow "<code>" "</code>")
2582 ("+" (:strike-through t) "<del>" "</del>")
2584 "Special syntax for emphasised text.
2585 Text starting and ending with a special character will be emphasized, for
2586 example *bold*, _underlined_ and /italic/. This variable sets the marker
2587 characters, the face to bbe used by font-lock for highlighting in Org-mode
2588 emacs buffers, and the HTML tags to be used for this.
2589 Use customize to modify this, or restart emacs after changing it."
2590 :group 'org-font-lock
2591 :set 'org-set-emph-re
2592 :type '(repeat
2593 (list
2594 (string :tag "Marker character")
2595 (choice
2596 (face :tag "Font-lock-face")
2597 (plist :tag "Face property list"))
2598 (string :tag "HTML start tag")
2599 (string :tag "HTML end tag"))))
2601 (defgroup org-faces nil
2602 "Faces in Org-mode."
2603 :tag "Org Faces"
2604 :group 'org-font-lock)
2606 (defun org-compatible-face (specs)
2607 "Make a compatible face specification.
2608 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2609 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2610 to the top of the list. The `min-colors' attribute will be removed from
2611 any other entries, and any resulting duplicates will be removed entirely."
2612 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2613 (let (r e a)
2614 (while (setq e (pop specs))
2615 (cond
2616 ((memq (car e) '(t default)) (push e r))
2617 ((setq a (member '(min-colors 8) (car e)))
2618 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2619 (cdr e)))))
2620 ((setq a (assq 'min-colors (car e)))
2621 (setq e (cons (delq a (car e)) (cdr e)))
2622 (or (assoc (car e) r) (push e r)))
2623 (t (or (assoc (car e) r) (push e r)))))
2624 (nreverse r))
2625 specs))
2627 (defface org-hide
2628 '((((background light)) (:foreground "white"))
2629 (((background dark)) (:foreground "black")))
2630 "Face used to hide leading stars in headlines.
2631 The forground color of this face should be equal to the background
2632 color of the frame."
2633 :group 'org-faces)
2635 (defface org-level-1 ;; font-lock-function-name-face
2636 (org-compatible-face
2637 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2638 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2639 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2640 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2641 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2642 (t (:bold t))))
2643 "Face used for level 1 headlines."
2644 :group 'org-faces)
2646 (defface org-level-2 ;; font-lock-variable-name-face
2647 (org-compatible-face
2648 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2649 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2650 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2651 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2652 (t (:bold t))))
2653 "Face used for level 2 headlines."
2654 :group 'org-faces)
2656 (defface org-level-3 ;; font-lock-keyword-face
2657 (org-compatible-face
2658 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2659 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2660 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2661 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2662 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2663 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2664 (t (:bold t))))
2665 "Face used for level 3 headlines."
2666 :group 'org-faces)
2668 (defface org-level-4 ;; font-lock-comment-face
2669 (org-compatible-face
2670 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2671 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2672 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2673 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2674 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2675 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2676 (t (:bold t))))
2677 "Face used for level 4 headlines."
2678 :group 'org-faces)
2680 (defface org-level-5 ;; font-lock-type-face
2681 (org-compatible-face
2682 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2683 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2684 (((class color) (min-colors 8)) (:foreground "green"))))
2685 "Face used for level 5 headlines."
2686 :group 'org-faces)
2688 (defface org-level-6 ;; font-lock-constant-face
2689 (org-compatible-face
2690 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2691 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2692 (((class color) (min-colors 8)) (:foreground "magenta"))))
2693 "Face used for level 6 headlines."
2694 :group 'org-faces)
2696 (defface org-level-7 ;; font-lock-builtin-face
2697 (org-compatible-face
2698 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2699 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2700 (((class color) (min-colors 8)) (:foreground "blue"))))
2701 "Face used for level 7 headlines."
2702 :group 'org-faces)
2704 (defface org-level-8 ;; font-lock-string-face
2705 (org-compatible-face
2706 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2707 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2708 (((class color) (min-colors 8)) (:foreground "green"))))
2709 "Face used for level 8 headlines."
2710 :group 'org-faces)
2712 (defface org-special-keyword ;; font-lock-string-face
2713 (org-compatible-face
2714 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2715 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2716 (t (:italic t))))
2717 "Face used for special keywords."
2718 :group 'org-faces)
2720 (defface org-warning ;; font-lock-warning-face
2721 (org-compatible-face
2722 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2723 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2724 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2725 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2726 (t (:bold t))))
2727 "Face for deadlines and TODO keywords."
2728 :group 'org-faces)
2730 (defface org-headline-done ;; font-lock-string-face
2731 (org-compatible-face
2732 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2733 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2734 (((class color) (min-colors 8) (background light)) (:bold nil))))
2735 "Face used to indicate that a headline is DONE.
2736 This face is only used if `org-fontify-done-headline' is set."
2737 :group 'org-faces)
2739 (defface org-archived ; similar to shadow
2740 (org-compatible-face
2741 '((((class color grayscale) (min-colors 88) (background light))
2742 (:foreground "grey50"))
2743 (((class color grayscale) (min-colors 88) (background dark))
2744 (:foreground "grey70"))
2745 (((class color) (min-colors 8) (background light))
2746 (:foreground "green"))
2747 (((class color) (min-colors 8) (background dark))
2748 (:foreground "yellow"))))
2749 "Face for headline with the ARCHIVE tag."
2750 :group 'org-faces)
2752 (defface org-link
2753 '((((class color) (background light)) (:foreground "Purple" :underline t))
2754 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2755 (t (:underline t)))
2756 "Face for links."
2757 :group 'org-faces)
2759 (defface org-date
2760 '((((class color) (background light)) (:foreground "Purple" :underline t))
2761 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2762 (t (:underline t)))
2763 "Face for links."
2764 :group 'org-faces)
2766 (defface org-tag
2767 '((t (:bold t)))
2768 "Face for tags."
2769 :group 'org-faces)
2771 (defface org-todo ;; font-lock-warning-face
2772 (org-compatible-face
2773 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2774 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2775 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2776 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2777 (t (:inverse-video t :bold t))))
2778 "Face for TODO keywords."
2779 :group 'org-faces)
2781 (defface org-done ;; font-lock-type-face
2782 (org-compatible-face
2783 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2784 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2785 (((class color) (min-colors 8)) (:foreground "green"))
2786 (t (:bold t))))
2787 "Face used for DONE."
2788 :group 'org-faces)
2790 (defface org-table ;; font-lock-function-name-face
2791 (org-compatible-face
2792 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2793 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2794 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2795 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2796 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2797 (((class color) (min-colors 8) (background dark)))))
2798 "Face used for tables."
2799 :group 'org-faces)
2801 (defface org-formula
2802 (org-compatible-face
2803 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2804 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2805 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2806 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2807 (t (:bold t :italic t))))
2808 "Face for formulas."
2809 :group 'org-faces)
2811 (defface org-scheduled-today
2812 (org-compatible-face
2813 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2814 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2815 (((class color) (min-colors 8)) (:foreground "green"))
2816 (t (:bold t :italic t))))
2817 "Face for items scheduled for a certain day."
2818 :group 'org-faces)
2820 (defface org-scheduled-previously
2821 (org-compatible-face
2822 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2823 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2824 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2825 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2826 (t (:bold t))))
2827 "Face for items scheduled previously, and not yet done."
2828 :group 'org-faces)
2830 (defface org-upcoming-deadline
2831 (org-compatible-face
2832 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2833 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2834 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2835 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2836 (t (:bold t))))
2837 "Face for items scheduled previously, and not yet done."
2838 :group 'org-faces)
2840 (defface org-time-grid ;; font-lock-variable-name-face
2841 (org-compatible-face
2842 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2843 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2844 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2845 "Face used for time grids."
2846 :group 'org-faces)
2848 (defconst org-level-faces
2849 '(org-level-1 org-level-2 org-level-3 org-level-4
2850 org-level-5 org-level-6 org-level-7 org-level-8
2852 (defconst org-n-levels (length org-level-faces))
2855 ;; Variables for pre-computed regular expressions, all buffer local
2856 (defvar org-done-string nil
2857 "The last string in `org-todo-keywords', indicating an item is DONE.")
2858 (make-variable-buffer-local 'org-done-string)
2859 (defvar org-todo-regexp nil
2860 "Matches any of the TODO state keywords.")
2861 (make-variable-buffer-local 'org-todo-regexp)
2862 (defvar org-not-done-regexp nil
2863 "Matches any of the TODO state keywords except the last one.")
2864 (make-variable-buffer-local 'org-not-done-regexp)
2865 (defvar org-todo-line-regexp nil
2866 "Matches a headline and puts TODO state into group 2 if present.")
2867 (make-variable-buffer-local 'org-todo-line-regexp)
2868 (defvar org-todo-line-tags-regexp nil
2869 "Matches a headline and puts TODO state into group 2 if present.
2870 Also put tags into group 4 if tags are present.")
2871 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2872 (defvar org-nl-done-regexp nil
2873 "Matches newline followed by a headline with the DONE keyword.")
2874 (make-variable-buffer-local 'org-nl-done-regexp)
2875 (defvar org-looking-at-done-regexp nil
2876 "Matches the DONE keyword a point.")
2877 (make-variable-buffer-local 'org-looking-at-done-regexp)
2878 (defvar org-todo-kwd-priority-p nil
2879 "Do TODO items have priorities?")
2880 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2881 (defvar org-todo-kwd-max-priority nil
2882 "Maximum priority of TODO items.")
2883 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2884 (defvar org-ds-keyword-length 12
2885 "Maximum length of the Deadline and SCHEDULED keywords.")
2886 (make-variable-buffer-local 'org-ds-keyword-length)
2887 (defvar org-deadline-regexp nil
2888 "Matches the DEADLINE keyword.")
2889 (make-variable-buffer-local 'org-deadline-regexp)
2890 (defvar org-deadline-time-regexp nil
2891 "Matches the DEADLINE keyword together with a time stamp.")
2892 (make-variable-buffer-local 'org-deadline-time-regexp)
2893 (defvar org-deadline-line-regexp nil
2894 "Matches the DEADLINE keyword and the rest of the line.")
2895 (make-variable-buffer-local 'org-deadline-line-regexp)
2896 (defvar org-scheduled-regexp nil
2897 "Matches the SCHEDULED keyword.")
2898 (make-variable-buffer-local 'org-scheduled-regexp)
2899 (defvar org-scheduled-time-regexp nil
2900 "Matches the SCHEDULED keyword together with a time stamp.")
2901 (make-variable-buffer-local 'org-scheduled-time-regexp)
2902 (defvar org-closed-time-regexp nil
2903 "Matches the CLOSED keyword together with a time stamp.")
2904 (make-variable-buffer-local 'org-closed-time-regexp)
2906 (defvar org-keyword-time-regexp nil
2907 "Matches any of the 3 keywords, together with the time stamp.")
2908 (make-variable-buffer-local 'org-keyword-time-regexp)
2909 (defvar org-maybe-keyword-time-regexp nil
2910 "Matches a timestamp, possibly preceeded by a keyword.")
2911 (make-variable-buffer-local 'org-keyword-time-regexp)
2913 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2914 rear-nonsticky t mouse-map t)
2915 "Properties to remove when a string without properties is wanted.")
2917 (defsubst org-match-string-no-properties (num &optional string)
2918 (if (featurep 'xemacs)
2919 (let ((s (match-string num string)))
2920 (remove-text-properties 0 (length s) org-rm-props s)
2922 (match-string-no-properties num string)))
2924 (defsubst org-no-properties (s)
2925 (remove-text-properties 0 (length s) org-rm-props s)
2928 (defsubst org-get-alist-option (option key)
2929 (cond ((eq key t) t)
2930 ((eq option t) t)
2931 ((assoc key option) (cdr (assoc key option)))
2932 (t (cdr (assq 'default option)))))
2934 (defsubst org-set-local (var value)
2935 "Make VAR local in current buffer and set it to VALUE."
2936 (set (make-variable-buffer-local var) value))
2938 (defsubst org-mode-p ()
2939 "Check if the current buffer is in Org-mode."
2940 (eq major-mode 'org-mode))
2942 (defsubst org-last (list)
2943 "Return the last element of LIST."
2944 (car (last list)))
2946 (defun org-let (list &rest body)
2947 (eval (cons 'let (cons list body))))
2948 (put 'org-let 'lisp-indent-function 1)
2950 (defun org-let2 (list1 list2 &rest body)
2951 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
2952 (put 'org-let2 'lisp-indent-function 2)
2954 (defconst org-startup-options
2955 '(("fold" org-startup-folded t)
2956 ("overview" org-startup-folded t)
2957 ("nofold" org-startup-folded nil)
2958 ("showall" org-startup-folded nil)
2959 ("content" org-startup-folded content)
2960 ("hidestars" org-hide-leading-stars t)
2961 ("showstars" org-hide-leading-stars nil)
2962 ("odd" org-odd-levels-only t)
2963 ("oddeven" org-odd-levels-only nil)
2964 ("align" org-startup-align-all-tables t)
2965 ("noalign" org-startup-align-all-tables nil)
2966 ("customtime" org-display-custom-times t)
2967 ("logging" org-log-done t)
2968 ("nologging" org-log-done nil)
2969 ("dlcheck" org-startup-with-deadline-check t)
2970 ("nodlcheck" org-startup-with-deadline-check nil)))
2972 (defun org-set-regexps-and-options ()
2973 "Precompute regular expressions for current buffer."
2974 (when (org-mode-p)
2975 (let ((re (org-make-options-regexp
2976 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2977 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
2978 (splitre "[ \t]+")
2979 kwds int key value cat arch tags links)
2980 (save-excursion
2981 (save-restriction
2982 (widen)
2983 (goto-char (point-min))
2984 (while (re-search-forward re nil t)
2985 (setq key (match-string 1) value (org-match-string-no-properties 2))
2986 (cond
2987 ((equal key "CATEGORY")
2988 (if (string-match "[ \t]+$" value)
2989 (setq value (replace-match "" t t value)))
2990 (setq cat (intern value)))
2991 ((equal key "SEQ_TODO")
2992 (setq int 'sequence
2993 kwds (append kwds (org-split-string value splitre))))
2994 ((equal key "PRI_TODO")
2995 (setq int 'priority
2996 kwds (append kwds (org-split-string value splitre))))
2997 ((equal key "TYP_TODO")
2998 (setq int 'type
2999 kwds (append kwds (org-split-string value splitre))))
3000 ((equal key "TAGS")
3001 (setq tags (append tags (org-split-string value splitre))))
3002 ((equal key "LINK")
3003 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3004 (push (cons (match-string 1 value)
3005 (org-trim (match-string 2 value)))
3006 links)))
3007 ((equal key "STARTUP")
3008 (let ((opts (org-split-string value splitre))
3009 l var val)
3010 (while (setq l (assoc (pop opts) org-startup-options))
3011 (setq var (nth 1 l) val (nth 2 l))
3012 (set (make-local-variable var) val))))
3013 ((equal key "ARCHIVE")
3014 (string-match " *$" value)
3015 (setq arch (replace-match "" t t value))
3016 (remove-text-properties 0 (length arch)
3017 '(face t fontified t) arch)))
3019 (and cat (org-set-local 'org-category cat))
3020 (and kwds (org-set-local 'org-todo-keywords kwds))
3021 (and arch (org-set-local 'org-archive-location arch))
3022 (and int (org-set-local 'org-todo-interpretation int))
3023 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3024 (when tags
3025 (let (e tgs)
3026 (while (setq e (pop tags))
3027 (cond
3028 ((equal e "{") (push '(:startgroup) tgs))
3029 ((equal e "}") (push '(:endgroup) tgs))
3030 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3031 (push (cons (match-string 1 e)
3032 (string-to-char (match-string 2 e)))
3033 tgs))
3034 (t (push (list e) tgs))))
3035 (org-set-local 'org-tag-alist nil)
3036 (while (setq e (pop tgs))
3037 (or (and (stringp (car e))
3038 (assoc (car e) org-tag-alist))
3039 (push e org-tag-alist))))))
3041 ;; Compute the regular expressions and other local variables
3042 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
3043 org-todo-kwd-max-priority (1- (length org-todo-keywords))
3044 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3045 (length org-scheduled-string)))
3046 org-done-string
3047 (nth (1- (length org-todo-keywords)) org-todo-keywords)
3048 org-todo-regexp
3049 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
3050 "\\|") "\\)\\>")
3051 org-not-done-regexp
3052 (concat "\\<\\("
3053 (mapconcat 'regexp-quote
3054 (nreverse (cdr (reverse org-todo-keywords)))
3055 "\\|")
3056 "\\)\\>")
3057 org-todo-line-regexp
3058 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3059 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3060 "\\)\\>\\)? *\\(.*\\)")
3061 org-nl-done-regexp
3062 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
3063 org-todo-line-tags-regexp
3064 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3065 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3066 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3067 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
3068 org-deadline-regexp (concat "\\<" org-deadline-string)
3069 org-deadline-time-regexp
3070 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3071 org-deadline-line-regexp
3072 (concat "\\<\\(" org-deadline-string "\\).*")
3073 org-scheduled-regexp
3074 (concat "\\<" org-scheduled-string)
3075 org-scheduled-time-regexp
3076 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3077 org-closed-time-regexp
3078 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3079 org-keyword-time-regexp
3080 (concat "\\<\\(" org-scheduled-string
3081 "\\|" org-deadline-string
3082 "\\|" org-closed-string
3083 "\\|" org-clock-string "\\)"
3084 " *[[<]\\([^]>]+\\)[]>]")
3085 org-maybe-keyword-time-regexp
3086 (concat "\\(\\<\\(" org-scheduled-string
3087 "\\|" org-deadline-string
3088 "\\|" org-closed-string
3089 "\\|" org-clock-string "\\)\\)?"
3090 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3092 (org-set-font-lock-defaults)))
3094 ;; Tell the compiler about dynamically scoped variables,
3095 ;; and variables from other packages
3096 (defvar calc-embedded-close-formula) ; defined by the calc package
3097 (defvar calc-embedded-open-formula) ; defined by the calc package
3098 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
3099 (defvar zmacs-regions) ; XEmacs regions
3100 (defvar original-date) ; dynamically scoped in calendar
3101 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
3102 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3103 (defvar org-html-entities) ; defined later in this file
3104 (defvar org-goto-start-pos) ; dynamically scoped parameter
3105 (defvar org-time-was-given) ; dynamically scoped parameter
3106 (defvar org-ts-what) ; dynamically scoped parameter
3107 (defvar org-current-export-file) ; dynamically scoped parameter
3108 (defvar org-current-export-dir) ; dynamically scoped parameter
3109 (defvar mark-active) ; Emacs only, not available in XEmacs.
3110 (defvar timecnt) ; dynamically scoped parameter
3111 (defvar levels-open) ; dynamically scoped parameter
3112 (defvar entry) ; dynamically scoped parameter
3113 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
3114 (defvar date) ; dynamically scoped parameter
3115 (defvar description) ; dynamically scoped parameter
3116 (defvar ans1) ; dynamically scoped parameter
3117 (defvar ans2) ; dynamically scoped parameter
3118 (defvar starting-day) ; local variable
3119 (defvar include-all-loc) ; local variable
3120 (defvar vm-message-pointer) ; from vm
3121 (defvar vm-folder-directory) ; from vm
3122 (defvar gnus-other-frame-object) ; from gnus
3123 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
3124 (defvar wl-summary-buffer-folder-name) ; from wanderlust
3125 (defvar gnus-group-name) ; from gnus
3126 (defvar gnus-article-current) ; from gnus
3127 (defvar w3m-current-url) ; from w3m
3128 (defvar w3m-current-title) ; from w3m
3129 (defvar mh-progs) ; from MH-E
3130 (defvar mh-current-folder) ; from MH-E
3131 (defvar mh-show-folder-buffer) ; from MH-E
3132 (defvar mh-index-folder) ; from MH-E
3133 (defvar mh-searcher) ; from MH-E
3134 (defvar org-selected-point) ; dynamically scoped parameter
3135 (defvar calendar-mode-map) ; from calendar.el
3136 (defvar last-arg) ; local variable
3137 (defvar remember-save-after-remembering) ; from remember.el
3138 (defvar remember-data-file) ; from remember.el
3139 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3140 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3141 (defvar orgtbl-mode) ; defined later in this file
3142 (defvar Info-current-file) ; from info.el
3143 (defvar Info-current-node) ; from info.el
3144 (defvar texmathp-why) ; from texmathp.el
3145 (defvar org-latex-regexps)
3147 ;;; Define the mode
3149 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3150 (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."))
3152 (defvar org-struct-menu) ; defined later in this file
3153 (defvar org-org-menu) ; defined later in this file
3154 (defvar org-tbl-menu) ; defined later in this file
3156 ;; We use a before-change function to check if a table might need
3157 ;; an update.
3158 (defvar org-table-may-need-update t
3159 "Indicates that a table might need an update.
3160 This variable is set by `org-before-change-function'.
3161 `org-table-align' sets it back to nil.")
3162 (defvar org-mode-map)
3163 (defvar org-mode-hook nil)
3164 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3165 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3168 ;;;###autoload
3169 (define-derived-mode org-mode outline-mode "Org"
3170 "Outline-based notes management and organizer, alias
3171 \"Carsten's outline-mode for keeping track of everything.\"
3173 Org-mode develops organizational tasks around a NOTES file which
3174 contains information about projects as plain text. Org-mode is
3175 implemented on top of outline-mode, which is ideal to keep the content
3176 of large files well structured. It supports ToDo items, deadlines and
3177 time stamps, which magically appear in the diary listing of the Emacs
3178 calendar. Tables are easily created with a built-in table editor.
3179 Plain text URL-like links connect to websites, emails (VM), Usenet
3180 messages (Gnus), BBDB entries, and any files related to the project.
3181 For printing and sharing of notes, an Org-mode file (or a part of it)
3182 can be exported as a structured ASCII or HTML file.
3184 The following commands are available:
3186 \\{org-mode-map}"
3188 ;; Get rid of Outline menus, they are not needed
3189 ;; Need to do this here because define-derived-mode sets up
3190 ;; the keymap so late. Still, it is a waste to call this each time
3191 ;; we switch another buffer into org-mode.
3192 (if (featurep 'xemacs)
3193 (progn
3194 ;; Assume this is Greg's port, it used easymenu
3195 (easy-menu-remove outline-mode-menu-heading)
3196 (easy-menu-remove outline-mode-menu-show)
3197 (easy-menu-remove outline-mode-menu-hide))
3198 (define-key org-mode-map [menu-bar headings] 'undefined)
3199 (define-key org-mode-map [menu-bar hide] 'undefined)
3200 (define-key org-mode-map [menu-bar show] 'undefined))
3202 (easy-menu-add org-org-menu)
3203 (easy-menu-add org-tbl-menu)
3204 (org-install-agenda-files-menu)
3205 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3206 (org-add-to-invisibility-spec '(org-cwidth))
3207 (when (featurep 'xemacs)
3208 (org-set-local 'line-move-ignore-invisible t))
3209 (setq outline-regexp "\\*+")
3210 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
3211 (setq outline-level 'org-outline-level)
3212 (when (and org-ellipsis (stringp org-ellipsis))
3213 (unless org-display-table
3214 (setq org-display-table (make-display-table)))
3215 (set-display-table-slot org-display-table
3216 4 (string-to-vector org-ellipsis))
3217 (setq buffer-display-table org-display-table))
3218 (org-set-regexps-and-options)
3219 ;; Calc embedded
3220 (org-set-local 'calc-embedded-open-mode "# ")
3221 (modify-syntax-entry ?# "<")
3222 (if org-startup-truncated (setq truncate-lines t))
3223 (org-set-local 'font-lock-unfontify-region-function
3224 'org-unfontify-region)
3225 ;; Activate before-change-function
3226 (org-set-local 'org-table-may-need-update t)
3227 (org-add-hook 'before-change-functions 'org-before-change-function nil
3228 'local)
3229 ;; Check for running clock before killing a buffer
3230 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3231 ;; Paragraphs and auto-filling
3232 (org-set-autofill-regexps)
3233 (org-update-radio-target-regexp)
3235 (if (and org-insert-mode-line-in-empty-file
3236 (interactive-p)
3237 (= (point-min) (point-max)))
3238 (insert " -*- mode: org -*-\n\n"))
3240 (unless org-inhibit-startup
3241 (when org-startup-align-all-tables
3242 (let ((bmp (buffer-modified-p)))
3243 (org-table-map-tables 'org-table-align)
3244 (set-buffer-modified-p bmp)))
3245 (if org-startup-with-deadline-check
3246 (call-interactively 'org-check-deadlines)
3247 (cond
3248 ((eq org-startup-folded t)
3249 (org-cycle '(4)))
3250 ((eq org-startup-folded 'content)
3251 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3252 (org-cycle '(4)) (org-cycle '(4))))))))
3254 (defsubst org-call-with-arg (command arg)
3255 "Call COMMAND interactively, but pretend prefix are was ARG."
3256 (let ((current-prefix-arg arg)) (call-interactively command)))
3258 (defsubst org-current-line (&optional pos)
3259 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
3261 (defun org-current-time ()
3262 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3263 (if (> org-time-stamp-rounding-minutes 0)
3264 (let ((r org-time-stamp-rounding-minutes)
3265 (time (decode-time)))
3266 (apply 'encode-time
3267 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3268 (nthcdr 2 time))))
3269 (current-time)))
3271 (defun org-add-props (string plist &rest props)
3272 "Add text properties to entire string, from beginning to end.
3273 PLIST may be a list of properties, PROPS are individual properties and values
3274 that will be added to PLIST. Returns the string that was modified."
3275 (add-text-properties
3276 0 (length string) (if props (append plist props) plist) string)
3277 string)
3278 (put 'org-add-props 'lisp-indent-function 2)
3281 ;;; Font-Lock stuff
3283 (defvar org-mouse-map (make-sparse-keymap))
3284 (define-key org-mouse-map
3285 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3286 (define-key org-mouse-map
3287 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3288 (when org-mouse-1-follows-link
3289 (define-key org-mouse-map [follow-link] 'mouse-face))
3290 (when org-tab-follows-link
3291 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3292 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3293 (when org-return-follows-link
3294 (define-key org-mouse-map [(return)] 'org-open-at-point)
3295 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3297 (require 'font-lock)
3299 (defconst org-non-link-chars "]\t\n\r<>")
3300 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3301 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3302 (defconst org-link-re-with-space
3303 (concat
3304 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3305 "\\([^" org-non-link-chars " ]"
3306 "[^" org-non-link-chars "]*"
3307 "[^" org-non-link-chars " ]\\)>?")
3308 "Matches a link with spaces, optional angular brackets around it.")
3310 (defconst org-link-re-with-space2
3311 (concat
3312 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3313 "\\([^" org-non-link-chars " ]"
3314 "[^]\t\n\r]*"
3315 "[^" org-non-link-chars " ]\\)>?")
3316 "Matches a link with spaces, optional angular brackets around it.")
3318 (defconst org-angle-link-re
3319 (concat
3320 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3321 "\\([^" org-non-link-chars " ]"
3322 "[^" org-non-link-chars "]*"
3323 "\\)>")
3324 "Matches link with angular brackets, spaces are allowed.")
3325 (defconst org-plain-link-re
3326 (concat
3327 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3328 "\\([^]\t\n\r<>,;() ]+\\)")
3329 "Matches plain link, without spaces.")
3331 (defconst org-bracket-link-regexp
3332 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3333 "Matches a link in double brackets.")
3335 (defconst org-bracket-link-analytic-regexp
3336 (concat
3337 "\\[\\["
3338 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3339 "\\([^]]+\\)"
3340 "\\]"
3341 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3342 "\\]"))
3343 ; 1: http:
3344 ; 2: http
3345 ; 3: path
3346 ; 4: [desc]
3347 ; 5: desc
3349 (defconst org-ts-lengths
3350 (cons (length (format-time-string (car org-time-stamp-formats)))
3351 (length (format-time-string (cdr org-time-stamp-formats))))
3352 "This holds the lengths of the two different time formats.")
3353 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3354 "Regular expression for fast time stamp matching.")
3355 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3356 "Regular expression for fast time stamp matching.")
3357 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3358 "Regular expression matching time strings for analysis.")
3359 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3360 "Regular expression matching time stamps, with groups.")
3361 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3362 "Regular expression matching time stamps (also [..]), with groups.")
3363 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3364 "Regular expression matching a time stamp range.")
3365 (defconst org-tr-regexp-both
3366 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3367 "Regular expression matching a time stamp range.")
3368 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3369 org-ts-regexp "\\)?")
3370 "Regular expression matching a time stamp or time stamp range.")
3371 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3372 org-ts-regexp-both "\\)?")
3373 "Regular expression matching a time stamp or time stamp range.
3374 The time stamps may be either active or inactive.")
3376 (defvar org-�§emph-face nil)
3378 (defun org-do-emphasis-faces (limit)
3379 "Run through the buffer and add overlays to links."
3380 (if (re-search-forward org-emph-re limit t)
3381 (progn
3382 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3383 'face
3384 (nth 1 (assoc (match-string 3)
3385 org-emphasis-alist)))
3386 (add-text-properties (match-beginning 2) (match-end 2)
3387 '(font-lock-multiline t))
3388 (backward-char 1)
3389 t)))
3391 (defun org-activate-plain-links (limit)
3392 "Run through the buffer and add overlays to links."
3393 (if (re-search-forward org-plain-link-re limit t)
3394 (progn
3395 (add-text-properties (match-beginning 0) (match-end 0)
3396 (list 'mouse-face 'highlight
3397 'rear-nonsticky t
3398 'keymap org-mouse-map
3400 t)))
3402 (defun org-activate-angle-links (limit)
3403 "Run through the buffer and add overlays to links."
3404 (if (re-search-forward org-angle-link-re limit t)
3405 (progn
3406 (add-text-properties (match-beginning 0) (match-end 0)
3407 (list 'mouse-face 'highlight
3408 'rear-nonsticky t
3409 'keymap org-mouse-map
3411 t)))
3413 (defmacro org-maybe-intangible (props)
3414 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3415 In emacs 21, invisible text is not avoided by the command loop, so the
3416 intangible property is needed to make sure point skips this text.
3417 In Emacs 22, this is not necessary. The intangible text property has
3418 led to problems with flyspell. These problems are fixed in flyspell.el,
3419 but we still avoid setting the property in Emacs 22 and later.
3420 We use a macro so that the test can happen at compilation time."
3421 (if (< emacs-major-version 22)
3422 `(append '(intangible t) ,props)
3423 props))
3425 (defun org-activate-bracket-links (limit)
3426 "Run through the buffer and add overlays to bracketed links."
3427 (if (re-search-forward org-bracket-link-regexp limit t)
3428 (let* ((help (concat "LINK: "
3429 (org-match-string-no-properties 1)))
3430 ;; FIXME: above we should remove the escapes.
3431 ;; but that requires another match, protecting match data,
3432 ;; a lot of overhead for font-lock.
3433 (ip (org-maybe-intangible
3434 (list 'invisible 'org-link 'rear-nonsticky t
3435 'keymap org-mouse-map 'mouse-face 'highlight
3436 'help-echo help)))
3437 (vp (list 'rear-nonsticky t
3438 'keymap org-mouse-map 'mouse-face 'highlight
3439 'help-echo help)))
3440 ;; We need to remove the invisible property here. Table narrowing
3441 ;; may have made some of this invisible.
3442 (remove-text-properties (match-beginning 0) (match-end 0)
3443 '(invisible nil))
3444 (if (match-end 3)
3445 (progn
3446 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3447 (add-text-properties (match-beginning 3) (match-end 3) vp)
3448 (add-text-properties (match-end 3) (match-end 0) ip))
3449 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3450 (add-text-properties (match-beginning 1) (match-end 1) vp)
3451 (add-text-properties (match-end 1) (match-end 0) ip))
3452 t)))
3454 (defun org-activate-dates (limit)
3455 "Run through the buffer and add overlays to dates."
3456 ; (if (re-search-forward org-tsr-regexp limit t)
3457 ; (if (re-search-forward
3458 ; (if org-display-custom-times org-ts-regexp-both org-tsr-regexp-both)
3459 ; limit t)
3460 (if (re-search-forward org-tsr-regexp-both limit t)
3461 (progn
3462 (add-text-properties (match-beginning 0) (match-end 0)
3463 (list 'mouse-face 'highlight
3464 'rear-nonsticky t
3465 'keymap org-mouse-map))
3466 (when org-display-custom-times
3467 (if (match-end 3)
3468 (org-display-custom-time (match-beginning 3) (match-end 3)))
3469 (org-display-custom-time (match-beginning 1) (match-end 1)))
3470 t)))
3472 (defvar org-target-link-regexp nil
3473 "Regular expression matching radio targets in plain text.")
3474 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3475 "Regular expression matching a link target.")
3476 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3477 "Regular expression matching a link target.")
3479 (defun org-activate-target-links (limit)
3480 "Run through the buffer and add overlays to target matches."
3481 (when org-target-link-regexp
3482 (let ((case-fold-search t))
3483 (if (re-search-forward org-target-link-regexp limit t)
3484 (progn
3485 (add-text-properties (match-beginning 0) (match-end 0)
3486 (list 'mouse-face 'highlight
3487 'rear-nonsticky t
3488 'keymap org-mouse-map
3489 'help-echo "Radio target link"
3490 'org-linked-text t))
3491 t)))))
3493 (defun org-update-radio-target-regexp ()
3494 "Find all radio targets in this file and update the regular expression."
3495 (interactive)
3496 (when (memq 'radio org-activate-links)
3497 (setq org-target-link-regexp
3498 (org-make-target-link-regexp (org-all-targets 'radio)))
3499 (org-restart-font-lock)))
3501 (defun org-hide-wide-columns (limit)
3502 (let (s e)
3503 (setq s (text-property-any (point) (or limit (point-max))
3504 'org-cwidth t))
3505 (when s
3506 (setq e (next-single-property-change s 'org-cwidth))
3507 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3508 (goto-char e)
3509 t)))
3511 (defun org-restart-font-lock ()
3512 "Restart font-lock-mode, to force refontification."
3513 (when (and (boundp 'font-lock-mode) font-lock-mode)
3514 (font-lock-mode -1)
3515 (font-lock-mode 1)))
3517 (defun org-all-targets (&optional radio)
3518 "Return a list of all targets in this file.
3519 With optional argument RADIO, only find radio targets."
3520 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3521 rtn)
3522 (save-excursion
3523 (goto-char (point-min))
3524 (while (re-search-forward re nil t)
3525 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3526 rtn)))
3528 (defun org-make-target-link-regexp (targets)
3529 "Make regular expression matching all strings in TARGETS.
3530 The regular expression finds the targets also if there is a line break
3531 between words."
3532 (and targets
3533 (concat
3534 "\\<\\("
3535 (mapconcat
3536 (lambda (x)
3537 (while (string-match " +" x)
3538 (setq x (replace-match "\\s-+" t t x)))
3540 targets
3541 "\\|")
3542 "\\)\\>")))
3544 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3545 "Matches CamelCase words, possibly with a star before it.")
3547 (defun org-activate-camels (limit)
3548 "Run through the buffer and add overlays to dates."
3549 (if (re-search-forward org-camel-regexp limit t)
3550 (progn
3551 (add-text-properties (match-beginning 0) (match-end 0)
3552 (list 'mouse-face 'highlight
3553 'rear-nonsticky t
3554 'keymap org-mouse-map))
3555 t)))
3557 (defun org-activate-tags (limit)
3558 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3559 (progn
3560 (add-text-properties (match-beginning 1) (match-end 1)
3561 (list 'mouse-face 'highlight
3562 'rear-nonsticky t
3563 'keymap org-mouse-map))
3564 t)))
3566 (defun org-font-lock-level ()
3567 (save-excursion
3568 (org-back-to-heading t)
3569 (- (match-end 0) (match-beginning 0))))
3571 (defun org-outline-level ()
3572 (save-excursion
3573 (looking-at outline-regexp)
3574 (if (match-beginning 1)
3575 (+ (org-get-string-indentation (match-string 1)) 1000)
3576 (- (match-end 0) (match-beginning 0)))))
3578 (defvar org-font-lock-keywords nil)
3580 (defun org-set-font-lock-defaults ()
3581 (let* ((em org-fontify-emphasized-text)
3582 (lk org-activate-links)
3583 (org-font-lock-extra-keywords
3584 ;; Headlines
3585 (list
3586 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3587 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3588 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3589 (1 'org-table))
3590 ;; Links
3591 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3592 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3593 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3594 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3595 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3596 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3597 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3598 (if org-table-limit-column-width
3599 '(org-hide-wide-columns (0 nil append)))
3600 ;; TODO lines
3601 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3602 '(1 'org-todo t))
3603 ;; Priorities
3604 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3605 ;; Special keywords
3606 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3607 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3608 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3609 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3610 ;; Emphasis
3611 (if em
3612 (if (featurep 'xemacs)
3613 '(org-do-emphasis-faces (0 nil append))
3614 '(org-do-emphasis-faces)))
3615 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3616 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3617 2 'bold prepend)
3618 (if org-provide-checkbox-statistics
3619 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3620 (0 (org-get-checkbox-statistics-face) t)))
3621 ;; COMMENT
3622 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3623 "\\|" org-quote-string "\\)\\>")
3624 '(1 'org-special-keyword t))
3625 '("^#.*" (0 'font-lock-comment-face t))
3626 ;; DONE
3627 (if org-fontify-done-headline
3628 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3629 '(1 'org-done t) '(2 'org-headline-done t))
3630 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3631 '(1 'org-done t)))
3632 ;; Table stuff
3633 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3634 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3635 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3636 (if org-format-transports-properties-p
3637 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3638 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3640 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3641 ;; Now set the full font-lock-keywords
3642 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3643 (org-set-local 'font-lock-defaults
3644 '(org-font-lock-keywords t nil nil backward-paragraph))
3645 (kill-local-variable 'font-lock-keywords) nil))
3647 (defvar org-m nil)
3648 (defvar org-l nil)
3649 (defvar org-f nil)
3650 (defun org-get-level-face (n)
3651 "Get the right face for match N in font-lock matching of healdines."
3652 (setq org-l (- (match-end 2) (match-beginning 1)))
3653 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3654 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3655 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3656 (cond
3657 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3658 ((eq n 2) org-f)
3659 (t (if org-level-color-stars-only nil org-f))))
3661 (defun org-unfontify-region (beg end &optional maybe_loudly)
3662 "Remove fontification and activation overlays from links."
3663 (font-lock-default-unfontify-region beg end)
3664 (let* ((buffer-undo-list t)
3665 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3666 (inhibit-modification-hooks t)
3667 deactivate-mark buffer-file-name buffer-file-truename)
3668 (remove-text-properties beg end
3669 '(mouse-face t keymap t org-linked-text t
3670 rear-nonsticky t
3671 invisible t intangible t))))
3673 ;;; Visibility cycling
3675 (defvar org-cycle-global-status nil)
3676 (make-variable-buffer-local 'org-cycle-global-status)
3677 (defvar org-cycle-subtree-status nil)
3678 (make-variable-buffer-local 'org-cycle-subtree-status)
3680 ;;;###autoload
3681 (defun org-cycle (&optional arg)
3682 "Visibility cycling for Org-mode.
3684 - When this function is called with a prefix argument, rotate the entire
3685 buffer through 3 states (global cycling)
3686 1. OVERVIEW: Show only top-level headlines.
3687 2. CONTENTS: Show all headlines of all levels, but no body text.
3688 3. SHOW ALL: Show everything.
3690 - When point is at the beginning of a headline, rotate the subtree started
3691 by this line through 3 different states (local cycling)
3692 1. FOLDED: Only the main headline is shown.
3693 2. CHILDREN: The main headline and the direct children are shown.
3694 From this state, you can move to one of the children
3695 and zoom in further.
3696 3. SUBTREE: Show the entire subtree, including body text.
3698 - When there is a numeric prefix, go up to a heading with level ARG, do
3699 a `show-subtree' and return to the previous cursor position. If ARG
3700 is negative, go up that many levels.
3702 - When point is not at the beginning of a headline, execute
3703 `indent-relative', like TAB normally does. See the option
3704 `org-cycle-emulate-tab' for details.
3706 - Special case: if point is the the beginning of the buffer and there is
3707 no headline in line 1, this function will act as if called with prefix arg."
3708 (interactive "P")
3709 (let* ((outline-regexp
3710 (if (and (org-mode-p) org-cycle-include-plain-lists)
3711 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3712 outline-regexp))
3713 (bob-special (and org-cycle-global-at-bob (bobp)
3714 (not (looking-at outline-regexp))))
3715 (org-cycle-hook
3716 (if bob-special
3717 (delq 'org-optimize-window-after-visibility-change
3718 (copy-sequence org-cycle-hook))
3719 org-cycle-hook))
3720 (pos (point)))
3722 (if (or bob-special (equal arg '(4)))
3723 ;; special case: use global cycling
3724 (setq arg t))
3726 (cond
3728 ((org-at-table-p 'any)
3729 ;; Enter the table or move to the next field in the table
3730 (or (org-table-recognize-table.el)
3731 (progn
3732 (if arg (org-table-edit-field t)
3733 (org-table-justify-field-maybe)
3734 (call-interactively 'org-table-next-field)))))
3736 ((eq arg t) ;; Global cycling
3738 (cond
3739 ((and (eq last-command this-command)
3740 (eq org-cycle-global-status 'overview))
3741 ;; We just created the overview - now do table of contents
3742 ;; This can be slow in very large buffers, so indicate action
3743 (message "CONTENTS...")
3744 (org-content)
3745 (message "CONTENTS...done")
3746 (setq org-cycle-global-status 'contents)
3747 (run-hook-with-args 'org-cycle-hook 'contents))
3749 ((and (eq last-command this-command)
3750 (eq org-cycle-global-status 'contents))
3751 ;; We just showed the table of contents - now show everything
3752 (show-all)
3753 (message "SHOW ALL")
3754 (setq org-cycle-global-status 'all)
3755 (run-hook-with-args 'org-cycle-hook 'all))
3758 ;; Default action: go to overview
3759 (org-overview)
3760 (message "OVERVIEW")
3761 (setq org-cycle-global-status 'overview)
3762 (run-hook-with-args 'org-cycle-hook 'overview))))
3764 ((integerp arg)
3765 ;; Show-subtree, ARG levels up from here.
3766 (save-excursion
3767 (org-back-to-heading)
3768 (outline-up-heading (if (< arg 0) (- arg)
3769 (- (funcall outline-level) arg)))
3770 (org-show-subtree)))
3772 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3773 ;; At a heading: rotate between three different views
3774 (org-back-to-heading)
3775 (let ((goal-column 0) eoh eol eos)
3776 ;; First, some boundaries
3777 (save-excursion
3778 (org-back-to-heading)
3779 (save-excursion
3780 (beginning-of-line 2)
3781 (while (and (not (eobp)) ;; this is like `next-line'
3782 (get-char-property (1- (point)) 'invisible))
3783 (beginning-of-line 2)) (setq eol (point)))
3784 (outline-end-of-heading) (setq eoh (point))
3785 (org-end-of-subtree t) (setq eos (point))
3786 (outline-next-heading))
3787 ;; Find out what to do next and set `this-command'
3788 (cond
3789 ((and (= eos eoh)
3790 ;; Nothing is hidden behind this heading
3791 (message "EMPTY ENTRY")
3792 (setq org-cycle-subtree-status nil)))
3793 ((>= eol eos)
3794 ;; Entire subtree is hidden in one line: open it
3795 (org-show-entry)
3796 (show-children)
3797 (message "CHILDREN")
3798 (setq org-cycle-subtree-status 'children)
3799 (run-hook-with-args 'org-cycle-hook 'children))
3800 ((and (eq last-command this-command)
3801 (eq org-cycle-subtree-status 'children))
3802 ;; We just showed the children, now show everything.
3803 (org-show-subtree)
3804 (message "SUBTREE")
3805 (setq org-cycle-subtree-status 'subtree)
3806 (run-hook-with-args 'org-cycle-hook 'subtree))
3808 ;; Default action: hide the subtree.
3809 (hide-subtree)
3810 (message "FOLDED")
3811 (setq org-cycle-subtree-status 'folded)
3812 (run-hook-with-args 'org-cycle-hook 'folded)))))
3814 ;; TAB emulation
3815 (buffer-read-only (org-back-to-heading))
3817 ((org-try-cdlatex-tab))
3819 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3820 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3821 (or (and (eq org-cycle-emulate-tab 'white)
3822 (= (match-end 0) (point-at-eol)))
3823 (and (eq org-cycle-emulate-tab 'whitestart)
3824 (>= (match-end 0) pos))))
3826 (eq org-cycle-emulate-tab t))
3827 (if (and (looking-at "[ \n\r\t]")
3828 (string-match "^[ \t]*$" (buffer-substring
3829 (point-at-bol) (point))))
3830 (progn
3831 (beginning-of-line 1)
3832 (and (looking-at "[ \t]+") (replace-match ""))))
3833 (indent-relative))
3835 (t (save-excursion
3836 (org-back-to-heading)
3837 (org-cycle))))))
3839 ;;;###autoload
3840 (defun org-global-cycle (&optional arg)
3841 "Cycle the global visibility. For details see `org-cycle'."
3842 (interactive "P")
3843 (let ((org-cycle-include-plain-lists
3844 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3845 (if (integerp arg)
3846 (progn
3847 (show-all)
3848 (hide-sublevels arg)
3849 (setq org-cycle-global-status 'contents))
3850 (org-cycle '(4)))))
3852 (defun org-overview ()
3853 "Switch to overview mode, shoing only top-level headlines.
3854 Really, this shows all headlines with level equal or greater than the level
3855 of the first headline in the buffer. This is important, because if the
3856 first headline is not level one, then (hide-sublevels 1) gives confusing
3857 results."
3858 (interactive)
3859 (hide-sublevels (save-excursion
3860 (goto-char (point-min))
3861 (if (re-search-forward (concat "^" outline-regexp) nil t)
3862 (progn
3863 (goto-char (match-beginning 0))
3864 (funcall outline-level))
3865 1))))
3867 ;; FIXME: allow an argument to give a limiting level for this.
3868 (defun org-content ()
3869 "Show all headlines in the buffer, like a table of contents"
3870 (interactive)
3871 (save-excursion
3872 ;; Visit all headings and show their offspring
3873 (goto-char (point-max))
3874 (catch 'exit
3875 (while (and (progn (condition-case nil
3876 (outline-previous-visible-heading 1)
3877 (error (goto-char (point-min))))
3879 (looking-at outline-regexp))
3880 (show-branches)
3881 (if (bobp) (throw 'exit nil))))))
3884 (defun org-optimize-window-after-visibility-change (state)
3885 "Adjust the window after a change in outline visibility.
3886 This function is the default value of the hook `org-cycle-hook'."
3887 (when (get-buffer-window (current-buffer))
3888 (cond
3889 ((eq state 'overview) (org-first-headline-recenter 1))
3890 ((eq state 'content) nil)
3891 ((eq state 'all) nil)
3892 ((eq state 'folded) nil)
3893 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3894 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3896 (defun org-subtree-end-visible-p ()
3897 "Is the end of the current subtree visible?"
3898 (pos-visible-in-window-p
3899 (save-excursion (org-end-of-subtree t) (point))))
3901 (defun org-first-headline-recenter (&optional N)
3902 "Move cursor to the first headline and recenter the headline.
3903 Optional argument N means, put the headline into the Nth line of the window."
3904 (goto-char (point-min))
3905 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3906 (beginning-of-line)
3907 (recenter (prefix-numeric-value N))))
3909 (defvar org-goto-window-configuration nil)
3910 (defvar org-goto-marker nil)
3911 (defvar org-goto-map (make-sparse-keymap))
3912 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3913 (while (setq cmd (pop cmds))
3914 (substitute-key-definition cmd cmd org-goto-map global-map)))
3915 (define-key org-goto-map "\C-m" 'org-goto-ret)
3916 (define-key org-goto-map [(left)] 'org-goto-left)
3917 (define-key org-goto-map [(right)] 'org-goto-right)
3918 (define-key org-goto-map [(?q)] 'org-goto-quit)
3919 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3920 (define-key org-goto-map "\C-i" 'org-cycle)
3921 (define-key org-goto-map [(tab)] 'org-cycle)
3922 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3923 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3924 (define-key org-goto-map "n" 'outline-next-visible-heading)
3925 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3926 (define-key org-goto-map "f" 'outline-forward-same-level)
3927 (define-key org-goto-map "b" 'outline-backward-same-level)
3928 (define-key org-goto-map "u" 'outline-up-heading)
3929 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3930 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3931 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3932 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3933 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3934 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3935 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3937 (defconst org-goto-help
3938 "Select a location to jump to, press RET
3939 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3941 (defun org-goto ()
3942 "Go to a different location of the document, keeping current visibility.
3944 When you want to go to a different location in a document, the fastest way
3945 is often to fold the entire buffer and then dive into the tree. This
3946 method has the disadvantage, that the previous location will be folded,
3947 which may not be what you want.
3949 This command works around this by showing a copy of the current buffer in
3950 overview mode. You can dive into the tree in that copy, to find the
3951 location you want to reach. When pressing RET, the command returns to the
3952 original buffer in which the visibility is still unchanged. It then jumps
3953 to the new location, making it and the headline hierarchy above it visible."
3954 (interactive)
3955 (let* ((org-goto-start-pos (point))
3956 (selected-point
3957 (org-get-location (current-buffer) org-goto-help)))
3958 (if selected-point
3959 (progn
3960 (org-mark-ring-push org-goto-start-pos)
3961 (goto-char selected-point)
3962 (if (or (org-invisible-p) (org-invisible-p2))
3963 (org-show-hierarchy-above 'org-goto)))
3964 (error "Quit"))))
3966 (defun org-get-location (buf help)
3967 "Let the user select a location in the Org-mode buffer BUF.
3968 This function uses a recursive edit. It returns the selected position
3969 or nil."
3970 (let (org-selected-point)
3971 (save-excursion
3972 (save-window-excursion
3973 (delete-other-windows)
3974 (switch-to-buffer (get-buffer-create "*org-goto*"))
3975 (with-output-to-temp-buffer "*Help*"
3976 (princ help))
3977 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3978 (setq buffer-read-only nil)
3979 (erase-buffer)
3980 (insert-buffer-substring buf)
3981 (let ((org-startup-truncated t)
3982 (org-startup-folded t)
3983 (org-startup-align-all-tables nil)
3984 (org-startup-with-deadline-check nil))
3985 (org-mode))
3986 (setq buffer-read-only t)
3987 (if (boundp 'org-goto-start-pos)
3988 (goto-char org-goto-start-pos)
3989 (goto-char (point-min)))
3990 (org-beginning-of-line)
3991 (message "Select location and press RET")
3992 ;; now we make sure that during selection, ony very few keys work
3993 ;; and that it is impossible to switch to another window.
3994 (let ((gm (current-global-map))
3995 (overriding-local-map org-goto-map))
3996 (unwind-protect
3997 (progn
3998 (use-global-map org-goto-map)
3999 (recursive-edit))
4000 (use-global-map gm)))))
4001 (kill-buffer "*org-goto*")
4002 org-selected-point))
4004 (defun org-goto-ret (&optional arg)
4005 "Finish `org-goto' by going to the new location."
4006 (interactive "P")
4007 (setq org-selected-point (point)
4008 current-prefix-arg arg)
4009 (throw 'exit nil))
4011 (defun org-goto-left ()
4012 "Finish `org-goto' by going to the new location."
4013 (interactive)
4014 (if (org-on-heading-p)
4015 (progn
4016 (beginning-of-line 1)
4017 (setq org-selected-point (point)
4018 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4019 (throw 'exit nil))
4020 (error "Not on a heading")))
4022 (defun org-goto-right ()
4023 "Finish `org-goto' by going to the new location."
4024 (interactive)
4025 (if (org-on-heading-p)
4026 (progn
4027 (outline-end-of-subtree)
4028 (or (eobp) (forward-char 1))
4029 (setq org-selected-point (point)
4030 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4031 (throw 'exit nil))
4032 (error "Not on a heading")))
4034 (defun org-goto-quit ()
4035 "Finish `org-goto' without cursor motion."
4036 (interactive)
4037 (setq org-selected-point nil)
4038 (throw 'exit nil))
4040 ;;; Promotion, Demotion, Inserting new headlines
4042 (defvar org-ignore-region nil
4043 "To temporarily disable the active region.")
4045 (defun org-insert-heading (&optional force-heading)
4046 "Insert a new heading or item with same depth at point.
4047 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4048 If point is at the beginning of a headline, insert a sibling before the
4049 current headline. If point is in the middle of a headline, split the headline
4050 at that position and make the rest of the headline part of the sibling below
4051 the current headline."
4052 (interactive "P")
4053 (if (= (buffer-size) 0)
4054 (insert "\n* ")
4055 (when (or force-heading (not (org-insert-item)))
4056 (let* ((head (save-excursion
4057 (condition-case nil
4058 (progn
4059 (org-back-to-heading)
4060 (match-string 0))
4061 (error "*"))))
4062 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4063 pos)
4064 (cond
4065 ((and (org-on-heading-p) (bolp)
4066 (save-excursion (backward-char 1) (not (org-invisible-p))))
4067 (open-line (if blank 2 1)))
4068 ((and (bolp) (save-excursion
4069 (backward-char 1) (not (org-invisible-p))))
4070 nil)
4071 (t (newline (if blank 2 1))))
4072 (insert head) (just-one-space)
4073 (setq pos (point))
4074 (end-of-line 1)
4075 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4076 (run-hooks 'org-insert-heading-hook)))))
4078 (defun org-in-item-p ()
4079 "It the cursor inside a plain list item.
4080 Does not have to be the first line."
4081 (save-excursion
4082 (condition-case nil
4083 (progn
4084 (org-beginning-of-item)
4085 (org-at-item-p)
4087 (error nil))))
4089 (defun org-insert-item (&optional checkbox)
4090 "Insert a new item at the current level.
4091 Return t when things worked, nil when we are not in an item."
4092 (when (save-excursion
4093 (condition-case nil
4094 (progn
4095 (org-beginning-of-item)
4096 (org-at-item-p)
4097 (if (org-invisible-p) (error "Invisible item"))
4099 (error nil)))
4100 (let* ((bul (match-string 0))
4101 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
4102 (match-end 0)))
4103 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
4104 pos)
4105 (cond
4106 ((and (org-at-item-p) (<= (point) eow))
4107 ;; before the bullet
4108 (beginning-of-line 1)
4109 (open-line (if blank 2 1)))
4110 ((<= (point) eow)
4111 (beginning-of-line 1))
4112 (t (newline (if blank 2 1))))
4113 (insert bul (if checkbox "[ ]" ""))
4114 (just-one-space)
4115 (setq pos (point))
4116 (end-of-line 1)
4117 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
4118 (org-maybe-renumber-ordered-list)
4119 (and checkbox (org-update-checkbox-count-maybe))
4122 (defun org-insert-todo-heading (arg)
4123 "Insert a new heading with the same level and TODO state as current heading.
4124 If the heading has no TODO state, or if the state is DONE, use the first
4125 state (TODO by default). Also with prefix arg, force first state."
4126 (interactive "P")
4127 (when (not (org-insert-item 'checkbox))
4128 (org-insert-heading)
4129 (save-excursion
4130 (org-back-to-heading)
4131 (outline-previous-heading)
4132 (looking-at org-todo-line-regexp))
4133 (if (or arg
4134 (not (match-beginning 2))
4135 (equal (match-string 2) org-done-string))
4136 (insert (car org-todo-keywords) " ")
4137 (insert (match-string 2) " "))))
4139 (defun org-promote-subtree ()
4140 "Promote the entire subtree.
4141 See also `org-promote'."
4142 (interactive)
4143 (save-excursion
4144 (org-map-tree 'org-promote))
4145 (org-fix-position-after-promote))
4147 (defun org-demote-subtree ()
4148 "Demote the entire subtree. See `org-demote'.
4149 See also `org-promote'."
4150 (interactive)
4151 (save-excursion
4152 (org-map-tree 'org-demote))
4153 (org-fix-position-after-promote))
4156 (defun org-do-promote ()
4157 "Promote the current heading higher up the tree.
4158 If the region is active in `transient-mark-mode', promote all headings
4159 in the region."
4160 (interactive)
4161 (save-excursion
4162 (if (org-region-active-p)
4163 (org-map-region 'org-promote (region-beginning) (region-end))
4164 (org-promote)))
4165 (org-fix-position-after-promote))
4167 (defun org-do-demote ()
4168 "Demote the current heading lower down the tree.
4169 If the region is active in `transient-mark-mode', demote all headings
4170 in the region."
4171 (interactive)
4172 (save-excursion
4173 (if (org-region-active-p)
4174 (org-map-region 'org-demote (region-beginning) (region-end))
4175 (org-demote)))
4176 (org-fix-position-after-promote))
4178 (defun org-fix-position-after-promote ()
4179 "Make sure that after pro/demotion cursor position is right."
4180 (if (and (equal (char-after) ?\n)
4181 (save-excursion
4182 (skip-chars-backward "a-zA-Z0-9_@")
4183 (looking-at org-todo-regexp)))
4184 (insert " "))
4185 (and (equal (char-after) ?\ )
4186 (equal (char-before) ?*)
4187 (forward-char 1)))
4189 (defun org-get-legal-level (level &optional change)
4190 "Rectify a level change under the influence of `org-odd-levels-only'
4191 LEVEL is a current level, CHANGE is by how much the level should be
4192 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4193 even level numbers will become the next higher odd number."
4194 (if org-odd-levels-only
4195 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4196 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4197 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4198 (max 1 (+ level change))))
4200 (defun org-promote ()
4201 "Promote the current heading higher up the tree.
4202 If the region is active in `transient-mark-mode', promote all headings
4203 in the region."
4204 (org-back-to-heading t)
4205 (let* ((level (save-match-data (funcall outline-level)))
4206 (up-head (make-string (org-get-legal-level level -1) ?*))
4207 (diff (abs (- level (length up-head)))))
4208 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
4209 (replace-match up-head nil t)
4210 ;; Fixup tag positioning
4211 (and org-auto-align-tags (org-set-tags nil t))
4212 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4214 (defun org-demote ()
4215 "Demote the current heading lower down the tree.
4216 If the region is active in `transient-mark-mode', demote all headings
4217 in the region."
4218 (org-back-to-heading t)
4219 (let* ((level (save-match-data (funcall outline-level)))
4220 (down-head (make-string (org-get-legal-level level 1) ?*))
4221 (diff (abs (- level (length down-head)))))
4222 (replace-match down-head nil t)
4223 ;; Fixup tag positioning
4224 (and org-auto-align-tags (org-set-tags nil t))
4225 (if org-adapt-indentation (org-fixup-indentation diff))))
4227 (defun org-map-tree (fun)
4228 "Call FUN for every heading underneath the current one."
4229 (org-back-to-heading)
4230 (let ((level (funcall outline-level)))
4231 (save-excursion
4232 (funcall fun)
4233 (while (and (progn
4234 (outline-next-heading)
4235 (> (funcall outline-level) level))
4236 (not (eobp)))
4237 (funcall fun)))))
4239 (defun org-map-region (fun beg end)
4240 "Call FUN for every heading between BEG and END."
4241 (let ((org-ignore-region t))
4242 (save-excursion
4243 (setq end (copy-marker end))
4244 (goto-char beg)
4245 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4246 (< (point) end))
4247 (funcall fun))
4248 (while (and (progn
4249 (outline-next-heading)
4250 (< (point) end))
4251 (not (eobp)))
4252 (funcall fun)))))
4254 (defun org-fixup-indentation (diff)
4255 "Change the indentation in the current entry by DIFF
4256 However, if any line in the current entry has no indentation, or if it
4257 would end up with no indentation after the change, nothing at all is done."
4258 (save-excursion
4259 (let ((end (save-excursion (outline-next-heading)
4260 (point-marker)))
4261 (prohibit (if (> diff 0)
4262 "^\\S-"
4263 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4264 col)
4265 (unless (save-excursion (re-search-forward prohibit end t))
4266 (while (re-search-forward "^[ \t]+" end t)
4267 (goto-char (match-end 0))
4268 (setq col (current-column))
4269 (if (< diff 0) (replace-match ""))
4270 (indent-to (+ diff col))))
4271 (move-marker end nil))))
4273 ;;; Vertical tree motion, cutting and pasting of subtrees
4275 (defun org-move-subtree-up (&optional arg)
4276 "Move the current subtree up past ARG headlines of the same level."
4277 (interactive "p")
4278 (org-move-subtree-down (- (prefix-numeric-value arg))))
4280 (defun org-move-subtree-down (&optional arg)
4281 "Move the current subtree down past ARG headlines of the same level."
4282 (interactive "p")
4283 (setq arg (prefix-numeric-value arg))
4284 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4285 'outline-get-last-sibling))
4286 (ins-point (make-marker))
4287 (cnt (abs arg))
4288 beg end txt folded)
4289 ;; Select the tree
4290 (org-back-to-heading)
4291 (setq beg (point))
4292 (save-match-data
4293 (save-excursion (outline-end-of-heading)
4294 (setq folded (org-invisible-p)))
4295 (outline-end-of-subtree))
4296 (outline-next-heading)
4297 (setq end (point))
4298 ;; Find insertion point, with error handling
4299 (goto-char beg)
4300 (while (> cnt 0)
4301 (or (and (funcall movfunc) (looking-at outline-regexp))
4302 (progn (goto-char beg)
4303 (error "Cannot move past superior level or buffer limit")))
4304 (setq cnt (1- cnt)))
4305 (if (> arg 0)
4306 ;; Moving forward - still need to move over subtree
4307 (progn (outline-end-of-subtree)
4308 (outline-next-heading)
4309 (if (not (or (looking-at (concat "^" outline-regexp))
4310 (bolp)))
4311 (newline))))
4312 (move-marker ins-point (point))
4313 (setq txt (buffer-substring beg end))
4314 (delete-region beg end)
4315 (insert txt)
4316 (goto-char ins-point)
4317 (if folded (hide-subtree))
4318 (move-marker ins-point nil)))
4320 (defvar org-subtree-clip ""
4321 "Clipboard for cut and paste of subtrees.
4322 This is actually only a copy of the kill, because we use the normal kill
4323 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4325 (defvar org-subtree-clip-folded nil
4326 "Was the last copied subtree folded?
4327 This is used to fold the tree back after pasting.")
4329 (defun org-cut-subtree ()
4330 "Cut the current subtree into the clipboard.
4331 This is a short-hand for marking the subtree and then cutting it."
4332 (interactive)
4333 (org-copy-subtree 'cut))
4335 (defun org-copy-subtree (&optional cut)
4336 "Cut the current subtree into the clipboard.
4337 This is a short-hand for marking the subtree and then copying it.
4338 If CUT is non nil, actually cut the subtree."
4339 (interactive)
4340 (let (beg end folded)
4341 (org-back-to-heading)
4342 (setq beg (point))
4343 (save-match-data
4344 (save-excursion (outline-end-of-heading)
4345 (setq folded (org-invisible-p)))
4346 (outline-end-of-subtree))
4347 (if (equal (char-after) ?\n) (forward-char 1))
4348 (setq end (point))
4349 (goto-char beg)
4350 (when (> end beg)
4351 (setq org-subtree-clip-folded folded)
4352 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4353 (setq org-subtree-clip (current-kill 0))
4354 (message "%s: Subtree with %d characters"
4355 (if cut "Cut" "Copied")
4356 (length org-subtree-clip)))))
4358 (defun org-paste-subtree (&optional level tree)
4359 "Paste the clipboard as a subtree, with modification of headline level.
4360 The entire subtree is promoted or demoted in order to match a new headline
4361 level. By default, the new level is derived from the visible headings
4362 before and after the insertion point, and taken to be the inferior headline
4363 level of the two. So if the previous visible heading is level 3 and the
4364 next is level 4 (or vice versa), level 4 will be used for insertion.
4365 This makes sure that the subtree remains an independent subtree and does
4366 not swallow low level entries.
4368 You can also force a different level, either by using a numeric prefix
4369 argument, or by inserting the heading marker by hand. For example, if the
4370 cursor is after \"*****\", then the tree will be shifted to level 5.
4372 If you want to insert the tree as is, just use \\[yank].
4374 If optional TREE is given, use this text instead of the kill ring."
4375 (interactive "P")
4376 (unless (org-kill-is-subtree-p tree)
4377 (error
4378 (substitute-command-keys
4379 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4380 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4381 (^re (concat "^\\(" outline-regexp "\\)"))
4382 (re (concat "\\(" outline-regexp "\\)"))
4383 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4385 (old-level (if (string-match ^re txt)
4386 (- (match-end 0) (match-beginning 0))
4387 -1))
4388 (force-level (cond (level (prefix-numeric-value level))
4389 ((string-match
4390 ^re_ (buffer-substring (point-at-bol) (point)))
4391 (- (match-end 0) (match-beginning 0)))
4392 (t nil)))
4393 (previous-level (save-excursion
4394 (condition-case nil
4395 (progn
4396 (outline-previous-visible-heading 1)
4397 (if (looking-at re)
4398 (- (match-end 0) (match-beginning 0))
4400 (error 1))))
4401 (next-level (save-excursion
4402 (condition-case nil
4403 (progn
4404 (outline-next-visible-heading 1)
4405 (if (looking-at re)
4406 (- (match-end 0) (match-beginning 0))
4408 (error 1))))
4409 (new-level (or force-level (max previous-level next-level)))
4410 (shift (if (or (= old-level -1)
4411 (= new-level -1)
4412 (= old-level new-level))
4414 (- new-level old-level)))
4415 (shift1 shift)
4416 (delta (if (> shift 0) -1 1))
4417 (func (if (> shift 0) 'org-demote 'org-promote))
4418 (org-odd-levels-only nil)
4419 beg end)
4420 ;; Remove the forces level indicator
4421 (if force-level
4422 (delete-region (point-at-bol) (point)))
4423 ;; Make sure we start at the beginning of an empty line
4424 (if (not (bolp)) (insert "\n"))
4425 (if (not (looking-at "[ \t]*$"))
4426 (progn (insert "\n") (backward-char 1)))
4427 ;; Paste
4428 (setq beg (point))
4429 (if (string-match "[ \t\r\n]+\\'" txt)
4430 (setq txt (replace-match "\n" t t txt)))
4431 (insert txt)
4432 (setq end (point))
4433 (if (looking-at "[ \t\r\n]+")
4434 (replace-match "\n"))
4435 (goto-char beg)
4436 ;; Shift if necessary
4437 (if (= shift 0)
4438 (message "Pasted at level %d, without shift" new-level)
4439 (save-restriction
4440 (narrow-to-region beg end)
4441 (while (not (= shift 0))
4442 (org-map-region func (point-min) (point-max))
4443 (setq shift (+ delta shift)))
4444 (goto-char (point-min))
4445 (message "Pasted at level %d, with shift by %d levels"
4446 new-level shift1)))
4447 (if (and kill-ring
4448 (eq org-subtree-clip (current-kill 0))
4449 org-subtree-clip-folded)
4450 ;; The tree was folded before it was killed/copied
4451 (hide-subtree))))
4453 (defun org-kill-is-subtree-p (&optional txt)
4454 "Check if the current kill is an outline subtree, or a set of trees.
4455 Returns nil if kill does not start with a headline, or if the first
4456 headline level is not the largest headline level in the tree.
4457 So this will actually accept several entries of equal levels as well,
4458 which is OK for `org-paste-subtree'.
4459 If optional TXT is given, check this string instead of the current kill."
4460 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4461 (start-level (and kill
4462 (string-match (concat "\\`" outline-regexp) kill)
4463 (- (match-end 0) (match-beginning 0))))
4464 (re (concat "^" outline-regexp))
4465 (start 1))
4466 (if (not start-level)
4467 nil ;; does not even start with a heading
4468 (catch 'exit
4469 (while (setq start (string-match re kill (1+ start)))
4470 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4471 (throw 'exit nil)))
4472 t))))
4474 (defun org-narrow-to-subtree ()
4475 "Narrow buffer to the current subtree."
4476 (interactive)
4477 (save-excursion
4478 (narrow-to-region
4479 (progn (org-back-to-heading) (point))
4480 (progn (org-end-of-subtree t) (point)))))
4482 ;;; Plain list items
4484 (defun org-at-item-p ()
4485 "Is point in a line starting a hand-formatted item?"
4486 (let ((llt org-plain-list-ordered-item-terminator))
4487 (save-excursion
4488 (goto-char (point-at-bol))
4489 (looking-at
4490 (cond
4491 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4492 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4493 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4494 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4496 (defun org-at-item-checkbox-p ()
4497 "Is point at a line starting a plain-list item with a checklet?"
4498 (and (org-at-item-p)
4499 (save-excursion
4500 (goto-char (match-end 0))
4501 (skip-chars-forward " \t")
4502 (looking-at "\\[[ X]\\]"))))
4504 (defun org-toggle-checkbox (&optional arg)
4505 "Toggle the checkbox in the current line."
4506 (interactive "P")
4507 (catch 'exit
4508 (let (beg end status (firstnew 'unknown))
4509 (cond
4510 ((org-region-active-p)
4511 (setq beg (region-beginning) end (region-end)))
4512 ((org-on-heading-p)
4513 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4514 ((org-at-item-checkbox-p)
4515 (save-excursion
4516 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4517 (throw 'exit t))
4518 (t (error "Not at a checkbox or heading, and no active region")))
4519 (save-excursion
4520 (goto-char beg)
4521 (while (< (point) end)
4522 (when (org-at-item-checkbox-p)
4523 (setq status (equal (match-string 0) "[X]"))
4524 (when (eq firstnew 'unknown)
4525 (setq firstnew (not status)))
4526 (replace-match
4527 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4528 (beginning-of-line 2)))))
4529 (org-update-checkbox-count-maybe))
4531 (defun org-update-checkbox-count-maybe ()
4532 "Update checkbox statistics unless turned off by user."
4533 (when org-provide-checkbox-statistics
4534 (org-update-checkbox-count)))
4536 (defun org-update-checkbox-count (&optional all)
4537 "Update the checkbox statistics in the current section.
4538 This will find all statistic cookies like [57%] and [6/12] and update them
4539 with the current numbers. With optional prefix argument ALL, do this for
4540 the whole buffer."
4541 (interactive "P")
4542 (save-excursion
4543 (let* ((buffer-invisibility-spec nil) ; Emacs 21 compatibility
4544 (beg (progn (outline-back-to-heading) (point)))
4545 (end (move-marker (make-marker)
4546 (progn (outline-next-heading) (point))))
4547 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
4548 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
4549 b1 e1 f1 c-on c-off lim (cstat 0))
4550 (when all
4551 (goto-char (point-min))
4552 (outline-next-heading)
4553 (setq beg (point) end (point-max)))
4554 (goto-char beg)
4555 (while (re-search-forward re end t)
4556 (setq cstat (1+ cstat)
4557 b1 (match-beginning 0)
4558 e1 (match-end 0)
4559 f1 (match-beginning 1)
4560 lim (cond
4561 ((org-on-heading-p) (outline-next-heading) (point))
4562 ((org-at-item-p) (org-end-of-item) (point))
4563 (t nil))
4564 c-on 0 c-off 0)
4565 (goto-char e1)
4566 (when lim
4567 (while (re-search-forward re-box lim t)
4568 (if (equal (match-string 2) "[ ]")
4569 (setq c-off (1+ c-off))
4570 (setq c-on (1+ c-on))))
4571 (delete-region b1 e1)
4572 (goto-char b1)
4573 (insert (if f1
4574 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
4575 (format "[%d/%d]" c-on (+ c-on c-off))))))
4576 (when (interactive-p)
4577 (message "Checkbox satistics updated %s (%d places)"
4578 (if all "in entire file" "in current outline entry") cstat)))))
4580 (defun org-get-checkbox-statistics-face ()
4581 "Select the face for checkbox statistics.
4582 The face will be `org-done' when all relevant boxes are checked. Otherwise
4583 it will be `org-todo'."
4584 (if (match-end 1)
4585 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
4586 (if (and (> (match-end 2) (match-beginning 2))
4587 (equal (match-string 2) (match-string 3)))
4588 'org-done
4589 'org-todo)))
4591 (defun org-get-indentation (&optional line)
4592 "Get the indentation of the current line, interpreting tabs.
4593 When LINE is given, assume it represents a line and compute its indentation."
4594 (if line
4595 (if (string-match "^ *" (org-remove-tabs line))
4596 (match-end 0))
4597 (save-excursion
4598 (beginning-of-line 1)
4599 (skip-chars-forward " \t")
4600 (current-column))))
4602 (defun org-remove-tabs (s &optional width)
4603 "Replace tabulators in S with spaces.
4604 Assumes that s is a single line, starting in column 0."
4605 (setq width (or width tab-width))
4606 (while (string-match "\t" s)
4607 (setq s (replace-match
4608 (make-string
4609 (- (* width (/ (+ (match-beginning 0) width) width))
4610 (match-beginning 0)) ?\ )
4611 t t s)))
4614 ;; FIXME: document properly.
4615 (defun org-fix-indentation (line ind)
4616 "If the current indenation is smaller than ind1, leave it alone.
4617 If it is larger than ind, reduce it by ind."
4618 (let* ((l (org-remove-tabs line))
4619 (i (org-get-indentation l))
4620 (i1 (car ind)) (i2 (cdr ind)))
4621 (if (>= i i2) (setq l (substring line i2)))
4622 (if (> i1 0)
4623 (concat (make-string i1 ?\ ) l)
4624 l)))
4626 (defun org-beginning-of-item ()
4627 "Go to the beginning of the current hand-formatted item.
4628 If the cursor is not in an item, throw an error."
4629 (interactive)
4630 (let ((pos (point))
4631 (limit (save-excursion (org-back-to-heading)
4632 (beginning-of-line 2) (point)))
4633 ind ind1)
4634 (if (org-at-item-p)
4635 (beginning-of-line 1)
4636 (beginning-of-line 1)
4637 (skip-chars-forward " \t")
4638 (setq ind (current-column))
4639 (if (catch 'exit
4640 (while t
4641 (beginning-of-line 0)
4642 (if (< (point) limit) (throw 'exit nil))
4643 (unless (looking-at "[ \t]*$")
4644 (skip-chars-forward " \t")
4645 (setq ind1 (current-column))
4646 (if (< ind1 ind)
4647 (throw 'exit (org-at-item-p))))))
4649 (goto-char pos)
4650 (error "Not in an item")))))
4652 (defun org-end-of-item ()
4653 "Go to the end of the current hand-formatted item.
4654 If the cursor is not in an item, throw an error."
4655 (interactive)
4656 (let ((pos (point))
4657 (limit (save-excursion (outline-next-heading) (point)))
4658 (ind (save-excursion
4659 (org-beginning-of-item)
4660 (skip-chars-forward " \t")
4661 (current-column)))
4662 ind1)
4663 (if (catch 'exit
4664 (while t
4665 (beginning-of-line 2)
4666 (if (>= (point) limit) (throw 'exit t))
4667 (unless (looking-at "[ \t]*$")
4668 (skip-chars-forward " \t")
4669 (setq ind1 (current-column))
4670 (if (<= ind1 ind) (throw 'exit t)))))
4671 (beginning-of-line 1)
4672 (goto-char pos)
4673 (error "Not in an item"))))
4675 (defun org-next-item ()
4676 "Move to the beginning of the next item in the current plain list.
4677 Error if not at a plain list, or if this is the last item in the list."
4678 (interactive)
4679 (let (ind ind1 (pos (point)))
4680 (org-beginning-of-item)
4681 (setq ind (org-get-indentation))
4682 (org-end-of-item)
4683 (setq ind1 (org-get-indentation))
4684 (unless (and (org-at-item-p) (= ind ind1))
4685 (goto-char pos)
4686 (error "On last item"))))
4688 (defun org-previous-item ()
4689 "Move to the beginning of the previous item in the current plain list.
4690 Error if not at a plain list, or if this is the last item in the list."
4691 (interactive)
4692 (let (beg ind (pos (point)))
4693 (org-beginning-of-item)
4694 (setq beg (point))
4695 (setq ind (org-get-indentation))
4696 (goto-char beg)
4697 (catch 'exit
4698 (while t
4699 (beginning-of-line 0)
4700 (if (looking-at "[ \t]*$")
4702 (if (<= (org-get-indentation) ind)
4703 (throw 'exit t)))))
4704 (condition-case nil
4705 (org-beginning-of-item)
4706 (error (goto-char pos)
4707 (error "On first item")))))
4709 (defun org-move-item-down ()
4710 "Move the plain list item at point down, i.e. swap with following item.
4711 Subitems (items with larger indentation) are considered part of the item,
4712 so this really moves item trees."
4713 (interactive)
4714 (let (beg end ind ind1 (pos (point)) txt)
4715 (org-beginning-of-item)
4716 (setq beg (point))
4717 (setq ind (org-get-indentation))
4718 (org-end-of-item)
4719 (setq end (point))
4720 (setq ind1 (org-get-indentation))
4721 (if (and (org-at-item-p) (= ind ind1))
4722 (progn
4723 (org-end-of-item)
4724 (setq txt (buffer-substring beg end))
4725 (save-excursion
4726 (delete-region beg end))
4727 (setq pos (point))
4728 (insert txt)
4729 (goto-char pos)
4730 (org-maybe-renumber-ordered-list))
4731 (goto-char pos)
4732 (error "Cannot move this item further down"))))
4734 (defun org-move-item-up (arg)
4735 "Move the plain list item at point up, i.e. swap with previous item.
4736 Subitems (items with larger indentation) are considered part of the item,
4737 so this really moves item trees."
4738 (interactive "p")
4739 (let (beg end ind ind1 (pos (point)) txt)
4740 (org-beginning-of-item)
4741 (setq beg (point))
4742 (setq ind (org-get-indentation))
4743 (org-end-of-item)
4744 (setq end (point))
4745 (goto-char beg)
4746 (catch 'exit
4747 (while t
4748 (beginning-of-line 0)
4749 (if (looking-at "[ \t]*$")
4751 (if (<= (setq ind1 (org-get-indentation)) ind)
4752 (throw 'exit t)))))
4753 (condition-case nil
4754 (org-beginning-of-item)
4755 (error (goto-char beg)
4756 (error "Cannot move this item further up")))
4757 (setq ind1 (org-get-indentation))
4758 (if (and (org-at-item-p) (= ind ind1))
4759 (progn
4760 (setq txt (buffer-substring beg end))
4761 (save-excursion
4762 (delete-region beg end))
4763 (setq pos (point))
4764 (insert txt)
4765 (goto-char pos)
4766 (org-maybe-renumber-ordered-list))
4767 (goto-char pos)
4768 (error "Cannot move this item further up"))))
4770 (defun org-maybe-renumber-ordered-list ()
4771 "Renumber the ordered list at point if setup allows it.
4772 This tests the user option `org-auto-renumber-ordered-lists' before
4773 doing the renumbering."
4774 (and org-auto-renumber-ordered-lists
4775 (org-at-item-p)
4776 (match-beginning 3)
4777 (org-renumber-ordered-list 1)))
4779 (defun org-get-string-indentation (s)
4780 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4781 (let ((n -1) (i 0) (w tab-width) c)
4782 (catch 'exit
4783 (while (< (setq n (1+ n)) (length s))
4784 (setq c (aref s n))
4785 (cond ((= c ?\ ) (setq i (1+ i)))
4786 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4787 (t (throw 'exit t)))))
4790 (defun org-renumber-ordered-list (arg)
4791 "Renumber an ordered plain list.
4792 Cursor needs to be in the first line of an item, the line that starts
4793 with something like \"1.\" or \"2)\"."
4794 (interactive "p")
4795 (unless (and (org-at-item-p)
4796 (match-beginning 3))
4797 (error "This is not an ordered list"))
4798 (let ((line (org-current-line))
4799 (col (current-column))
4800 (ind (org-get-string-indentation
4801 (buffer-substring (point-at-bol) (match-beginning 3))))
4802 ;; (term (substring (match-string 3) -1))
4803 ind1 (n (1- arg)))
4804 ;; find where this list begins
4805 (catch 'exit
4806 (while t
4807 (catch 'next
4808 (beginning-of-line 0)
4809 (if (looking-at "[ \t]*$") (throw 'next t))
4810 (skip-chars-forward " \t") (setq ind1 (current-column))
4811 (if (or (< ind1 ind)
4812 (and (= ind1 ind)
4813 (not (org-at-item-p))))
4814 (throw 'exit t)))))
4815 ;; Walk forward and replace these numbers
4816 (catch 'exit
4817 (while t
4818 (catch 'next
4819 (beginning-of-line 2)
4820 (if (eobp) (throw 'exit nil))
4821 (if (looking-at "[ \t]*$") (throw 'next nil))
4822 (skip-chars-forward " \t") (setq ind1 (current-column))
4823 (if (> ind1 ind) (throw 'next t))
4824 (if (< ind1 ind) (throw 'exit t))
4825 (if (not (org-at-item-p)) (throw 'exit nil))
4826 (if (not (match-beginning 3))
4827 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4828 (delete-region (match-beginning 3) (1- (match-end 3)))
4829 (goto-char (match-beginning 3))
4830 (insert (format "%d" (setq n (1+ n)))))))
4831 (goto-line line)
4832 (move-to-column col)))
4834 (defvar org-last-indent-begin-marker (make-marker))
4835 (defvar org-last-indent-end-marker (make-marker))
4837 (defun org-outdent-item (arg)
4838 "Outdent a local list item."
4839 (interactive "p")
4840 (org-indent-item (- arg)))
4842 (defun org-indent-item (arg)
4843 "Indent a local list item."
4844 (interactive "p")
4845 (unless (org-at-item-p)
4846 (error "Not on an item"))
4847 (save-excursion
4848 (let (beg end ind ind1)
4849 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4850 (setq beg org-last-indent-begin-marker
4851 end org-last-indent-end-marker)
4852 (org-beginning-of-item)
4853 (setq beg (move-marker org-last-indent-begin-marker (point)))
4854 (org-end-of-item)
4855 (setq end (move-marker org-last-indent-end-marker (point))))
4856 (goto-char beg)
4857 (skip-chars-forward " \t") (setq ind (current-column))
4858 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4859 (while (< (point) end)
4860 (beginning-of-line 1)
4861 (skip-chars-forward " \t") (setq ind1 (current-column))
4862 (delete-region (point-at-bol) (point))
4863 (indent-to-column (+ ind1 arg))
4864 (beginning-of-line 2)))))
4866 ;;; Archiving
4868 (defun org-archive-subtree (&optional find-done)
4869 "Move the current subtree to the archive.
4870 The archive can be a certain top-level heading in the current file, or in
4871 a different file. The tree will be moved to that location, the subtree
4872 heading be marked DONE, and the current time will be added.
4874 When called with prefix argument FIND-DONE, find whole trees without any
4875 open TODO items and archive them (after getting confirmation from the user).
4876 If the cursor is not at a headline when this comand is called, try all level
4877 1 trees. If the cursor is on a headline, only try the direct children of
4878 this heading. "
4879 (interactive "P")
4880 (if find-done
4881 (org-archive-all-done)
4882 ;; Save all relevant TODO keyword-relatex variables
4884 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4885 (tr-org-todo-keywords org-todo-keywords)
4886 (tr-org-todo-interpretation org-todo-interpretation)
4887 (tr-org-done-string org-done-string)
4888 (tr-org-todo-regexp org-todo-regexp)
4889 (tr-org-todo-line-regexp org-todo-line-regexp)
4890 (this-buffer (current-buffer))
4891 file heading buffer level newfile-p)
4892 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4893 (progn
4894 (setq file (format (match-string 1 org-archive-location)
4895 (file-name-nondirectory buffer-file-name))
4896 heading (match-string 2 org-archive-location)))
4897 (error "Invalid `org-archive-location'"))
4898 (if (> (length file) 0)
4899 (setq newfile-p (not (file-exists-p file))
4900 buffer (find-file-noselect file))
4901 (setq buffer (current-buffer)))
4902 (unless buffer
4903 (error "Cannot access file \"%s\"" file))
4904 (if (and (> (length heading) 0)
4905 (string-match "^\\*+" heading))
4906 (setq level (match-end 0))
4907 (setq heading nil level 0))
4908 (save-excursion
4909 ;; We first only copy, in case something goes wrong
4910 ;; we need to protect this-command, to avoid kill-region sets it,
4911 ;; which would lead to duplication of subtrees
4912 (let (this-command) (org-copy-subtree))
4913 (set-buffer buffer)
4914 ;; Enforce org-mode for the archive buffer
4915 (if (not (org-mode-p))
4916 ;; Force the mode for future visits.
4917 (let ((org-insert-mode-line-in-empty-file t))
4918 (call-interactively 'org-mode)))
4919 (when newfile-p
4920 (goto-char (point-max))
4921 (insert (format "\nArchived entries from file %s\n\n"
4922 (buffer-file-name this-buffer))))
4923 ;; Force the TODO keywords of the original buffer
4924 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4925 (org-todo-keywords tr-org-todo-keywords)
4926 (org-todo-interpretation tr-org-todo-interpretation)
4927 (org-done-string tr-org-done-string)
4928 (org-todo-regexp tr-org-todo-regexp)
4929 (org-todo-line-regexp tr-org-todo-line-regexp))
4930 (goto-char (point-min))
4931 (if heading
4932 (progn
4933 (if (re-search-forward
4934 (concat "\\(^\\|\r\\)"
4935 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4936 nil t)
4937 (goto-char (match-end 0))
4938 ;; Heading not found, just insert it at the end
4939 (goto-char (point-max))
4940 (or (bolp) (insert "\n"))
4941 (insert "\n" heading "\n")
4942 (end-of-line 0))
4943 ;; Make the subtree visible
4944 (show-subtree)
4945 (org-end-of-subtree t)
4946 (skip-chars-backward " \t\r\n")
4947 (and (looking-at "[ \t\r\n]*")
4948 (replace-match "\n\n")))
4949 ;; No specific heading, just go to end of file.
4950 (goto-char (point-max)) (insert "\n"))
4951 ;; Paste
4952 (org-paste-subtree (1+ level))
4953 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4954 (if org-archive-mark-done
4955 (org-todo (length org-todo-keywords)))
4956 ;; Move cursor to right after the TODO keyword
4957 (when org-archive-stamp-time
4958 (beginning-of-line 1)
4959 (looking-at org-todo-line-regexp)
4960 (goto-char (or (match-end 2) (match-beginning 3)))
4961 (org-insert-time-stamp (org-current-time) t t "(" ")"))
4962 ;; Save the buffer, if it is not the same buffer.
4963 (if (not (eq this-buffer buffer)) (save-buffer))))
4964 ;; Here we are back in the original buffer. Everything seems to have
4965 ;; worked. So now cut the tree and finish up.
4966 (let (this-command) (org-cut-subtree))
4967 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4968 (message "Subtree archived %s"
4969 (if (eq this-buffer buffer)
4970 (concat "under heading: " heading)
4971 (concat "in file: " (abbreviate-file-name file)))))))
4973 (defun org-archive-all-done (&optional tag)
4974 "Archive sublevels of the current tree without open TODO items.
4975 If the cursor is not on a headline, try all level 1 trees. If
4976 it is on a headline, try all direct children.
4977 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4978 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4979 (rea (concat ".*:" org-archive-tag ":"))
4980 (begm (make-marker))
4981 (endm (make-marker))
4982 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4983 "Move subtree to archive (no open TODO items)? "))
4984 beg end (cntarch 0))
4985 (if (org-on-heading-p)
4986 (progn
4987 (setq re1 (concat "^" (regexp-quote
4988 (make-string
4989 (1+ (- (match-end 0) (match-beginning 0)))
4990 ?*))
4991 " "))
4992 (move-marker begm (point))
4993 (move-marker endm (org-end-of-subtree t)))
4994 (setq re1 "^* ")
4995 (move-marker begm (point-min))
4996 (move-marker endm (point-max)))
4997 (save-excursion
4998 (goto-char begm)
4999 (while (re-search-forward re1 endm t)
5000 (setq beg (match-beginning 0)
5001 end (save-excursion (org-end-of-subtree t) (point)))
5002 (goto-char beg)
5003 (if (re-search-forward re end t)
5004 (goto-char end)
5005 (goto-char beg)
5006 (if (and (or (not tag) (not (looking-at rea)))
5007 (y-or-n-p question))
5008 (progn
5009 (if tag
5010 (org-toggle-tag org-archive-tag 'on)
5011 (org-archive-subtree))
5012 (setq cntarch (1+ cntarch)))
5013 (goto-char end)))))
5014 (message "%d trees archived" cntarch)))
5016 (defun org-cycle-hide-archived-subtrees (state)
5017 "Re-hide all archived subtrees after a visibility state change."
5018 (when (and (not org-cycle-open-archived-trees)
5019 (not (memq state '(overview folded))))
5020 (save-excursion
5021 (let* ((globalp (memq state '(contents all)))
5022 (beg (if globalp (point-min) (point)))
5023 (end (if globalp (point-max) (org-end-of-subtree t))))
5024 (org-hide-archived-subtrees beg end)
5025 (goto-char beg)
5026 (if (looking-at (concat ".*:" org-archive-tag ":"))
5027 (message (substitute-command-keys
5028 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5030 (defun org-force-cycle-archived ()
5031 "Cycle subtree even if it is archived."
5032 (interactive)
5033 (setq this-command 'org-cycle)
5034 (let ((org-cycle-open-archived-trees t))
5035 (call-interactively 'org-cycle)))
5037 (defun org-hide-archived-subtrees (beg end)
5038 "Re-hide all archived subtrees after a visibility state change."
5039 (save-excursion
5040 (let* ((re (concat ":" org-archive-tag ":")))
5041 (goto-char beg)
5042 (while (re-search-forward re end t)
5043 (and (org-on-heading-p) (hide-subtree))
5044 (org-end-of-subtree t)))))
5046 (defun org-toggle-tag (tag &optional onoff)
5047 "Toggle the tag TAG for the current line.
5048 If ONOFF is `on' or `off', don't toggle but set to this state."
5049 (unless (org-on-heading-p) (error "Not on headling"))
5050 (let (res current)
5051 (save-excursion
5052 (beginning-of-line)
5053 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5054 (point-at-eol) t)
5055 (progn
5056 (setq current (match-string 1))
5057 (replace-match ""))
5058 (setq current ""))
5059 (setq current (nreverse (org-split-string current ":")))
5060 (cond
5061 ((eq onoff 'on)
5062 (setq res t)
5063 (or (member tag current) (push tag current)))
5064 ((eq onoff 'off)
5065 (or (not (member tag current)) (setq current (delete tag current))))
5066 (t (if (member tag current)
5067 (setq current (delete tag current))
5068 (setq res t)
5069 (push tag current))))
5070 (end-of-line 1)
5071 (when current
5072 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5073 (org-set-tags nil t))
5074 res))
5076 (defun org-toggle-archive-tag (&optional arg)
5077 "Toggle the archive tag for the current headline.
5078 With prefix ARG, check all children of current headline and offer tagging
5079 the children that do not contain any open TODO items."
5080 (interactive "P")
5081 (if arg
5082 (org-archive-all-done 'tag)
5083 (let (set)
5084 (save-excursion
5085 (org-back-to-heading t)
5086 (setq set (org-toggle-tag org-archive-tag))
5087 (when set (hide-subtree)))
5088 (and set (beginning-of-line 1))
5089 (message "Subtree %s" (if set "archived" "unarchived")))))
5091 (defvar org-agenda-multi nil) ; dynammically scoped
5092 (defvar org-agenda-buffer-name "*Org Agenda*")
5093 (defvar org-pre-agenda-window-conf nil)
5094 (defun org-prepare-agenda ()
5095 (if org-agenda-multi
5096 (progn
5097 (setq buffer-read-only nil)
5098 (goto-char (point-max))
5099 (unless (= (point) 1)
5100 (insert "\n" (make-string (window-width) ?=) "\n"))
5101 (narrow-to-region (point) (point-max)))
5102 (org-agenda-maybe-reset-markers 'force)
5103 (org-prepare-agenda-buffers (org-agenda-files))
5104 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
5105 (awin (get-buffer-window abuf)))
5106 (cond
5107 ((equal (current-buffer) abuf) nil)
5108 (awin (select-window awin))
5109 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
5110 ((equal org-agenda-window-setup 'current-window)
5111 (switch-to-buffer abuf))
5112 ((equal org-agenda-window-setup 'other-window)
5113 (switch-to-buffer-other-window abuf))
5114 ((equal org-agenda-window-setup 'other-frame)
5115 (switch-to-buffer-other-frame abuf))
5116 ((equal org-agenda-window-setup 'reorganize-frame)
5117 (delete-other-windows)
5118 (switch-to-buffer-other-window abuf))))
5119 (setq buffer-read-only nil)
5120 (erase-buffer)
5121 (org-agenda-mode))
5122 (setq buffer-read-only nil))
5124 (defun org-finalize-agenda ()
5125 "Finishing touch for the agenda buffer, called just before displaying it."
5126 (unless org-agenda-multi
5127 (org-agenda-align-tags)
5128 (save-excursion
5129 (let ((buffer-read-only))
5130 (goto-char (point-min))
5131 (while (org-activate-bracket-links (point-max))
5132 (add-text-properties (match-beginning 0) (match-end 0)
5133 '(face org-link))))
5134 (run-hooks 'org-finalize-agenda-hook))))
5136 (defun org-prepare-agenda-buffers (files)
5137 "Create buffers for all agenda files, protect archived trees and comments."
5138 (interactive)
5139 (let ((pa '(:org-archived t))
5140 (pc '(:org-comment t))
5141 (pall '(:org-archived t :org-comment t))
5142 (rea (concat ":" org-archive-tag ":"))
5143 bmp file re)
5144 (save-excursion
5145 (while (setq file (pop files))
5146 (org-check-agenda-file file)
5147 (set-buffer (org-get-agenda-file-buffer file))
5148 (widen)
5149 (setq bmp (buffer-modified-p))
5150 (save-excursion
5151 (remove-text-properties (point-min) (point-max) pall)
5152 (when org-agenda-skip-archived-trees
5153 (goto-char (point-min))
5154 (while (re-search-forward rea nil t)
5155 (if (org-on-heading-p)
5156 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
5157 (goto-char (point-min))
5158 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
5159 (while (re-search-forward re nil t)
5160 (add-text-properties
5161 (match-beginning 0) (org-end-of-subtree t) pc)))
5162 (set-buffer-modified-p bmp)))))
5164 (defun org-agenda-skip ()
5165 "Throw to `:skip' in places that should be skipped."
5166 (let ((p (point-at-bol)))
5167 (and org-agenda-skip-archived-trees
5168 (get-text-property p :org-archived)
5169 (org-end-of-subtree t)
5170 (throw :skip t))
5171 (and (get-text-property p :org-comment)
5172 (org-end-of-subtree t)
5173 (throw :skip t))
5174 (if (equal (char-after p) ?#) (throw :skip t))))
5176 (defun org-agenda-toggle-archive-tag ()
5177 "Toggle the archive tag for the current entry."
5178 (interactive)
5179 (org-agenda-check-no-diary)
5180 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
5181 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
5182 (org-agenda-error)))
5183 (buffer (marker-buffer hdmarker))
5184 (pos (marker-position hdmarker))
5185 (buffer-read-only nil)
5186 newhead)
5187 (with-current-buffer buffer
5188 (widen)
5189 (goto-char pos)
5190 (org-show-hierarchy-above 'agenda)
5191 (save-excursion
5192 (and (outline-next-heading)
5193 (org-flag-heading nil))) ; show the next heading
5194 (call-interactively 'org-toggle-archive-tag)
5195 (end-of-line 1)
5196 (setq newhead (org-get-heading)))
5197 (org-agenda-change-all-lines newhead hdmarker)
5198 (beginning-of-line 1)))
5200 ;;; Dynamic blocks
5202 (defun org-find-dblock (name)
5203 "Find the first dynamic block with name NAME in the buffer.
5204 If not found, stay at current position and return nil."
5205 (let (pos)
5206 (save-excursion
5207 (goto-char (point-min))
5208 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
5209 nil t)
5210 (match-beginning 0))))
5211 (if pos (goto-char pos))
5212 pos))
5214 (defconst org-dblock-start-re
5215 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
5216 "Matches the startline of a dynamic block, with parameters.")
5218 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
5219 "Matches the end of a dyhamic block.")
5221 (defun org-create-dblock (plist)
5222 "Create a dynamic block section, with parameters taken from PLIST.
5223 PLIST must containe a :name entry which is used as name of the block."
5224 (unless (bolp) (newline))
5225 (let ((name (plist-get plist :name)))
5226 (insert "#+BEGIN: " name)
5227 (while plist
5228 (if (eq (car plist) :name)
5229 (setq plist (cddr plist))
5230 (insert " " (prin1-to-string (pop plist)))))
5231 (insert "\n\n#+END:\n")
5232 (beginning-of-line -2)))
5234 (defun org-prepare-dblock ()
5235 "Prepare dynamic block for refresh.
5236 This empties the block, puts the cursor at the insert position and returns
5237 the property list including an extra property :name with the block name."
5238 (unless (looking-at org-dblock-start-re)
5239 (error "Not at a dynamic block"))
5240 (let* ((begdel (1+ (match-end 0)))
5241 (name (match-string 1))
5242 (params (append (list :name name)
5243 (read (concat "(" (match-string 3) ")")))))
5244 (unless (re-search-forward org-dblock-end-re nil t)
5245 (error "Dynamic block not terminated"))
5246 (delete-region begdel (match-beginning 0))
5247 (goto-char begdel)
5248 (open-line 1)
5249 params))
5251 (defun org-map-dblocks (&optional command)
5252 "Apply COMMAND to all dynamic blocks in the current buffer.
5253 If COMMAND is not given, use `org-update-dblock'."
5254 (let ((cmd (or command 'org-update-dblock))
5255 pos)
5256 (save-excursion
5257 (goto-char (point-min))
5258 (while (re-search-forward org-dblock-start-re nil t)
5259 (goto-char (setq pos (match-beginning 0)))
5260 (condition-case nil
5261 (funcall cmd)
5262 (error (message "Error during update of dynamic block")))
5263 (goto-char pos)
5264 (unless (re-search-forward org-dblock-end-re nil t)
5265 (error "Dynamic block not terminated"))))))
5267 (defun org-dblock-update (&optional arg)
5268 "User command for updating dynamic blocks.
5269 Update the dynamic block at point. With prefix ARG, update all dynamic
5270 blocks in the buffer."
5271 (interactive "P")
5272 (if arg
5273 (org-update-all-dblocks)
5274 (or (looking-at org-dblock-start-re)
5275 (org-beginning-of-dblock))
5276 (org-update-dblock)))
5278 (defun org-update-dblock ()
5279 "Update the dynamic block at point
5280 This means to empty the block, parse for parameters and then call
5281 the correct writing function."
5282 (let* ((pos (point))
5283 (params (org-prepare-dblock))
5284 (name (plist-get params :name))
5285 (cmd (intern (concat "org-dblock-write:" name))))
5286 (funcall cmd params)
5287 (goto-char pos)))
5289 (defun org-beginning-of-dblock ()
5290 "Find the beginning of the dynamic block at point.
5291 Error if there is no scuh block at point."
5292 (let ((pos (point))
5293 beg)
5294 (end-of-line 1)
5295 (if (and (re-search-backward org-dblock-start-re nil t)
5296 (setq beg (match-beginning 0))
5297 (re-search-forward org-dblock-end-re nil t)
5298 (> (match-end 0) pos))
5299 (goto-char beg)
5300 (goto-char pos)
5301 (error "Not in a dynamic block"))))
5303 (defun org-update-all-dblocks ()
5304 "Update all dynamic blocks in the buffer.
5305 This function can be used in a hook."
5306 (when (org-mode-p)
5307 (org-map-dblocks 'org-update-dblock)))
5310 ;;; Completion
5312 (defun org-complete (&optional arg)
5313 "Perform completion on word at point.
5314 At the beginning of a headline, this completes TODO keywords as given in
5315 `org-todo-keywords'.
5316 If the current word is preceded by a backslash, completes the TeX symbols
5317 that are supported for HTML support.
5318 If the current word is preceded by \"#+\", completes special words for
5319 setting file options.
5320 In the line after \"#+STARTUP:, complete valid keywords.\"
5321 At all other locations, this simply calls `ispell-complete-word'."
5322 (interactive "P")
5323 (catch 'exit
5324 (let* ((end (point))
5325 (beg1 (save-excursion
5326 (skip-chars-backward "a-zA-Z_@0-9")
5327 (point)))
5328 (beg (save-excursion
5329 (skip-chars-backward "a-zA-Z0-9_:$")
5330 (point)))
5331 (confirm (lambda (x) (stringp (car x))))
5332 (camel (equal (char-before beg) ?*))
5333 (tag (equal (char-before beg1) ?:))
5334 (texp (equal (char-before beg) ?\\))
5335 (link (equal (char-before beg) ?\[))
5336 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
5337 beg)
5338 "#+"))
5339 (startup (string-match "^#\\+STARTUP:.*"
5340 (buffer-substring (point-at-bol) (point))))
5341 (completion-ignore-case opt)
5342 (type nil)
5343 (tbl nil)
5344 (table (cond
5345 (opt
5346 (setq type :opt)
5347 (mapcar (lambda (x)
5348 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
5349 (cons (match-string 2 x) (match-string 1 x)))
5350 (org-split-string (org-get-current-options) "\n")))
5351 (startup
5352 (setq type :startup)
5353 org-startup-options)
5354 (link (append org-link-abbrev-alist-local
5355 org-link-abbrev-alist))
5356 (texp
5357 (setq type :tex)
5358 org-html-entities)
5359 ((string-match "\\`\\*+[ \t]*\\'"
5360 (buffer-substring (point-at-bol) beg))
5361 (setq type :todo)
5362 (mapcar 'list org-todo-keywords))
5363 (camel
5364 (setq type :camel)
5365 (save-excursion
5366 (goto-char (point-min))
5367 (while (re-search-forward org-todo-line-regexp nil t)
5368 (push (list
5369 (if org-file-link-context-use-camel-case
5370 (org-make-org-heading-camel (match-string 3) t)
5371 (org-make-org-heading-search-string
5372 (match-string 3) t)))
5373 tbl)))
5374 tbl)
5375 (tag (setq type :tag beg beg1)
5376 (or org-tag-alist (org-get-buffer-tags)))
5377 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
5378 (pattern (buffer-substring-no-properties beg end))
5379 (completion (try-completion pattern table confirm)))
5380 (cond ((eq completion t)
5381 (if (equal type :opt)
5382 (insert (substring (cdr (assoc (upcase pattern) table))
5383 (length pattern)))))
5384 ((null completion)
5385 (message "Can't find completion for \"%s\"" pattern)
5386 (ding))
5387 ((not (string= pattern completion))
5388 (delete-region beg end)
5389 (if (string-match " +$" completion)
5390 (setq completion (replace-match "" t t completion)))
5391 (insert completion)
5392 (if (get-buffer-window "*Completions*")
5393 (delete-window (get-buffer-window "*Completions*")))
5394 (if (assoc completion table)
5395 (if (eq type :todo) (insert " ")
5396 (if (eq type :tag) (insert ":"))))
5397 (if (and (equal type :opt) (assoc completion table))
5398 (message "%s" (substitute-command-keys
5399 "Press \\[org-complete] again to insert example settings"))))
5401 (message "Making completion list...")
5402 (let ((list (sort (all-completions pattern table confirm)
5403 'string<)))
5404 (with-output-to-temp-buffer "*Completions*"
5405 (condition-case nil
5406 ;; Protection needed for XEmacs and emacs 21
5407 (display-completion-list list pattern)
5408 (error (display-completion-list list)))))
5409 (message "Making completion list...%s" "done"))))))
5411 ;;; Comments, TODO and DEADLINE
5413 (defun org-toggle-comment ()
5414 "Change the COMMENT state of an entry."
5415 (interactive)
5416 (save-excursion
5417 (org-back-to-heading)
5418 (if (looking-at (concat outline-regexp
5419 "\\( +\\<" org-comment-string "\\>\\)"))
5420 (replace-match "" t t nil 1)
5421 (if (looking-at outline-regexp)
5422 (progn
5423 (goto-char (match-end 0))
5424 (insert " " org-comment-string))))))
5426 (defvar org-last-todo-state-is-todo nil
5427 "This is non-nil when the last TODO state change led to a TODO state.
5428 If the last change removed the TODO tag or switched to DONE, then
5429 this is nil.")
5431 (defun org-todo (&optional arg)
5432 "Change the TODO state of an item.
5433 The state of an item is given by a keyword at the start of the heading,
5434 like
5435 *** TODO Write paper
5436 *** DONE Call mom
5438 The different keywords are specified in the variable `org-todo-keywords'.
5439 By default the available states are \"TODO\" and \"DONE\".
5440 So for this example: when the item starts with TODO, it is changed to DONE.
5441 When it starts with DONE, the DONE is removed. And when neither TODO nor
5442 DONE are present, add TODO at the beginning of the heading.
5444 With prefix arg, use completion to determine the new state. With numeric
5445 prefix arg, switch to that state."
5446 (interactive "P")
5447 (save-excursion
5448 (org-back-to-heading)
5449 (if (looking-at outline-regexp) (goto-char (match-end 0)))
5450 (or (looking-at (concat " +" org-todo-regexp " *"))
5451 (looking-at " *"))
5452 (let* ((this (match-string 1))
5453 (completion-ignore-case t)
5454 (member (member this org-todo-keywords))
5455 (tail (cdr member))
5456 (state (cond
5457 ((equal arg '(4))
5458 ;; Read a state with completion
5459 (completing-read "State: " (mapcar (lambda(x) (list x))
5460 org-todo-keywords)
5461 nil t))
5462 ((eq arg 'right)
5463 (if this
5464 (if tail (car tail) nil)
5465 (car org-todo-keywords)))
5466 ((eq arg 'left)
5467 (if (equal member org-todo-keywords)
5469 (if this
5470 (nth (- (length org-todo-keywords) (length tail) 2)
5471 org-todo-keywords)
5472 org-done-string)))
5473 (arg
5474 ;; user requests a specific state
5475 (nth (1- (prefix-numeric-value arg))
5476 org-todo-keywords))
5477 ((null member) (car org-todo-keywords))
5478 ((null tail) nil) ;; -> first entry
5479 ((eq org-todo-interpretation 'sequence)
5480 (car tail))
5481 ((memq org-todo-interpretation '(type priority))
5482 (if (eq this-command last-command)
5483 (car tail)
5484 (if (> (length tail) 0) org-done-string nil)))
5485 (t nil)))
5486 (next (if state (concat " " state " ") " ")))
5487 (replace-match next t t)
5488 (setq org-last-todo-state-is-todo
5489 (not (equal state org-done-string)))
5490 (when org-log-done
5491 (if (equal state org-done-string)
5492 (org-add-planning-info 'closed (org-current-time) 'scheduled)
5493 (if (not this)
5494 (org-add-planning-info nil nil 'closed))))
5495 ;; Fixup tag positioning
5496 (and org-auto-align-tags (org-set-tags nil t))
5497 (run-hooks 'org-after-todo-state-change-hook)))
5498 ;; Fixup cursor location if close to the keyword
5499 (if (and (outline-on-heading-p)
5500 (not (bolp))
5501 (save-excursion (beginning-of-line 1)
5502 (looking-at org-todo-line-regexp))
5503 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5504 (progn
5505 (goto-char (or (match-end 2) (match-end 1)))
5506 (just-one-space))))
5508 (defun org-show-todo-tree (arg)
5509 "Make a compact tree which shows all headlines marked with TODO.
5510 The tree will show the lines where the regexp matches, and all higher
5511 headlines above the match.
5512 With \\[universal-argument] prefix, also show the DONE entries.
5513 With a numeric prefix N, construct a sparse tree for the Nth element
5514 of `org-todo-keywords'."
5515 (interactive "P")
5516 (let ((case-fold-search nil)
5517 (kwd-re
5518 (cond ((null arg) org-not-done-regexp)
5519 ((equal arg '(4)) org-todo-regexp)
5520 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5521 (regexp-quote (nth (1- (prefix-numeric-value arg))
5522 org-todo-keywords)))
5523 (t (error "Invalid prefix argument: %s" arg)))))
5524 (message "%d TODO entries found"
5525 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5527 (defun org-deadline ()
5528 "Insert the DEADLINE: string to make a deadline.
5529 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5530 to modify it to the correct date."
5531 (interactive)
5532 (org-add-planning-info 'deadline nil 'closed))
5534 (defun org-schedule ()
5535 "Insert the SCHEDULED: string to schedule a TODO item.
5536 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5537 to modify it to the correct date."
5538 (interactive)
5539 (org-add-planning-info 'scheduled nil 'closed))
5541 (defun org-add-planning-info (what &optional time &rest remove)
5542 "Insert new timestamp with keyword in the line directly after the headline.
5543 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5544 If non is given, the user is prompted for a date.
5545 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5546 be removed."
5547 (interactive)
5548 (when what (setq time (or time (org-read-date nil 'to-time))))
5549 (when (and org-insert-labeled-timestamps-at-point
5550 (member what '(scheduled deadline)))
5551 (insert
5552 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
5553 (org-insert-time-stamp time)
5554 (setq what nil))
5555 (save-excursion
5556 (save-restriction
5557 (let (col list elt ts buffer-invisibility-spec)
5558 (org-back-to-heading t)
5559 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5560 (goto-char (match-end 1))
5561 (setq col (current-column))
5562 (goto-char (1+ (match-end 0)))
5563 (if (and (not (looking-at outline-regexp))
5564 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5565 "[^\r\n]*"))
5566 (not (equal (match-string 1) org-clock-string)))
5567 (narrow-to-region (match-beginning 0) (match-end 0))
5568 (insert "\n")
5569 (backward-char 1)
5570 (narrow-to-region (point) (point))
5571 (indent-to-column col))
5572 ;; Check if we have to remove something.
5573 (setq list (cons what remove))
5574 (while list
5575 (setq elt (pop list))
5576 (goto-char (point-min))
5577 (when (or (and (eq elt 'scheduled)
5578 (re-search-forward org-scheduled-time-regexp nil t))
5579 (and (eq elt 'deadline)
5580 (re-search-forward org-deadline-time-regexp nil t))
5581 (and (eq elt 'closed)
5582 (re-search-forward org-closed-time-regexp nil t)))
5583 (replace-match "")
5584 (if (looking-at " +") (replace-match ""))))
5585 (goto-char (point-max))
5586 (when what
5587 (insert
5588 (if (not (equal (char-before) ?\ )) " " "")
5589 (cond ((eq what 'scheduled) org-scheduled-string)
5590 ((eq what 'deadline) org-deadline-string)
5591 ((eq what 'closed) org-closed-string))
5592 " ")
5593 (org-insert-time-stamp time nil (eq what 'closed))
5594 (end-of-line 1)
5595 (org-add-log-maybe 'done))
5596 (goto-char (point-min))
5597 (widen)
5598 (if (looking-at "[ \t]+\r?\n")
5599 (replace-match ""))
5600 ts))))
5602 (defvar org-log-note-marker (make-marker))
5603 (defvar org-log-note-purpose nil)
5604 (defvar org-log-note-window-configuration nil)
5606 (defun org-add-log-maybe (&optional purpose)
5607 (when (and (listp org-log-done)
5608 (memq purpose org-log-done))
5609 (move-marker org-log-note-marker (point))
5610 (setq org-log-note-purpose purpose)
5611 (add-hook 'post-command-hook 'org-add-log-note 'append)))
5613 (defun org-add-log-note (&optional purpose)
5614 "Pop up a window for taking a note, and add this note later at point."
5615 (remove-hook 'post-command-hook 'org-add-log-note)
5616 (setq org-log-note-window-configuration (current-window-configuration))
5617 (delete-other-windows)
5618 (switch-to-buffer (marker-buffer org-log-note-marker))
5619 (goto-char org-log-note-marker)
5620 (switch-to-buffer-other-window "*Org Note*")
5621 (erase-buffer)
5622 (org-mode)
5623 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
5624 (cond
5625 ((eq org-log-note-purpose 'clock-out) "stopped clock")
5626 ((eq org-log-note-purpose 'done) "closed todo item")
5627 (t (error "This should not happen")))))
5628 (org-set-local 'org-finish-function 'org-store-log-note))
5630 (defun org-store-log-note ()
5631 "Finish taking a log note, and insert it to where it belongs."
5632 (let ((txt (buffer-string))
5633 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
5634 lines ind)
5635 (kill-buffer (current-buffer))
5636 (if (string-match "^#.*\n[ \t\\n]*" txt)
5637 (setq txt (replace-match "" t t txt)))
5638 (when (string-match "\\S-" txt)
5639 (if (string-match "\\s-+\\'" txt)
5640 (setq txt (replace-match "" t t txt)))
5641 (setq lines (org-split-string txt "\n"))
5642 (and note (string-match "\\S-" note) (push note lines))
5643 (save-excursion
5644 (set-buffer (marker-buffer org-log-note-marker))
5645 (save-excursion
5646 (goto-char org-log-note-marker)
5647 (if (not (bolp)) (newline))
5648 (indent-relative t)
5649 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
5650 (insert " - " (pop lines))
5651 (while lines
5652 (insert "\n" ind (pop lines))))))
5653 (set-window-configuration org-log-note-window-configuration)))
5655 (defvar org-occur-highlights nil)
5656 (make-variable-buffer-local 'org-occur-highlights)
5658 (defun org-occur (regexp &optional keep-previous callback)
5659 "Make a compact tree which shows all matches of REGEXP.
5660 The tree will show the lines where the regexp matches, and all higher
5661 headlines above the match. It will also show the heading after the match,
5662 to make sure editing the matching entry is easy.
5663 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
5664 call to `org-occur' will be kept, to allow stacking of calls to this
5665 command.
5666 If CALLBACK is non-nil, it is a function which is called to confirm
5667 that the match should indeed be shown."
5668 (interactive "sRegexp: \nP")
5669 (or keep-previous (org-remove-occur-highlights nil nil t))
5670 (let ((cnt 0))
5671 (save-excursion
5672 (goto-char (point-min))
5673 (if (or (not keep-previous) ; do not want to keep
5674 (not org-occur-highlights)) ; no previous matches
5675 ;; hide everything
5676 (org-overview))
5677 (while (re-search-forward regexp nil t)
5678 (when (or (not callback)
5679 (save-match-data (funcall callback)))
5680 (setq cnt (1+ cnt))
5681 (org-highlight-new-match (match-beginning 0) (match-end 0))
5682 (org-show-hierarchy-above 'occur-tree))))
5683 (when org-remove-highlights-with-change
5684 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5685 nil 'local))
5686 (unless org-sparse-tree-open-archived-trees
5687 (org-hide-archived-subtrees (point-min) (point-max)))
5688 (run-hooks 'org-occur-hook)
5689 (if (interactive-p)
5690 (message "%d match(es) for regexp %s" cnt regexp))
5691 cnt))
5693 (defun org-show-hierarchy-above (&optional context)
5694 "Make sure point and the headings hierarchy above is visible."
5695 (catch 'exit
5696 (if (org-on-heading-p t)
5697 (org-flag-heading nil) ; only show the heading
5698 (and (or (org-invisible-p) (org-invisible-p2))
5699 (org-show-hidden-entry))) ; show entire entry
5700 (save-excursion
5701 (and (org-get-alist-option org-show-following-heading context)
5702 (outline-next-heading)
5703 (org-flag-heading nil))) ; show the next heading
5704 (when (org-get-alist-option org-show-hierarchy-above context)
5705 (save-excursion ; show all higher headings
5706 (while (and (condition-case nil
5707 (progn (org-up-heading-all 1) t)
5708 (error nil))
5709 (not (bobp)))
5710 (org-flag-heading nil))))))
5712 ;; Overlay compatibility functions
5713 (defun org-make-overlay (beg end &optional buffer)
5714 (if (featurep 'xemacs)
5715 (make-extent beg end buffer)
5716 (make-overlay beg end buffer)))
5717 (defun org-delete-overlay (ovl)
5718 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5719 (defun org-detatch-overlay (ovl)
5720 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5721 (defun org-move-overlay (ovl beg end &optional buffer)
5722 (if (featurep 'xemacs)
5723 (set-extent-endpoints ovl beg end buffer)
5724 (move-overlay ovl beg end buffer)))
5725 (defun org-overlay-put (ovl prop value)
5726 (if (featurep 'xemacs)
5727 (set-extent-property ovl prop value)
5728 (overlay-put ovl prop value)))
5729 (defun org-overlay-get (ovl prop)
5730 (if (featurep 'xemacs)
5731 (extent-property ovl prop)
5732 (overlay-get ovl prop)))
5733 (defun org-overlays-at (pos)
5734 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5735 (defun org-overlays-in (&optional start end)
5736 (if (featurep 'xemacs)
5737 (extent-list nil start end)
5738 (overlays-in start end)))
5739 (defun org-overlay-start (o)
5740 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5741 (defun org-overlay-end (o)
5742 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5744 (defun org-highlight-new-match (beg end)
5745 "Highlight from BEG to END and mark the highlight is an occur headline."
5746 (let ((ov (org-make-overlay beg end)))
5747 (org-overlay-put ov 'face 'secondary-selection)
5748 (push ov org-occur-highlights)))
5750 (defvar org-inhibit-highlight-removal nil)
5751 (defun org-remove-occur-highlights (&optional beg end noremove)
5752 "Remove the occur highlights from the buffer.
5753 BEG and END are ignored. If NOREMOVE is nil, remove this function
5754 from the `before-change-functions' in the current buffer."
5755 (interactive)
5756 (unless org-inhibit-highlight-removal
5757 (mapc 'org-delete-overlay org-occur-highlights)
5758 (setq org-occur-highlights nil)
5759 (unless noremove
5760 (remove-hook 'before-change-functions
5761 'org-remove-occur-highlights 'local))))
5763 ;;; Priorities
5765 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5766 "Regular expression matching the priority indicator.")
5768 (defvar org-remove-priority-next-time nil)
5770 (defun org-priority-up ()
5771 "Increase the priority of the current item."
5772 (interactive)
5773 (org-priority 'up))
5775 (defun org-priority-down ()
5776 "Decrease the priority of the current item."
5777 (interactive)
5778 (org-priority 'down))
5780 (defun org-priority (&optional action)
5781 "Change the priority of an item by ARG.
5782 ACTION can be set, up, or down."
5783 (interactive)
5784 (setq action (or action 'set))
5785 (let (current new news have remove)
5786 (save-excursion
5787 (org-back-to-heading)
5788 (if (looking-at org-priority-regexp)
5789 (setq current (string-to-char (match-string 2))
5790 have t)
5791 (setq current org-default-priority))
5792 (cond
5793 ((eq action 'set)
5794 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5795 (setq new (read-char-exclusive))
5796 (cond ((equal new ?\ ) (setq remove t))
5797 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5798 (error "Priority must be between `%c' and `%c'"
5799 ?A org-lowest-priority))))
5800 ((eq action 'up)
5801 (setq new (1- current)))
5802 ((eq action 'down)
5803 (setq new (1+ current)))
5804 (t (error "Invalid action")))
5805 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5806 (setq news (format "%c" new))
5807 (if have
5808 (if remove
5809 (replace-match "" t t nil 1)
5810 (replace-match news t t nil 2))
5811 (if remove
5812 (error "No priority cookie found in line")
5813 (looking-at org-todo-line-regexp)
5814 (if (match-end 2)
5815 (progn
5816 (goto-char (match-end 2))
5817 (insert " [#" news "]"))
5818 (goto-char (match-beginning 3))
5819 (insert "[#" news "] ")))))
5820 (if remove
5821 (message "Priority removed")
5822 (message "Priority of current item set to %s" news))))
5825 (defun org-get-priority (s)
5826 "Find priority cookie and return priority."
5827 (save-match-data
5828 (if (not (string-match org-priority-regexp s))
5829 (* 1000 (- org-lowest-priority org-default-priority))
5830 (* 1000 (- org-lowest-priority
5831 (string-to-char (match-string 2 s)))))))
5833 ;;; Timestamps
5835 (defvar org-last-changed-timestamp nil)
5837 (defun org-time-stamp (arg)
5838 "Prompt for a date/time and insert a time stamp.
5839 If the user specifies a time like HH:MM, or if this command is called
5840 with a prefix argument, the time stamp will contain date and time.
5841 Otherwise, only the date will be included. All parts of a date not
5842 specified by the user will be filled in from the current date/time.
5843 So if you press just return without typing anything, the time stamp
5844 will represent the current date/time. If there is already a timestamp
5845 at the cursor, it will be modified."
5846 (interactive "P")
5847 (let (org-time-was-given time)
5848 (cond
5849 ((and (org-at-timestamp-p)
5850 (eq last-command 'org-time-stamp)
5851 (eq this-command 'org-time-stamp))
5852 (insert "--")
5853 (setq time (let ((this-command this-command))
5854 (org-read-date arg 'totime)))
5855 (org-insert-time-stamp time (or org-time-was-given arg)))
5856 ((org-at-timestamp-p)
5857 (setq time (let ((this-command this-command))
5858 (org-read-date arg 'totime)))
5859 (when (org-at-timestamp-p) ; just to get the match data
5860 (replace-match "")
5861 (setq org-last-changed-timestamp
5862 (org-insert-time-stamp time (or org-time-was-given arg))))
5863 (message "Timestamp updated"))
5865 (setq time (let ((this-command this-command))
5866 (org-read-date arg 'totime)))
5867 (org-insert-time-stamp time (or org-time-was-given arg))))))
5869 (defun org-time-stamp-inactive (&optional arg)
5870 "Insert an inactive time stamp.
5871 An inactive time stamp is enclosed in square brackets instead of angle
5872 brackets. It is inactive in the sense that it does not trigger agenda entries,
5873 does not link to the calendar and cannot be changed with the S-cursor keys.
5874 So these are more for recording a certain time/date."
5875 (interactive "P")
5876 (let (org-time-was-given time)
5877 (setq time (org-read-date arg 'totime))
5878 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
5880 (defvar org-date-ovl (org-make-overlay 1 1))
5881 (org-overlay-put org-date-ovl 'face 'org-warning)
5882 (org-detatch-overlay org-date-ovl)
5884 (defun org-read-date (&optional with-time to-time from-string)
5885 "Read a date and make things smooth for the user.
5886 The prompt will suggest to enter an ISO date, but you can also enter anything
5887 which will at least partially be understood by `parse-time-string'.
5888 Unrecognized parts of the date will default to the current day, month, year,
5889 hour and minute. For example,
5890 3-2-5 --> 2003-02-05
5891 feb 15 --> currentyear-02-15
5892 sep 12 9 --> 2009-09-12
5893 12:45 --> today 12:45
5894 22 sept 0:34 --> currentyear-09-22 0:34
5895 12 --> currentyear-currentmonth-12
5896 Fri --> nearest Friday (today or later)
5897 etc.
5898 The function understands only English month and weekday abbreviations,
5899 but this can be configured with the variables `parse-time-months' and
5900 `parse-time-weekdays'.
5902 While prompting, a calendar is popped up - you can also select the
5903 date with the mouse (button 1). The calendar shows a period of three
5904 months. To scroll it to other months, use the keys `>' and `<'.
5905 If you don't like the calendar, turn it off with
5906 \(setq org-popup-calendar-for-date-prompt Nil)
5908 With optional argument TO-TIME, the date will immediately be converted
5909 to an internal time.
5910 With an optional argument WITH-TIME, the prompt will suggest to also
5911 insert a time. Note that when WITH-TIME is not set, you can still
5912 enter a time, and this function will inform the calling routine about
5913 this change. The calling routine may then choose to change the format
5914 used to insert the time stamp into the buffer to include the time."
5915 (require 'parse-time)
5916 (let* ((org-time-stamp-rounding-minutes
5917 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5918 (ct (org-current-time))
5919 (default-time
5920 ;; Default time is either today, or, when entering a range,
5921 ;; the range start.
5922 (if (save-excursion
5923 (re-search-backward
5924 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5925 (- (point) 20) t))
5926 (apply
5927 'encode-time
5928 (mapcar (lambda(x) (or x 0))
5929 (parse-time-string (match-string 1))))
5930 ct))
5931 (calendar-move-hook nil)
5932 (view-diary-entries-initially nil)
5933 (view-calendar-holidays-initially nil)
5934 (timestr (format-time-string
5935 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5936 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5937 ans ans1 ans2
5938 second minute hour day month year tl wday wday1)
5940 (cond
5941 (from-string (setq ans from-string))
5942 (org-popup-calendar-for-date-prompt
5943 (save-excursion
5944 (save-window-excursion
5945 (calendar)
5946 (calendar-forward-day (- (time-to-days default-time)
5947 (calendar-absolute-from-gregorian
5948 (calendar-current-date))))
5949 (org-eval-in-calendar nil)
5950 (let* ((old-map (current-local-map))
5951 (map (copy-keymap calendar-mode-map))
5952 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5953 (define-key map (kbd "RET") 'org-calendar-select)
5954 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5955 'org-calendar-select-mouse)
5956 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5957 'org-calendar-select-mouse)
5958 (define-key minibuffer-local-map [(meta shift left)]
5959 (lambda () (interactive)
5960 (org-eval-in-calendar '(calendar-backward-month 1))))
5961 (define-key minibuffer-local-map [(meta shift right)]
5962 (lambda () (interactive)
5963 (org-eval-in-calendar '(calendar-forward-month 1))))
5964 (define-key minibuffer-local-map [(shift up)]
5965 (lambda () (interactive)
5966 (org-eval-in-calendar '(calendar-backward-week 1))))
5967 (define-key minibuffer-local-map [(shift down)]
5968 (lambda () (interactive)
5969 (org-eval-in-calendar '(calendar-forward-week 1))))
5970 (define-key minibuffer-local-map [(shift left)]
5971 (lambda () (interactive)
5972 (org-eval-in-calendar '(calendar-backward-day 1))))
5973 (define-key minibuffer-local-map [(shift right)]
5974 (lambda () (interactive)
5975 (org-eval-in-calendar '(calendar-forward-day 1))))
5976 (define-key minibuffer-local-map ">"
5977 (lambda () (interactive)
5978 (org-eval-in-calendar '(scroll-calendar-left 1))))
5979 (define-key minibuffer-local-map "<"
5980 (lambda () (interactive)
5981 (org-eval-in-calendar '(scroll-calendar-right 1))))
5982 (unwind-protect
5983 (progn
5984 (use-local-map map)
5985 (setq ans (read-string prompt "" nil nil))
5986 (if (not (string-match "\\S-" ans)) (setq ans nil))
5987 (setq ans (or ans1 ans ans2)))
5988 (use-local-map old-map))))))
5989 (t ; Naked prompt only
5990 (setq ans (read-string prompt "" nil timestr))))
5991 (org-detatch-overlay org-date-ovl)
5993 (if (string-match
5994 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5995 (progn
5996 (setq year (if (match-end 2)
5997 (string-to-number (match-string 2 ans))
5998 (string-to-number (format-time-string "%Y")))
5999 month (string-to-number (match-string 3 ans))
6000 day (string-to-number (match-string 4 ans)))
6001 (if (< year 100) (setq year (+ 2000 year)))
6002 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
6003 t nil ans))))
6004 (setq tl (parse-time-string ans)
6005 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
6006 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
6007 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
6008 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
6009 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
6010 second (or (nth 0 tl) 0)
6011 wday (nth 6 tl))
6012 (when (and wday (not (nth 3 tl)))
6013 ;; Weekday was given, but no day, so pick that day in the week
6014 ;; on or after the derived date.
6015 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
6016 (unless (equal wday wday1)
6017 (setq day (+ day (% (- wday wday1 -7) 7)))))
6018 (if (and (boundp 'org-time-was-given)
6019 (nth 2 tl))
6020 (setq org-time-was-given t))
6021 (if (< year 100) (setq year (+ 2000 year)))
6022 (if to-time
6023 (encode-time second minute hour day month year)
6024 (if (or (nth 1 tl) (nth 2 tl))
6025 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
6026 (format "%04d-%02d-%02d" year month day)))))
6028 (defun org-eval-in-calendar (form)
6029 "Eval FORM in the calendar window and return to current window.
6030 Also, store the cursor date in variable ans2."
6031 (let ((sw (selected-window)))
6032 (select-window (get-buffer-window "*Calendar*"))
6033 (eval form)
6034 (when (calendar-cursor-to-date)
6035 (let* ((date (calendar-cursor-to-date))
6036 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
6037 (setq ans2 (format-time-string "%Y-%m-%d" time))))
6038 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
6039 (select-window sw)))
6041 (defun org-calendar-select ()
6042 "Return to `org-read-date' with the date currently selected.
6043 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
6044 (interactive)
6045 (when (calendar-cursor-to-date)
6046 (let* ((date (calendar-cursor-to-date))
6047 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
6048 (setq ans1 (format-time-string "%Y-%m-%d" time)))
6049 (if (active-minibuffer-window) (exit-minibuffer))))
6051 (defun org-insert-time-stamp (time &optional with-hm inactive pre post)
6052 "Insert a date stamp for the date given by the internal TIME.
6053 WITH-HM means, use the stamp format that includes the time of the day.
6054 INACTIVE means use square brackets instead of angular ones, so that the
6055 stamp will not contribute to the agenda.
6056 PRE and POST are optional strings to be inserted before and after the
6057 stamp.
6058 The command returns the inserted time stamp."
6059 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
6060 stamp)
6061 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
6062 (insert (or pre ""))
6063 (insert (setq stamp (format-time-string fmt time)))
6064 (insert (or post ""))
6065 stamp))
6067 (defun org-toggle-time-stamp-overlays ()
6068 "Toggle the use of custom time stamp formats."
6069 (interactive)
6070 (setq org-display-custom-times (not org-display-custom-times))
6071 (unless org-display-custom-times
6072 (let ((p (point-min)) (bmp (buffer-modified-p)))
6073 (while (setq p (next-single-property-change p 'display))
6074 (if (and (get-text-property p 'display)
6075 (eq (get-text-property p 'face) 'org-date))
6076 (remove-text-properties
6077 p (setq p (next-single-property-change p 'display))
6078 '(display t))))
6079 (set-buffer-modified-p bmp)))
6080 (if (featurep 'xemacs)
6081 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
6082 (org-restart-font-lock)
6083 (setq org-table-may-need-update t)
6084 (if org-display-custom-times
6085 (message "Time stamps are overlayed with custom format")
6086 (message "Time stamp overlays removed")))
6088 (defun org-display-custom-time (beg end)
6089 "Overlay modified time stamp format over timestamp between BED and END."
6090 (let* ((t1 (save-match-data
6091 (org-parse-time-string (buffer-substring beg end) t)))
6092 (w1 (- end beg))
6093 (with-hm (and (nth 1 t1) (nth 2 t1)))
6094 (inactive (= (char-before (1- beg)) ?\[))
6095 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
6096 (time (mapcar (lambda (x) (or x 0)) t1))
6097 (str (org-add-props
6098 (format-time-string
6099 (substring tf 1 -1) (apply 'encode-time time))
6100 nil 'mouse-face 'highlight))
6101 (w2 (length str)))
6102 (if (not (= w2 w1))
6103 (add-text-properties (1+ beg) (+ 2 beg)
6104 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
6105 (if (featurep 'xemacs)
6106 (progn
6107 (put-text-property beg end 'invisible t)
6108 (put-text-property beg end 'end-glyph (make-glyph str)))
6109 (put-text-property beg end 'display str))))
6111 (defun org-days-to-time (timestamp-string)
6112 "Difference between TIMESTAMP-STRING and now in days."
6113 (- (time-to-days (org-time-string-to-time timestamp-string))
6114 (time-to-days (current-time))))
6116 (defun org-deadline-close (timestamp-string &optional ndays)
6117 "Is the time in TIMESTAMP-STRING close to the current date?"
6118 (and (< (org-days-to-time timestamp-string)
6119 (or ndays org-deadline-warning-days))
6120 (not (org-entry-is-done-p))))
6122 (defun org-calendar-select-mouse (ev)
6123 "Return to `org-read-date' with the date currently selected.
6124 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
6125 (interactive "e")
6126 (mouse-set-point ev)
6127 (when (calendar-cursor-to-date)
6128 (let* ((date (calendar-cursor-to-date))
6129 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
6130 (setq ans1 (format-time-string "%Y-%m-%d" time)))
6131 (if (active-minibuffer-window) (exit-minibuffer))))
6133 (defun org-check-deadlines (ndays)
6134 "Check if there are any deadlines due or past due.
6135 A deadline is considered due if it happens within `org-deadline-warning-days'
6136 days from today's date. If the deadline appears in an entry marked DONE,
6137 it is not shown. The prefix arg NDAYS can be used to test that many
6138 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
6139 (interactive "P")
6140 (let* ((org-warn-days
6141 (cond
6142 ((equal ndays '(4)) 100000)
6143 (ndays (prefix-numeric-value ndays))
6144 (t org-deadline-warning-days)))
6145 (case-fold-search nil)
6146 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
6147 (callback
6148 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
6150 (message "%d deadlines past-due or due within %d days"
6151 (org-occur regexp nil callback)
6152 org-warn-days)))
6154 (defun org-evaluate-time-range (&optional to-buffer)
6155 "Evaluate a time range by computing the difference between start and end.
6156 Normally the result is just printed in the echo area, but with prefix arg
6157 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
6158 If the time range is actually in a table, the result is inserted into the
6159 next column.
6160 For time difference computation, a year is assumed to be exactly 365
6161 days in order to avoid rounding problems."
6162 (interactive "P")
6164 (org-clock-update-time-maybe)
6165 (save-excursion
6166 (unless (org-at-date-range-p)
6167 (goto-char (point-at-bol))
6168 (re-search-forward org-tr-regexp (point-at-eol) t))
6169 (if (not (org-at-date-range-p))
6170 (error "Not at a time-stamp range, and none found in current line")))
6171 (let* ((ts1 (match-string 1))
6172 (ts2 (match-string 2))
6173 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
6174 (match-end (match-end 0))
6175 (time1 (org-time-string-to-time ts1))
6176 (time2 (org-time-string-to-time ts2))
6177 (t1 (time-to-seconds time1))
6178 (t2 (time-to-seconds time2))
6179 (diff (abs (- t2 t1)))
6180 (negative (< (- t2 t1) 0))
6181 ;; (ys (floor (* 365 24 60 60)))
6182 (ds (* 24 60 60))
6183 (hs (* 60 60))
6184 (fy "%dy %dd %02d:%02d")
6185 (fy1 "%dy %dd")
6186 (fd "%dd %02d:%02d")
6187 (fd1 "%dd")
6188 (fh "%02d:%02d")
6189 y d h m align)
6190 (if havetime
6191 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
6193 d (floor (/ diff ds)) diff (mod diff ds)
6194 h (floor (/ diff hs)) diff (mod diff hs)
6195 m (floor (/ diff 60)))
6196 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
6198 d (floor (+ (/ diff ds) 0.5))
6199 h 0 m 0))
6200 (if (not to-buffer)
6201 (message (org-make-tdiff-string y d h m))
6202 (when (org-at-table-p)
6203 (goto-char match-end)
6204 (setq align t)
6205 (and (looking-at " *|") (goto-char (match-end 0))))
6206 (if (looking-at
6207 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
6208 (replace-match ""))
6209 (if negative (insert " -"))
6210 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
6211 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
6212 (insert " " (format fh h m))))
6213 (if align (org-table-align))
6214 (message "Time difference inserted")))))
6216 (defun org-make-tdiff-string (y d h m)
6217 (let ((fmt "")
6218 (l nil))
6219 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
6220 l (push y l)))
6221 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
6222 l (push d l)))
6223 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
6224 l (push h l)))
6225 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
6226 l (push m l)))
6227 (apply 'format fmt (nreverse l))))
6229 (defun org-time-string-to-time (s)
6230 (apply 'encode-time (org-parse-time-string s)))
6232 (defun org-parse-time-string (s &optional nodefault)
6233 "Parse the standard Org-mode time string.
6234 This should be a lot faster than the normal `parse-time-string'.
6235 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
6236 hour and minute fields will be nil if not given."
6237 (if (string-match org-ts-regexp1 s)
6238 (list 0
6239 (if (or (match-beginning 8) (not nodefault))
6240 (string-to-number (or (match-string 8 s) "0")))
6241 (if (or (match-beginning 7) (not nodefault))
6242 (string-to-number (or (match-string 7 s) "0")))
6243 (string-to-number (match-string 4 s))
6244 (string-to-number (match-string 3 s))
6245 (string-to-number (match-string 2 s))
6246 nil nil nil)
6247 (make-list 9 0)))
6249 (defun org-timestamp-up (&optional arg)
6250 "Increase the date item at the cursor by one.
6251 If the cursor is on the year, change the year. If it is on the month or
6252 the day, change that.
6253 With prefix ARG, change by that many units."
6254 (interactive "p")
6255 (org-timestamp-change (prefix-numeric-value arg)))
6257 (defun org-timestamp-down (&optional arg)
6258 "Decrease the date item at the cursor by one.
6259 If the cursor is on the year, change the year. If it is on the month or
6260 the day, change that.
6261 With prefix ARG, change by that many units."
6262 (interactive "p")
6263 (org-timestamp-change (- (prefix-numeric-value arg))))
6265 (defun org-timestamp-up-day (&optional arg)
6266 "Increase the date in the time stamp by one day.
6267 With prefix ARG, change that many days."
6268 (interactive "p")
6269 (if (and (not (org-at-timestamp-p t))
6270 (org-on-heading-p))
6271 (org-todo 'up)
6272 (org-timestamp-change (prefix-numeric-value arg) 'day)))
6274 (defun org-timestamp-down-day (&optional arg)
6275 "Decrease the date in the time stamp by one day.
6276 With prefix ARG, change that many days."
6277 (interactive "p")
6278 (if (and (not (org-at-timestamp-p t))
6279 (org-on-heading-p))
6280 (org-todo 'down)
6281 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
6283 (defsubst org-pos-in-match-range (pos n)
6284 (and (match-beginning n)
6285 (<= (match-beginning n) pos)
6286 (>= (match-end n) pos)))
6288 (defun org-at-timestamp-p (&optional also-inactive)
6289 "Determine if the cursor is in or at a timestamp."
6290 (interactive)
6291 (let* ((tsr (if also-inactive org-ts-regexp3 org-ts-regexp2))
6292 (pos (point))
6293 (ans (or (looking-at tsr)
6294 (save-excursion
6295 (skip-chars-backward "^[<\n\r\t")
6296 (if (> (point) 1) (backward-char 1))
6297 (and (looking-at tsr)
6298 (> (- (match-end 0) pos) -1))))))
6299 (and (boundp 'org-ts-what)
6300 (setq org-ts-what
6301 (cond
6302 ((org-pos-in-match-range pos 2) 'year)
6303 ((org-pos-in-match-range pos 3) 'month)
6304 ((org-pos-in-match-range pos 7) 'hour)
6305 ((org-pos-in-match-range pos 8) 'minute)
6306 ((or (org-pos-in-match-range pos 4)
6307 (org-pos-in-match-range pos 5)) 'day)
6308 (t 'day))))
6309 ans))
6311 (defun org-timestamp-change (n &optional what)
6312 "Change the date in the time stamp at point.
6313 The date will be changed by N times WHAT. WHAT can be `day', `month',
6314 `year', `minute', `second'. If WHAT is not given, the cursor position
6315 in the timestamp determines what will be changed."
6316 (let ((pos (point))
6317 with-hm inactive
6318 org-ts-what
6319 ts time time0)
6320 (if (not (org-at-timestamp-p t))
6321 (error "Not at a timestamp"))
6322 (if (and (not what) (not (eq org-ts-what 'day))
6323 org-display-custom-times
6324 (get-text-property (point) 'display)
6325 (not (get-text-property (1- (point)) 'display)))
6326 (setq org-ts-what 'day))
6327 (setq org-ts-what (or what org-ts-what)
6328 with-hm (<= (abs (- (cdr org-ts-lengths)
6329 (- (match-end 0) (match-beginning 0))))
6331 inactive (= (char-after (match-beginning 0)) ?\[)
6332 ts (match-string 0))
6333 (replace-match "")
6334 (setq time0 (org-parse-time-string ts))
6335 (setq time
6336 (apply 'encode-time
6337 (append
6338 (list (or (car time0) 0))
6339 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
6340 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
6341 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
6342 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
6343 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
6344 (nthcdr 6 time0))))
6345 (if (eq what 'calendar)
6346 (let ((cal-date
6347 (save-excursion
6348 (save-match-data
6349 (set-buffer "*Calendar*")
6350 (calendar-cursor-to-date)))))
6351 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
6352 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
6353 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
6354 (setcar time0 (or (car time0) 0))
6355 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
6356 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
6357 (setq time (apply 'encode-time time0))))
6358 (org-insert-time-stamp time with-hm inactive)
6359 (org-clock-update-time-maybe)
6360 (goto-char pos)
6361 ;; Try to recenter the calendar window, if any
6362 (if (and org-calendar-follow-timestamp-change
6363 (get-buffer-window "*Calendar*" t)
6364 (memq org-ts-what '(day month year)))
6365 (org-recenter-calendar (time-to-days time)))))
6367 (defun org-recenter-calendar (date)
6368 "If the calendar is visible, recenter it to DATE."
6369 (let* ((win (selected-window))
6370 (cwin (get-buffer-window "*Calendar*" t))
6371 (calendar-move-hook nil))
6372 (when cwin
6373 (select-window cwin)
6374 (calendar-goto-date (if (listp date) date
6375 (calendar-gregorian-from-absolute date)))
6376 (select-window win))))
6378 (defun org-goto-calendar (&optional arg)
6379 "Go to the Emacs calendar at the current date.
6380 If there is a time stamp in the current line, go to that date.
6381 A prefix ARG can be used to force the current date."
6382 (interactive "P")
6383 (let ((tsr org-ts-regexp) diff
6384 (calendar-move-hook nil)
6385 (view-calendar-holidays-initially nil)
6386 (view-diary-entries-initially nil))
6387 (if (or (org-at-timestamp-p)
6388 (save-excursion
6389 (beginning-of-line 1)
6390 (looking-at (concat ".*" tsr))))
6391 (let ((d1 (time-to-days (current-time)))
6392 (d2 (time-to-days
6393 (org-time-string-to-time (match-string 1)))))
6394 (setq diff (- d2 d1))))
6395 (calendar)
6396 (calendar-goto-today)
6397 (if (and diff (not arg)) (calendar-forward-day diff))))
6399 (defun org-date-from-calendar ()
6400 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
6401 If there is already a time stamp at the cursor position, update it."
6402 (interactive)
6403 (org-timestamp-change 0 'calendar))
6405 ;;; The clock for measuring work time.
6407 (defvar org-clock-marker (make-marker)
6408 "Marker recording the last clock-in.")
6410 (defun org-clock-in ()
6411 "Start the clock on the current item.
6412 If necessary, clock-out of the currently active clock."
6413 (interactive)
6414 (org-clock-out t)
6415 (let (ts)
6416 (save-excursion
6417 (org-back-to-heading t)
6418 (beginning-of-line 2)
6419 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6420 (not (equal (match-string 1) org-clock-string)))
6421 (beginning-of-line 1))
6422 (insert "\n") (backward-char 1)
6423 (indent-relative)
6424 (insert org-clock-string " ")
6425 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
6426 (move-marker org-clock-marker (point))
6427 (message "Clock started at %s" ts))))
6429 (defun org-clock-out (&optional fail-quietly)
6430 "Stop the currently running clock.
6431 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
6432 (interactive)
6433 (catch 'exit
6434 (if (not (marker-buffer org-clock-marker))
6435 (if fail-quietly (throw 'exit t) (error "No active clock")))
6436 (let (ts te s h m)
6437 (save-excursion
6438 (set-buffer (marker-buffer org-clock-marker))
6439 (goto-char org-clock-marker)
6440 (beginning-of-line 1)
6441 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6442 (equal (match-string 1) org-clock-string))
6443 (setq ts (match-string 2))
6444 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
6445 (goto-char org-clock-marker)
6446 (insert "--")
6447 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
6448 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
6449 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
6450 h (floor (/ s 3600))
6451 s (- s (* 3600 h))
6452 m (floor (/ s 60))
6453 s (- s (* 60 s)))
6454 (insert " => " (format "%2d:%02d" h m))
6455 (move-marker org-clock-marker nil)
6456 (org-add-log-maybe 'clock-out)
6457 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
6459 (defun org-clock-cancel ()
6460 "Cancel the running clock be removing the start timestamp."
6461 (interactive)
6462 (if (not (marker-buffer org-clock-marker))
6463 (error "No active clock"))
6464 (save-excursion
6465 (set-buffer (marker-buffer org-clock-marker))
6466 (goto-char org-clock-marker)
6467 (delete-region (1- (point-at-bol)) (point-at-eol)))
6468 (message "Clock canceled"))
6470 (defvar org-clock-file-total-minutes nil
6471 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
6472 (make-variable-buffer-local 'org-clock-file-total-minutes)
6474 (defun org-clock-sum (&optional tstart tend)
6475 "Sum the times for each subtree.
6476 Puts the resulting times in minutes as a text property on each headline."
6477 (interactive)
6478 (let* ((bmp (buffer-modified-p))
6479 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
6480 org-clock-string
6481 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
6482 (lmax 30)
6483 (ltimes (make-vector lmax 0))
6484 (t1 0)
6485 (level 0)
6486 ts te dt
6487 time)
6488 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
6489 (save-excursion
6490 (goto-char (point-max))
6491 (while (re-search-backward re nil t)
6492 (if (match-end 2)
6493 ;; A time
6494 (setq ts (match-string 2)
6495 te (match-string 3)
6496 ts (time-to-seconds
6497 (apply 'encode-time (org-parse-time-string ts)))
6498 te (time-to-seconds
6499 (apply 'encode-time (org-parse-time-string te)))
6500 ts (if tstart (max ts tstart) ts)
6501 te (if tend (min te tend) te)
6502 dt (- te ts)
6503 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
6504 ;; A headline
6505 (setq level (- (match-end 1) (match-beginning 1)))
6506 (when (or (> t1 0) (> (aref ltimes level) 0))
6507 (loop for l from 0 to level do
6508 (aset ltimes l (+ (aref ltimes l) t1)))
6509 (setq t1 0 time (aref ltimes level))
6510 (loop for l from level to (1- lmax) do
6511 (aset ltimes l 0))
6512 (goto-char (match-beginning 0))
6513 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
6514 (setq org-clock-file-total-minutes (aref ltimes 0)))
6515 (set-buffer-modified-p bmp)))
6517 (defun org-clock-display (&optional total-only)
6518 "Show subtree times in the entire buffer.
6519 If TOTAL-ONLY is non-nil, only show the total time for the entire file
6520 in the echo area."
6521 (interactive)
6522 (org-remove-clock-overlays)
6523 (let (time h m p)
6524 (org-clock-sum)
6525 (unless total-only
6526 (save-excursion
6527 (goto-char (point-min))
6528 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6529 (goto-char p)
6530 (when (setq time (get-text-property p :org-clock-minutes))
6531 (org-put-clock-overlay time (funcall outline-level))))
6532 (setq h (/ org-clock-file-total-minutes 60)
6533 m (- org-clock-file-total-minutes (* 60 h)))
6534 ;; Arrange to remove the overlays upon next change.
6535 (when org-remove-highlights-with-change
6536 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
6537 nil 'local))))
6538 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
6540 (defvar org-clock-overlays nil)
6541 (make-variable-buffer-local 'org-clock-overlays)
6543 (defun org-put-clock-overlay (time &optional level)
6544 "Put an overlays on the current line, displaying TIME.
6545 If LEVEL is given, prefix time with a corresponding number of stars.
6546 This creates a new overlay and stores it in `org-clock-overlays', so that it
6547 will be easy to remove."
6548 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
6549 (l (if level (org-get-legal-level level 0) 0))
6550 (off 0)
6551 ov tx)
6552 (move-to-column c)
6553 (unless (eolp) (skip-chars-backward "^ \t"))
6554 (skip-chars-backward " \t")
6555 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6556 tx (concat (buffer-substring (1- (point)) (point))
6557 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6558 (org-add-props (format "%s %2d:%02d%s"
6559 (make-string l ?*) h m
6560 (make-string (- 10 l) ?\ ))
6561 '(face secondary-selection))
6562 ""))
6563 (if (not (featurep 'xemacs))
6564 (org-overlay-put ov 'display tx)
6565 (org-overlay-put ov 'invisible t)
6566 (org-overlay-put ov 'end-glyph (make-glyph tx)))
6567 (push ov org-clock-overlays)))
6569 (defun org-remove-clock-overlays (&optional beg end noremove)
6570 "Remove the occur highlights from the buffer.
6571 BEG and END are ignored. If NOREMOVE is nil, remove this function
6572 from the `before-change-functions' in the current buffer."
6573 (interactive)
6574 (unless org-inhibit-highlight-removal
6575 (mapc 'org-delete-overlay org-clock-overlays)
6576 (setq org-clock-overlays nil)
6577 (unless noremove
6578 (remove-hook 'before-change-functions
6579 'org-remove-clock-overlays 'local))))
6581 (defun org-clock-out-if-current ()
6582 "Clock out if the current entry contains the running clock.
6583 This is used to stop the clock after a TODO entry is marked DONE."
6584 (when (and (equal state org-done-string)
6585 (equal (marker-buffer org-clock-marker) (current-buffer))
6586 (< (point) org-clock-marker)
6587 (> (save-excursion (outline-next-heading) (point))
6588 org-clock-marker))
6589 ;; Clock out, but don't accept a logging message for this.
6590 (let ((org-log-done (if (and (listp org-log-done)
6591 (member 'clock-out org-log-done))
6592 '(done)
6593 org-log-done)))
6594 (org-clock-out))))
6596 (add-hook 'org-after-todo-state-change-hook
6597 'org-clock-out-if-current)
6599 (defun org-check-running-clock ()
6600 "Check if the current buffer contains the running clock.
6601 If yes, offer to stop it and to save the buffer with the changes."
6602 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6603 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6604 (buffer-name))))
6605 (org-clock-out)
6606 (when (y-or-n-p "Save changed buffer?")
6607 (save-buffer))))
6609 (defun org-clock-report ()
6610 "Create a table containing a report about clocked time.
6611 If the buffer contains lines
6612 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6614 #+END: clocktable
6615 then the table will be inserted between these lines, replacing whatever
6616 is was there before. If these lines are not in the buffer, the table
6617 is inserted at point, surrounded by the special lines.
6618 The BEGIN line can contain parameters. Allowed are:
6619 :maxlevel The maximum level to be included in the table. Default is 3.
6620 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6621 (interactive)
6622 (org-remove-clock-overlays)
6623 (unless (org-find-dblock "clocktable")
6624 (org-create-dblock (list :name "clocktable"
6625 :maxlevel 2 :emphasize nil)))
6626 (org-update-dblock))
6628 (defun org-clock-update-time-maybe ()
6629 "If this is a CLOCK line, update it and return t.
6630 Otherwise, return nil."
6631 (interactive)
6632 (save-excursion
6633 (beginning-of-line 1)
6634 (skip-chars-forward " \t")
6635 (when (looking-at org-clock-string)
6636 (let ((re (concat "[ \t]*" org-clock-string
6637 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
6638 "\\([ \t]*=>.*\\)?"))
6639 ts te h m s)
6640 (if (not (looking-at re))
6642 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
6643 (end-of-line 1)
6644 (setq ts (match-string 1)
6645 te (match-string 2))
6646 (setq s (- (time-to-seconds
6647 (apply 'encode-time (org-parse-time-string te)))
6648 (time-to-seconds
6649 (apply 'encode-time (org-parse-time-string ts))))
6650 h (floor (/ s 3600))
6651 s (- s (* 3600 h))
6652 m (floor (/ s 60))
6653 s (- s (* 60 s)))
6654 (insert " => " (format "%2d:%02d" h m))
6655 t)))))
6657 (defun org-clock-special-range (key &optional time as-strings)
6658 "Return two times bordering a special time range.
6659 Key is a symbol specifying the range and can be one of `today', `yesterday',
6660 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
6661 A week starts Monday 0:00 and ends Sunday 24:00.
6662 The range is determined relative to TIME. TIME defaults to the current time.
6663 The return value is a cons cell with two internal times like the ones
6664 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
6665 the returned times will be formatted strings."
6666 (let* ((tm (decode-time (or time (current-time))))
6667 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
6668 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
6669 (dow (nth 6 tm))
6670 s1 m1 h1 d1 month1 y1 diff ts te fm)
6671 (cond
6672 ((eq key 'today)
6673 (setq h 0 m 0 h1 24 m1 0))
6674 ((eq key 'yesterday)
6675 (setq d (1- d) h 0 m 0 h1 24 m1 0))
6676 ((eq key 'thisweek)
6677 (setq diff (if (= dow 0) 6 (1- dow))
6678 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6679 ((eq key 'lastweek)
6680 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
6681 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6682 ((eq key 'thismonth)
6683 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
6684 ((eq key 'lastmonth)
6685 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
6686 ((eq key 'thisyear)
6687 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
6688 ((eq key 'lastyear)
6689 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
6690 (t (error "No such time block %s" key)))
6691 (setq ts (encode-time s m h d month y)
6692 te (encode-time (or s1 s) (or m1 m) (or h1 h)
6693 (or d1 d) (or month1 month) (or y1 y)))
6694 (setq fm (cdr org-time-stamp-formats))
6695 (if as-strings
6696 (cons (format-time-string fm ts) (format-time-string fm te))
6697 (cons ts te))))
6699 (defun org-dblock-write:clocktable (params)
6700 "Write the standard clocktable."
6701 (let ((hlchars '((1 . "*") (2 . ?/)))
6702 (emph nil)
6703 (ins (make-marker))
6704 ipos time h m p level hlc hdl maxlevel
6705 ts te cc block)
6706 (setq maxlevel (or (plist-get params :maxlevel) 3)
6707 emph (plist-get params :emphasize)
6708 ts (plist-get params :tstart)
6709 te (plist-get params :tend)
6710 block (plist-get params :block))
6711 (when block
6712 (setq cc (org-clock-special-range block nil t)
6713 ts (car cc) te (cdr cc)))
6714 (if ts (setq ts (time-to-seconds
6715 (apply 'encode-time (org-parse-time-string ts)))))
6716 (if te (setq te (time-to-seconds
6717 (apply 'encode-time (org-parse-time-string te)))))
6718 (move-marker ins (point))
6719 (setq ipos (point))
6720 ;; FIXME: does not yet use org-insert-time-stamp or custom format
6721 (insert-before-markers "Clock summary at ["
6722 (substring
6723 (format-time-string (cdr org-time-stamp-formats))
6724 1 -1)
6725 "]."
6726 (if block
6727 (format " Considered range is /%s/." block)
6729 "\n\n|L|Headline|Time|\n")
6730 (org-clock-sum ts te)
6731 (setq h (/ org-clock-file-total-minutes 60)
6732 m (- org-clock-file-total-minutes (* 60 h)))
6733 (insert-before-markers "|-\n|0|" "*Total file time*| "
6734 (format "*%d:%02d*" h m)
6735 "|\n")
6736 (goto-char (point-min))
6737 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6738 (goto-char p)
6739 (when (setq time (get-text-property p :org-clock-minutes))
6740 (save-excursion
6741 (beginning-of-line 1)
6742 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6743 (setq level (- (match-end 1) (match-beginning 1)))
6744 (<= level maxlevel))
6745 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6746 hdl (match-string 2)
6747 h (/ time 60)
6748 m (- time (* 60 h)))
6749 (goto-char ins)
6750 (if (= level 1) (insert-before-markers "|-\n"))
6751 (insert-before-markers
6752 "| " (int-to-string level) "|" hlc hdl hlc " |"
6753 (make-string (1- level) ?|)
6755 (format "%d:%02d" h m)
6757 " |\n")))))
6758 (goto-char ins)
6759 (backward-delete-char 1)
6760 (goto-char ipos)
6761 (skip-chars-forward "^|")
6762 (org-table-align)))
6764 (defun org-collect-clock-time-entries ()
6765 "Return an internal list with clocking information.
6766 This list has one entry for each CLOCK interval.
6767 FIXME: describe the elements."
6768 (interactive)
6769 (let ((re (concat "^[ \t]*" org-clock-string
6770 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6771 rtn beg end next cont level title total closedp leafp
6772 clockpos titlepos h m donep)
6773 (save-excursion
6774 (org-clock-sum)
6775 (goto-char (point-min))
6776 (while (re-search-forward re nil t)
6777 (setq clockpos (match-beginning 0)
6778 beg (match-string 1) end (match-string 2)
6779 cont (match-end 0))
6780 (setq beg (apply 'encode-time (org-parse-time-string beg))
6781 end (apply 'encode-time (org-parse-time-string end)))
6782 (org-back-to-heading t)
6783 (setq donep (org-entry-is-done-p))
6784 (setq titlepos (point)
6785 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6786 h (/ total 60) m (- total (* 60 h))
6787 total (cons h m))
6788 (looking-at "\\(\\*+\\) +\\(.*\\)")
6789 (setq level (- (match-end 1) (match-beginning 1))
6790 title (org-match-string-no-properties 2))
6791 (save-excursion (outline-next-heading) (setq next (point)))
6792 (setq closedp (re-search-forward org-closed-time-regexp next t))
6793 (goto-char next)
6794 (setq leafp (and (looking-at "^\\*+ ")
6795 (<= (- (match-end 0) (point)) level)))
6796 (push (list beg end clockpos closedp donep
6797 total title titlepos level leafp)
6798 rtn)
6799 (goto-char cont)))
6800 (nreverse rtn)))
6802 ;;; Agenda, and Diary Integration
6804 ;;; Define the mode
6806 (defvar org-agenda-mode-map (make-sparse-keymap)
6807 "Keymap for `org-agenda-mode'.")
6809 (defvar org-agenda-menu) ; defined later in this file.
6810 (defvar org-agenda-follow-mode nil)
6811 (defvar org-agenda-show-log nil)
6812 (defvar org-agenda-redo-command nil)
6813 (defvar org-agenda-mode-hook nil)
6814 (defvar org-agenda-type nil)
6815 (defvar org-agenda-force-single-file nil)
6817 (defun org-agenda-mode ()
6818 "Mode for time-sorted view on action items in Org-mode files.
6820 The following commands are available:
6822 \\{org-agenda-mode-map}"
6823 (interactive)
6824 (kill-all-local-variables)
6825 (setq major-mode 'org-agenda-mode)
6826 (setq mode-name "Org-Agenda")
6827 (use-local-map org-agenda-mode-map)
6828 (easy-menu-add org-agenda-menu)
6829 (if org-startup-truncated (setq truncate-lines t))
6830 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6831 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6832 (unless org-agenda-keep-modes
6833 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6834 org-agenda-show-log nil))
6835 (easy-menu-change
6836 '("Agenda") "Agenda Files"
6837 (append
6838 (list
6839 (vector
6840 (if (get 'org-agenda-files 'org-restrict)
6841 "Restricted to single file"
6842 "Edit File List")
6843 '(org-edit-agenda-file-list)
6844 (not (get 'org-agenda-files 'org-restrict)))
6845 "--")
6846 (mapcar 'org-file-menu-entry (org-agenda-files))))
6847 (org-agenda-set-mode-name)
6848 (apply
6849 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6850 (list 'org-agenda-mode-hook)))
6852 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6853 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6854 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6855 (define-key org-agenda-mode-map " " 'org-agenda-show)
6856 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6857 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6858 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6859 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6860 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6861 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6862 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6863 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6864 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6865 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6866 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6867 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6868 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6870 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6871 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6872 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6873 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6874 (while l (define-key org-agenda-mode-map
6875 (int-to-string (pop l)) 'digit-argument)))
6877 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6878 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6879 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6880 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6881 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6882 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6883 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6884 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
6885 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6886 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6887 (define-key org-agenda-mode-map "n" 'next-line)
6888 (define-key org-agenda-mode-map "p" 'previous-line)
6889 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6890 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6891 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6892 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6893 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6894 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6895 (eval-after-load "calendar"
6896 '(define-key calendar-mode-map org-calendar-to-agenda-key
6897 'org-calendar-goto-agenda))
6898 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6899 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6900 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6901 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6902 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6903 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6904 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6905 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6906 (define-key org-agenda-mode-map "O" 'org-clock-out)
6907 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6908 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6909 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6910 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6911 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6912 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6913 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6914 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6915 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6916 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6917 "Local keymap for agenda entries from Org-mode.")
6919 (define-key org-agenda-keymap
6920 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6921 (define-key org-agenda-keymap
6922 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6923 (when org-agenda-mouse-1-follows-link
6924 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6925 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6926 '("Agenda"
6927 ("Agenda Files")
6928 "--"
6929 ["Show" org-agenda-show t]
6930 ["Go To (other window)" org-agenda-goto t]
6931 ["Go To (this window)" org-agenda-switch-to t]
6932 ["Follow Mode" org-agenda-follow-mode
6933 :style toggle :selected org-agenda-follow-mode :active t]
6934 "--"
6935 ["Cycle TODO" org-agenda-todo t]
6936 ("Tags"
6937 ["Show all Tags" org-agenda-show-tags t]
6938 ["Set Tags" org-agenda-set-tags t])
6939 ("Schedule"
6940 ["Schedule" org-agenda-schedule t]
6941 ["Set Deadline" org-agenda-deadline t]
6942 "--"
6943 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6944 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6945 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6946 ("Priority"
6947 ["Set Priority" org-agenda-priority t]
6948 ["Increase Priority" org-agenda-priority-up t]
6949 ["Decrease Priority" org-agenda-priority-down t]
6950 ["Show Priority" org-agenda-show-priority t])
6951 "--"
6952 ;; ["New agenda command" org-agenda t]
6953 ["Rebuild buffer" org-agenda-redo t]
6954 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
6955 "--"
6956 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6957 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6958 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6959 "--"
6960 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6961 :style radio :selected (equal org-agenda-ndays 1)]
6962 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6963 :style radio :selected (equal org-agenda-ndays 7)]
6964 "--"
6965 ["Show Logbook entries" org-agenda-log-mode
6966 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6967 ["Include Diary" org-agenda-toggle-diary
6968 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6969 ["Use Time Grid" org-agenda-toggle-time-grid
6970 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6971 "--"
6972 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6973 ("Calendar Commands"
6974 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6975 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6976 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6977 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6978 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6979 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6980 "--"
6981 ["Quit" org-agenda-quit t]
6982 ["Exit and Release Buffers" org-agenda-exit t]
6985 (defvar org-agenda-restrict nil)
6986 (defvar org-agenda-restrict-begin (make-marker))
6987 (defvar org-agenda-restrict-end (make-marker))
6988 (defvar org-agenda-last-dispatch-buffer nil)
6990 ;;;###autoload
6991 (defun org-agenda (arg)
6992 "Dispatch agenda commands to collect entries to the agenda buffer.
6993 Prompts for a character to select a command. Any prefix arg will be passed
6994 on to the selected command. The default selections are:
6996 a Call `org-agenda-list' to display the agenda for current day or week.
6997 t Call `org-todo-list' to display the global todo list.
6998 T Call `org-todo-list' to display the global todo list, select only
6999 entries with a specific TODO keyword (the user gets a prompt).
7000 m Call `org-tags-view' to display headlines with tags matching
7001 a condition (the user is prompted for the condition).
7002 M Like `m', but select only TODO entries, no ordinary headlines.
7003 l Create a timeeline for the current buffer.
7005 More commands can be added by configuring the variable
7006 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
7007 searches can be pre-defined in this way.
7009 If the current buffer is in Org-mode and visiting a file, you can also
7010 first press `1' to indicate that the agenda should be temporarily (until the
7011 next use of \\[org-agenda]) restricted to the current file."
7012 (interactive "P")
7013 (catch 'exit
7014 (let* ((buf (current-buffer))
7015 (bfn (buffer-file-name (buffer-base-buffer)))
7016 (restrict-ok (and bfn (org-mode-p)))
7017 (custom org-agenda-custom-commands)
7018 c entry key type match lprops)
7019 ;; Turn off restriction
7020 (put 'org-agenda-files 'org-restrict nil)
7021 (setq org-agenda-restrict nil)
7022 (move-marker org-agenda-restrict-begin nil)
7023 (move-marker org-agenda-restrict-end nil)
7024 ;; Remember where this call originated
7025 (setq org-agenda-last-dispatch-buffer (current-buffer))
7026 (save-window-excursion
7027 (delete-other-windows)
7028 (switch-to-buffer-other-window " *Agenda Commands*")
7029 (erase-buffer)
7030 (insert
7031 "Press key for an agenda command:
7032 --------------------------------
7033 a Agenda for current week or day
7034 t List of all TODO entries T Entries with special TODO kwd
7035 m Match a TAGS query M Like m, but only TODO entries
7036 L Timeline for current buffer C Configure custom agenda commands")
7037 (while (setq entry (pop custom))
7038 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
7039 (insert (format "\n%-4s%-14s: %s"
7041 (cond
7042 ((stringp type) type)
7043 ((eq type 'tags) "Tags query")
7044 ((eq type 'todo) "TODO keyword")
7045 ((eq type 'tags-tree) "Tags tree")
7046 ((eq type 'todo-tree) "TODO kwd tree")
7047 ((eq type 'occur-tree) "Occur tree")
7048 (t "???"))
7049 (if (stringp match)
7050 (org-add-props match nil 'face 'org-warning)
7051 (format "set of %d commands" (+ -2 (length entry)))))))
7052 (if restrict-ok
7053 (insert "\n"
7054 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
7056 (goto-char (point-min))
7057 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
7058 (message "Press key for agenda command%s"
7059 (if restrict-ok ", or [1] or [0] to restrict" ""))
7060 (setq c (read-char-exclusive))
7061 (message "")
7062 (when (memq c '(?L ?1 ?0))
7063 (if restrict-ok
7064 (put 'org-agenda-files 'org-restrict (list bfn))
7065 (error "Cannot restrict agenda to current buffer"))
7066 (with-current-buffer " *Agenda Commands*"
7067 (goto-char (point-max))
7068 (delete-region (point-at-bol) (point))
7069 (goto-char (point-min)))
7070 (when (eq c ?0)
7071 (setq org-agenda-restrict t)
7072 (with-current-buffer buf
7073 (if (org-region-active-p)
7074 (progn
7075 (move-marker org-agenda-restrict-begin (region-beginning))
7076 (move-marker org-agenda-restrict-end (region-end)))
7077 (save-excursion
7078 (org-back-to-heading t)
7079 (move-marker org-agenda-restrict-begin (point))
7080 (move-marker org-agenda-restrict-end
7081 (progn (org-end-of-subtree t)))))))
7082 (unless (eq c ?L)
7083 (message "Press key for agenda command%s"
7084 (if restrict-ok " (restricted to current file)" ""))
7085 (setq c (read-char-exclusive)))
7086 (message "")))
7087 (require 'calendar) ; FIXME: can we avoid this for some commands?
7088 ;; For example the todo list should not need it (but does...)
7089 (cond
7090 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
7091 ((equal c ?a) (call-interactively 'org-agenda-list))
7092 ((equal c ?t) (call-interactively 'org-todo-list))
7093 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
7094 ((equal c ?m) (call-interactively 'org-tags-view))
7095 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
7096 ((equal c ?L)
7097 (unless restrict-ok
7098 (error "This is not an Org-mode file"))
7099 (org-call-with-arg 'org-timeline arg))
7100 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
7101 (if (symbolp (nth 1 entry))
7102 (progn
7103 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
7104 lprops (nth 3 entry))
7105 (cond
7106 ((eq type 'tags)
7107 (org-let lprops '(org-tags-view current-prefix-arg match)))
7108 ((eq type 'tags-todo)
7109 (org-let lprops '(org-tags-view '(4) match)))
7110 ((eq type 'todo)
7111 (org-let lprops '(org-todo-list match)))
7112 ((eq type 'tags-tree)
7113 (org-check-for-org-mode)
7114 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
7115 ((eq type 'todo-tree)
7116 (org-check-for-org-mode)
7117 (org-let lprops
7118 '(org-occur (concat "^" outline-regexp "[ \t]*"
7119 (regexp-quote match) "\\>"))))
7120 ((eq type 'occur-tree)
7121 (org-check-for-org-mode)
7122 (org-let lprops '(org-occur match)))
7123 (t (error "Invalid custom agenda command type %s" type))))
7124 (org-run-agenda-series (cddr entry))))
7125 (t (error "Invalid key"))))))
7127 ;; FIXME: what is the meaning of WINDOW?????
7128 (defun org-run-agenda-series (series &optional window)
7129 (org-prepare-agenda)
7130 (let* ((org-agenda-multi t)
7131 (redo (list 'org-run-agenda-series (list 'quote series)))
7132 (org-select-agenda-window t)
7133 (cmds (car series))
7134 (gprops (nth 1 series))
7135 cmd type match lprops)
7136 (while (setq cmd (pop cmds))
7137 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
7138 (cond
7139 ((eq type 'agenda)
7140 (call-interactively 'org-agenda-list))
7141 ((eq type 'alltodo)
7142 (call-interactively 'org-todo-list))
7143 ((eq type 'tags)
7144 (org-let2 gprops lprops
7145 '(org-tags-view current-prefix-arg match)))
7146 ((eq type 'tags-todo)
7147 (org-let2 gprops lprops
7148 '(org-tags-view '(4) match)))
7149 ((eq type 'todo)
7150 (org-let2 gprops lprops
7151 '(org-todo-list match)))
7152 (t (error "Invalid type in command series"))))
7153 (widen)
7154 (setq org-agenda-redo-command redo)
7155 (goto-char (point-min)))
7156 (org-finalize-agenda))
7158 ;;;###autoload
7159 (defmacro org-batch-agenda (cmd-key &rest parameters)
7160 "Run an agenda command in batch mode, send result to STDOUT.
7161 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
7162 Paramters are alternating variable names and values that will be bound
7163 before running the agenda command."
7164 (let (pars)
7165 (while parameters
7166 (push (list (pop parameters) (if parameters (pop parameters))) pars))
7167 (flet ((read-char-exclusive () (string-to-char cmd-key)))
7168 (eval (list 'let (nreverse pars) '(org-agenda nil))))
7169 (set-buffer "*Org Agenda*")
7170 (princ (buffer-string))))
7172 (defmacro org-no-read-only (&rest body)
7173 "Inhibit read-only for BODY."
7174 `(let ((inhibit-read-only t)) ,@body))
7176 (defun org-check-for-org-mode ()
7177 "Make sure current buffer is in org-mode. Error if not."
7178 (or (org-mode-p)
7179 (error "Cannot execute org-mode agenda command on buffer in %s."
7180 major-mode)))
7182 (defun org-fit-agenda-window ()
7183 "Fit the window to the buffer size."
7184 (and org-fit-agenda-window
7185 (memq org-agenda-window-setup '(reorganize-frame))
7186 (fboundp 'fit-window-to-buffer)
7187 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
7188 (/ (frame-height) 2))))
7190 (defun org-agenda-files (&optional unrestricted)
7191 "Get the list of agenda files.
7192 Optional UNRESTRICTED means return the full list even if a restriction
7193 is currently in place."
7194 (cond
7195 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
7196 ((stringp org-agenda-files) (org-read-agenda-file-list))
7197 ((listp org-agenda-files) org-agenda-files)
7198 (t (error "Invalid value of `org-agenda-files'"))))
7200 (defvar org-window-configuration)
7202 (defun org-edit-agenda-file-list ()
7203 "Edit the list of agenda files.
7204 Depending on setup, this either uses customize to edit the variable
7205 `org-agenda-files', or it visits the file that is holding the list. In the
7206 latter case, the buffer is set up in a way that saving it automatically kills
7207 the buffer and restores the previous window configuration."
7208 (interactive)
7209 (if (stringp org-agenda-files)
7210 (let ((cw (current-window-configuration)))
7211 (find-file org-agenda-files)
7212 (org-set-local 'org-window-configuration cw)
7213 (org-add-hook 'after-save-hook
7214 (lambda ()
7215 (set-window-configuration
7216 (prog1 org-window-configuration
7217 (kill-buffer (current-buffer))))
7218 (org-install-agenda-files-menu)
7219 (message "New agenda file list installed"))
7220 nil 'local)
7221 (message (substitute-command-keys
7222 "Edit list and finish with \\[save-buffer]")))
7223 (customize-variable 'org-agenda-files)))
7225 (defun org-store-new-agenda-file-list (list)
7226 "Set new value for the agenda file list and save it correcly."
7227 (if (stringp org-agenda-files)
7228 (let ((f org-agenda-files) b)
7229 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
7230 (with-temp-file f
7231 (insert (mapconcat 'identity list "\n") "\n")))
7232 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
7233 (setq org-agenda-files list)
7234 (customize-save-variable 'org-agenda-files org-agenda-files))))
7236 (defun org-read-agenda-file-list ()
7237 "Read the list of agenda files from a file."
7238 (when (stringp org-agenda-files)
7239 (with-temp-buffer
7240 (insert-file-contents org-agenda-files)
7241 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
7243 (defvar org-agenda-markers nil
7244 "List of all currently active markers created by `org-agenda'.")
7245 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
7246 "Creation time of the last agenda marker.")
7248 (defun org-agenda-new-marker (&optional pos)
7249 "Return a new agenda marker.
7250 Org-mode keeps a list of these markers and resets them when they are
7251 no longer in use."
7252 (let ((m (copy-marker (or pos (point)))))
7253 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
7254 (push m org-agenda-markers)
7257 (defun org-agenda-maybe-reset-markers (&optional force)
7258 "Reset markers created by `org-agenda'. But only if they are old enough."
7259 (if (or (and force (not org-agenda-multi))
7260 (> (- (time-to-seconds (current-time))
7261 org-agenda-last-marker-time)
7263 (while org-agenda-markers
7264 (move-marker (pop org-agenda-markers) nil))))
7266 (defvar org-agenda-new-buffers nil
7267 "Buffers created to visit agenda files.")
7269 (defun org-get-agenda-file-buffer (file)
7270 "Get a buffer visiting FILE. If the buffer needs to be created, add
7271 it to the list of buffers which might be released later."
7272 (let ((buf (find-buffer-visiting file)))
7273 (if buf
7274 buf ; just return it
7275 ;; Make a new buffer and remember it
7276 (setq buf (find-file-noselect file))
7277 (if buf (push buf org-agenda-new-buffers))
7278 buf)))
7280 (defun org-release-buffers (blist)
7281 "Release all buffers in list, asking the user for confirmation when needed.
7282 When a buffer is unmodified, it is just killed. When modified, it is saved
7283 \(if the user agrees) and then killed."
7284 (let (buf file)
7285 (while (setq buf (pop blist))
7286 (setq file (buffer-file-name buf))
7287 (when (and (buffer-modified-p buf)
7288 file
7289 (y-or-n-p (format "Save file %s? " file)))
7290 (with-current-buffer buf (save-buffer)))
7291 (kill-buffer buf))))
7293 (defun org-timeline (&optional include-all)
7294 "Show a time-sorted view of the entries in the current org file.
7295 Only entries with a time stamp of today or later will be listed. With
7296 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
7297 under the current date.
7298 If the buffer contains an active region, only check the region for
7299 dates."
7300 (interactive "P")
7301 (require 'calendar)
7302 (org-compile-prefix-format 'timeline)
7303 (org-set-sorting-strategy 'timeline)
7304 (let* ((dopast t)
7305 (dotodo include-all)
7306 (doclosed org-agenda-show-log)
7307 (entry buffer-file-name)
7308 (date (calendar-current-date))
7309 (win (selected-window))
7310 (pos1 (point))
7311 (beg (if (org-region-active-p) (region-beginning) (point-min)))
7312 (end (if (org-region-active-p) (region-end) (point-max)))
7313 (day-numbers (org-get-all-dates beg end 'no-ranges
7314 t doclosed ; always include today
7315 org-timeline-show-empty-dates))
7316 (today (time-to-days (current-time)))
7317 (past t)
7318 args
7319 s e rtn d emptyp)
7320 (setq org-agenda-redo-command
7321 (list 'progn
7322 (list 'switch-to-buffer-other-window (current-buffer))
7323 (list 'org-timeline (list 'quote include-all))))
7324 (if (not dopast)
7325 ;; Remove past dates from the list of dates.
7326 (setq day-numbers (delq nil (mapcar (lambda(x)
7327 (if (>= x today) x nil))
7328 day-numbers))))
7329 (org-prepare-agenda)
7330 (if doclosed (push :closed args))
7331 (push :timestamp args)
7332 (if dotodo (push :todo args))
7333 (while (setq d (pop day-numbers))
7334 (if (and (listp d) (eq (car d) :omitted))
7335 (progn
7336 (setq s (point))
7337 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
7338 (put-text-property s (1- (point)) 'face 'org-level-3))
7339 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
7340 (if (and (>= d today)
7341 dopast
7342 past)
7343 (progn
7344 (setq past nil)
7345 (insert (make-string 79 ?-) "\n")))
7346 (setq date (calendar-gregorian-from-absolute d))
7347 (setq s (point))
7348 (setq rtn (and (not emptyp)
7349 (apply 'org-agenda-get-day-entries
7350 entry date args)))
7351 (if (or rtn (equal d today) org-timeline-show-empty-dates)
7352 (progn
7353 (insert (calendar-day-name date) " "
7354 (number-to-string (extract-calendar-day date)) " "
7355 (calendar-month-name (extract-calendar-month date)) " "
7356 (number-to-string (extract-calendar-year date)) "\n")
7357 (put-text-property s (1- (point)) 'face
7358 'org-level-3)
7359 (if (equal d today)
7360 (put-text-property s (1- (point)) 'org-today t))
7361 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
7362 (put-text-property s (1- (point)) 'day d)))))
7363 (goto-char (point-min))
7364 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
7365 (point-min)))
7366 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
7367 (org-finalize-agenda)
7368 (setq buffer-read-only t)
7369 (when (not org-select-agenda-window)
7370 (select-window win)
7371 (goto-char pos1))))
7373 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
7374 (defvar org-agenda-last-arguments nil
7375 "The arguments of the previous call to org-agenda")
7377 ;;;###autoload
7378 (defun org-agenda-list (&optional include-all start-day ndays)
7379 "Produce a weekly view from all files in variable `org-agenda-files'.
7380 The view will be for the current week, but from the overview buffer you
7381 will be able to go to other weeks.
7382 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
7383 also be shown, under the current date.
7384 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
7385 on the days are also shown. See the variable `org-log-done' for how
7386 to turn on logging.
7387 START-DAY defaults to TODAY, or to the most recent match for the weekday
7388 given in `org-agenda-start-on-weekday'.
7389 NDAYS defaults to `org-agenda-ndays'."
7390 (interactive "P")
7391 (if org-agenda-overriding-arguments
7392 (setq include-all (car org-agenda-overriding-arguments)
7393 start-day (nth 1 org-agenda-overriding-arguments)
7394 ndays (nth 2 org-agenda-overriding-arguments)))
7395 (setq org-agenda-last-arguments (list include-all start-day ndays))
7396 (org-compile-prefix-format 'agenda)
7397 (org-set-sorting-strategy 'agenda)
7398 (require 'calendar)
7399 (let* ((org-agenda-start-on-weekday
7400 (if (or (equal ndays 1)
7401 (and (null ndays) (equal 1 org-agenda-ndays)))
7402 nil org-agenda-start-on-weekday))
7403 (thefiles (org-agenda-files))
7404 (files thefiles)
7405 (win (selected-window))
7406 (today (time-to-days (current-time)))
7407 (sd (or start-day today))
7408 (start (if (or (null org-agenda-start-on-weekday)
7409 (< org-agenda-ndays 7))
7411 (let* ((nt (calendar-day-of-week
7412 (calendar-gregorian-from-absolute sd)))
7413 (n1 org-agenda-start-on-weekday)
7414 (d (- nt n1)))
7415 (- sd (+ (if (< d 0) 7 0) d)))))
7416 (day-numbers (list start))
7417 ;FIXME (inhibit-redisplay t)
7418 s e rtn rtnall file date d start-pos end-pos todayp nd)
7419 (setq org-agenda-redo-command
7420 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
7421 ;; Make the list of days
7422 (setq ndays (or ndays org-agenda-ndays)
7423 nd ndays)
7424 (while (> ndays 1)
7425 (push (1+ (car day-numbers)) day-numbers)
7426 (setq ndays (1- ndays)))
7427 (setq day-numbers (nreverse day-numbers))
7428 (org-prepare-agenda)
7429 (org-set-local 'starting-day (car day-numbers))
7430 (org-set-local 'include-all-loc include-all)
7431 (when (and (or include-all org-agenda-include-all-todo)
7432 (member today day-numbers))
7433 (setq files thefiles
7434 rtnall nil)
7435 (while (setq file (pop files))
7436 (catch 'nextfile
7437 (org-check-agenda-file file)
7438 (setq date (calendar-gregorian-from-absolute today)
7439 rtn (org-agenda-get-day-entries
7440 file date :todo))
7441 (setq rtnall (append rtnall rtn))))
7442 (when rtnall
7443 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
7444 (add-text-properties (point-min) (1- (point))
7445 (list 'face 'org-level-3))
7446 (insert (org-finalize-agenda-entries rtnall) "\n")))
7447 (setq s (point))
7448 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
7449 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
7450 (while (setq d (pop day-numbers))
7451 (setq date (calendar-gregorian-from-absolute d)
7452 s (point))
7453 (if (or (setq todayp (= d today))
7454 (and (not start-pos) (= d sd)))
7455 (setq start-pos (point))
7456 (if (and start-pos (not end-pos))
7457 (setq end-pos (point))))
7458 (setq files thefiles
7459 rtnall nil)
7460 (while (setq file (pop files))
7461 (catch 'nextfile
7462 (org-check-agenda-file file)
7463 (if org-agenda-show-log
7464 (setq rtn (org-agenda-get-day-entries
7465 file date
7466 :deadline :scheduled :timestamp :closed))
7467 (setq rtn (org-agenda-get-day-entries
7468 file date
7469 :deadline :scheduled :timestamp)))
7470 (setq rtnall (append rtnall rtn))))
7471 (if org-agenda-include-diary
7472 (progn
7473 (require 'diary-lib)
7474 (setq rtn (org-get-entries-from-diary date))
7475 (setq rtnall (append rtnall rtn))))
7476 (if (or rtnall org-agenda-show-all-dates)
7477 (progn
7478 (insert (format "%-9s %2d %s %4d\n"
7479 (calendar-day-name date)
7480 (extract-calendar-day date)
7481 (calendar-month-name (extract-calendar-month date))
7482 (extract-calendar-year date)))
7483 (put-text-property s (1- (point)) 'face
7484 'org-level-3)
7485 (if todayp (put-text-property s (1- (point)) 'org-today t))
7487 (if rtnall (insert
7488 (org-finalize-agenda-entries
7489 (org-agenda-add-time-grid-maybe
7490 rtnall nd todayp))
7491 "\n"))
7492 (put-text-property s (1- (point)) 'day d))))
7493 (goto-char (point-min))
7494 (org-fit-agenda-window)
7495 (unless (and (pos-visible-in-window-p (point-min))
7496 (pos-visible-in-window-p (point-max)))
7497 (goto-char (1- (point-max)))
7498 (recenter -1)
7499 (if (not (pos-visible-in-window-p (or start-pos 1)))
7500 (progn
7501 (goto-char (or start-pos 1))
7502 (recenter 1))))
7503 (goto-char (or start-pos 1))
7504 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
7505 (org-finalize-agenda)
7506 (setq buffer-read-only t)
7507 (if (not org-select-agenda-window) (select-window win))
7508 (message "")))
7510 (defvar org-select-this-todo-keyword nil)
7512 ;;;###autoload
7513 (defun org-todo-list (arg)
7514 "Show all TODO entries from all agenda file in a single list.
7515 The prefix arg can be used to select a specific TODO keyword and limit
7516 the list to these. When using \\[universal-argument], you will be prompted
7517 for a keyword. A numeric prefix directly selects the Nth keyword in
7518 `org-todo-keywords'."
7519 (interactive "P")
7520 (org-compile-prefix-format 'todo)
7521 (org-set-sorting-strategy 'todo)
7522 (let* ((today (time-to-days (current-time)))
7523 (date (calendar-gregorian-from-absolute today))
7524 (win (selected-window))
7525 (kwds org-todo-keywords)
7526 (completion-ignore-case t)
7527 (org-select-this-todo-keyword
7528 (if (stringp arg) arg
7529 (and arg (integerp arg) (> arg 0)
7530 (nth (1- arg) org-todo-keywords))))
7531 rtn rtnall files file pos)
7532 (when (equal arg '(4))
7533 (setq org-select-this-todo-keyword
7534 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
7535 nil t)))
7536 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
7537 (org-prepare-agenda)
7538 (org-set-local 'last-arg arg)
7539 (org-set-local 'org-todo-keywords kwds)
7540 (setq org-agenda-redo-command
7541 '(org-todo-list (or current-prefix-arg last-arg)))
7542 (setq files (org-agenda-files)
7543 rtnall nil)
7544 (while (setq file (pop files))
7545 (catch 'nextfile
7546 (org-check-agenda-file file)
7547 (setq rtn (org-agenda-get-day-entries file date :todo))
7548 (setq rtnall (append rtnall rtn))))
7549 (insert "Global list of TODO items of type: ")
7550 (add-text-properties (point-min) (1- (point))
7551 (list 'face 'org-level-3))
7552 (setq pos (point))
7553 (insert (or org-select-this-todo-keyword "ALL") "\n")
7554 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7555 (setq pos (point))
7556 (unless org-agenda-multi
7557 (insert
7558 "Available with `N r': (0)ALL "
7559 (let ((n 0))
7560 (mapconcat (lambda (x)
7561 (format "(%d)%s" (setq n (1+ n)) x))
7562 org-todo-keywords " "))
7563 "\n"))
7564 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7565 (when rtnall
7566 (insert (org-finalize-agenda-entries rtnall) "\n"))
7567 (goto-char (point-min))
7568 (org-fit-agenda-window)
7569 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
7570 (org-finalize-agenda)
7571 (setq buffer-read-only t)
7572 (if (not org-select-agenda-window) (select-window win))))
7574 (defun org-check-agenda-file (file)
7575 "Make sure FILE exists. If not, ask user what to do."
7576 (when (not (file-exists-p file))
7577 (message "non-existent file %s. [R]emove from list or [A]bort?"
7578 (abbreviate-file-name file))
7579 (let ((r (downcase (read-char-exclusive))))
7580 (cond
7581 ((equal r ?r)
7582 (org-remove-file file)
7583 (throw 'nextfile t))
7584 (t (error "Abort"))))))
7586 (defun org-agenda-check-type (error &rest types)
7587 "Check if agenda buffer is of allowed type.
7588 If ERROR is non-nil, throw an error, otherwise just return nil."
7589 (if (memq org-agenda-type types)
7591 (if error
7592 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
7593 nil)))
7595 (defun org-agenda-quit ()
7596 "Exit agenda by removing the window or the buffer."
7597 (interactive)
7598 (let ((buf (current-buffer)))
7599 (if (not (one-window-p)) (delete-window))
7600 (kill-buffer buf)
7601 (org-agenda-maybe-reset-markers 'force))
7602 ;; Maybe restore the pre-agenda window configuration.
7603 (and org-agenda-restore-windows-after-quit
7604 (not (eq org-agenda-window-setup 'other-frame))
7605 org-pre-agenda-window-conf
7606 (set-window-configuration org-pre-agenda-window-conf)))
7608 (defun org-agenda-exit ()
7609 "Exit agenda by removing the window or the buffer.
7610 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
7611 Org-mode buffers visited directly by the user will not be touched."
7612 (interactive)
7613 (org-release-buffers org-agenda-new-buffers)
7614 (setq org-agenda-new-buffers nil)
7615 (org-agenda-quit))
7617 (defun org-save-all-org-buffers ()
7618 "Save all Org-mode buffers without user confirmation."
7619 (interactive)
7620 (message "Saving all Org-mode buffers...")
7621 (save-some-buffers t 'org-mode-p)
7622 (message "Saving all Org-mode buffers... done"))
7624 (defun org-agenda-redo ()
7625 "Rebuild Agenda.
7626 When this is the global TODO list, a prefix argument will be interpreted."
7627 (interactive)
7628 (let* ((org-agenda-keep-modes t)
7629 (line (org-current-line))
7630 (window-line (- line (org-current-line (window-start)))))
7631 (message "Rebuilding agenda buffer...")
7632 (eval org-agenda-redo-command)
7633 (message "Rebuilding agenda buffer...done")
7634 (goto-line line)
7635 (recenter window-line)))
7637 (defun org-agenda-goto-today ()
7638 "Go to today."
7639 (interactive)
7640 (org-agenda-check-type t 'timeline 'agenda)
7641 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
7642 (cond
7643 (tdpos (goto-char tdpos))
7644 ((eq org-agenda-type 'agenda)
7645 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
7646 (setf (nth 1 org-agenda-overriding-arguments) nil)
7647 (org-agenda-redo)
7648 (org-agenda-find-today-or-agenda)))
7649 (t (error "Cannot find today")))))
7651 (defun org-agenda-find-today-or-agenda ()
7652 (goto-char
7653 (or (text-property-any (point-min) (point-max) 'org-today t)
7654 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
7655 (point-min))))
7657 (defun org-agenda-later (arg)
7658 "Go forward in time by `org-agenda-ndays' days.
7659 With prefix ARG, go forward that many times `org-agenda-ndays'."
7660 (interactive "p")
7661 (org-agenda-check-type t 'agenda)
7662 (let ((org-agenda-overriding-arguments
7663 (list (car org-agenda-last-arguments)
7664 (+ starting-day (* arg org-agenda-ndays))
7665 nil t)))
7666 (org-agenda-redo)
7667 (org-agenda-find-today-or-agenda)))
7669 (defun org-agenda-earlier (arg)
7670 "Go back in time by `org-agenda-ndays' days.
7671 With prefix ARG, go back that many times `org-agenda-ndays'."
7672 (interactive "p")
7673 (org-agenda-check-type t 'agenda)
7674 (let ((org-agenda-overriding-arguments
7675 (list (car org-agenda-last-arguments)
7676 (- starting-day (* arg org-agenda-ndays))
7677 nil t)))
7678 (org-agenda-redo)
7679 (org-agenda-find-today-or-agenda)))
7681 (defun org-agenda-week-view ()
7682 "Switch to weekly view for agenda."
7683 (interactive)
7684 (org-agenda-check-type t 'agenda)
7685 (if (= org-agenda-ndays 7)
7686 (error "This is already the week view"))
7687 (setq org-agenda-ndays 7)
7688 (let ((org-agenda-overriding-arguments
7689 (list (car org-agenda-last-arguments)
7690 (or (get-text-property (point) 'day)
7691 starting-day)
7692 nil t)))
7693 (org-agenda-redo)
7694 (org-agenda-find-today-or-agenda))
7695 (org-agenda-set-mode-name)
7696 (message "Switched to week view"))
7698 (defun org-agenda-day-view ()
7699 "Switch to daily view for agenda."
7700 (interactive)
7701 (org-agenda-check-type t 'agenda)
7702 (if (= org-agenda-ndays 1)
7703 (error "This is already the day view"))
7704 (setq org-agenda-ndays 1)
7705 (let ((org-agenda-overriding-arguments
7706 (list (car org-agenda-last-arguments)
7707 (or (get-text-property (point) 'day)
7708 starting-day)
7709 nil t)))
7710 (org-agenda-redo)
7711 (org-agenda-find-today-or-agenda))
7712 (org-agenda-set-mode-name)
7713 (message "Switched to day view"))
7715 (defun org-agenda-next-date-line (&optional arg)
7716 "Jump to the next line indicating a date in agenda buffer."
7717 (interactive "p")
7718 (org-agenda-check-type t 'agenda 'timeline)
7719 (beginning-of-line 1)
7720 (if (looking-at "^\\S-") (forward-char 1))
7721 (if (not (re-search-forward "^\\S-" nil t arg))
7722 (progn
7723 (backward-char 1)
7724 (error "No next date after this line in this buffer")))
7725 (goto-char (match-beginning 0)))
7727 (defun org-agenda-previous-date-line (&optional arg)
7728 "Jump to the previous line indicating a date in agenda buffer."
7729 (interactive "p")
7730 (org-agenda-check-type t 'agenda 'timeline)
7731 (beginning-of-line 1)
7732 (if (not (re-search-backward "^\\S-" nil t arg))
7733 (error "No previous date before this line in this buffer")))
7735 ;; Initialize the highlight
7736 (defvar org-hl (org-make-overlay 1 1))
7737 (org-overlay-put org-hl 'face 'highlight)
7739 (defun org-highlight (begin end &optional buffer)
7740 "Highlight a region with overlay."
7741 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
7742 org-hl begin end (or buffer (current-buffer))))
7744 (defun org-unhighlight ()
7745 "Detach overlay INDEX."
7746 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
7749 (defun org-agenda-follow-mode ()
7750 "Toggle follow mode in an agenda buffer."
7751 (interactive)
7752 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
7753 (org-agenda-set-mode-name)
7754 (message "Follow mode is %s"
7755 (if org-agenda-follow-mode "on" "off")))
7757 (defun org-agenda-log-mode ()
7758 "Toggle log mode in an agenda buffer."
7759 (interactive)
7760 (org-agenda-check-type t 'agenda 'timeline)
7761 (setq org-agenda-show-log (not org-agenda-show-log))
7762 (org-agenda-set-mode-name)
7763 (org-agenda-redo)
7764 (message "Log mode is %s"
7765 (if org-agenda-show-log "on" "off")))
7767 (defun org-agenda-toggle-diary ()
7768 "Toggle diary inclusion in an agenda buffer."
7769 (interactive)
7770 (org-agenda-check-type t 'agenda)
7771 (setq org-agenda-include-diary (not org-agenda-include-diary))
7772 (org-agenda-redo)
7773 (org-agenda-set-mode-name)
7774 (message "Diary inclusion turned %s"
7775 (if org-agenda-include-diary "on" "off")))
7777 (defun org-agenda-toggle-time-grid ()
7778 "Toggle time grid in an agenda buffer."
7779 (interactive)
7780 (org-agenda-check-type t 'agenda)
7781 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
7782 (org-agenda-redo)
7783 (org-agenda-set-mode-name)
7784 (message "Time-grid turned %s"
7785 (if org-agenda-use-time-grid "on" "off")))
7787 (defun org-agenda-set-mode-name ()
7788 "Set the mode name to indicate all the small mode settings."
7789 (setq mode-name
7790 (concat "Org-Agenda"
7791 (if (equal org-agenda-ndays 1) " Day" "")
7792 (if (equal org-agenda-ndays 7) " Week" "")
7793 (if org-agenda-follow-mode " Follow" "")
7794 (if org-agenda-include-diary " Diary" "")
7795 (if org-agenda-use-time-grid " Grid" "")
7796 (if org-agenda-show-log " Log" "")))
7797 (force-mode-line-update))
7799 (defun org-agenda-post-command-hook ()
7800 (and (eolp) (not (bolp)) (backward-char 1))
7801 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
7802 (if (and org-agenda-follow-mode
7803 (get-text-property (point) 'org-marker))
7804 (org-agenda-show)))
7806 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
7808 (defun org-get-entries-from-diary (date)
7809 "Get the (Emacs Calendar) diary entries for DATE."
7810 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
7811 (diary-display-hook '(fancy-diary-display))
7812 (list-diary-entries-hook
7813 (cons 'org-diary-default-entry list-diary-entries-hook))
7814 (diary-file-name-prefix-function nil) ; turn this feature off
7815 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7816 entries
7817 (org-disable-agenda-to-diary t))
7818 (save-excursion
7819 (save-window-excursion
7820 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7821 (if (not (get-buffer fancy-diary-buffer))
7822 (setq entries nil)
7823 (with-current-buffer fancy-diary-buffer
7824 (setq buffer-read-only nil)
7825 (if (= (point-max) 1)
7826 ;; No entries
7827 (setq entries nil)
7828 ;; Omit the date and other unnecessary stuff
7829 (org-agenda-cleanup-fancy-diary)
7830 ;; Add prefix to each line and extend the text properties
7831 (if (= (point-max) 1)
7832 (setq entries nil)
7833 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7834 (set-buffer-modified-p nil)
7835 (kill-buffer fancy-diary-buffer)))
7836 (when entries
7837 (setq entries (org-split-string entries "\n"))
7838 (setq entries
7839 (mapcar
7840 (lambda (x)
7841 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7842 ;; Extend the text properties to the beginning of the line
7843 (org-add-props x (text-properties-at (1- (length x)) x)))
7844 entries)))))
7846 (defun org-agenda-cleanup-fancy-diary ()
7847 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7848 This gets rid of the date, the underline under the date, and
7849 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7850 date. It also removes lines that contain only whitespace."
7851 (goto-char (point-min))
7852 (if (looking-at ".*?:[ \t]*")
7853 (progn
7854 (replace-match "")
7855 (re-search-forward "\n=+$" nil t)
7856 (replace-match "")
7857 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7858 (re-search-forward "\n=+$" nil t)
7859 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7860 (goto-char (point-min))
7861 (while (re-search-forward "^ +\n" nil t)
7862 (replace-match ""))
7863 (goto-char (point-min))
7864 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7865 (replace-match "")))
7867 ;; Make sure entries from the diary have the right text properties.
7868 (eval-after-load "diary-lib"
7869 '(if (boundp 'diary-modify-entry-list-string-function)
7870 ;; We can rely on the hook, nothing to do
7872 ;; Hook not avaiable, must use advice to make this work
7873 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7874 "Make the position visible."
7875 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7876 (stringp string)
7877 buffer-file-name)
7878 (setq string (org-modify-diary-entry-string string))))))
7880 (defun org-modify-diary-entry-string (string)
7881 "Add text properties to string, allowing org-mode to act on it."
7882 (org-add-props string nil
7883 'mouse-face 'highlight
7884 'keymap org-agenda-keymap
7885 'help-echo (format "mouse-2 or RET jump to diary file %s"
7886 (abbreviate-file-name buffer-file-name))
7887 'org-agenda-diary-link t
7888 'org-marker (org-agenda-new-marker (point-at-bol))))
7890 (defun org-diary-default-entry ()
7891 "Add a dummy entry to the diary.
7892 Needed to avoid empty dates which mess up holiday display."
7893 ;; Catch the error if dealing with the new add-to-diary-alist
7894 (when org-disable-agenda-to-diary
7895 (condition-case nil
7896 (add-to-diary-list original-date "Org-mode dummy" "")
7897 (error
7898 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7900 ;;;###autoload
7901 (defun org-cycle-agenda-files ()
7902 "Cycle through the files in `org-agenda-files'.
7903 If the current buffer visits an agenda file, find the next one in the list.
7904 If the current buffer does not, find the first agenda file."
7905 (interactive)
7906 (let* ((fs (org-agenda-files t))
7907 (files (append fs (list (car fs))))
7908 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7909 file)
7910 (unless files (error "No agenda files"))
7911 (catch 'exit
7912 (while (setq file (pop files))
7913 (if (equal (file-truename file) tcf)
7914 (when (car files)
7915 (find-file (car files))
7916 (throw 'exit t))))
7917 (find-file (car fs)))))
7919 (defun org-agenda-file-to-end ()
7920 "Move/add the current file to the end of the agenda file list.
7921 If the file is not present in the list, it is appended to the list. If it is
7922 present, it is moved there."
7923 (interactive)
7924 (org-agenda-file-to-front 'to-end))
7926 (defun org-agenda-file-to-front (&optional to-end)
7927 "Move/add the current file to the top of the agenda file list.
7928 If the file is not present in the list, it is added to the front. If it is
7929 present, it is moved there. With optional argument TO-END, add/move to the
7930 end of the list."
7931 (interactive "P")
7932 (let ((file-alist (mapcar (lambda (x)
7933 (cons (file-truename x) x))
7934 (org-agenda-files t)))
7935 (ctf (file-truename buffer-file-name))
7936 x had)
7937 (setq x (assoc ctf file-alist) had x)
7939 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7940 (if to-end
7941 (setq file-alist (append (delq x file-alist) (list x)))
7942 (setq file-alist (cons x (delq x file-alist))))
7943 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7944 (org-install-agenda-files-menu)
7945 (message "File %s to %s of agenda file list"
7946 (if had "moved" "added") (if to-end "end" "front"))))
7948 (defun org-remove-file (&optional file)
7949 "Remove current file from the list of files in variable `org-agenda-files'.
7950 These are the files which are being checked for agenda entries.
7951 Optional argument FILE means, use this file instead of the current."
7952 (interactive)
7953 (let* ((file (or file buffer-file-name))
7954 (true-file (file-truename file))
7955 (afile (abbreviate-file-name file))
7956 (files (delq nil (mapcar
7957 (lambda (x)
7958 (if (equal true-file
7959 (file-truename x))
7960 nil x))
7961 (org-agenda-files t)))))
7962 (if (not (= (length files) (length (org-agenda-files t))))
7963 (progn
7964 (org-store-new-agenda-file-list files)
7965 (org-install-agenda-files-menu)
7966 (message "Removed file: %s" afile))
7967 (message "File was not in list: %s" afile))))
7969 (defun org-file-menu-entry (file)
7970 (vector file (list 'find-file file) t))
7972 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7973 "Return a list of all relevant day numbers from BEG to END buffer positions.
7974 If NO-RANGES is non-nil, include only the start and end dates of a range,
7975 not every single day in the range. If FORCE-TODAY is non-nil, make
7976 sure that TODAY is included in the list. If INACTIVE is non-nil, also
7977 inactive time stamps (those in square brackets) are included.
7978 When EMPTY is non-nil, also include days without any entries."
7979 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
7980 dates dates1 date day day1 day2 ts1 ts2)
7981 (if force-today
7982 (setq dates (list (time-to-days (current-time)))))
7983 (save-excursion
7984 (goto-char beg)
7985 (while (re-search-forward re end t)
7986 (setq day (time-to-days (org-time-string-to-time
7987 (substring (match-string 1) 0 10))))
7988 (or (memq day dates) (push day dates)))
7989 (unless no-ranges
7990 (goto-char beg)
7991 (while (re-search-forward org-tr-regexp end t)
7992 (setq ts1 (substring (match-string 1) 0 10)
7993 ts2 (substring (match-string 2) 0 10)
7994 day1 (time-to-days (org-time-string-to-time ts1))
7995 day2 (time-to-days (org-time-string-to-time ts2)))
7996 (while (< (setq day1 (1+ day1)) day2)
7997 (or (memq day1 dates) (push day1 dates)))))
7998 (setq dates (sort dates '<))
7999 (when empty
8000 (while (setq day (pop dates))
8001 (setq day2 (car dates))
8002 (push day dates1)
8003 (when (and day2 empty)
8004 (if (or (eq empty t)
8005 (and (numberp empty) (<= (- day2 day) empty)))
8006 (while (< (setq day (1+ day)) day2)
8007 (push (list day) dates1))
8008 (push (cons :omitted (- day2 day)) dates1))))
8009 (setq dates (nreverse dates1)))
8010 dates)))
8012 ;;;###autoload
8013 (defun org-diary (&rest args)
8014 "Return diary information from org-files.
8015 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
8016 It accesses org files and extracts information from those files to be
8017 listed in the diary. The function accepts arguments specifying what
8018 items should be listed. The following arguments are allowed:
8020 :timestamp List the headlines of items containing a date stamp or
8021 date range matching the selected date. Deadlines will
8022 also be listed, on the expiration day.
8024 :deadline List any deadlines past due, or due within
8025 `org-deadline-warning-days'. The listing occurs only
8026 in the diary for *today*, not at any other date. If
8027 an entry is marked DONE, it is no longer listed.
8029 :scheduled List all items which are scheduled for the given date.
8030 The diary for *today* also contains items which were
8031 scheduled earlier and are not yet marked DONE.
8033 :todo List all TODO items from the org-file. This may be a
8034 long list - so this is not turned on by default.
8035 Like deadlines, these entries only show up in the
8036 diary for *today*, not at any other date.
8038 The call in the diary file should look like this:
8040 &%%(org-diary) ~/path/to/some/orgfile.org
8042 Use a separate line for each org file to check. Or, if you omit the file name,
8043 all files listed in `org-agenda-files' will be checked automatically:
8045 &%%(org-diary)
8047 If you don't give any arguments (as in the example above), the default
8048 arguments (:deadline :scheduled :timestamp) are used. So the example above may
8049 also be written as
8051 &%%(org-diary :deadline :timestamp :scheduled)
8053 The function expects the lisp variables `entry' and `date' to be provided
8054 by the caller, because this is how the calendar works. Don't use this
8055 function from a program - use `org-agenda-get-day-entries' instead."
8056 (org-agenda-maybe-reset-markers)
8057 (org-compile-prefix-format 'agenda)
8058 (org-set-sorting-strategy 'agenda)
8059 (setq args (or args '(:deadline :scheduled :timestamp)))
8060 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
8061 (list entry)
8062 (org-agenda-files t)))
8063 file rtn results)
8064 ;; If this is called during org-agenda, don't return any entries to
8065 ;; the calendar. Org Agenda will list these entries itself.
8066 (if org-disable-agenda-to-diary (setq files nil))
8067 (while (setq file (pop files))
8068 (setq rtn (apply 'org-agenda-get-day-entries file date args))
8069 (setq results (append results rtn)))
8070 (if results
8071 (concat (org-finalize-agenda-entries results) "\n"))))
8072 (defvar org-category-table nil)
8073 (defun org-get-category-table ()
8074 "Get the table of categories and positions in current buffer."
8075 (let (tbl)
8076 (save-excursion
8077 (goto-char (point-min))
8078 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
8079 (push (cons (point) (org-trim (match-string 2))) tbl)))
8080 tbl))
8081 (defun org-get-category (&optional pos)
8082 "Get the category applying to position POS."
8083 (if (not org-category-table)
8084 (cond
8085 ((null org-category)
8086 (setq org-category
8087 (if buffer-file-name
8088 (file-name-sans-extension
8089 (file-name-nondirectory buffer-file-name))
8090 "???")))
8091 ((symbolp org-category) (symbol-name org-category))
8092 (t org-category))
8093 (let ((tbl org-category-table)
8094 (pos (or pos (point))))
8095 (while (and tbl (> (caar tbl) pos))
8096 (pop tbl))
8097 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
8098 org-category-table))))))
8100 (defun org-agenda-get-day-entries (file date &rest args)
8101 "Does the work for `org-diary' and `org-agenda'.
8102 FILE is the path to a file to be checked for entries. DATE is date like
8103 the one returned by `calendar-current-date'. ARGS are symbols indicating
8104 which kind of entries should be extracted. For details about these, see
8105 the documentation of `org-diary'."
8106 (setq args (or args '(:deadline :scheduled :timestamp)))
8107 (let* ((org-startup-with-deadline-check nil)
8108 (org-startup-folded nil)
8109 (org-startup-align-all-tables nil)
8110 (buffer (if (file-exists-p file)
8111 (org-get-agenda-file-buffer file)
8112 (error "No such file %s" file)))
8113 arg results rtn)
8114 (if (not buffer)
8115 ;; If file does not exist, make sure an error message ends up in diary
8116 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8117 (with-current-buffer buffer
8118 (unless (org-mode-p)
8119 (error "Agenda file %s is not in `org-mode'" file))
8120 (setq org-category-table (org-get-category-table))
8121 (let ((case-fold-search nil))
8122 (save-excursion
8123 (save-restriction
8124 (if org-agenda-restrict
8125 (narrow-to-region org-agenda-restrict-begin
8126 org-agenda-restrict-end)
8127 (widen))
8128 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
8129 (while (setq arg (pop args))
8130 (cond
8131 ((and (eq arg :todo)
8132 (equal date (calendar-current-date)))
8133 (setq rtn (org-agenda-get-todos))
8134 (setq results (append results rtn)))
8135 ((eq arg :timestamp)
8136 (setq rtn (org-agenda-get-blocks))
8137 (setq results (append results rtn))
8138 (setq rtn (org-agenda-get-timestamps))
8139 (setq results (append results rtn)))
8140 ((eq arg :scheduled)
8141 (setq rtn (org-agenda-get-scheduled))
8142 (setq results (append results rtn)))
8143 ((eq arg :closed)
8144 (setq rtn (org-agenda-get-closed))
8145 (setq results (append results rtn)))
8146 ((and (eq arg :deadline)
8147 (equal date (calendar-current-date)))
8148 (setq rtn (org-agenda-get-deadlines))
8149 (setq results (append results rtn))))))))
8150 results))))
8152 (defun org-entry-is-done-p ()
8153 "Is the current entry marked DONE?"
8154 (save-excursion
8155 (and (re-search-backward "[\r\n]\\*" nil t)
8156 (looking-at org-nl-done-regexp))))
8158 (defun org-at-date-range-p (&optional inactive-ok)
8159 "Is the cursor inside a date range?"
8160 (interactive)
8161 (save-excursion
8162 (catch 'exit
8163 (let ((pos (point)))
8164 (skip-chars-backward "^[<\r\n")
8165 (skip-chars-backward "<[")
8166 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8167 (>= (match-end 0) pos)
8168 (throw 'exit t))
8169 (skip-chars-backward "^<[\r\n")
8170 (skip-chars-backward "<[")
8171 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8172 (>= (match-end 0) pos)
8173 (throw 'exit t)))
8174 nil)))
8176 (defun org-agenda-get-todos ()
8177 "Return the TODO information for agenda display."
8178 (let* ((props (list 'face nil
8179 'done-face 'org-done
8180 'org-not-done-regexp org-not-done-regexp
8181 'mouse-face 'highlight
8182 'keymap org-agenda-keymap
8183 'help-echo
8184 (format "mouse-2 or RET jump to org file %s"
8185 (abbreviate-file-name buffer-file-name))))
8186 (regexp (concat "[\n\r]\\*+ *\\("
8187 (if org-select-this-todo-keyword
8188 (concat "\\<\\(" org-select-this-todo-keyword
8189 "\\)\\>")
8190 org-not-done-regexp)
8191 "[^\n\r]*\\)"))
8192 (deadline-re (concat ".*\\(\n[^*].*\\)?" org-deadline-time-regexp))
8193 (sched-re (concat ".*\\(\n[^*].*\\)?" org-scheduled-time-regexp))
8194 ; FIXME why was this wriong? (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
8195 marker priority category tags
8196 ee txt)
8197 (goto-char (point-min))
8198 (while (re-search-forward regexp nil t)
8199 (catch :skip
8200 (save-match-data
8201 (beginning-of-line)
8202 (when (or (and org-agenda-todo-ignore-scheduled
8203 (looking-at sched-re))
8204 (and org-agenda-todo-ignore-deadlines
8205 (looking-at deadline-re)
8206 (org-deadline-close (match-string 2))))
8208 ;; FIXME: the following test also happens below, but we need it here
8209 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
8210 (throw :skip nil)))
8211 (org-agenda-skip)
8212 (goto-char (match-beginning 1))
8213 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
8214 category (org-get-category)
8215 tags (org-get-tags-at (point))
8216 txt (org-format-agenda-item "" (match-string 1) category tags)
8217 priority
8218 (+ (org-get-priority txt)
8219 (if org-todo-kwd-priority-p
8220 (- org-todo-kwd-max-priority -2
8221 (length
8222 (member (match-string 2) org-todo-keywords)))
8223 1)))
8224 (org-add-props txt props
8225 'org-marker marker 'org-hd-marker marker
8226 'priority priority 'category category)
8227 (push txt ee)
8228 (if org-agenda-todo-list-sublevels
8229 (goto-char (match-end 1))
8230 (org-end-of-subtree 'invisible))))
8231 (nreverse ee)))
8233 (defconst org-agenda-no-heading-message
8234 "No heading for this item in buffer or region.")
8236 (defun org-agenda-get-timestamps ()
8237 "Return the date stamp information for agenda display."
8238 (let* ((props (list 'face nil
8239 'org-not-done-regexp org-not-done-regexp
8240 'mouse-face 'highlight
8241 'keymap org-agenda-keymap
8242 'help-echo
8243 (format "mouse-2 or RET jump to org file %s"
8244 (abbreviate-file-name buffer-file-name))))
8245 (regexp (regexp-quote
8246 (substring
8247 (format-time-string
8248 (car org-time-stamp-formats)
8249 (apply 'encode-time ; DATE bound by calendar
8250 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
8251 0 11)))
8252 marker hdmarker deadlinep scheduledp donep tmp priority category
8253 ee txt timestr tags)
8254 (goto-char (point-min))
8255 (while (re-search-forward regexp nil t)
8256 (catch :skip
8257 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
8258 (org-agenda-skip)
8259 (setq marker (org-agenda-new-marker (match-beginning 0))
8260 category (org-get-category (match-beginning 0))
8261 tmp (buffer-substring (max (point-min)
8262 (- (match-beginning 0)
8263 org-ds-keyword-length))
8264 (match-beginning 0))
8265 timestr (buffer-substring (match-beginning 0) (point-at-eol))
8266 deadlinep (string-match org-deadline-regexp tmp)
8267 scheduledp (string-match org-scheduled-regexp tmp)
8268 donep (org-entry-is-done-p))
8269 (if (string-match ">" timestr)
8270 ;; substring should only run to end of time stamp
8271 (setq timestr (substring timestr 0 (match-end 0))))
8272 (save-excursion
8273 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8274 (progn
8275 (goto-char (match-end 1))
8276 (setq hdmarker (org-agenda-new-marker)
8277 tags (org-get-tags-at))
8278 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8279 (setq txt (org-format-agenda-item
8280 (format "%s%s"
8281 (if deadlinep "Deadline: " "")
8282 (if scheduledp "Scheduled: " ""))
8283 (match-string 1) category tags timestr)))
8284 (setq txt org-agenda-no-heading-message))
8285 (setq priority (org-get-priority txt))
8286 (org-add-props txt props
8287 'org-marker marker 'org-hd-marker hdmarker)
8288 (if deadlinep
8289 (org-add-props txt nil
8290 'face (if donep 'org-done 'org-warning)
8291 'undone-face 'org-warning 'done-face 'org-done
8292 'category category 'priority (+ 100 priority))
8293 (if scheduledp
8294 (org-add-props txt nil
8295 'face 'org-scheduled-today
8296 'undone-face 'org-scheduled-today 'done-face 'org-done
8297 'category category 'priority (+ 99 priority))
8298 (org-add-props txt nil 'priority priority 'category category)))
8299 (push txt ee))
8300 (outline-next-heading)))
8301 (nreverse ee)))
8303 (defun org-agenda-get-closed ()
8304 "Return the logged TODO entries for agenda display."
8305 (let* ((props (list 'mouse-face 'highlight
8306 'org-not-done-regexp org-not-done-regexp
8307 'keymap org-agenda-keymap
8308 'help-echo
8309 (format "mouse-2 or RET jump to org file %s"
8310 (abbreviate-file-name buffer-file-name))))
8311 (regexp (concat
8312 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
8313 (regexp-quote
8314 (substring
8315 (format-time-string
8316 (car org-time-stamp-formats)
8317 (apply 'encode-time ; DATE bound by calendar
8318 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
8319 1 11))))
8320 marker hdmarker priority category tags closedp
8321 ee txt timestr)
8322 (goto-char (point-min))
8323 (while (re-search-forward regexp nil t)
8324 (catch :skip
8325 (org-agenda-skip)
8326 (setq marker (org-agenda-new-marker (match-beginning 0))
8327 closedp (equal (match-string 1) org-closed-string)
8328 category (org-get-category (match-beginning 0))
8329 timestr (buffer-substring (match-beginning 0) (point-at-eol))
8330 ;; donep (org-entry-is-done-p)
8332 (if (string-match "\\]" timestr)
8333 ;; substring should only run to end of time stamp
8334 (setq timestr (substring timestr 0 (match-end 0))))
8335 (save-excursion
8336 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8337 (progn
8338 (goto-char (match-end 1))
8339 (setq hdmarker (org-agenda-new-marker)
8340 tags (org-get-tags-at))
8341 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8342 (setq txt (org-format-agenda-item
8343 (if closedp "Closed: " "Clocked: ")
8344 (match-string 1) category tags timestr)))
8345 (setq txt org-agenda-no-heading-message))
8346 (setq priority 100000)
8347 (org-add-props txt props
8348 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
8349 'priority priority 'category category
8350 'undone-face 'org-warning 'done-face 'org-done)
8351 (push txt ee))
8352 (outline-next-heading)))
8353 (nreverse ee)))
8355 (defun org-agenda-get-deadlines ()
8356 "Return the deadline information for agenda display."
8357 (let* ((wdays org-deadline-warning-days)
8358 (props (list 'mouse-face 'highlight
8359 'org-not-done-regexp org-not-done-regexp
8360 'keymap org-agenda-keymap
8361 'help-echo
8362 (format "mouse-2 or RET jump to org file %s"
8363 (abbreviate-file-name buffer-file-name))))
8364 (regexp org-deadline-time-regexp)
8365 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
8366 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
8367 d2 diff pos pos1 category tags
8368 ee txt head face)
8369 (goto-char (point-min))
8370 (while (re-search-forward regexp nil t)
8371 (catch :skip
8372 (org-agenda-skip)
8373 (setq pos (1- (match-beginning 1))
8374 d2 (time-to-days
8375 (org-time-string-to-time (match-string 1)))
8376 diff (- d2 d1))
8377 ;; When to show a deadline in the calendar:
8378 ;; If the expiration is within wdays warning time.
8379 ;; Past-due deadlines are only shown on the current date
8380 (if (and (< diff wdays) todayp (not (= diff 0)))
8381 (save-excursion
8382 (setq category (org-get-category))
8383 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
8384 (progn
8385 (goto-char (match-end 0))
8386 (setq pos1 (match-end 1))
8387 (setq tags (org-get-tags-at pos1))
8388 (setq head (buffer-substring-no-properties
8389 (point)
8390 (progn (skip-chars-forward "^\r\n")
8391 (point))))
8392 (if (string-match org-looking-at-done-regexp head)
8393 (setq txt nil)
8394 (setq txt (org-format-agenda-item
8395 (format "In %3d d.: " diff) head category tags))))
8396 (setq txt org-agenda-no-heading-message))
8397 (when txt
8398 (setq face (cond ((<= diff 0) 'org-warning)
8399 ((<= diff 5) 'org-upcoming-deadline)
8400 (t nil)))
8401 (org-add-props txt props
8402 'org-marker (org-agenda-new-marker pos)
8403 'org-hd-marker (org-agenda-new-marker pos1)
8404 'priority (+ (- 10 diff) (org-get-priority txt))
8405 'category category
8406 'face face 'undone-face face 'done-face 'org-done)
8407 (push txt ee))))))
8408 ee))
8410 (defun org-agenda-get-scheduled ()
8411 "Return the scheduled information for agenda display."
8412 (let* ((props (list 'face 'org-scheduled-previously
8413 'org-not-done-regexp org-not-done-regexp
8414 'undone-face 'org-scheduled-previously
8415 'done-face 'org-done
8416 'mouse-face 'highlight
8417 'keymap org-agenda-keymap
8418 'help-echo
8419 (format "mouse-2 or RET jump to org file %s"
8420 (abbreviate-file-name buffer-file-name))))
8421 (regexp org-scheduled-time-regexp)
8422 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
8423 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
8424 d2 diff pos pos1 category tags
8425 ee txt head)
8426 (goto-char (point-min))
8427 (while (re-search-forward regexp nil t)
8428 (catch :skip
8429 (org-agenda-skip)
8430 (setq pos (1- (match-beginning 1))
8431 d2 (time-to-days
8432 (org-time-string-to-time (match-string 1)))
8433 diff (- d2 d1))
8434 ;; When to show a scheduled item in the calendar:
8435 ;; If it is on or past the date.
8436 (if (and (< diff 0) todayp)
8437 (save-excursion
8438 (setq category (org-get-category))
8439 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
8440 (progn
8441 (goto-char (match-end 0))
8442 (setq pos1 (match-end 1))
8443 (setq tags (org-get-tags-at))
8444 (setq head (buffer-substring-no-properties
8445 (point)
8446 (progn (skip-chars-forward "^\r\n") (point))))
8447 (if (string-match org-looking-at-done-regexp head)
8448 (setq txt nil)
8449 (setq txt (org-format-agenda-item
8450 (format "Sched.%2dx: " (- 1 diff)) head
8451 category tags))))
8452 (setq txt org-agenda-no-heading-message))
8453 (when txt
8454 (org-add-props txt props
8455 'org-marker (org-agenda-new-marker pos)
8456 'org-hd-marker (org-agenda-new-marker pos1)
8457 'priority (+ (- 5 diff) (org-get-priority txt))
8458 'category category)
8459 (push txt ee))))))
8460 ee))
8462 (defun org-agenda-get-blocks ()
8463 "Return the date-range information for agenda display."
8464 (let* ((props (list 'face nil
8465 'org-not-done-regexp org-not-done-regexp
8466 'mouse-face 'highlight
8467 'keymap org-agenda-keymap
8468 'help-echo
8469 (format "mouse-2 or RET jump to org file %s"
8470 (abbreviate-file-name buffer-file-name))))
8471 (regexp org-tr-regexp)
8472 (d0 (calendar-absolute-from-gregorian date))
8473 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
8474 (goto-char (point-min))
8475 (while (re-search-forward regexp nil t)
8476 (catch :skip
8477 (org-agenda-skip)
8478 (setq pos (point))
8479 (setq timestr (match-string 0)
8480 s1 (match-string 1)
8481 s2 (match-string 2)
8482 d1 (time-to-days (org-time-string-to-time s1))
8483 d2 (time-to-days (org-time-string-to-time s2)))
8484 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
8485 ;; Only allow days between the limits, because the normal
8486 ;; date stamps will catch the limits.
8487 (save-excursion
8488 (setq marker (org-agenda-new-marker (point)))
8489 (setq category (org-get-category))
8490 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8491 (progn
8492 (setq hdmarker (org-agenda-new-marker (match-end 1)))
8493 (goto-char (match-end 1))
8494 (setq tags (org-get-tags-at))
8495 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8496 (setq txt (org-format-agenda-item
8497 (format (if (= d1 d2) "" "(%d/%d): ")
8498 (1+ (- d0 d1)) (1+ (- d2 d1)))
8499 (match-string 1) category tags
8500 (if (= d0 d1) timestr))))
8501 (setq txt org-agenda-no-heading-message))
8502 (org-add-props txt props
8503 'org-marker marker 'org-hd-marker hdmarker
8504 'priority (org-get-priority txt) 'category category)
8505 (push txt ee)))
8506 (goto-char pos)))
8507 ;; Sort the entries by expiration date.
8508 (nreverse ee)))
8510 (defconst org-plain-time-of-day-regexp
8511 (concat
8512 "\\(\\<[012]?[0-9]"
8513 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
8514 "\\(--?"
8515 "\\(\\<[012]?[0-9]"
8516 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
8517 "\\)?")
8518 "Regular expression to match a plain time or time range.
8519 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
8520 groups carry important information:
8521 0 the full match
8522 1 the first time, range or not
8523 8 the second time, if it is a range.")
8525 (defconst org-stamp-time-of-day-regexp
8526 (concat
8527 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
8528 "\\([012][0-9]:[0-5][0-9]\\)>"
8529 "\\(--?"
8530 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
8531 "Regular expression to match a timestamp time or time range.
8532 After a match, the following groups carry important information:
8533 0 the full match
8534 1 date plus weekday, for backreferencing to make sure both times on same day
8535 2 the first time, range or not
8536 4 the second time, if it is a range.")
8538 (defvar org-prefix-has-time nil
8539 "A flag, set by `org-compile-prefix-format'.
8540 The flag is set if the currently compiled format contains a `%t'.")
8541 (defvar org-prefix-has-tag nil
8542 "A flag, set by `org-compile-prefix-format'.
8543 The flag is set if the currently compiled format contains a `%T'.")
8545 (defun org-format-agenda-item (extra txt &optional category tags dotime
8546 noprefix)
8547 "Format TXT to be inserted into the agenda buffer.
8548 In particular, it adds the prefix and corresponding text properties. EXTRA
8549 must be a string and replaces the `%s' specifier in the prefix format.
8550 CATEGORY (string, symbol or nil) may be used to overrule the default
8551 category taken from local variable or file name. It will replace the `%c'
8552 specifier in the format. DOTIME, when non-nil, indicates that a
8553 time-of-day should be extracted from TXT for sorting of this entry, and for
8554 the `%t' specifier in the format. When DOTIME is a string, this string is
8555 searched for a time before TXT is. NOPREFIX is a flag and indicates that
8556 only the correctly processes TXT should be returned - this is used by
8557 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
8558 (save-match-data
8559 ;; Diary entries sometimes have extra whitespace at the beginning
8560 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
8561 (let* ((category (or category
8562 org-category
8563 (if buffer-file-name
8564 (file-name-sans-extension
8565 (file-name-nondirectory buffer-file-name))
8566 "")))
8567 (tag (if tags (nth (1- (length tags)) tags) ""))
8568 time ;; needed for the eval of the prefix format
8569 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
8570 (time-of-day (and dotime (org-get-time-of-day ts)))
8571 stamp plain s0 s1 s2 rtn)
8572 (when (and dotime time-of-day org-prefix-has-time)
8573 ;; Extract starting and ending time and move them to prefix
8574 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
8575 (setq plain (string-match org-plain-time-of-day-regexp ts)))
8576 (setq s0 (match-string 0 ts)
8577 s1 (match-string (if plain 1 2) ts)
8578 s2 (match-string (if plain 8 4) ts))
8580 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
8581 ;; them, we might want to remove them there to avoid duplication.
8582 ;; The user can turn this off with a variable.
8583 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
8584 (string-match (concat (regexp-quote s0) " *") txt)
8585 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
8586 (= (match-beginning 0) 0)
8588 (setq txt (replace-match "" nil nil txt))))
8589 ;; Normalize the time(s) to 24 hour
8590 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
8591 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
8593 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
8594 ;; Tags are in the string
8595 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
8596 (and org-agenda-remove-tags-when-in-prefix
8597 org-prefix-has-tag))
8598 (setq txt (replace-match "" t t txt))
8599 (setq txt (replace-match
8600 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
8601 (match-string 2 txt))
8602 t t txt))))
8604 ;; Create the final string
8605 (if noprefix
8606 (setq rtn txt)
8607 ;; Prepare the variables needed in the eval of the compiled format
8608 (setq time (cond (s2 (concat s1 "-" s2))
8609 (s1 (concat s1 "......"))
8610 (t ""))
8611 extra (or extra "")
8612 category (if (symbolp category) (symbol-name category) category))
8613 ;; Evaluate the compiled format
8614 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
8616 ;; And finally add the text properties
8617 (org-add-props rtn nil
8618 'category (downcase category) 'tags tags
8619 'prefix-length (- (length rtn) (length txt))
8620 'time-of-day time-of-day
8621 'dotime dotime))))
8623 (defvar org-agenda-sorting-strategy)
8624 (defvar org-agenda-sorting-strategy-selected nil)
8626 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
8627 (catch 'exit
8628 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
8629 ((and todayp (member 'today (car org-agenda-time-grid))))
8630 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
8631 ((member 'weekly (car org-agenda-time-grid)))
8632 (t (throw 'exit list)))
8633 (let* ((have (delq nil (mapcar
8634 (lambda (x) (get-text-property 1 'time-of-day x))
8635 list)))
8636 (string (nth 1 org-agenda-time-grid))
8637 (gridtimes (nth 2 org-agenda-time-grid))
8638 (req (car org-agenda-time-grid))
8639 (remove (member 'remove-match req))
8640 new time)
8641 (if (and (member 'require-timed req) (not have))
8642 ;; don't show empty grid
8643 (throw 'exit list))
8644 (while (setq time (pop gridtimes))
8645 (unless (and remove (member time have))
8646 (setq time (int-to-string time))
8647 (push (org-format-agenda-item
8648 nil string "" nil
8649 (concat (substring time 0 -2) ":" (substring time -2)))
8650 new)
8651 (put-text-property
8652 1 (length (car new)) 'face 'org-time-grid (car new))))
8653 (if (member 'time-up org-agenda-sorting-strategy-selected)
8654 (append new list)
8655 (append list new)))))
8657 (defun org-compile-prefix-format (key)
8658 "Compile the prefix format into a Lisp form that can be evaluated.
8659 The resulting form is returned and stored in the variable
8660 `org-prefix-format-compiled'."
8661 (setq org-prefix-has-time nil org-prefix-has-tag nil)
8662 (let ((s (cond
8663 ((stringp org-agenda-prefix-format)
8664 org-agenda-prefix-format)
8665 ((assq key org-agenda-prefix-format)
8666 (cdr (assq key org-agenda-prefix-format)))
8667 (t " %-12:c%?-12t% s")))
8668 (start 0)
8669 varform vars var e c f opt)
8670 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
8671 s start)
8672 (setq var (cdr (assoc (match-string 4 s)
8673 '(("c" . category) ("t" . time) ("s" . extra)
8674 ("T" . tag))))
8675 c (or (match-string 3 s) "")
8676 opt (match-beginning 1)
8677 start (1+ (match-beginning 0)))
8678 (if (equal var 'time) (setq org-prefix-has-time t))
8679 (if (equal var 'tag) (setq org-prefix-has-tag t))
8680 (setq f (concat "%" (match-string 2 s) "s"))
8681 (if opt
8682 (setq varform
8683 `(if (equal "" ,var)
8685 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
8686 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
8687 (setq s (replace-match "%s" t nil s))
8688 (push varform vars))
8689 (setq vars (nreverse vars))
8690 (setq org-prefix-format-compiled `(format ,s ,@vars))))
8692 (defun org-set-sorting-strategy (key)
8693 (if (symbolp (car org-agenda-sorting-strategy))
8694 ;; the old format
8695 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
8696 (setq org-agenda-sorting-strategy-selected
8697 (or (cdr (assq key org-agenda-sorting-strategy))
8698 (cdr (assq 'agenda org-agenda-sorting-strategy))
8699 '(time-up category-keep priority-down)))))
8701 (defun org-get-time-of-day (s &optional string mod24)
8702 "Check string S for a time of day.
8703 If found, return it as a military time number between 0 and 2400.
8704 If not found, return nil.
8705 The optional STRING argument forces conversion into a 5 character wide string
8706 HH:MM."
8707 (save-match-data
8708 (when
8710 (string-match
8711 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
8712 (string-match
8713 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
8714 (let* ((h (string-to-number (match-string 1 s)))
8715 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
8716 (ampm (if (match-end 4) (downcase (match-string 4 s))))
8717 (am-p (equal ampm "am"))
8718 (h1 (cond ((not ampm) h)
8719 ((= h 12) (if am-p 0 12))
8720 (t (+ h (if am-p 0 12)))))
8721 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
8722 (mod h1 24) h1))
8723 (t0 (+ (* 100 h2) m))
8724 (t1 (concat (if (>= h1 24) "+" " ")
8725 (if (< t0 100) "0" "")
8726 (if (< t0 10) "0" "")
8727 (int-to-string t0))))
8728 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
8730 (defun org-finalize-agenda-entries (list &optional nosort)
8731 "Sort and concatenate the agenda items."
8732 (setq list (mapcar 'org-agenda-highlight-todo list))
8733 (if nosort
8734 list
8735 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
8737 (defun org-agenda-highlight-todo (x)
8738 (let (re pl)
8739 (if (eq x 'line)
8740 (save-excursion
8741 (beginning-of-line 1)
8742 (setq re (get-text-property (point) 'org-not-done-regexp))
8743 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
8744 (and (looking-at (concat "[ \t]*\\.*" re))
8745 (add-text-properties (match-beginning 0) (match-end 0)
8746 '(face org-todo))))
8747 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
8748 pl (get-text-property 0 'prefix-length x))
8749 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
8750 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
8751 '(face org-todo) x))
8752 x)))
8754 (defsubst org-cmp-priority (a b)
8755 "Compare the priorities of string A and B."
8756 (let ((pa (or (get-text-property 1 'priority a) 0))
8757 (pb (or (get-text-property 1 'priority b) 0)))
8758 (cond ((> pa pb) +1)
8759 ((< pa pb) -1)
8760 (t nil))))
8762 (defsubst org-cmp-category (a b)
8763 "Compare the string values of categories of strings A and B."
8764 (let ((ca (or (get-text-property 1 'category a) ""))
8765 (cb (or (get-text-property 1 'category b) "")))
8766 (cond ((string-lessp ca cb) -1)
8767 ((string-lessp cb ca) +1)
8768 (t nil))))
8770 (defsubst org-cmp-tag (a b)
8771 "Compare the string values of categories of strings A and B."
8772 (let ((ta (car (last (get-text-property 1 'tags a))))
8773 (tb (car (last (get-text-property 1 'tags b)))))
8774 (cond ((not ta) +1)
8775 ((not tb) -1)
8776 ((string-lessp ta tb) -1)
8777 ((string-lessp tb ta) +1)
8778 (t nil))))
8780 (defsubst org-cmp-time (a b)
8781 "Compare the time-of-day values of strings A and B."
8782 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
8783 (ta (or (get-text-property 1 'time-of-day a) def))
8784 (tb (or (get-text-property 1 'time-of-day b) def)))
8785 (cond ((< ta tb) -1)
8786 ((< tb ta) +1)
8787 (t nil))))
8789 (defun org-entries-lessp (a b)
8790 "Predicate for sorting agenda entries."
8791 ;; The following variables will be used when the form is evaluated.
8792 (let* ((time-up (org-cmp-time a b))
8793 (time-down (if time-up (- time-up) nil))
8794 (priority-up (org-cmp-priority a b))
8795 (priority-down (if priority-up (- priority-up) nil))
8796 (category-up (org-cmp-category a b))
8797 (category-down (if category-up (- category-up) nil))
8798 (category-keep (if category-up +1 nil))
8799 (tag-up (org-cmp-tag a b))
8800 (tag-down (if tag-up (- tag-up) nil)))
8801 (cdr (assoc
8802 (eval (cons 'or org-agenda-sorting-strategy-selected))
8803 '((-1 . t) (1 . nil) (nil . nil))))))
8805 (defun org-agenda-show-priority ()
8806 "Show the priority of the current item.
8807 This priority is composed of the main priority given with the [#A] cookies,
8808 and by additional input from the age of a schedules or deadline entry."
8809 (interactive)
8810 (let* ((pri (get-text-property (point-at-bol) 'priority)))
8811 (message "Priority is %d" (if pri pri -1000))))
8813 (defun org-agenda-show-tags ()
8814 "Show the tags applicable to the current item."
8815 (interactive)
8816 (let* ((tags (get-text-property (point-at-bol) 'tags)))
8817 (if tags
8818 (message "Tags are :%s:"
8819 (org-no-properties (mapconcat 'identity tags ":")))
8820 (message "No tags associated with this line"))))
8822 (defun org-agenda-goto (&optional highlight)
8823 "Go to the Org-mode file which contains the item at point."
8824 (interactive)
8825 (let* ((marker (or (get-text-property (point) 'org-marker)
8826 (org-agenda-error)))
8827 (buffer (marker-buffer marker))
8828 (pos (marker-position marker)))
8829 (switch-to-buffer-other-window buffer)
8830 (widen)
8831 (goto-char pos)
8832 (when (org-mode-p)
8833 (org-show-hierarchy-above 'agenda)
8834 (save-excursion
8835 (and (outline-next-heading)
8836 (org-flag-heading nil)))) ; show the next heading
8837 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
8839 (defun org-agenda-switch-to (&optional delete-other-windows)
8840 "Go to the Org-mode file which contains the item at point."
8841 (interactive)
8842 (let* ((marker (or (get-text-property (point) 'org-marker)
8843 (org-agenda-error)))
8844 (buffer (marker-buffer marker))
8845 (pos (marker-position marker)))
8846 (switch-to-buffer buffer)
8847 (and delete-other-windows (delete-other-windows))
8848 (widen)
8849 (goto-char pos)
8850 (when (org-mode-p)
8851 (org-show-hierarchy-above 'agenda)
8852 (save-excursion
8853 (and (outline-next-heading)
8854 (org-flag-heading nil)))))) ; show the next heading
8856 (defun org-agenda-goto-mouse (ev)
8857 "Go to the Org-mode file which contains the item at the mouse click."
8858 (interactive "e")
8859 (mouse-set-point ev)
8860 (org-agenda-goto))
8862 (defun org-agenda-show ()
8863 "Display the Org-mode file which contains the item at point."
8864 (interactive)
8865 (let ((win (selected-window)))
8866 (org-agenda-goto t)
8867 (select-window win)))
8869 (defun org-agenda-recenter (arg)
8870 "Display the Org-mode file which contains the item at point and recenter."
8871 (interactive "P")
8872 (let ((win (selected-window)))
8873 (org-agenda-goto t)
8874 (recenter arg)
8875 (select-window win)))
8877 (defun org-agenda-show-mouse (ev)
8878 "Display the Org-mode file which contains the item at the mouse click."
8879 (interactive "e")
8880 (mouse-set-point ev)
8881 (org-agenda-show))
8883 (defun org-agenda-check-no-diary ()
8884 "Check if the entry is a diary link and abort if yes."
8885 (if (get-text-property (point) 'org-agenda-diary-link)
8886 (org-agenda-error)))
8888 (defun org-agenda-error ()
8889 (error "Command not allowed in this line"))
8891 (defvar org-last-heading-marker (make-marker)
8892 "Marker pointing to the headline that last changed its TODO state
8893 by a remote command from the agenda.")
8895 (defun org-agenda-todo (&optional arg)
8896 "Cycle TODO state of line at point, also in Org-mode file.
8897 This changes the line at point, all other lines in the agenda referring to
8898 the same tree node, and the headline of the tree node in the Org-mode file."
8899 (interactive "P")
8900 (org-agenda-check-no-diary)
8901 (let* ((col (current-column))
8902 (marker (or (get-text-property (point) 'org-marker)
8903 (org-agenda-error)))
8904 (buffer (marker-buffer marker))
8905 (pos (marker-position marker))
8906 (hdmarker (get-text-property (point) 'org-hd-marker))
8907 (buffer-read-only nil)
8908 newhead)
8909 (with-current-buffer buffer
8910 (widen)
8911 (goto-char pos)
8912 (org-show-hierarchy-above 'agenda)
8913 (save-excursion
8914 (and (outline-next-heading)
8915 (org-flag-heading nil))) ; show the next heading
8916 (org-todo arg)
8917 (and (bolp) (forward-char 1))
8918 (setq newhead (org-get-heading))
8919 (save-excursion
8920 (org-back-to-heading)
8921 (move-marker org-last-heading-marker (point))))
8922 (beginning-of-line 1)
8923 (save-excursion
8924 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8925 (move-to-column col)))
8927 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8928 "Change all lines in the agenda buffer which match HDMARKER.
8929 The new content of the line will be NEWHEAD (as modified by
8930 `org-format-agenda-item'). HDMARKER is checked with
8931 `equal' against all `org-hd-marker' text properties in the file.
8932 If FIXFACE is non-nil, the face of each item is modified acording to
8933 the new TODO state."
8934 (let* (props m pl undone-face done-face finish new dotime cat tags)
8935 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
8936 (save-excursion
8937 (goto-char (point-max))
8938 (beginning-of-line 1)
8939 (while (not finish)
8940 (setq finish (bobp))
8941 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8942 (equal m hdmarker))
8943 (setq props (text-properties-at (point))
8944 dotime (get-text-property (point) 'dotime)
8945 cat (get-text-property (point) 'category)
8946 tags (get-text-property (point) 'tags)
8947 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
8948 pl (get-text-property (point) 'prefix-length)
8949 undone-face (get-text-property (point) 'undone-face)
8950 done-face (get-text-property (point) 'done-face))
8951 (move-to-column pl)
8952 (if (looking-at ".*")
8953 (progn
8954 (replace-match new t t)
8955 (beginning-of-line 1)
8956 (add-text-properties (point-at-bol) (point-at-eol) props)
8957 (when fixface
8958 (add-text-properties
8959 (point-at-bol) (point-at-eol)
8960 (list 'face
8961 (if org-last-todo-state-is-todo
8962 undone-face done-face)))
8963 (org-agenda-highlight-todo 'line))
8964 ;; (org-agenda-align-tags 'line) ;; done below by finalize
8965 (beginning-of-line 1))
8966 (error "Line update did not work")))
8967 (beginning-of-line 0)))
8968 (org-finalize-agenda)))
8970 (defun org-agenda-align-tags (&optional line)
8971 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
8972 (let ((buffer-read-only))
8973 (save-excursion
8974 (goto-char (if line (point-at-bol) (point-min)))
8975 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
8976 (if line (point-at-eol) nil) t)
8977 (delete-region (match-beginning 1) (match-end 1))
8978 (goto-char (match-beginning 1))
8979 (insert (org-add-props
8980 (make-string (max 1 (- org-agenda-align-tags-to-column
8981 (current-column))) ?\ )
8982 (text-properties-at (point))))))))
8984 (defun org-agenda-priority-up ()
8985 "Increase the priority of line at point, also in Org-mode file."
8986 (interactive)
8987 (org-agenda-priority 'up))
8989 (defun org-agenda-priority-down ()
8990 "Decrease the priority of line at point, also in Org-mode file."
8991 (interactive)
8992 (org-agenda-priority 'down))
8994 (defun org-agenda-priority (&optional force-direction)
8995 "Set the priority of line at point, also in Org-mode file.
8996 This changes the line at point, all other lines in the agenda referring to
8997 the same tree node, and the headline of the tree node in the Org-mode file."
8998 (interactive)
8999 (org-agenda-check-no-diary)
9000 (let* ((marker (or (get-text-property (point) 'org-marker)
9001 (org-agenda-error)))
9002 (buffer (marker-buffer marker))
9003 (pos (marker-position marker))
9004 (hdmarker (get-text-property (point) 'org-hd-marker))
9005 (buffer-read-only nil)
9006 newhead)
9007 (with-current-buffer buffer
9008 (widen)
9009 (goto-char pos)
9010 (org-show-hierarchy-above 'agenda)
9011 (save-excursion
9012 (and (outline-next-heading)
9013 (org-flag-heading nil))) ; show the next heading
9014 (funcall 'org-priority force-direction)
9015 (end-of-line 1)
9016 (setq newhead (org-get-heading)))
9017 (org-agenda-change-all-lines newhead hdmarker)
9018 (beginning-of-line 1)))
9020 (defun org-get-tags-at (&optional pos)
9021 "Get a list of all headline tags applicable at POS.
9022 POS defaults to point. If tags are inherited, the list contains
9023 the targets in the same sequence as the headlines appear, i.e.
9024 the tags of the current headline come last."
9025 (interactive)
9026 (let (tags)
9027 (save-excursion
9028 (goto-char (or pos (point)))
9029 (save-match-data
9030 (org-back-to-heading t)
9031 (condition-case nil
9032 (while t
9033 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
9034 (setq tags (append (org-split-string
9035 (org-match-string-no-properties 1) ":")
9036 tags)))
9037 (or org-use-tag-inheritance (error ""))
9038 (org-up-heading-all 1))
9039 (error nil))))
9040 tags))
9042 (defun org-agenda-set-tags ()
9043 "Set tags for the current headline."
9044 (interactive)
9045 (org-agenda-check-no-diary)
9046 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
9047 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
9048 (org-agenda-error)))
9049 (buffer (marker-buffer hdmarker))
9050 (pos (marker-position hdmarker))
9051 (buffer-read-only nil)
9052 newhead)
9053 (with-current-buffer buffer
9054 (widen)
9055 (goto-char pos)
9056 (org-show-hierarchy-above 'agenda)
9057 (save-excursion
9058 (and (outline-next-heading)
9059 (org-flag-heading nil))) ; show the next heading
9060 (call-interactively 'org-set-tags)
9061 (end-of-line 1)
9062 (setq newhead (org-get-heading)))
9063 (org-agenda-change-all-lines newhead hdmarker)
9064 (beginning-of-line 1)))
9066 (defun org-agenda-date-later (arg &optional what)
9067 "Change the date of this item to one day later."
9068 (interactive "p")
9069 (org-agenda-check-type t 'agenda 'timeline)
9070 (org-agenda-check-no-diary)
9071 (let* ((marker (or (get-text-property (point) 'org-marker)
9072 (org-agenda-error)))
9073 (buffer (marker-buffer marker))
9074 (pos (marker-position marker)))
9075 (with-current-buffer buffer
9076 (widen)
9077 (goto-char pos)
9078 (if (not (org-at-timestamp-p))
9079 (error "Cannot find time stamp"))
9080 (org-timestamp-change arg (or what 'day))
9081 (message "Time stamp changed to %s" org-last-changed-timestamp))))
9083 (defun org-agenda-date-earlier (arg &optional what)
9084 "Change the date of this item to one day earlier."
9085 (interactive "p")
9086 (org-agenda-date-later (- arg) what))
9088 (defun org-agenda-date-prompt (arg)
9089 "Change the date of this item. Date is prompted for, with default today.
9090 The prefix ARG is passed to the `org-time-stamp' command and can therefore
9091 be used to request time specification in the time stamp."
9092 (interactive "P")
9093 (org-agenda-check-type t 'agenda 'timeline)
9094 (org-agenda-check-no-diary)
9095 (let* ((marker (or (get-text-property (point) 'org-marker)
9096 (org-agenda-error)))
9097 (buffer (marker-buffer marker))
9098 (pos (marker-position marker)))
9099 (with-current-buffer buffer
9100 (widen)
9101 (goto-char pos)
9102 (if (not (org-at-timestamp-p))
9103 (error "Cannot find time stamp"))
9104 (org-time-stamp arg)
9105 (message "Time stamp changed to %s" org-last-changed-timestamp))))
9107 (defun org-agenda-schedule (arg)
9108 "Schedule the item at point."
9109 (interactive "P")
9110 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
9111 (org-agenda-check-no-diary)
9112 (let* ((marker (or (get-text-property (point) 'org-marker)
9113 (org-agenda-error)))
9114 (buffer (marker-buffer marker))
9115 (pos (marker-position marker))
9116 (org-insert-labeled-timestamps-at-point nil)
9118 (with-current-buffer buffer
9119 (widen)
9120 (goto-char pos)
9121 (setq ts (org-schedule))
9122 (message "Item scheduled for %s" ts))))
9124 (defun org-agenda-deadline (arg)
9125 "Schedule the item at point."
9126 (interactive "P")
9127 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
9128 (org-agenda-check-no-diary)
9129 (let* ((marker (or (get-text-property (point) 'org-marker)
9130 (org-agenda-error)))
9131 (buffer (marker-buffer marker))
9132 (pos (marker-position marker))
9133 (org-insert-labeled-timestamps-at-point nil)
9135 (with-current-buffer buffer
9136 (widen)
9137 (goto-char pos)
9138 (setq ts (org-deadline))
9139 (message "Deadline for this item set to %s" ts))))
9141 (defun org-get-heading ()
9142 "Return the heading of the current entry, without the stars."
9143 (save-excursion
9144 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
9145 (if (and (re-search-backward "[\r\n]\\*" nil t)
9146 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
9147 (match-string 1)
9148 "")))
9150 (defun org-agenda-clock-in (&optional arg)
9151 "Start the clock on the currently selected item."
9152 (interactive "P")
9153 (org-agenda-check-no-diary)
9154 (let* ((marker (or (get-text-property (point) 'org-marker)
9155 (org-agenda-error)))
9156 (pos (marker-position marker)))
9157 (with-current-buffer (marker-buffer marker)
9158 (widen)
9159 (goto-char pos)
9160 (org-clock-in))))
9162 (defun org-agenda-diary-entry ()
9163 "Make a diary entry, like the `i' command from the calendar.
9164 All the standard commands work: block, weekly etc."
9165 (interactive)
9166 (org-agenda-check-type t 'agenda 'timeline)
9167 (require 'diary-lib)
9168 (let* ((char (progn
9169 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
9170 (read-char-exclusive)))
9171 (cmd (cdr (assoc char
9172 '((?d . insert-diary-entry)
9173 (?w . insert-weekly-diary-entry)
9174 (?m . insert-monthly-diary-entry)
9175 (?y . insert-yearly-diary-entry)
9176 (?a . insert-anniversary-diary-entry)
9177 (?b . insert-block-diary-entry)
9178 (?c . insert-cyclic-diary-entry)))))
9179 (oldf (symbol-function 'calendar-cursor-to-date))
9180 (point (point))
9181 (mark (or (mark t) (point))))
9182 (unless cmd
9183 (error "No command associated with <%c>" char))
9184 (unless (and (get-text-property point 'day)
9185 (or (not (equal ?b char))
9186 (get-text-property mark 'day)))
9187 (error "Don't know which date to use for diary entry"))
9188 ;; We implement this by hacking the `calendar-cursor-to-date' function
9189 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
9190 (let ((calendar-mark-ring
9191 (list (calendar-gregorian-from-absolute
9192 (or (get-text-property mark 'day)
9193 (get-text-property point 'day))))))
9194 (unwind-protect
9195 (progn
9196 (fset 'calendar-cursor-to-date
9197 (lambda (&optional error)
9198 (calendar-gregorian-from-absolute
9199 (get-text-property point 'day))))
9200 (call-interactively cmd))
9201 (fset 'calendar-cursor-to-date oldf)))))
9204 (defun org-agenda-execute-calendar-command (cmd)
9205 "Execute a calendar command from the agenda, with the date associated to
9206 the cursor position."
9207 (org-agenda-check-type t 'agenda 'timeline)
9208 (require 'diary-lib)
9209 (unless (get-text-property (point) 'day)
9210 (error "Don't know which date to use for calendar command"))
9211 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
9212 (point (point))
9213 (date (calendar-gregorian-from-absolute
9214 (get-text-property point 'day)))
9215 (displayed-day (extract-calendar-day date))
9216 (displayed-month (extract-calendar-month date))
9217 (displayed-year (extract-calendar-year date)))
9218 (unwind-protect
9219 (progn
9220 (fset 'calendar-cursor-to-date
9221 (lambda (&optional error)
9222 (calendar-gregorian-from-absolute
9223 (get-text-property point 'day))))
9224 (call-interactively cmd))
9225 (fset 'calendar-cursor-to-date oldf))))
9227 (defun org-agenda-phases-of-moon ()
9228 "Display the phases of the moon for the 3 months around the cursor date."
9229 (interactive)
9230 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
9232 (defun org-agenda-holidays ()
9233 "Display the holidays for the 3 months around the cursor date."
9234 (interactive)
9235 (org-agenda-execute-calendar-command 'list-calendar-holidays))
9237 (defun org-agenda-sunrise-sunset (arg)
9238 "Display sunrise and sunset for the cursor date.
9239 Latitude and longitude can be specified with the variables
9240 `calendar-latitude' and `calendar-longitude'. When called with prefix
9241 argument, latitude and longitude will be prompted for."
9242 (interactive "P")
9243 (let ((calendar-longitude (if arg nil calendar-longitude))
9244 (calendar-latitude (if arg nil calendar-latitude))
9245 (calendar-location-name
9246 (if arg "the given coordinates" calendar-location-name)))
9247 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
9249 (defun org-agenda-goto-calendar ()
9250 "Open the Emacs calendar with the date at the cursor."
9251 (interactive)
9252 (org-agenda-check-type t 'agenda 'timeline)
9253 (let* ((day (or (get-text-property (point) 'day)
9254 (error "Don't know which date to open in calendar")))
9255 (date (calendar-gregorian-from-absolute day))
9256 (calendar-move-hook nil)
9257 (view-calendar-holidays-initially nil)
9258 (view-diary-entries-initially nil))
9259 (calendar)
9260 (calendar-goto-date date)))
9262 (defun org-calendar-goto-agenda ()
9263 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
9264 This is a command that has to be installed in `calendar-mode-map'."
9265 (interactive)
9266 (org-agenda-list nil (calendar-absolute-from-gregorian
9267 (calendar-cursor-to-date))
9268 nil))
9270 (defun org-agenda-convert-date ()
9271 (interactive)
9272 (org-agenda-check-type t 'agenda 'timeline)
9273 (let ((day (get-text-property (point) 'day))
9274 date s)
9275 (unless day
9276 (error "Don't know which date to convert"))
9277 (setq date (calendar-gregorian-from-absolute day))
9278 (setq s (concat
9279 "Gregorian: " (calendar-date-string date) "\n"
9280 "ISO: " (calendar-iso-date-string date) "\n"
9281 "Day of Yr: " (calendar-day-of-year-string date) "\n"
9282 "Julian: " (calendar-julian-date-string date) "\n"
9283 "Astron. JD: " (calendar-astro-date-string date)
9284 " (Julian date number at noon UTC)\n"
9285 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
9286 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
9287 "French: " (calendar-french-date-string date) "\n"
9288 "Mayan: " (calendar-mayan-date-string date) "\n"
9289 "Coptic: " (calendar-coptic-date-string date) "\n"
9290 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
9291 "Persian: " (calendar-persian-date-string date) "\n"
9292 "Chinese: " (calendar-chinese-date-string date) "\n"))
9293 (with-output-to-temp-buffer "*Dates*"
9294 (princ s))
9295 (if (fboundp 'fit-window-to-buffer)
9296 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
9298 ;;; Tags
9300 (defun org-scan-tags (action matcher &optional todo-only)
9301 "Scan headline tags with inheritance and produce output ACTION.
9302 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
9303 evaluated, testing if a given set of tags qualifies a headline for
9304 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
9305 are included in the output."
9306 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9307 (mapconcat 'regexp-quote
9308 (nreverse (cdr (reverse org-todo-keywords)))
9309 "\\|")
9310 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
9311 (props (list 'face nil
9312 'done-face 'org-done
9313 'undone-face nil
9314 'mouse-face 'highlight
9315 'org-not-done-regexp org-not-done-regexp
9316 'keymap org-agenda-keymap
9317 'help-echo
9318 (format "mouse-2 or RET jump to org file %s"
9319 (abbreviate-file-name buffer-file-name))))
9320 lspos
9321 tags tags-list tags-alist (llast 0) rtn level category i txt
9322 todo marker)
9323 (save-excursion
9324 (goto-char (point-min))
9325 (when (eq action 'sparse-tree) (org-overview))
9326 (while (re-search-forward re nil t)
9327 (catch :skip
9328 (and (eq action 'agenda) (org-agenda-skip))
9329 (setq todo (if (match-end 1) (match-string 2))
9330 tags (if (match-end 4) (match-string 4)))
9331 (goto-char (setq lspos (1+ (match-beginning 0))))
9332 (setq level (funcall outline-level)
9333 category (org-get-category))
9334 (setq i llast llast level)
9335 ;; remove tag lists from same and sublevels
9336 (while (>= i level)
9337 (when (setq entry (assoc i tags-alist))
9338 (setq tags-alist (delete entry tags-alist)))
9339 (setq i (1- i)))
9340 ;; add the nex tags
9341 (when tags
9342 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9343 tags-alist
9344 (cons (cons level tags) tags-alist)))
9345 ;; compile tags for current headline
9346 (setq tags-list
9347 (if org-use-tag-inheritance
9348 (apply 'append (mapcar 'cdr tags-alist))
9349 tags))
9350 (when (and (or (not todo-only) todo)
9351 (eval matcher)
9352 (or (not org-agenda-skip-archived-trees)
9353 (not (member org-archive-tag tags-list))))
9354 ;; list this headline
9355 (if (eq action 'sparse-tree)
9356 (progn
9357 (org-show-hierarchy-above 'tags-tree))
9358 (setq txt (org-format-agenda-item
9360 (concat
9361 (if org-tags-match-list-sublevels
9362 (make-string (1- level) ?.) "")
9363 (org-get-heading))
9364 category tags-list))
9365 (goto-char lspos)
9366 (setq marker (org-agenda-new-marker))
9367 (org-add-props txt props
9368 'org-marker marker 'org-hd-marker marker 'category category)
9369 (push txt rtn))
9370 ;; if we are to skip sublevels, jump to end of subtree
9371 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9372 (when (and (eq action 'sparse-tree)
9373 (not org-sparse-tree-open-archived-trees))
9374 (org-hide-archived-subtrees (point-min) (point-max)))
9375 (nreverse rtn)))
9377 (defun org-tags-sparse-tree (&optional arg match)
9378 "Create a sparse tree according to tags search string MATCH.
9379 MATCH can contain positive and negative selection of tags, like
9380 \"+WORK+URGENT-WITHBOSS\"."
9381 (interactive "P")
9382 (let ((org-show-following-heading nil)
9383 (org-show-hierarchy-above nil))
9384 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
9386 ;; FIXME: remove this function.
9387 (defun org-make-tags-matcher-old (match)
9388 "Create the TAGS matcher form for the tags-selecting string MATCH."
9389 (unless match
9390 ;; Get a new match request, with completion
9391 (setq org-last-tags-completion-table
9392 (or org-tag-alist
9393 org-last-tags-completion-table))
9394 (setq match (completing-read
9395 "Tags: " 'org-tags-completion-function nil nil nil
9396 'org-tags-history)))
9397 ;; parse the string and create a lisp form
9398 (let ((match0 match) minus tag mm matcher orterms term orlist)
9399 (setq orterms (org-split-string match "|"))
9400 (while (setq term (pop orterms))
9401 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
9402 (setq minus (and (match-end 1)
9403 (equal (match-string 1 term) "-"))
9404 tag (match-string 2 term)
9405 term (substring term (match-end 0))
9406 mm (list 'member (downcase tag) 'tags-list)
9407 mm (if minus (list 'not mm) mm))
9408 (push mm matcher))
9409 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
9410 orlist)
9411 (setq matcher nil))
9412 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9413 ;; Return the string and lisp forms of the matcher
9414 (cons match0 matcher)))
9417 (defun org-make-tags-matcher (match)
9418 "Create the TAGS//TODO matcher form for the selection string MATCH."
9419 (unless match
9420 ;; Get a new match request, with completion
9421 (setq org-last-tags-completion-table
9422 (or org-tag-alist
9423 org-last-tags-completion-table))
9424 (setq match (completing-read
9425 "Match: " 'org-tags-completion-function nil nil nil
9426 'org-tags-history))) ; FIXME: SHould we have a separate history for this?
9428 ;; Parse the string and create a lisp form
9429 (let ((match0 match) minus tag mm
9430 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9431 orterms term orlist)
9432 (if (string-match "/+" match)
9433 ;; match contains also a todo-matching request
9434 (setq tagsmatch (substring match 0 (match-beginning 0))
9435 todomatch (substring match (match-end 0)))
9436 ;; only matching tags
9437 (setq tagsmatch match todomatch nil))
9439 ;; Make the tags matcher
9440 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9441 (setq tagsmatcher t)
9442 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9443 (while (setq term (pop orterms))
9444 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
9445 (setq minus (and (match-end 1)
9446 (equal (match-string 1 term) "-"))
9447 tag (match-string 2 term)
9448 term (substring term (match-end 0))
9449 mm (list 'member (downcase tag) 'tags-list)
9450 mm (if minus (list 'not mm) mm))
9451 (push mm tagsmatcher))
9452 (push (if (> (length tagsmatcher) 1)
9453 (cons 'and tagsmatcher)
9454 (car tagsmatcher))
9455 orlist)
9456 (setq tagsmatcher nil))
9457 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
9459 ;; Make the todo matcher ;; FIXME: reduce syntax richness?
9460 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9461 (setq todomatcher t)
9462 (setq orterms (org-split-string todomatch "|") orlist nil)
9463 (while (setq term (pop orterms))
9464 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
9465 (setq minus (and (match-end 1)
9466 (equal (match-string 1 term) "-"))
9467 kwd (match-string 2 term)
9468 term (substring term (match-end 0))
9469 mm (list 'equal 'todo kwd)
9470 mm (if minus (list 'not mm) mm))
9471 (push mm todomatcher))
9472 (push (if (> (length todomatcher) 1)
9473 (cons 'and todomatcher)
9474 (car todomatcher))
9475 orlist)
9476 (setq todomatcher nil))
9477 (setq todomatcher (if (> (length orlist) 1)
9478 (cons 'or orlist) (car orlist))))
9480 ;; Return the string and lisp forms of the matcher
9481 (setq matcher (if todomatcher
9482 (list 'and tagsmatcher todomatcher)
9483 tagsmatcher))
9484 (cons match0 matcher)))
9486 ;;;###autoload
9487 (defun org-tags-view (&optional todo-only match)
9488 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
9489 The prefix arg TODO-ONLY limits the search to TODO entries."
9490 (interactive "P")
9491 (org-compile-prefix-format 'tags)
9492 (org-set-sorting-strategy 'tags)
9493 (let* ((org-tags-match-list-sublevels
9494 (if todo-only t org-tags-match-list-sublevels))
9495 (win (selected-window))
9496 (completion-ignore-case t)
9497 rtn rtnall files file pos matcher
9498 buffer)
9499 (setq matcher (org-make-tags-matcher match)
9500 match (car matcher) matcher (cdr matcher))
9501 (org-prepare-agenda)
9502 (setq org-agenda-redo-command
9503 (list 'org-tags-view (list 'quote todo-only)
9504 (list 'if 'current-prefix-arg nil match)))
9505 (setq files (org-agenda-files)
9506 rtnall nil)
9507 (while (setq file (pop files))
9508 (catch 'nextfile
9509 (org-check-agenda-file file)
9510 (setq buffer (if (file-exists-p file)
9511 (org-get-agenda-file-buffer file)
9512 (error "No such file %s" file)))
9513 (if (not buffer)
9514 ;; If file does not exist, merror message to agenda
9515 (setq rtn (list
9516 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
9517 rtnall (append rtnall rtn))
9518 (with-current-buffer buffer
9519 (unless (org-mode-p)
9520 (error "Agenda file %s is not in `org-mode'" file))
9521 (setq org-category-table (org-get-category-table))
9522 (save-excursion
9523 (save-restriction
9524 (if org-agenda-restrict
9525 (narrow-to-region org-agenda-restrict-begin
9526 org-agenda-restrict-end)
9527 (widen))
9528 (setq rtn (org-scan-tags 'agenda matcher todo-only))
9529 (setq rtnall (append rtnall rtn))))))))
9530 (insert "Headlines with TAGS match: ")
9531 (add-text-properties (point-min) (1- (point))
9532 (list 'face 'org-level-3))
9533 (setq pos (point))
9534 (insert match "\n")
9535 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
9536 (setq pos (point))
9537 (unless org-agenda-multi
9538 (insert "Press `C-u r' to search again with new search string\n"))
9539 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
9540 (when rtnall
9541 (insert (org-finalize-agenda-entries rtnall) "\n"))
9542 (goto-char (point-min))
9543 (org-fit-agenda-window)
9544 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
9545 (org-finalize-agenda)
9546 (setq buffer-read-only t)
9547 (if (not org-select-agenda-window) (select-window win))))
9549 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9550 (defun org-set-tags (&optional arg just-align)
9551 "Set the tags for the current headline.
9552 With prefix ARG, realign all tags in headings in the current buffer."
9553 (interactive "P")
9554 (let* ((re (concat "^" outline-regexp))
9555 (col (current-column))
9556 (current (org-get-tags))
9557 table current-tags inherited-tags ; computed below when needed
9558 tags empty invis)
9559 (if arg
9560 (save-excursion
9561 (goto-char (point-min))
9562 (let (buffer-invisibility-spec) ; Emacs 21 compatibility
9563 (while (re-search-forward re nil t)
9564 (org-set-tags nil t)))
9565 (message "All tags realigned to column %d" org-tags-column))
9566 (if just-align
9567 (setq tags current)
9568 (setq table (or org-tag-alist (org-get-buffer-tags))
9569 org-last-tags-completion-table table
9570 current-tags (org-split-string current ":")
9571 inherited-tags (nreverse
9572 (nthcdr (length current-tags)
9573 (nreverse (org-get-tags-at))))
9574 tags
9575 (if (or (eq t org-use-fast-tag-selection)
9576 (and org-use-fast-tag-selection
9577 (delq nil (mapcar 'cdr table))))
9578 (org-fast-tag-selection current-tags inherited-tags table)
9579 (let ((org-add-colon-after-tag-completion t))
9580 (completing-read "Tags: " 'org-tags-completion-function
9581 nil nil current 'org-tags-history))))
9582 (while (string-match "[-+&]+" tags)
9583 (setq tags (replace-match ":" t t tags))))
9584 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
9585 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9586 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9587 (if (equal current "")
9588 (progn
9589 (end-of-line 1)
9590 (or empty (insert " ")))
9591 (beginning-of-line 1)
9592 (setq invis (org-invisible-p))
9593 (looking-at (concat ".*?\\([ \t]*" (regexp-quote current) "\\)[ \t]*"))
9594 (delete-region (match-beginning 1) (match-end 1))
9595 (goto-char (match-beginning 1))
9596 (insert (if empty "" " ")))
9597 (if (equal tags "")
9598 (save-excursion
9599 (beginning-of-line 1)
9600 (skip-chars-forward "*")
9601 (if (= (char-after) ?\ ) (forward-char 1))
9602 (and (re-search-forward "[ \t]+$" (point-at-eol) t)
9603 (replace-match "")))
9604 (let (buffer-invisibility-spec) ; Emacs 21 compatibility
9605 (move-to-column (max (current-column)
9606 (if (> org-tags-column 0)
9607 org-tags-column
9608 (- (- org-tags-column) (length tags))))
9610 (insert tags)
9611 (if (and (not invis) (org-invisible-p))
9612 (outline-flag-region (point) (point-at-bol) nil))) ; show
9613 (move-to-column col))))
9615 (defun org-tags-completion-function (string predicate &optional flag)
9616 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9617 (confirm (lambda (x) (stringp (car x)))))
9618 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9619 (setq s1 (match-string 1 string)
9620 s2 (match-string 2 string))
9621 (setq s1 "" s2 string))
9622 (cond
9623 ((eq flag nil)
9624 ;; try completion
9625 (setq rtn (try-completion s2 ctable confirm))
9626 (if (stringp rtn)
9627 (concat s1 s2 (substring rtn (length s2))
9628 (if (and org-add-colon-after-tag-completion
9629 (assoc rtn ctable))
9630 ":" "")))
9632 ((eq flag t)
9633 ;; all-completions
9634 (all-completions s2 ctable confirm)
9636 ((eq flag 'lambda)
9637 ;; exact match?
9638 (assoc s2 ctable)))
9641 (defun org-fast-tag-insert (kwd tags face &optional end)
9642 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9643 (insert (format "%-12s" (concat kwd ":"))
9644 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9645 (or end "")))
9647 (defun org-fast-tag-selection (current inherited table)
9648 "Fast tag selection with single keys.
9649 CURRENT is the current list of tags in the headline, INHERITED is the
9650 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9651 possibly with grouping information.
9652 If the keys are nil, a-z are automatically assigned.
9653 Returns the new tags string, or nil to not change the current settings."
9654 (let* ((maxlen (apply 'max (mapcar
9655 (lambda (x)
9656 (if (stringp (car x)) (string-width (car x)) 0))
9657 table)))
9658 (buf (current-buffer))
9659 (buffer-tags nil)
9660 (fwidth (+ maxlen 3 1 3))
9661 (ncol (/ (- (window-width) 4) fwidth))
9662 (i-face 'org-done)
9663 (c-face 'org-tag)
9664 tg cnt e c char c1 c2 ntable tbl rtn
9665 groups ingroup)
9666 (save-window-excursion
9667 (delete-other-windows)
9668 (split-window-vertically)
9669 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
9670 (erase-buffer)
9671 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9672 (org-fast-tag-insert "Current" current c-face "\n\n")
9673 (setq tbl table char ?a cnt 0)
9674 (while (setq e (pop tbl))
9675 (cond
9676 ((equal e '(:startgroup))
9677 (push '() groups) (setq ingroup t)
9678 (when (not (= cnt 0))
9679 (setq cnt 0)
9680 (insert "\n"))
9681 (insert "{ "))
9682 ((equal e '(:endgroup))
9683 (setq ingroup nil cnt 0)
9684 (insert "}\n"))
9686 (setq tg (car e) c2 nil)
9687 (if (cdr e)
9688 (setq c (cdr e))
9689 ;; automatically assign a character.
9690 (setq c1 (string-to-char
9691 (downcase (substring
9692 tg (if (= (string-to-char tg) ?@) 1 0)))))
9693 (if (or (rassoc c1 ntable) (rassoc c1 table))
9694 (while (or (rassoc char ntable) (rassoc char table))
9695 (setq char (1+ char)))
9696 (setq c2 c1))
9697 (setq c (or c2 char)))
9698 (if ingroup (push tg (car groups)))
9699 (setq tg (org-add-props tg nil 'face
9700 (cond
9701 ((member tg current) c-face)
9702 ((member tg inherited) i-face)
9703 (t nil))))
9704 (if (and (= cnt 0) (not ingroup)) (insert " "))
9705 (insert "[" c "] " tg (make-string
9706 (- fwidth 4 (length tg)) ?\ ))
9707 (push (cons tg c) ntable)
9708 (when (= (setq cnt (1+ cnt)) ncol)
9709 (insert "\n")
9710 (if ingroup (insert " "))
9711 (setq cnt 0)))))
9712 (setq ntable (nreverse ntable))
9713 (insert "\n")
9714 (goto-char (point-min))
9715 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
9716 (setq rtn
9717 (catch 'exit
9718 (while t
9719 (message "[a-z..]:Toggle [SPC] clear [RET] accept [TAB] free tag%s"
9720 (if groups " [!] no goups" ""))
9721 (setq c (read-char-exclusive))
9722 (cond
9723 ((= c ?\r) (throw 'exit t))
9724 ((= c ?!)
9725 (setq groups nil)
9726 (goto-char (point-min))
9727 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9728 ((or (= c ?\C-g)
9729 (and (= c ?q) (not (rassoc c ntable))))
9730 (setq quit-flag t))
9731 ((= c ?\ ) (setq current nil))
9732 ((= c ?\t)
9733 (condition-case nil
9734 (setq tg (completing-read
9735 "Tag: "
9736 (or buffer-tags
9737 (with-current-buffer buf
9738 (org-get-buffer-tags)))))
9739 (quit (setq tg "")))
9740 (when (string-match "\\S-" tg)
9741 (add-to-list 'buffer-tags (list tg))
9742 (if (member tg current)
9743 (setq current (delete tg current))
9744 (push tg current))))
9745 ((setq e (rassoc c ntable) tg (car e))
9746 (if (member tg current)
9747 (setq current (delete tg current))
9748 (loop for g in groups do
9749 (if (member tg g)
9750 (mapcar (lambda (x)
9751 (setq current (delete x current)))
9752 g)))
9753 (push tg current))))
9754 ;; Create a sorted list
9755 (setq current
9756 (sort current
9757 (lambda (a b)
9758 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9759 (goto-char (point-min))
9760 (beginning-of-line 2)
9761 (delete-region (point) (point-at-eol))
9762 (org-fast-tag-insert "Current" current c-face)
9763 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
9764 (setq tg (match-string 1))
9765 (add-text-properties (match-beginning 1) (match-end 1)
9766 (list 'face
9767 (cond
9768 ((member tg current) c-face)
9769 ((member tg inherited) i-face)
9770 (t nil)))))
9771 (goto-char (point-min)))))
9772 (if rtn
9773 (mapconcat 'identity current ":")
9774 nil))))
9776 (defun org-get-tags ()
9777 "Get the TAGS string in the current headline."
9778 (unless (org-on-heading-p t)
9779 (error "Not on a heading"))
9780 (save-excursion
9781 (beginning-of-line 1)
9782 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
9783 (org-match-string-no-properties 1)
9784 "")))
9786 (defun org-get-buffer-tags ()
9787 "Get a table of all tags used in the buffer, for completion."
9788 (let (tags)
9789 (save-excursion
9790 (goto-char (point-min))
9791 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
9792 (mapc (lambda (x) (add-to-list 'tags x))
9793 (org-split-string (org-match-string-no-properties 1) ":"))))
9794 (mapcar 'list tags)))
9796 ;;; Link Stuff
9798 (defvar org-create-file-search-functions nil
9799 "List of functions to construct the right search string for a file link.
9800 These functions are called in turn with point at the location to
9801 which the link should point.
9803 A function in the hook should first test if it would like to
9804 handle this file type, for example by checking the major-mode or
9805 the file extension. If it decides not to handle this file, it
9806 should just return nil to give other functions a chance. If it
9807 does handle the file, it must return the search string to be used
9808 when following the link. The search string will be part of the
9809 file link, given after a double colon, and `org-open-at-point'
9810 will automatically search for it. If special measures must be
9811 taken to make the search successful, another function should be
9812 added to the companion hook `org-execute-file-search-functions',
9813 which see.
9815 A function in this hook may also use `setq' to set the variable
9816 `description' to provide a suggestion for the descriptive text to
9817 be used for this link when it gets inserted into an Org-mode
9818 buffer with \\[org-insert-link].")
9820 (defvar org-execute-file-search-functions nil
9821 "List of functions to execute a file search triggered by a link.
9823 Functions added to this hook must accept a single argument, the
9824 search string that was part of the file link, the part after the
9825 double colon. The function must first check if it would like to
9826 handle this search, for example by checking the major-mode or the
9827 file extension. If it decides not to handle this search, it
9828 should just return nil to give other functions a chance. If it
9829 does handle the search, it must return a non-nil value to keep
9830 other functions from trying.
9832 Each function can access the current prefix argument through the
9833 variable `current-prefix-argument'. Note that a single prefix is
9834 used to force opening a link in Emacs, so it may be good to only
9835 use a numeric or double prefix to guide the search function.
9837 In case this is needed, a function in this hook can also restore
9838 the window configuration before `org-open-at-point' was called using:
9840 (set-window-configuration org-window-config-before-follow-link)")
9842 (defun org-find-file-at-mouse (ev)
9843 "Open file link or URL at mouse."
9844 (interactive "e")
9845 (mouse-set-point ev)
9846 (org-open-at-point 'in-emacs))
9848 (defun org-open-at-mouse (ev)
9849 "Open file link or URL at mouse."
9850 (interactive "e")
9851 (mouse-set-point ev)
9852 (org-open-at-point))
9854 (defvar org-window-config-before-follow-link nil
9855 "The window configuration before following a link.
9856 This is saved in case the need arises to restore it.")
9858 ;; FIXME: IN-EMACS is used for many purposes, maybe rename this argument???
9859 (defun org-open-at-point (&optional in-emacs)
9860 "Open link at or after point.
9861 If there is no link at point, this function will search forward up to
9862 the end of the current subtree.
9863 Normally, files will be opened by an appropriate application. If the
9864 optional argument IN-EMACS is non-nil, Emacs will visit the file."
9865 (interactive "P")
9866 (setq org-window-config-before-follow-link (current-window-configuration))
9867 (org-remove-occur-highlights nil nil t)
9868 (if (org-at-timestamp-p t)
9869 (org-follow-timestamp-link)
9870 (let (type path link line search (pos (point)))
9871 (catch 'match
9872 (save-excursion
9873 (skip-chars-forward "^]\n\r")
9874 (when (and (re-search-backward "\\[\\[" nil t)
9875 (looking-at org-bracket-link-regexp)
9876 (<= (match-beginning 0) pos)
9877 (>= (match-end 0) pos))
9878 (setq link (org-link-unescape (org-match-string-no-properties 1)))
9879 (while (string-match " *\n *" link)
9880 (setq link (replace-match " " t t link)))
9881 (setq link (org-link-expand-abbrev link))
9882 (if (string-match org-link-re-with-space2 link)
9883 (setq type (match-string 1 link)
9884 path (match-string 2 link))
9885 (setq type "thisfile"
9886 path link))
9887 (throw 'match t)))
9889 (when (get-text-property (point) 'org-linked-text)
9890 (setq type "thisfile"
9891 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9892 (1+ (point)) (point))
9893 path (buffer-substring
9894 (previous-single-property-change pos 'org-linked-text)
9895 (next-single-property-change pos 'org-linked-text)))
9896 (throw 'match t))
9898 (save-excursion
9899 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
9900 (if (equal (char-before) ?<) (backward-char 1))
9901 (when (or (looking-at org-angle-link-re)
9902 (looking-at org-plain-link-re)
9903 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
9904 (re-search-forward org-plain-link-re (point-at-eol) t))
9905 (<= (match-beginning 0) pos)
9906 (>= (match-end 0) pos)))
9907 (setq type (match-string 1)
9908 path (match-string 2))
9909 (throw 'match t)))
9910 (save-excursion
9911 (skip-chars-backward "^ \t\n\r")
9912 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9913 (setq type "tags"
9914 path (match-string 1))
9915 (while (string-match ":" path)
9916 (setq path (replace-match "+" t t path)))
9917 (throw 'match t)))
9918 (save-excursion
9919 (skip-chars-backward "a-zA-Z_")
9920 (when (and (memq 'camel org-activate-links)
9921 (looking-at org-camel-regexp))
9922 (setq type "camel" path (match-string 0))
9923 (if (equal (char-before) ?*)
9924 (setq path (concat "*" path))))
9925 (throw 'match t)))
9926 (unless path
9927 (error "No link found"))
9928 ;; Remove any trailing spaces in path
9929 (if (string-match " +\\'" path)
9930 (setq path (replace-match "" t t path)))
9932 (cond
9934 ((equal type "mailto")
9935 (let ((cmd (car org-link-mailto-program))
9936 (args (cdr org-link-mailto-program)) args1
9937 (address path) (subject "") a)
9938 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9939 (setq address (match-string 1 path)
9940 subject (org-link-escape (match-string 2 path))))
9941 (while args
9942 (cond
9943 ((not (stringp (car args))) (push (pop args) args1))
9944 (t (setq a (pop args))
9945 (if (string-match "%a" a)
9946 (setq a (replace-match address t t a)))
9947 (if (string-match "%s" a)
9948 (setq a (replace-match subject t t a)))
9949 (push a args1))))
9950 (apply cmd (nreverse args1))))
9952 ((member type '("http" "https" "ftp" "news"))
9953 (browse-url (concat type ":" path)))
9955 ((string= type "tags")
9956 (org-tags-view in-emacs path))
9957 ((or (string= type "camel")
9958 (string= type "thisfile"))
9959 (if in-emacs
9960 (switch-to-buffer-other-window
9961 (org-get-buffer-for-internal-link (current-buffer)))
9962 (org-mark-ring-push))
9963 (org-link-search
9964 path
9965 (cond ((equal in-emacs '(4)) 'occur)
9966 ((equal in-emacs '(16)) 'org-occur)
9967 (t nil))))
9969 ((string= type "file")
9970 (if (string-match "::\\([0-9]+\\)\\'" path)
9971 (setq line (string-to-number (match-string 1 path))
9972 path (substring path 0 (match-beginning 0)))
9973 (if (string-match "::\\(.+\\)\\'" path)
9974 (setq search (match-string 1 path)
9975 path (substring path 0 (match-beginning 0)))))
9976 (org-open-file path in-emacs line search))
9978 ((string= type "news")
9979 (org-follow-gnus-link path))
9981 ((string= type "bbdb")
9982 (org-follow-bbdb-link path))
9984 ((string= type "info")
9985 (org-follow-info-link path))
9987 ((string= type "gnus")
9988 (let (group article)
9989 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9990 (error "Error in Gnus link"))
9991 (setq group (match-string 1 path)
9992 article (match-string 3 path))
9993 (org-follow-gnus-link group article)))
9995 ((string= type "vm")
9996 (let (folder article)
9997 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9998 (error "Error in VM link"))
9999 (setq folder (match-string 1 path)
10000 article (match-string 3 path))
10001 ;; in-emacs is the prefix arg, will be interpreted as read-only
10002 (org-follow-vm-link folder article in-emacs)))
10004 ((string= type "wl")
10005 (let (folder article)
10006 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10007 (error "Error in Wanderlust link"))
10008 (setq folder (match-string 1 path)
10009 article (match-string 3 path))
10010 (org-follow-wl-link folder article)))
10012 ((string= type "mhe")
10013 (let (folder article)
10014 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10015 (error "Error in MHE link"))
10016 (setq folder (match-string 1 path)
10017 article (match-string 3 path))
10018 (org-follow-mhe-link folder article)))
10020 ((string= type "rmail")
10021 (let (folder article)
10022 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10023 (error "Error in RMAIL link"))
10024 (setq folder (match-string 1 path)
10025 article (match-string 3 path))
10026 (org-follow-rmail-link folder article)))
10028 ((string= type "shell")
10029 (let ((cmd path))
10030 (while (string-match "@{" cmd) ; FIXME: not needed for [[]] links
10031 (setq cmd (replace-match "<" t t cmd)))
10032 (while (string-match "@}" cmd) ; FIXME: not needed for [[]] links
10033 (setq cmd (replace-match ">" t t cmd)))
10034 (if (or (not org-confirm-shell-link-function)
10035 (funcall org-confirm-shell-link-function
10036 (format "Execute \"%s\" in shell? "
10037 (org-add-props cmd nil
10038 'face 'org-warning))))
10039 (progn
10040 (message "Executing %s" cmd)
10041 (shell-command cmd))
10042 (error "Abort"))))
10044 ((string= type "elisp")
10045 (let ((cmd path))
10046 (if (or (not org-confirm-elisp-link-function)
10047 (funcall org-confirm-elisp-link-function
10048 (format "Execute \"%s\" as elisp? "
10049 (org-add-props cmd nil
10050 'face 'org-warning))))
10051 (message "%s => %s" cmd (eval (read cmd)))
10052 (error "Abort"))))
10055 (browse-url-at-point))))))
10057 (defun org-link-expand-abbrev (link)
10058 "Apply replacements as defined in `org-link-abbrev-alist."
10059 (if (string-match "^\\([a-zA-Z]+\\)\\(::\\(.*\\)\\)?$" link)
10060 (let* ((key (match-string 1 link))
10061 (as (or (assoc key org-link-abbrev-alist-local)
10062 (assoc key org-link-abbrev-alist)))
10063 (tag (and (match-end 2) (match-string 3 link)))
10064 rpl)
10065 (if (not as)
10066 link
10067 (setq rpl (cdr as))
10068 (cond
10069 ((symbolp rpl) (funcall rpl tag))
10070 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
10071 (t (concat rpl tag)))))
10072 link))
10074 (defun org-link-search (s &optional type)
10075 "Search for a link search option.
10076 When S is a CamelCaseWord, search for a target, or for a sentence containing
10077 the words. If S is surrounded by forward slashes, it is interpreted as a
10078 regular expression. In org-mode files, this will create an `org-occur'
10079 sparse tree. In ordinary files, `occur' will be used to list matches.
10080 If the current buffer is in `dired-mode', grep will be used to search
10081 in all files."
10082 (let ((case-fold-search t)
10083 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10084 (pos (point))
10085 (pre "") (post "")
10086 words re0 re1 re2 re3 re4 re5 re2a reall camel)
10087 (cond
10088 ;; First check if there are any special
10089 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10090 ;; Now try the builtin stuff
10091 ((save-excursion
10092 (goto-char (point-min))
10093 (and
10094 (re-search-forward
10095 (concat "<<" (regexp-quote s0) ">>") nil t)
10096 (setq pos (match-beginning 0))))
10097 ;; There is an exact target for this
10098 (goto-char pos))
10099 ((string-match "^/\\(.*\\)/$" s)
10100 ;; A regular expression
10101 (cond
10102 ((org-mode-p)
10103 (org-occur (match-string 1 s)))
10104 ;;((eq major-mode 'dired-mode)
10105 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10106 (t (org-do-occur (match-string 1 s)))))
10107 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
10109 ;; A camel or a normal search string
10110 (when (equal (string-to-char s) ?*)
10111 ;; Anchor on headlines, post may include tags.
10112 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
10113 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
10114 s (substring s 1)))
10115 (remove-text-properties
10116 0 (length s)
10117 '(face nil mouse-face nil keymap nil fontified nil) s)
10118 ;; Make a series of regular expressions to find a match
10119 (setq words
10120 (if camel
10121 (org-camel-to-words s)
10122 (org-split-string s "[ \n\r\t]+"))
10123 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10124 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
10125 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10126 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10127 re1 (concat pre re2 post)
10128 re3 (concat pre re4 post)
10129 re5 (concat pre ".*" re4)
10130 re2 (concat pre re2)
10131 re2a (concat pre re2a)
10132 re4 (concat pre re4)
10133 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10134 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10135 re5 "\\)"
10137 (cond
10138 ((eq type 'org-occur) (org-occur reall))
10139 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10140 (t (goto-char (point-min))
10141 (if (or (org-search-not-link re0 nil t)
10142 (org-search-not-link re1 nil t)
10143 (org-search-not-link re2 nil t)
10144 (org-search-not-link re2a nil t)
10145 (org-search-not-link re3 nil t)
10146 (org-search-not-link re4 nil t)
10147 (org-search-not-link re5 nil t)
10149 (goto-char (match-beginning 1))
10150 (goto-char pos)
10151 (error "No match")))))
10153 ;; Normal string-search
10154 (goto-char (point-min))
10155 (if (search-forward s nil t)
10156 (goto-char (match-beginning 0))
10157 (error "No match"))))
10158 (and (org-mode-p) (org-show-hierarchy-above 'link-search))))
10160 (defun org-search-not-link (&rest args)
10161 "Execute `re-search-forward', but only accept matches that are not a link."
10162 (catch 'exit
10163 (let (p1)
10164 (while (apply 're-search-forward args)
10165 (setq p1 (point))
10166 (if (not (save-match-data
10167 (and (re-search-backward "\\[\\[" nil t)
10168 (looking-at org-bracket-link-regexp)
10169 (<= (match-beginning 0) p1)
10170 (>= (match-end 0) p1))))
10171 (progn (goto-char (match-end 0))
10172 (throw 'exit (point)))
10173 (goto-char (match-end 0)))))))
10175 (defun org-get-buffer-for-internal-link (buffer)
10176 "Return a buffer to be used for displaying the link target of internal links."
10177 (cond
10178 ((not org-display-internal-link-with-indirect-buffer)
10179 buffer)
10180 ((string-match "(Clone)$" (buffer-name buffer))
10181 (message "Buffer is already a clone, not making another one")
10182 ;; we also do not modify visibility in this case
10183 buffer)
10184 (t ; make a new indirect buffer for displaying the link
10185 (let* ((bn (buffer-name buffer))
10186 (ibn (concat bn "(Clone)"))
10187 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10188 (with-current-buffer ib (org-overview))
10189 ib))))
10191 (defun org-do-occur (regexp &optional cleanup)
10192 "Call the Emacs command `occur'.
10193 If CLEANUP is non-nil, remove the printout of the regular expression
10194 in the *Occur* buffer. This is useful if the regex is long and not useful
10195 to read."
10196 (occur regexp)
10197 (when cleanup
10198 (let ((cwin (selected-window)) win beg end)
10199 (when (setq win (get-buffer-window "*Occur*"))
10200 (select-window win))
10201 (goto-char (point-min))
10202 (when (re-search-forward "match[a-z]+" nil t)
10203 (setq beg (match-end 0))
10204 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10205 (setq end (1- (match-beginning 0)))))
10206 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
10207 (goto-char (point-min))
10208 (select-window cwin))))
10210 (defvar org-mark-ring nil
10211 "Mark ring for positions before jumps in Org-mode.")
10212 (defvar org-mark-ring-last-goto nil
10213 "Last position in the mark ring used to go back.")
10214 ;; Fill and close the ring
10215 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10216 (loop for i from 1 to org-mark-ring-length do
10217 (push (make-marker) org-mark-ring))
10218 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10219 org-mark-ring)
10221 (defun org-mark-ring-push (&optional pos buffer)
10222 "Put the current position or POS into the mark ring and rotate it."
10223 (interactive)
10224 (setq pos (or pos (point)))
10225 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10226 (move-marker (car org-mark-ring)
10227 (or pos (point))
10228 (or buffer (current-buffer)))
10229 (message
10230 (substitute-command-keys
10231 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10233 (defun org-mark-ring-goto (&optional n)
10234 "Jump to the previous position in the mark ring.
10235 With prefix arg N, jump back that many stored positions. When
10236 called several times in succession, walk through the entire ring.
10237 Org-mode commands jumping to a different position in the current file,
10238 or to another Org-mode file, automatically push the old position
10239 onto the ring."
10240 (interactive "p")
10241 (let (p m)
10242 (if (eq last-command this-command)
10243 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10244 (setq p org-mark-ring))
10245 (setq org-mark-ring-last-goto p)
10246 (setq m (car p))
10247 (switch-to-buffer (marker-buffer m))
10248 (goto-char m)
10249 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above 'mark-goto))))
10251 (defun org-camel-to-words (s)
10252 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
10253 (let ((case-fold-search nil)
10254 words)
10255 (while (string-match "[a-z][A-Z]" s)
10256 (push (substring s 0 (1+ (match-beginning 0))) words)
10257 (setq s (substring s (1+ (match-beginning 0)))))
10258 (nreverse (cons s words))))
10260 (defun org-remove-angle-brackets (s)
10261 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10262 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10264 (defun org-add-angle-brackets (s)
10265 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10266 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10269 (defun org-follow-timestamp-link ()
10270 (cond
10271 ((org-at-date-range-p t)
10272 (let ((org-agenda-start-on-weekday)
10273 (t1 (match-string 1))
10274 (t2 (match-string 2)))
10275 (setq t1 (time-to-days (org-time-string-to-time t1))
10276 t2 (time-to-days (org-time-string-to-time t2)))
10277 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10278 ((org-at-timestamp-p t)
10279 (org-agenda-list nil (time-to-days (org-time-string-to-time
10280 (substring (match-string 1) 0 10)))
10282 (t (error "This should not happen"))))
10285 (defun org-follow-bbdb-link (name)
10286 "Follow a BBDB link to NAME."
10287 (require 'bbdb)
10288 (let ((inhibit-redisplay t)
10289 (bbdb-electric-p nil))
10290 (catch 'exit
10291 ;; Exact match on name
10292 (bbdb-name (concat "\\`" name "\\'") nil)
10293 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10294 ;; Exact match on name
10295 (bbdb-company (concat "\\`" name "\\'") nil)
10296 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10297 ;; Partial match on name
10298 (bbdb-name name nil)
10299 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10300 ;; Partial match on company
10301 (bbdb-company name nil)
10302 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10303 ;; General match including network address and notes
10304 (bbdb name nil)
10305 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
10306 (delete-window (get-buffer-window "*BBDB*"))
10307 (error "No matching BBDB record")))))
10310 (defun org-follow-info-link (name)
10311 "Follow an info file & node link to NAME."
10312 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
10313 (string-match "\\(.*\\)" name))
10314 (progn
10315 (require 'info)
10316 (if (match-string 2 name) ; If there isn't a node, choose "Top"
10317 (Info-find-node (match-string 1 name) (match-string 2 name))
10318 (Info-find-node (match-string 1 name) "Top")))
10319 (message (concat "Could not open: " name))))
10321 (defun org-follow-gnus-link (&optional group article)
10322 "Follow a Gnus link to GROUP and ARTICLE."
10323 (require 'gnus)
10324 (funcall (cdr (assq 'gnus org-link-frame-setup)))
10325 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
10326 (if group (gnus-fetch-group group))
10327 (if article
10328 (or (gnus-summary-goto-article article nil 'force)
10329 (if (fboundp 'gnus-summary-insert-cached-articles)
10330 (progn
10331 (gnus-summary-insert-cached-articles)
10332 (gnus-summary-goto-article article nil 'force))
10333 (message "Message could not be found.")))))
10335 (defun org-follow-vm-link (&optional folder article readonly)
10336 "Follow a VM link to FOLDER and ARTICLE."
10337 (require 'vm)
10338 (setq article (org-add-angle-brackets article))
10339 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
10340 ;; ange-ftp or efs or tramp access
10341 (let ((user (or (match-string 1 folder) (user-login-name)))
10342 (host (match-string 2 folder))
10343 (file (match-string 3 folder)))
10344 (cond
10345 ((featurep 'tramp)
10346 ;; use tramp to access the file
10347 (if (featurep 'xemacs)
10348 (setq folder (format "[%s@%s]%s" user host file))
10349 (setq folder (format "/%s@%s:%s" user host file))))
10351 ;; use ange-ftp or efs
10352 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
10353 (setq folder (format "/%s@%s:%s" user host file))))))
10354 (when folder
10355 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
10356 (sit-for 0.1)
10357 (when article
10358 (vm-select-folder-buffer)
10359 (widen)
10360 (let ((case-fold-search t))
10361 (goto-char (point-min))
10362 (if (not (re-search-forward
10363 (concat "^" "message-id: *" (regexp-quote article))))
10364 (error "Could not find the specified message in this folder"))
10365 (vm-isearch-update)
10366 (vm-isearch-narrow)
10367 (vm-beginning-of-message)
10368 (vm-summarize)))))
10370 (defun org-follow-wl-link (folder article)
10371 "Follow a Wanderlust link to FOLDER and ARTICLE."
10372 (setq article (org-add-angle-brackets article))
10373 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
10374 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
10375 (wl-summary-redisplay))
10377 (defun org-follow-rmail-link (folder article)
10378 "Follow an RMAIL link to FOLDER and ARTICLE."
10379 (setq article (org-add-angle-brackets article))
10380 (let (message-number)
10381 (save-excursion
10382 (save-window-excursion
10383 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10384 (setq message-number
10385 (save-restriction
10386 (widen)
10387 (goto-char (point-max))
10388 (if (re-search-backward
10389 (concat "^Message-ID:\\s-+" (regexp-quote
10390 (or article "")))
10391 nil t)
10392 (rmail-what-message))))))
10393 (if message-number
10394 (progn
10395 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10396 (rmail-show-message message-number)
10397 message-number)
10398 (error "Message not found"))))
10400 ;; mh-e integration based on planner-mode
10401 (defun org-mhe-get-message-real-folder ()
10402 "Return the name of the current message real folder, so if you use
10403 sequences, it will now work."
10404 (save-excursion
10405 (let* ((folder
10406 (if (equal major-mode 'mh-folder-mode)
10407 mh-current-folder
10408 ;; Refer to the show buffer
10409 mh-show-folder-buffer))
10410 (end-index
10411 (if (boundp 'mh-index-folder)
10412 (min (length mh-index-folder) (length folder))))
10414 ;; a simple test on mh-index-data does not work, because
10415 ;; mh-index-data is always nil in a show buffer.
10416 (if (and (boundp 'mh-index-folder)
10417 (string= mh-index-folder (substring folder 0 end-index)))
10418 (if (equal major-mode 'mh-show-mode)
10419 (save-window-excursion
10420 (when (buffer-live-p (get-buffer folder))
10421 (progn
10422 (pop-to-buffer folder)
10423 (org-mhe-get-message-folder-from-index)
10426 (org-mhe-get-message-folder-from-index)
10428 folder
10432 (defun org-mhe-get-message-folder-from-index ()
10433 "Returns the name of the message folder in a index folder buffer."
10434 (save-excursion
10435 (mh-index-previous-folder)
10436 (re-search-forward "^\\(+.*\\)$" nil t)
10437 (message (match-string 1))))
10439 (defun org-mhe-get-message-folder ()
10440 "Return the name of the current message folder. Be careful if you
10441 use sequences."
10442 (save-excursion
10443 (if (equal major-mode 'mh-folder-mode)
10444 mh-current-folder
10445 ;; Refer to the show buffer
10446 mh-show-folder-buffer)))
10448 (defun org-mhe-get-message-num ()
10449 "Return the number of the current message. Be careful if you
10450 use sequences."
10451 (save-excursion
10452 (if (equal major-mode 'mh-folder-mode)
10453 (mh-get-msg-num nil)
10454 ;; Refer to the show buffer
10455 (mh-show-buffer-message-number))))
10457 (defun org-mhe-get-header (header)
10458 "Return a header of the message in folder mode. This will create a
10459 show buffer for the corresponding message. If you have a more clever
10460 idea..."
10461 (let* ((folder (org-mhe-get-message-folder))
10462 (num (org-mhe-get-message-num))
10463 (buffer (get-buffer-create (concat "show-" folder)))
10464 (header-field))
10465 (with-current-buffer buffer
10466 (mh-display-msg num folder)
10467 (if (equal major-mode 'mh-folder-mode)
10468 (mh-header-display)
10469 (mh-show-header-display))
10470 (set-buffer buffer)
10471 (setq header-field (mh-get-header-field header))
10472 (if (equal major-mode 'mh-folder-mode)
10473 (mh-show)
10474 (mh-show-show))
10475 header-field)))
10477 (defun org-follow-mhe-link (folder article)
10478 "Follow an MHE link to FOLDER and ARTICLE.
10479 If ARTICLE is nil FOLDER is shown. If the configuration variable
10480 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
10481 ARTICLE is searched in all folders. Indexed searches (swish++,
10482 namazu, and others supported by MH-E) will always search in all
10483 folders."
10484 (require 'mh-e)
10485 (require 'mh-search)
10486 (require 'mh-utils)
10487 (mh-find-path)
10488 (if (not article)
10489 (mh-visit-folder (mh-normalize-folder-name folder))
10490 (setq article (org-add-angle-brackets article))
10491 (mh-search-choose)
10492 (if (equal mh-searcher 'pick)
10493 (progn
10494 (mh-search folder (list "--message-id" article))
10495 (when (and org-mhe-search-all-folders
10496 (not (org-mhe-get-message-real-folder)))
10497 (kill-this-buffer)
10498 (mh-search "+" (list "--message-id" article))))
10499 (mh-search "+" article))
10500 (if (org-mhe-get-message-real-folder)
10501 (mh-show-msg 1)
10502 (kill-this-buffer)
10503 (error "Message not found"))))
10505 ;; BibTeX links
10507 ;; Use the custom search meachnism to construct and use search strings for
10508 ;; file links to BibTeX database entries.
10510 (defun org-create-file-search-in-bibtex ()
10511 "Create the search string and description for a BibTeX database entry."
10512 (when (eq major-mode 'bibtex-mode)
10513 ;; yes, we want to construct this search string.
10514 ;; Make a good description for this entry, using names, year and the title
10515 ;; Put it into the `description' variable which is dynamically scoped.
10516 (let ((bibtex-autokey-names 1)
10517 (bibtex-autokey-names-stretch 1)
10518 (bibtex-autokey-name-case-convert-function 'identity)
10519 (bibtex-autokey-name-separator " & ")
10520 (bibtex-autokey-additional-names " et al.")
10521 (bibtex-autokey-year-length 4)
10522 (bibtex-autokey-name-year-separator " ")
10523 (bibtex-autokey-titlewords 3)
10524 (bibtex-autokey-titleword-separator " ")
10525 (bibtex-autokey-titleword-case-convert-function 'identity)
10526 (bibtex-autokey-titleword-length 'infty)
10527 (bibtex-autokey-year-title-separator ": "))
10528 (setq description (bibtex-generate-autokey)))
10529 ;; Now parse the entry, get the key and return it.
10530 (save-excursion
10531 (bibtex-beginning-of-entry)
10532 (cdr (assoc "=key=" (bibtex-parse-entry))))))
10534 (defun org-execute-file-search-in-bibtex (s)
10535 "Find the link search string S as a key for a database entry."
10536 (when (eq major-mode 'bibtex-mode)
10537 ;; Yes, we want to do the search in this file.
10538 ;; We construct a regexp that searches for "@entrytype{" followed by the key
10539 (goto-char (point-min))
10540 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
10541 (regexp-quote s) "[ \t\n]*,") nil t)
10542 (goto-char (match-beginning 0)))
10543 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
10544 ;; Use double prefix to indicate that any web link should be browsed
10545 (let ((b (current-buffer)) (p (point)))
10546 ;; Restore the window configuration because we just use the web link
10547 (set-window-configuration org-window-config-before-follow-link)
10548 (save-excursion (set-buffer b) (goto-char p)
10549 (bibtex-url)))
10550 (recenter 0)) ; Move entry start to beginning of window
10551 ;; return t to indicate that the search is done.
10554 ;; Finally add the functions to the right hooks.
10555 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
10556 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
10558 ;; end of Bibtex link setup
10560 (defun org-upgrade-old-links (&optional query-description)
10561 "Transfer old <...> style links to new [[...]] style links.
10562 With arg query-description, ask at each match for a description text to use
10563 for this link."
10564 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
10565 (save-excursion
10566 (goto-char (point-min))
10567 (let ((re (concat "\\([^[]\\)<\\("
10568 "\\(" (mapconcat 'identity org-link-types "\\|")
10569 "\\):"
10570 "[^" org-non-link-chars "]+\\)>"))
10571 l1 l2 (cnt 0))
10572 (while (re-search-forward re nil t)
10573 (setq cnt (1+ cnt)
10574 l1 (org-match-string-no-properties 2)
10575 l2 (save-match-data (org-link-escape l1)))
10576 (when query-description (setq l1 (read-string "Desc: " l1)))
10577 (if (equal l1 l2)
10578 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
10579 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
10580 (message "%d matches have beed treated" cnt))))
10582 (defun org-open-file (path &optional in-emacs line search)
10583 "Open the file at PATH.
10584 First, this expands any special file name abbreviations. Then the
10585 configuration variable `org-file-apps' is checked if it contains an
10586 entry for this file type, and if yes, the corresponding command is launched.
10587 If no application is found, Emacs simply visits the file.
10588 With optional argument IN-EMACS, Emacs will visit the file.
10589 Optional LINE specifies a line to go to, optional SEARCH a string to
10590 search for. If LINE or SEARCH is given, the file will always be
10591 opened in Emacs.
10592 If the file does not exist, an error is thrown."
10593 (setq in-emacs (or in-emacs line search))
10594 (let* ((file (if (equal path "")
10595 buffer-file-name
10596 (substitute-in-file-name (expand-file-name path))))
10597 (apps (append org-file-apps (org-default-apps)))
10598 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10599 (dirp (if remp nil (file-directory-p file)))
10600 (dfile (downcase file))
10601 (old-buffer (current-buffer))
10602 (old-pos (point))
10603 (old-mode major-mode)
10604 ext cmd)
10605 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10606 (setq ext (match-string 1 dfile))
10607 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10608 (setq ext (match-string 1 dfile))))
10609 (if in-emacs
10610 (setq cmd 'emacs)
10611 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10612 (and dirp (cdr (assoc 'directory apps)))
10613 (cdr (assoc ext apps))
10614 (cdr (assoc t apps)))))
10615 (when (eq cmd 'mailcap)
10616 (require 'mailcap)
10617 (mailcap-parse-mailcaps)
10618 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10619 (command (mailcap-mime-info mime-type)))
10620 (if (stringp command)
10621 (setq cmd command)
10622 (setq cmd 'emacs))))
10623 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
10624 (not (file-exists-p file))
10625 (not org-open-non-existing-files))
10626 (error "No such file: %s" file))
10627 (cond
10628 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10629 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10630 (if (string-match "['\"]%s['\"]" cmd)
10631 (setq cmd (replace-match "%s" t t cmd)))
10632 (setq cmd (format cmd (shell-quote-argument file)))
10633 (save-window-excursion
10634 (shell-command (concat cmd " &"))))
10635 ((or (stringp cmd)
10636 (eq cmd 'emacs))
10637 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
10638 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
10639 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10640 (if line (goto-line line)
10641 (if search (org-link-search search))))
10642 ((consp cmd)
10643 (eval cmd))
10644 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10645 (and (org-mode-p) (eq old-mode 'org-mode)
10646 (or (not (equal old-buffer (current-buffer)))
10647 (not (equal old-pos (point))))
10648 (org-mark-ring-push old-pos old-buffer))))
10650 (defun org-default-apps ()
10651 "Return the default applications for this operating system."
10652 (cond
10653 ((eq system-type 'darwin)
10654 org-file-apps-defaults-macosx)
10655 ((eq system-type 'windows-nt)
10656 org-file-apps-defaults-windowsnt)
10657 (t org-file-apps-defaults-gnu)))
10659 (defun org-expand-file-name (path)
10660 "Replace special path abbreviations and expand the file name."
10661 (expand-file-name path))
10663 (defun org-file-remote-p (file)
10664 "Test whether FILE specifies a location on a remote system.
10665 Return non-nil if the location is indeed remote.
10667 For example, the filename \"/user@host:/foo\" specifies a location
10668 on the system \"/user@host:\"."
10669 (cond ((fboundp 'file-remote-p)
10670 (file-remote-p file))
10671 ((fboundp 'tramp-handle-file-remote-p)
10672 (tramp-handle-file-remote-p file))
10673 ((and (boundp 'ange-ftp-name-format)
10674 (string-match (car ange-ftp-name-format) file))
10676 (t nil)))
10678 (defvar org-insert-link-history nil
10679 "Minibuffer history for links inserted with `org-insert-link'.")
10681 (defvar org-stored-links nil
10682 "Contains the links stored with `org-store-link'.")
10684 ;;;###autoload
10685 (defun org-store-link (arg)
10686 "\\<org-mode-map>Store an org-link to the current location.
10687 This link can later be inserted into an org-buffer with
10688 \\[org-insert-link].
10689 For some link types, a prefix arg is interpreted:
10690 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
10691 For file links, arg negates `org-context-in-file-links'."
10692 (interactive "P")
10693 (let (link cpltxt desc description search txt (pos (point)))
10694 (cond
10696 ((eq major-mode 'bbdb-mode)
10697 (setq cpltxt (concat
10698 "bbdb:"
10699 (or (bbdb-record-name (bbdb-current-record))
10700 (bbdb-record-company (bbdb-current-record))))
10701 link (org-make-link cpltxt)))
10703 ((eq major-mode 'Info-mode)
10704 (setq link (org-make-link "info:"
10705 (file-name-nondirectory Info-current-file)
10706 ":" Info-current-node))
10707 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
10708 ":" Info-current-node)))
10710 ((eq major-mode 'calendar-mode)
10711 (let ((cd (calendar-cursor-to-date)))
10712 (setq link
10713 (format-time-string
10714 (car org-time-stamp-formats)
10715 (apply 'encode-time
10716 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
10717 nil nil nil))))))
10719 ((or (eq major-mode 'vm-summary-mode)
10720 (eq major-mode 'vm-presentation-mode))
10721 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
10722 (vm-follow-summary-cursor)
10723 (save-excursion
10724 (vm-select-folder-buffer)
10725 (let* ((message (car vm-message-pointer))
10726 (folder buffer-file-name)
10727 (subject (vm-su-subject message))
10728 (author (vm-su-full-name message))
10729 (message-id (vm-su-message-id message)))
10730 (setq message-id (org-remove-angle-brackets message-id))
10731 (setq folder (abbreviate-file-name folder))
10732 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
10733 folder)
10734 (setq folder (replace-match "" t t folder)))
10735 (setq cpltxt (concat author " on: " subject))
10736 (setq link (org-make-link "vm:" folder "#" message-id)))))
10738 ((eq major-mode 'wl-summary-mode)
10739 (let* ((msgnum (wl-summary-message-number))
10740 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
10741 msgnum 'message-id))
10742 (wl-message-entity (elmo-msgdb-overview-get-entity
10743 msgnum (wl-summary-buffer-msgdb)))
10744 (author (wl-summary-line-from)) ; FIXME: correct?
10745 (subject "???")) ; FIXME:
10746 (setq message-id (org-remove-angle-brackets message-id))
10747 (setq cpltxt (concat author " on: " subject))
10748 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
10749 "#" message-id))))
10751 ((or (equal major-mode 'mh-folder-mode)
10752 (equal major-mode 'mh-show-mode))
10753 (let ((from-header (org-mhe-get-header "From:"))
10754 (to-header (org-mhe-get-header "To:"))
10755 (subject (org-mhe-get-header "Subject:")))
10756 (setq cpltxt (concat from-header " on: " subject))
10757 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
10758 (org-remove-angle-brackets
10759 (org-mhe-get-header "Message-Id:"))))))
10761 ((eq major-mode 'rmail-mode)
10762 (save-excursion
10763 (save-restriction
10764 (rmail-narrow-to-non-pruned-header)
10765 (let ((folder buffer-file-name)
10766 (message-id (mail-fetch-field "message-id"))
10767 (author (mail-fetch-field "from"))
10768 (subject (mail-fetch-field "subject")))
10769 (setq message-id (org-remove-angle-brackets message-id))
10770 (setq cpltxt (concat author " on: " subject))
10771 (setq link (org-make-link "rmail:" folder "#" message-id))))))
10773 ((eq major-mode 'gnus-group-mode)
10774 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
10775 (gnus-group-group-name)) ; version
10776 ((fboundp 'gnus-group-name)
10777 (gnus-group-name))
10778 (t "???"))))
10779 (setq cpltxt (concat
10780 (if (org-xor arg org-usenet-links-prefer-google)
10781 "http://groups.google.com/groups?group="
10782 "gnus:")
10783 group)
10784 link (org-make-link cpltxt))))
10786 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
10787 (require 'gnus-sum)
10788 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
10789 (gnus-summary-beginning-of-article)
10790 (let* ((group (car gnus-article-current))
10791 (article (cdr gnus-article-current))
10792 (header (gnus-summary-article-header article))
10793 (author (mail-header-from header))
10794 (message-id (mail-header-id header))
10795 (date (mail-header-date header))
10796 (subject (gnus-summary-subject-string)))
10797 (setq cpltxt (concat author " on: " subject))
10798 (if (org-xor arg org-usenet-links-prefer-google)
10799 (setq link
10800 (concat
10801 cpltxt "\n "
10802 (format "http://groups.google.com/groups?as_umsgid=%s"
10803 (org-fixup-message-id-for-http message-id))))
10804 (setq link (org-make-link "gnus:" group
10805 "#" (number-to-string article))))))
10807 ((eq major-mode 'w3-mode)
10808 (setq cpltxt (url-view-url t)
10809 link (org-make-link cpltxt)))
10810 ((eq major-mode 'w3m-mode)
10811 (setq cpltxt (or w3m-current-title w3m-current-url)
10812 link (org-make-link w3m-current-url)))
10814 ((setq search (run-hook-with-args-until-success
10815 'org-create-file-search-functions))
10816 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10817 "::" search))
10818 (setq cpltxt (or description link)))
10820 ((eq major-mode 'image-mode)
10821 (setq cpltxt (concat "file:"
10822 (abbreviate-file-name buffer-file-name))
10823 link (org-make-link cpltxt)))
10825 ((eq major-mode 'dired-mode)
10826 ;; link to the file in the current line
10827 (setq cpltxt (concat "file:"
10828 (abbreviate-file-name
10829 (expand-file-name
10830 (dired-get-filename nil t))))
10831 link (org-make-link cpltxt)))
10833 ((org-mode-p)
10834 ;; Just link to current headline
10835 (setq cpltxt (concat "file:"
10836 (abbreviate-file-name buffer-file-name)))
10837 ;; Add a context search string
10838 (when (org-xor org-context-in-file-links arg)
10839 ;; Check if we are on a target
10840 (if (save-excursion
10841 (skip-chars-forward "^>\n\r")
10842 (and (re-search-backward "<<" nil t)
10843 (looking-at "<<\\(.*?\\)>>")
10844 (<= (match-beginning 0) pos)
10845 (>= (match-end 0) pos)))
10846 (setq cpltxt (concat cpltxt "::" (match-string 1)))
10847 (setq txt (cond
10848 ((org-on-heading-p) nil)
10849 ((org-region-active-p)
10850 (buffer-substring (region-beginning) (region-end)))
10851 (t (buffer-substring (point-at-bol) (point-at-eol)))))
10852 (when (or (null txt) (string-match "\\S-" txt))
10853 (setq cpltxt
10854 (concat cpltxt "::"
10855 (if org-file-link-context-use-camel-case
10856 (org-make-org-heading-camel txt)
10857 (org-make-org-heading-search-string txt)))
10858 desc "NONE"))))
10859 (if (string-match "::\\'" cpltxt)
10860 (setq cpltxt (substring cpltxt 0 -2)))
10861 (setq link (org-make-link cpltxt)))
10863 (buffer-file-name
10864 ;; Just link to this file here.
10865 (setq cpltxt (concat "file:"
10866 (abbreviate-file-name buffer-file-name)))
10867 ;; Add a context string
10868 (when (org-xor org-context-in-file-links arg)
10869 (setq txt (if (org-region-active-p)
10870 (buffer-substring (region-beginning) (region-end))
10871 (buffer-substring (point-at-bol) (point-at-eol))))
10872 ;; Only use search option if there is some text.
10873 (when (string-match "\\S-" txt)
10874 (setq cpltxt
10875 (concat cpltxt "::"
10876 (if org-file-link-context-use-camel-case
10877 (org-make-org-heading-camel txt)
10878 (org-make-org-heading-search-string txt)))
10879 desc "NONE")))
10880 (setq link (org-make-link cpltxt)))
10882 ((interactive-p)
10883 (error "Cannot link to a buffer which is not visiting a file"))
10885 (t (setq link nil)))
10887 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10888 (setq link (or link cpltxt)
10889 desc (or desc cpltxt))
10890 (if (equal desc "NONE") (setq desc nil))
10892 (if (and (interactive-p) link)
10893 (progn
10894 (setq org-stored-links
10895 (cons (list cpltxt link desc) org-stored-links))
10896 (message "Stored: %s" (or cpltxt link)))
10897 (org-make-link-string link desc))))
10899 (defun org-make-org-heading-search-string (&optional string heading)
10900 "Make search string for STRING or current headline."
10901 (interactive)
10902 (let ((s (or string (org-get-heading))))
10903 (unless (and string (not heading))
10904 ;; We are using a headline, clean up garbage in there.
10905 (if (string-match org-todo-regexp s)
10906 (setq s (replace-match "" t t s)))
10907 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10908 (setq s (replace-match "" t t s)))
10909 (setq s (org-trim s))
10910 (if (string-match (concat "^\\(" org-quote-string "\\|"
10911 org-comment-string "\\)") s)
10912 (setq s (replace-match "" t t s)))
10913 (while (string-match org-ts-regexp s)
10914 (setq s (replace-match "" t t s))))
10915 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10916 (setq s (replace-match " " t t s)))
10917 (or string (setq s (concat "*" s))) ; Add * for headlines
10918 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10920 (defun org-make-org-heading-camel (&optional string heading)
10921 "Make a CamelCase string for STRING or the current headline."
10922 (interactive)
10923 (let ((s (or string (org-get-heading))))
10924 (unless (and string (not heading))
10925 ;; We are using a headline, clean up garbage in there.
10926 (if (string-match org-todo-regexp s)
10927 (setq s (replace-match "" t t s)))
10928 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10929 (setq s (replace-match "" t t s)))
10930 (setq s (org-trim s))
10931 (if (string-match (concat "^\\(" org-quote-string "\\|"
10932 org-comment-string "\\)") s)
10933 (setq s (replace-match "" t t s)))
10934 (while (string-match org-ts-regexp s)
10935 (setq s (replace-match "" t t s))))
10936 (while (string-match "[^a-zA-Z_ \t]+" s)
10937 (setq s (replace-match " " t t s)))
10938 (or string (setq s (concat "*" s))) ; Add * for headlines
10939 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
10941 (defun org-make-link (&rest strings)
10942 "Concatenate STRINGS, format resulting string with `org-link-format'."
10943 (format org-link-format (apply 'concat strings)))
10945 (defun org-make-link-string (link &optional description)
10946 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10947 (if (eq org-link-style 'plain)
10948 (if (equal description link)
10949 link
10950 (concat description "\n" link))
10951 (when (stringp description)
10952 ;; Remove brackets from the description, they are fatal.
10953 (while (string-match "\\[\\|\\]" description)
10954 (setq description (replace-match "" t t description))))
10955 (when (equal (org-link-escape link) description)
10956 ;; No description needed, it is identical
10957 (setq description nil))
10958 (when (and (not description)
10959 (not (equal link (org-link-escape link))))
10960 (setq description link))
10961 (concat "[[" (org-link-escape link) "]"
10962 (if description (concat "[" description "]") "")
10963 "]")))
10965 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
10966 "Association list of escapes for some characters problematic in links.")
10968 (defun org-link-escape (text)
10969 "Escape charaters in TEXT that are problematic for links."
10970 (when text
10971 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10972 org-link-escape-chars "\\|")))
10973 (while (string-match re text)
10974 (setq text
10975 (replace-match
10976 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10977 t t text)))
10978 text)))
10980 (defun org-link-unescape (text)
10981 "Reverse the action of `org-link-escape'."
10982 (when text
10983 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10984 org-link-escape-chars "\\|")))
10985 (while (string-match re text)
10986 (setq text
10987 (replace-match
10988 (car (rassoc (match-string 0 text) org-link-escape-chars))
10989 t t text)))
10990 text)))
10992 (defun org-xor (a b)
10993 "Exclusive or."
10994 (if a (not b) b))
10996 (defun org-get-header (header)
10997 "Find a header field in the current buffer."
10998 (save-excursion
10999 (goto-char (point-min))
11000 (let ((case-fold-search t) s)
11001 (cond
11002 ((eq header 'from)
11003 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11004 (setq s (match-string 1)))
11005 (while (string-match "\"" s)
11006 (setq s (replace-match "" t t s)))
11007 (if (string-match "[<(].*" s)
11008 (setq s (replace-match "" t t s))))
11009 ((eq header 'message-id)
11010 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11011 (setq s (match-string 1))))
11012 ((eq header 'subject)
11013 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11014 (setq s (match-string 1)))))
11015 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11016 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11017 s)))
11020 (defun org-fixup-message-id-for-http (s)
11021 "Replace special characters in a message id, so it can be used in an http query."
11022 (while (string-match "<" s)
11023 (setq s (replace-match "%3C" t t s)))
11024 (while (string-match ">" s)
11025 (setq s (replace-match "%3E" t t s)))
11026 (while (string-match "@" s)
11027 (setq s (replace-match "%40" t t s)))
11030 (defun org-insert-link (&optional complete-file)
11031 "Insert a link. At the prompt, enter the link.
11033 Completion can be used to select a link previously stored with
11034 `org-store-link'. When the empty string is entered (i.e. if you just
11035 press RET at the prompt), the link defaults to the most recently
11036 stored link. As SPC triggers completion in the minibuffer, you need to
11037 use M-SPC or C-q SPC to force the insertion of a space character.
11039 You will also be prompted for a description, and if one is given, it will
11040 be displayed in the buffer instead of the link.
11042 If there is already a link at point, this command will allow you to edit link
11043 and description parts.
11045 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11046 selected using completion. The path to the file will be relative to
11047 the current directory if the file is in the current directory or a
11048 subdirectory. Otherwise, the link will be the absolute path as
11049 completed in the minibuffer (i.e. normally ~/path/to/file).
11051 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11052 is in the current directory or below.
11053 With three \\[universal-argument] prefixes, negate the meaning of
11054 `org-keep-stored-link-after-insertion'."
11055 (interactive "P")
11056 (let (link desc entry remove file (pos (point)))
11057 (cond
11058 ((save-excursion
11059 (skip-chars-forward "^]\n\r")
11060 (and (re-search-backward "\\[\\[" nil t)
11061 (looking-at org-bracket-link-regexp)
11062 (<= (match-beginning 0) pos)
11063 (>= (match-end 0) pos)))
11064 ;; We do have a link at point, and we are going to edit it.
11065 (setq remove (list (match-beginning 0) (match-end 0)))
11066 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11067 (setq link (read-string "Link: "
11068 (org-link-unescape
11069 (org-match-string-no-properties 1)))))
11070 ((equal complete-file '(4))
11071 ;; Completing read for file names.
11072 (setq file (read-file-name "File: "))
11073 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11074 (pwd1 (file-name-as-directory (abbreviate-file-name
11075 (expand-file-name ".")))))
11076 (cond
11077 ((equal complete-file '(16))
11078 (setq link (org-make-link
11079 "file:"
11080 (abbreviate-file-name (expand-file-name file)))))
11081 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11082 (setq link (org-make-link "file:" (match-string 1 file))))
11083 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11084 (expand-file-name file))
11085 (setq link (org-make-link
11086 "file:" (match-string 1 (expand-file-name file)))))
11087 (t (setq link (org-make-link "file:" file))))))
11089 ;; Read link, with completion for stored links.
11090 (setq link (org-completing-read
11091 "Link: " org-stored-links nil nil nil
11092 org-insert-link-history
11093 (or (car (car org-stored-links)))))
11094 (setq entry (assoc link org-stored-links))
11095 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11096 (not org-keep-stored-link-after-insertion))
11097 (setq org-stored-links (delq (assoc link org-stored-links)
11098 org-stored-links)))
11099 (setq link (if entry (nth 1 entry) link)
11100 desc (or desc (nth 2 entry)))))
11102 (if (string-match org-plain-link-re link)
11103 ;; URL-like link, normalize the use of angular brackets.
11104 (setq link (org-make-link (org-remove-angle-brackets link))))
11106 ;; Check if we are linking to the current file with a search option
11107 ;; If yes, simplify the link by using only the search option.
11108 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
11109 (let* ((path (match-string 1 link))
11110 (case-fold-search nil)
11111 (search (match-string 2 link)))
11112 (save-match-data
11113 (if (equal (file-truename buffer-file-name) (file-truename path))
11114 ;; We are linking to this same file, with a search option
11115 (setq link search)))))
11117 ;; Check if we can/should use a relative path. If yes, simplify the link
11118 (when (string-match "\\<file:\\(.*\\)" link)
11119 (let* ((path (match-string 1 link))
11120 (case-fold-search nil))
11121 (cond
11122 ((eq org-link-file-path-type 'absolute)
11123 (setq path (abbreviate-file-name (expand-file-name path))))
11124 ((eq org-link-file-path-type 'noabbrev)
11125 (setq path (expand-file-name path)))
11126 ((eq org-link-file-path-type 'relative)
11127 (setq path (file-relative-name path)))
11129 (save-match-data
11130 (if (string-match (concat "^" (regexp-quote
11131 (file-name-as-directory
11132 (expand-file-name "."))))
11133 (expand-file-name path))
11134 ;; We are linking a file with relative path name.
11135 (setq path (substring (expand-file-name path)
11136 (match-end 0)))))))
11137 (setq link (concat "file:" path))))
11139 (setq desc (read-string "Description: " desc))
11140 (unless (string-match "\\S-" desc) (setq desc nil))
11141 (if remove (apply 'delete-region remove))
11142 (insert (org-make-link-string link desc))))
11144 (defun org-completing-read (&rest args)
11145 (let ((minibuffer-local-completion-map
11146 (copy-keymap minibuffer-local-completion-map)))
11147 (define-key minibuffer-local-completion-map " " 'self-insert-command)
11148 (apply 'completing-read args)))
11150 ;;; Hooks for remember.el
11152 (defvar org-finish-function nil)
11154 ;;;###autoload
11155 (defun org-remember-annotation ()
11156 "Return a link to the current location as an annotation for remember.el.
11157 If you are using Org-mode files as target for data storage with
11158 remember.el, then the annotations should include a link compatible with the
11159 conventions in Org-mode. This function returns such a link."
11160 (org-store-link nil))
11162 (defconst org-remember-help
11163 "Select a destination location for the note.
11164 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
11165 RET at beg-of-buf -> Append to file as level 2 headline
11166 RET on headline -> Store as sublevel entry to current headline
11167 <left>/<right> -> before/after current headline, same headings level")
11169 ;;;###autoload
11170 (defun org-remember-apply-template ()
11171 "Initialize *remember* buffer with template, invoke `org-mode'.
11172 This function should be placed into `remember-mode-hook' and in fact requires
11173 to be run from that hook to fucntion properly."
11174 (if org-remember-templates
11176 (let* ((entry (if (= (length org-remember-templates) 1)
11177 (cdar org-remember-templates)
11178 (message "Select template: %s"
11179 (mapconcat
11180 (lambda (x) (char-to-string (car x)))
11181 org-remember-templates " "))
11182 (cdr (assoc (read-char-exclusive) org-remember-templates))))
11183 (tpl (car entry))
11184 (file (if (consp (cdr entry)) (nth 1 entry)))
11185 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
11186 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
11187 (v-u (concat "[" (substring v-t 1 -1) "]"))
11188 (v-U (concat "[" (substring v-T 1 -1) "]"))
11189 (v-a annotation) ; defined in `remember-mode'
11190 (v-i initial) ; defined in `remember-mode'
11191 (v-n user-full-name)
11193 (unless tpl (setq tpl "") (message "No template") (ding))
11194 (insert tpl) (goto-char (point-min))
11195 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
11196 (when (and initial (equal (match-string 0) "%i"))
11197 (save-match-data
11198 (let* ((lead (buffer-substring
11199 (point-at-bol) (match-beginning 0))))
11200 (setq v-i (mapconcat 'identity
11201 (org-split-string initial "\n")
11202 (concat "\n" lead))))))
11203 (replace-match
11204 (or (eval (intern (concat "v-" (match-string 1)))) "")
11205 t t))
11206 (let ((org-startup-folded nil)
11207 (org-startup-with-deadline-check nil))
11208 (org-mode))
11209 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
11210 (org-set-local 'org-default-notes-file file))
11211 (goto-char (point-min))
11212 (if (re-search-forward "%\\?" nil t) (replace-match "")))
11213 (let ((org-startup-folded nil)
11214 (org-startup-with-deadline-check nil))
11215 (org-mode)))
11216 (org-set-local 'org-finish-function 'remember-buffer))
11218 ;;;###autoload
11219 (defun org-remember-handler ()
11220 "Store stuff from remember.el into an org file.
11221 First prompts for an org file. If the user just presses return, the value
11222 of `org-default-notes-file' is used.
11223 Then the command offers the headings tree of the selected file in order to
11224 file the text at a specific location.
11225 You can either immediately press RET to get the note appended to the
11226 file, or you can use vertical cursor motion and visibility cycling (TAB) to
11227 find a better place. Then press RET or <left> or <right> in insert the note.
11229 Key Cursor position Note gets inserted
11230 -----------------------------------------------------------------------------
11231 RET buffer-start as level 2 heading at end of file
11232 RET on headline as sublevel of the heading at cursor
11233 RET no heading at cursor position, level taken from context.
11234 Or use prefix arg to specify level manually.
11235 <left> on headline as same level, before current heading
11236 <right> on headline as same level, after current heading
11238 So the fastest way to store the note is to press RET RET to append it to
11239 the default file. This way your current train of thought is not
11240 interrupted, in accordance with the principles of remember.el. But with
11241 little extra effort, you can push it directly to the correct location.
11243 Before being stored away, the function ensures that the text has a
11244 headline, i.e. a first line that starts with a \"*\". If not, a headline
11245 is constructed from the current date and some additional data.
11247 If the variable `org-adapt-indentation' is non-nil, the entire text is
11248 also indented so that it starts in the same column as the headline
11249 \(i.e. after the stars).
11251 See also the variable `org-reverse-note-order'."
11252 (catch 'quit
11253 (let* ((txt (buffer-substring (point-min) (point-max)))
11254 (fastp current-prefix-arg)
11255 (file (if fastp org-default-notes-file (org-get-org-file)))
11256 (visiting (find-buffer-visiting file))
11257 (org-startup-with-deadline-check nil)
11258 (org-startup-folded nil)
11259 (org-startup-align-all-tables nil)
11260 spos level indent reversed)
11261 ;; Modify text so that it becomes a nice subtree which can be inserted
11262 ;; into an org tree.
11263 (let* ((lines (split-string txt "\n"))
11264 first)
11265 ;; remove empty lines at the beginning
11266 (while (and lines (string-match "^[ \t]*\n" (car lines)))
11267 (setq lines (cdr lines)))
11268 (setq first (car lines) lines (cdr lines))
11269 (if (string-match "^\\*+" first)
11270 ;; Is already a headline
11271 (setq indent nil)
11272 ;; We need to add a headline: Use time and first buffer line
11273 (setq lines (cons first lines)
11274 first (concat "* " (current-time-string)
11275 " (" (remember-buffer-desc) ")")
11276 indent " "))
11277 (if (and org-adapt-indentation indent)
11278 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
11279 (setq txt (concat first "\n"
11280 (mapconcat 'identity lines "\n"))))
11281 ;; Find the file
11282 (if (not visiting)
11283 (find-file-noselect file))
11284 (with-current-buffer (get-file-buffer file)
11285 (save-excursion (and (goto-char (point-min))
11286 (not (re-search-forward "^\\* " nil t))
11287 (insert "\n* Notes\n")))
11288 (setq reversed (org-notes-order-reversed-p))
11289 (save-excursion
11290 (save-restriction
11291 (widen)
11292 ;; Ask the User for a location
11293 (setq spos (if fastp 1 (org-get-location
11294 (current-buffer)
11295 org-remember-help)))
11296 (if (not spos) (throw 'quit nil)) ; return nil to show we did
11297 ; not handle this note
11298 (goto-char spos)
11299 (cond ((bobp)
11300 ;; Put it at the start or end, as level 2
11301 (save-restriction
11302 (widen)
11303 (goto-char (if reversed (point-min) (point-max)))
11304 (if (not (bolp)) (newline))
11305 (org-paste-subtree 2 txt)))
11306 ((and (org-on-heading-p nil) (not current-prefix-arg))
11307 ;; Put it below this entry, at the beg/end of the subtree
11308 (org-back-to-heading)
11309 (setq level (funcall outline-level))
11310 (if reversed
11311 (outline-end-of-heading)
11312 (outline-end-of-subtree))
11313 (if (not (bolp)) (newline))
11314 (beginning-of-line 1)
11315 (org-paste-subtree (org-get-legal-level level 1) txt))
11317 ;; Put it right there, with automatic level determined by
11318 ;; org-paste-subtree or from prefix arg
11319 (org-paste-subtree current-prefix-arg txt)))
11320 (when remember-save-after-remembering
11321 (save-buffer)
11322 (if (not visiting) (kill-buffer (current-buffer)))))))))
11323 t) ;; return t to indicate that we took care of this note.
11325 (defun org-get-org-file ()
11326 "Read a filename, with default directory `org-directory'."
11327 (let ((default (or org-default-notes-file remember-data-file)))
11328 (read-file-name (format "File name [%s]: " default)
11329 (file-name-as-directory org-directory)
11330 default)))
11332 (defun org-notes-order-reversed-p ()
11333 "Check if the current file should receive notes in reversed order."
11334 (cond
11335 ((not org-reverse-note-order) nil)
11336 ((eq t org-reverse-note-order) t)
11337 ((not (listp org-reverse-note-order)) nil)
11338 (t (catch 'exit
11339 (let ((all org-reverse-note-order)
11340 entry)
11341 (while (setq entry (pop all))
11342 (if (string-match (car entry) buffer-file-name)
11343 (throw 'exit (cdr entry))))
11344 nil)))))
11346 ;;; Tables
11348 ;; Watch out: Here we are talking about two different kind of tables.
11349 ;; Most of the code is for the tables created with the Org-mode table editor.
11350 ;; Sometimes, we talk about tables created and edited with the table.el
11351 ;; Emacs package. We call the former org-type tables, and the latter
11352 ;; table.el-type tables.
11355 (defun org-before-change-function (beg end)
11356 "Every change indicates that a table might need an update."
11357 (setq org-table-may-need-update t))
11359 (defconst org-table-line-regexp "^[ \t]*|"
11360 "Detects an org-type table line.")
11361 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
11362 "Detects an org-type table line.")
11363 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
11364 "Detects a table line marked for automatic recalculation.")
11365 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
11366 "Detects a table line marked for automatic recalculation.")
11367 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
11368 "Detects a table line marked for automatic recalculation.")
11369 (defconst org-table-hline-regexp "^[ \t]*|-"
11370 "Detects an org-type table hline.")
11371 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
11372 "Detects a table-type table hline.")
11373 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
11374 "Detects an org-type or table-type table.")
11375 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
11376 "Searching from within a table (any type) this finds the first line
11377 outside the table.")
11378 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
11379 "Searching from within a table (any type) this finds the first line
11380 outside the table.")
11382 (defun org-table-create-with-table.el ()
11383 "Use the table.el package to insert a new table.
11384 If there is already a table at point, convert between Org-mode tables
11385 and table.el tables."
11386 (interactive)
11387 (require 'table)
11388 (cond
11389 ((org-at-table.el-p)
11390 (if (y-or-n-p "Convert table to Org-mode table? ")
11391 (org-table-convert)))
11392 ((org-at-table-p)
11393 (if (y-or-n-p "Convert table to table.el table? ")
11394 (org-table-convert)))
11395 (t (call-interactively 'table-insert))))
11397 (defun org-table-create-or-convert-from-region (arg)
11398 "Convert region to table, or create an empty table.
11399 If there is an active region, convert it to a table. If there is no such
11400 region, create an empty table."
11401 (interactive "P")
11402 (if (org-region-active-p)
11403 (org-table-convert-region (region-beginning) (region-end) arg)
11404 (org-table-create arg)))
11406 (defun org-table-create (&optional size)
11407 "Query for a size and insert a table skeleton.
11408 SIZE is a string Columns x Rows like for example \"3x2\"."
11409 (interactive "P")
11410 (unless size
11411 (setq size (read-string
11412 (concat "Table size Columns x Rows [e.g. "
11413 org-table-default-size "]: ")
11414 "" nil org-table-default-size)))
11416 (let* ((pos (point))
11417 (indent (make-string (current-column) ?\ ))
11418 (split (org-split-string size " *x *"))
11419 (rows (string-to-number (nth 1 split)))
11420 (columns (string-to-number (car split)))
11421 (line (concat (apply 'concat indent "|" (make-list columns " |"))
11422 "\n")))
11423 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
11424 (point-at-bol) (point)))
11425 (beginning-of-line 1)
11426 (newline))
11427 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
11428 (dotimes (i rows) (insert line))
11429 (goto-char pos)
11430 (if (> rows 1)
11431 ;; Insert a hline after the first row.
11432 (progn
11433 (end-of-line 1)
11434 (insert "\n|-")
11435 (goto-char pos)))
11436 (org-table-align)))
11438 (defun org-table-convert-region (beg0 end0 &optional nspace)
11439 "Convert region to a table.
11440 The region goes from BEG0 to END0, but these borders will be moved
11441 slightly, to make sure a beginning of line in the first line is included.
11442 When NSPACE is non-nil, it indicates the minimum number of spaces that
11443 separate columns (default: just one space)."
11444 (interactive "rP")
11445 (let* ((beg (min beg0 end0))
11446 (end (max beg0 end0))
11447 (tabsep t)
11449 (goto-char beg)
11450 (beginning-of-line 1)
11451 (setq beg (move-marker (make-marker) (point)))
11452 (goto-char end)
11453 (if (bolp) (backward-char 1) (end-of-line 1))
11454 (setq end (move-marker (make-marker) (point)))
11455 ;; Lets see if this is tab-separated material. If every nonempty line
11456 ;; contains a tab, we will assume that it is tab-separated material
11457 (if nspace
11458 (setq tabsep nil)
11459 (goto-char beg)
11460 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
11461 (if nspace (setq tabsep nil))
11462 (if tabsep
11463 (setq re "^\\|\t")
11464 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
11465 (max 1 (prefix-numeric-value nspace)))))
11466 (goto-char beg)
11467 (while (re-search-forward re end t)
11468 (replace-match "|" t t))
11469 (goto-char beg)
11470 (insert " ")
11471 (org-table-align)))
11473 (defun org-table-import (file arg)
11474 "Import FILE as a table.
11475 The file is assumed to be tab-separated. Such files can be produced by most
11476 spreadsheet and database applications. If no tabs (at least one per line)
11477 are found, lines will be split on whitespace into fields."
11478 (interactive "f\nP")
11479 (or (bolp) (newline))
11480 (let ((beg (point))
11481 (pm (point-max)))
11482 (insert-file-contents file)
11483 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
11485 (defun org-table-export ()
11486 "Export table as a tab-separated file.
11487 Such a file can be imported into a spreadsheet program like Excel."
11488 (interactive)
11489 (let* ((beg (org-table-begin))
11490 (end (org-table-end))
11491 (table (buffer-substring beg end))
11492 (file (read-file-name "Export table to: "))
11493 buf)
11494 (unless (or (not (file-exists-p file))
11495 (y-or-n-p (format "Overwrite file %s? " file)))
11496 (error "Abort"))
11497 (with-current-buffer (find-file-noselect file)
11498 (setq buf (current-buffer))
11499 (erase-buffer)
11500 (fundamental-mode)
11501 (insert table)
11502 (goto-char (point-min))
11503 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
11504 (replace-match "" t t)
11505 (end-of-line 1))
11506 (goto-char (point-min))
11507 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
11508 (replace-match "" t t)
11509 (goto-char (min (1+ (point)) (point-max))))
11510 (goto-char (point-min))
11511 (while (re-search-forward "^-[-+]*$" nil t)
11512 (replace-match "")
11513 (if (looking-at "\n")
11514 (delete-char 1)))
11515 (goto-char (point-min))
11516 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
11517 (replace-match "\t" t t))
11518 (save-buffer))
11519 (kill-buffer buf)))
11521 (defvar org-table-aligned-begin-marker (make-marker)
11522 "Marker at the beginning of the table last aligned.
11523 Used to check if cursor still is in that table, to minimize realignment.")
11524 (defvar org-table-aligned-end-marker (make-marker)
11525 "Marker at the end of the table last aligned.
11526 Used to check if cursor still is in that table, to minimize realignment.")
11527 (defvar org-table-last-alignment nil
11528 "List of flags for flushright alignment, from the last re-alignment.
11529 This is being used to correctly align a single field after TAB or RET.")
11530 (defvar org-table-last-column-widths nil
11531 "List of max width of fields in each column.
11532 This is being used to correctly align a single field after TAB or RET.")
11534 (defvar org-last-recalc-line nil)
11535 (defconst org-narrow-column-arrow "=>"
11536 "Used as display property in narrowed table columns.")
11538 (defun org-table-align ()
11539 "Align the table at point by aligning all vertical bars."
11540 (interactive)
11541 (let* (
11542 ;; Limits of table
11543 (beg (org-table-begin))
11544 (end (org-table-end))
11545 ;; Current cursor position
11546 (linepos (org-current-line))
11547 (colpos (org-table-current-column))
11548 (winstart (window-start))
11549 (winstartline (org-current-line (min winstart (1- (point-max)))))
11550 lines (new "") lengths l typenums ty fields maxfields i
11551 column
11552 (indent "") cnt frac
11553 rfmt hfmt
11554 (spaces '(1 . 1))
11555 (sp1 (car spaces))
11556 (sp2 (cdr spaces))
11557 (rfmt1 (concat
11558 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
11559 (hfmt1 (concat
11560 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
11561 emptystrings links dates narrow fmax f1 len c e)
11562 (untabify beg end)
11563 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
11564 ;; Check if we have links or dates
11565 (goto-char beg)
11566 (setq links (re-search-forward org-bracket-link-regexp end t))
11567 (goto-char beg)
11568 (setq dates (and org-display-custom-times
11569 (re-search-forward org-ts-regexp-both end t)))
11570 ;; Make sure the link properties are right
11571 (when links (goto-char beg) (while (org-activate-bracket-links end)))
11572 ;; Make sure the date properties are right
11573 (when dates (goto-char beg) (while (org-activate-dates end)))
11575 ;; Check if we are narrowing any columns
11576 (goto-char beg)
11577 (setq narrow (and org-format-transports-properties-p
11578 (re-search-forward "<[0-9]+>" end t)))
11579 ;; Get the rows
11580 (setq lines (org-split-string
11581 (buffer-substring beg end) "\n"))
11582 ;; Store the indentation of the first line
11583 (if (string-match "^ *" (car lines))
11584 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11585 ;; Mark the hlines by setting the corresponding element to nil
11586 ;; At the same time, we remove trailing space.
11587 (setq lines (mapcar (lambda (l)
11588 (if (string-match "^ *|-" l)
11590 (if (string-match "[ \t]+$" l)
11591 (substring l 0 (match-beginning 0))
11592 l)))
11593 lines))
11594 ;; Get the data fields by splitting the lines.
11595 (setq fields (mapcar
11596 (lambda (l)
11597 (org-split-string l " *| *"))
11598 (delq nil (copy-sequence lines))))
11599 ;; How many fields in the longest line?
11600 (condition-case nil
11601 (setq maxfields (apply 'max (mapcar 'length fields)))
11602 (error
11603 (kill-region beg end)
11604 (org-table-create org-table-default-size)
11605 (error "Empty table - created default table")))
11606 ;; A list of empty strings to fill any short rows on output
11607 (setq emptystrings (make-list maxfields ""))
11608 ;; Check for special formatting.
11609 (setq i -1)
11610 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
11611 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
11612 ;; Check if there is an explicit width specified
11613 (when (and org-table-limit-column-width narrow)
11614 (setq c column fmax nil)
11615 (while c
11616 (setq e (pop c))
11617 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
11618 (setq fmax (string-to-number (match-string 1 e)) c nil)))
11619 ;; Find fields that are wider than fmax, and shorten them
11620 (when fmax
11621 (loop for xx in column do
11622 (when (and (stringp xx)
11623 (> (org-string-width xx) fmax))
11624 (org-add-props xx nil
11625 'help-echo
11626 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
11627 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
11628 (unless (> f1 1)
11629 (error "Cannot narrow field starting with wide link \"%s\""
11630 (match-string 0 xx)))
11631 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
11632 (add-text-properties (- f1 2) f1
11633 (list 'display org-narrow-column-arrow)
11634 xx)))))
11635 ;; Get the maximum width for each column
11636 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
11637 ;; Get the fraction of numbers, to decide about alignment of the column
11638 (setq cnt 0 frac 0.0)
11639 (loop for x in column do
11640 (if (equal x "")
11642 (setq frac ( / (+ (* frac cnt)
11643 (if (string-match org-table-number-regexp x) 1 0))
11644 (setq cnt (1+ cnt))))))
11645 (push (>= frac org-table-number-fraction) typenums))
11646 (setq lengths (nreverse lengths) typenums (nreverse typenums))
11648 ;; Store the alignment of this table, for later editing of single fields
11649 (setq org-table-last-alignment typenums
11650 org-table-last-column-widths lengths)
11652 ;; With invisible characters, `format' does not get the field width right
11653 ;; So we need to make these fields wide by hand.
11654 (when links
11655 (loop for i from 0 upto (1- maxfields) do
11656 (setq len (nth i lengths))
11657 (loop for j from 0 upto (1- (length fields)) do
11658 (setq c (nthcdr i (car (nthcdr j fields))))
11659 (if (and (stringp (car c))
11660 (string-match org-bracket-link-regexp (car c))
11661 (< (org-string-width (car c)) len))
11662 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
11664 ;; Compute the formats needed for output of the table
11665 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
11666 (while (setq l (pop lengths))
11667 (setq ty (if (pop typenums) "" "-")) ; number types flushright
11668 (setq rfmt (concat rfmt (format rfmt1 ty l))
11669 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
11670 (setq rfmt (concat rfmt "\n")
11671 hfmt (concat (substring hfmt 0 -1) "|\n"))
11673 (setq new (mapconcat
11674 (lambda (l)
11675 (if l (apply 'format rfmt
11676 (append (pop fields) emptystrings))
11677 hfmt))
11678 lines ""))
11679 ;; Replace the old one
11680 (delete-region beg end)
11681 (move-marker end nil)
11682 (move-marker org-table-aligned-begin-marker (point))
11683 (insert new)
11684 (move-marker org-table-aligned-end-marker (point))
11685 (when (and orgtbl-mode (not (org-mode-p)))
11686 (goto-char org-table-aligned-begin-marker)
11687 (while (org-hide-wide-columns org-table-aligned-end-marker)))
11688 ;; Try to move to the old location
11689 (goto-line winstartline)
11690 (setq winstart (point-at-bol))
11691 (goto-line linepos)
11692 (set-window-start (selected-window) winstart 'noforce)
11693 (org-table-goto-column colpos)
11694 (setq org-table-may-need-update nil)
11697 (defun org-string-width (s)
11698 "Compute width of string, ignoring invisible characters.
11699 This ignores character with invisibility property `org-link', and also
11700 characters with property `org-cwidth', because these will become invisible
11701 upon the next fontification round."
11702 (let (b l)
11703 (when (or (eq t buffer-invisibility-spec)
11704 (assq 'org-link buffer-invisibility-spec))
11705 (while (setq b (text-property-any 0 (length s)
11706 'invisible 'org-link s))
11707 (setq s (concat (substring s 0 b)
11708 (substring s (or (next-single-property-change
11709 b 'invisible s) (length s)))))))
11710 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
11711 (setq s (concat (substring s 0 b)
11712 (substring s (or (next-single-property-change
11713 b 'org-cwidth s) (length s))))))
11714 (setq l (string-width s) b -1)
11715 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
11716 (setq l (- l (get-text-property b 'org-dwidth-n s))))
11719 (defun org-table-begin (&optional table-type)
11720 "Find the beginning of the table and return its position.
11721 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
11722 (save-excursion
11723 (if (not (re-search-backward
11724 (if table-type org-table-any-border-regexp
11725 org-table-border-regexp)
11726 nil t))
11727 (progn (goto-char (point-min)) (point))
11728 (goto-char (match-beginning 0))
11729 (beginning-of-line 2)
11730 (point))))
11732 (defun org-table-end (&optional table-type)
11733 "Find the end of the table and return its position.
11734 With argument TABLE-TYPE, go to the end of a table.el-type table."
11735 (save-excursion
11736 (if (not (re-search-forward
11737 (if table-type org-table-any-border-regexp
11738 org-table-border-regexp)
11739 nil t))
11740 (goto-char (point-max))
11741 (goto-char (match-beginning 0)))
11742 (point-marker)))
11744 (defun org-table-justify-field-maybe (&optional new)
11745 "Justify the current field, text to left, number to right.
11746 Optional argument NEW may specify text to replace the current field content."
11747 (cond
11748 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
11749 ((org-at-table-hline-p))
11750 ((and (not new)
11751 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
11752 (current-buffer)))
11753 (< (point) org-table-aligned-begin-marker)
11754 (>= (point) org-table-aligned-end-marker)))
11755 ;; This is not the same table, force a full re-align
11756 (setq org-table-may-need-update t))
11757 (t ;; realign the current field, based on previous full realign
11758 (let* ((pos (point)) s
11759 (col (org-table-current-column))
11760 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
11761 l f n o e)
11762 (when (> col 0)
11763 (skip-chars-backward "^|\n")
11764 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
11765 (progn
11766 (setq s (match-string 1)
11767 o (match-string 0)
11768 l (max 1 (- (match-end 0) (match-beginning 0) 3))
11769 e (not (= (match-beginning 2) (match-end 2))))
11770 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
11771 l (if e "|" (setq org-table-may-need-update t) ""))
11772 n (format f s))
11773 (if new
11774 (if (<= (length new) l) ;; FIXME: length -> str-width?
11775 (setq n (format f new))
11776 (setq n (concat new "|") org-table-may-need-update t)))
11777 (or (equal n o)
11778 (let (org-table-may-need-update)
11779 (replace-match n))))
11780 (setq org-table-may-need-update t))
11781 (goto-char pos))))))
11783 (defun org-table-next-field ()
11784 "Go to the next field in the current table, creating new lines as needed.
11785 Before doing so, re-align the table if necessary."
11786 (interactive)
11787 (org-table-maybe-eval-formula)
11788 (org-table-maybe-recalculate-line)
11789 (if (and org-table-automatic-realign
11790 org-table-may-need-update)
11791 (org-table-align))
11792 (let ((end (org-table-end)))
11793 (if (org-at-table-hline-p)
11794 (end-of-line 1))
11795 (condition-case nil
11796 (progn
11797 (re-search-forward "|" end)
11798 (if (looking-at "[ \t]*$")
11799 (re-search-forward "|" end))
11800 (if (and (looking-at "-")
11801 org-table-tab-jumps-over-hlines
11802 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
11803 (goto-char (match-beginning 1)))
11804 (if (looking-at "-")
11805 (progn
11806 (beginning-of-line 0)
11807 (org-table-insert-row 'below))
11808 (if (looking-at " ") (forward-char 1))))
11809 (error
11810 (org-table-insert-row 'below)))))
11812 (defun org-table-previous-field ()
11813 "Go to the previous field in the table.
11814 Before doing so, re-align the table if necessary."
11815 (interactive)
11816 (org-table-justify-field-maybe)
11817 (org-table-maybe-recalculate-line)
11818 (if (and org-table-automatic-realign
11819 org-table-may-need-update)
11820 (org-table-align))
11821 (if (org-at-table-hline-p)
11822 (end-of-line 1))
11823 (re-search-backward "|" (org-table-begin))
11824 (re-search-backward "|" (org-table-begin))
11825 (while (looking-at "|\\(-\\|[ \t]*$\\)")
11826 (re-search-backward "|" (org-table-begin)))
11827 (if (looking-at "| ?")
11828 (goto-char (match-end 0))))
11830 (defun org-table-next-row ()
11831 "Go to the next row (same column) in the current table.
11832 Before doing so, re-align the table if necessary."
11833 (interactive)
11834 (org-table-maybe-eval-formula)
11835 (org-table-maybe-recalculate-line)
11836 (if (or (looking-at "[ \t]*$")
11837 (save-excursion (skip-chars-backward " \t") (bolp)))
11838 (newline)
11839 (if (and org-table-automatic-realign
11840 org-table-may-need-update)
11841 (org-table-align))
11842 (let ((col (org-table-current-column)))
11843 (beginning-of-line 2)
11844 (if (or (not (org-at-table-p))
11845 (org-at-table-hline-p))
11846 (progn
11847 (beginning-of-line 0)
11848 (org-table-insert-row 'below)))
11849 (org-table-goto-column col)
11850 (skip-chars-backward "^|\n\r")
11851 (if (looking-at " ") (forward-char 1)))))
11853 (defun org-table-copy-down (n)
11854 "Copy a field down in the current column.
11855 If the field at the cursor is empty, copy into it the content of the nearest
11856 non-empty field above. With argument N, use the Nth non-empty field.
11857 If the current field is not empty, it is copied down to the next row, and
11858 the cursor is moved with it. Therefore, repeating this command causes the
11859 column to be filled row-by-row.
11860 If the variable `org-table-copy-increment' is non-nil and the field is an
11861 integer, it will be incremented while copying."
11862 (interactive "p")
11863 (let* ((colpos (org-table-current-column))
11864 (field (org-table-get-field))
11865 (non-empty (string-match "[^ \t]" field))
11866 (beg (org-table-begin))
11867 txt)
11868 (org-table-check-inside-data-field)
11869 (if non-empty
11870 (progn
11871 (setq txt (org-trim field))
11872 (org-table-next-row)
11873 (org-table-blank-field))
11874 (save-excursion
11875 (setq txt
11876 (catch 'exit
11877 (while (progn (beginning-of-line 1)
11878 (re-search-backward org-table-dataline-regexp
11879 beg t))
11880 (org-table-goto-column colpos t)
11881 (if (and (looking-at
11882 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
11883 (= (setq n (1- n)) 0))
11884 (throw 'exit (match-string 1))))))))
11885 (if txt
11886 (progn
11887 (if (and org-table-copy-increment
11888 (string-match "^[0-9]+$" txt))
11889 (setq txt (format "%d" (+ (string-to-number txt) 1))))
11890 (insert txt)
11891 (org-table-maybe-recalculate-line)
11892 (org-table-align))
11893 (error "No non-empty field found"))))
11895 (defun org-table-check-inside-data-field ()
11896 "Is point inside a table data field?
11897 I.e. not on a hline or before the first or after the last column?
11898 This actually throws an error, so it aborts the current command."
11899 (if (or (not (org-at-table-p))
11900 (= (org-table-current-column) 0)
11901 (org-at-table-hline-p)
11902 (looking-at "[ \t]*$"))
11903 (error "Not in table data field")))
11905 (defvar org-table-clip nil
11906 "Clipboard for table regions.")
11908 (defun org-table-blank-field ()
11909 "Blank the current table field or active region."
11910 (interactive)
11911 (org-table-check-inside-data-field)
11912 (if (and (interactive-p) (org-region-active-p))
11913 (let (org-table-clip)
11914 (org-table-cut-region (region-beginning) (region-end)))
11915 (skip-chars-backward "^|")
11916 (backward-char 1)
11917 (if (looking-at "|[^|\n]+")
11918 (let* ((pos (match-beginning 0))
11919 (match (match-string 0))
11920 (len (org-string-width match)))
11921 (replace-match (concat "|" (make-string (1- len) ?\ )))
11922 (goto-char (+ 2 pos))
11923 (substring match 1)))))
11925 (defun org-table-get-field (&optional n replace)
11926 "Return the value of the field in column N of current row.
11927 N defaults to current field.
11928 If REPLACE is a string, replace field with this value. The return value
11929 is always the old value."
11930 (and n (org-table-goto-column n))
11931 (skip-chars-backward "^|\n")
11932 (backward-char 1)
11933 (if (looking-at "|[^|\r\n]*")
11934 (let* ((pos (match-beginning 0))
11935 (val (buffer-substring (1+ pos) (match-end 0))))
11936 (if replace
11937 (replace-match (concat "|" replace)))
11938 (goto-char (min (point-at-eol) (+ 2 pos)))
11939 val)
11940 (forward-char 1) ""))
11942 (defun org-table-current-column ()
11943 "Find out which column we are in.
11944 When called interactively, column is also displayed in echo area."
11945 (interactive)
11946 (if (interactive-p) (org-table-check-inside-data-field))
11947 (save-excursion
11948 (let ((cnt 0) (pos (point)))
11949 (beginning-of-line 1)
11950 (while (search-forward "|" pos t)
11951 (setq cnt (1+ cnt)))
11952 (if (interactive-p) (message "This is table column %d" cnt))
11953 cnt)))
11955 (defun org-table-goto-column (n &optional on-delim force)
11956 "Move the cursor to the Nth column in the current table line.
11957 With optional argument ON-DELIM, stop with point before the left delimiter
11958 of the field.
11959 If there are less than N fields, just go to after the last delimiter.
11960 However, when FORCE is non-nil, create new columns if necessary."
11961 (interactive "p")
11962 (let ((pos (point-at-eol)))
11963 (beginning-of-line 1)
11964 (when (> n 0)
11965 (while (and (> (setq n (1- n)) -1)
11966 (or (search-forward "|" pos t)
11967 (and force
11968 (progn (end-of-line 1)
11969 (skip-chars-backward "^|")
11970 (insert " | "))))))
11971 ; (backward-char 2) t)))))
11972 (when (and force (not (looking-at ".*|")))
11973 (save-excursion (end-of-line 1) (insert " | ")))
11974 (if on-delim
11975 (backward-char 1)
11976 (if (looking-at " ") (forward-char 1))))))
11978 (defun org-at-table-p (&optional table-type)
11979 "Return t if the cursor is inside an org-type table.
11980 If TABLE-TYPE is non-nil, also check for table.el-type tables."
11981 (if org-enable-table-editor
11982 (save-excursion
11983 (beginning-of-line 1)
11984 (looking-at (if table-type org-table-any-line-regexp
11985 org-table-line-regexp)))
11986 nil))
11988 (defun org-at-table.el-p ()
11989 "Return t if and only if we are at a table.el table."
11990 (and (org-at-table-p 'any)
11991 (save-excursion
11992 (goto-char (org-table-begin 'any))
11993 (looking-at org-table1-hline-regexp))))
11995 (defun org-table-recognize-table.el ()
11996 "If there is a table.el table nearby, recognize it and move into it."
11997 (if org-table-tab-recognizes-table.el
11998 (if (org-at-table.el-p)
11999 (progn
12000 (beginning-of-line 1)
12001 (if (looking-at org-table-dataline-regexp)
12003 (if (looking-at org-table1-hline-regexp)
12004 (progn
12005 (beginning-of-line 2)
12006 (if (looking-at org-table-any-border-regexp)
12007 (beginning-of-line -1)))))
12008 (if (re-search-forward "|" (org-table-end t) t)
12009 (progn
12010 (require 'table)
12011 (if (table--at-cell-p (point))
12013 (message "recognizing table.el table...")
12014 (table-recognize-table)
12015 (message "recognizing table.el table...done")))
12016 (error "This should not happen..."))
12018 nil)
12019 nil))
12021 (defun org-at-table-hline-p ()
12022 "Return t if the cursor is inside a hline in a table."
12023 (if org-enable-table-editor
12024 (save-excursion
12025 (beginning-of-line 1)
12026 (looking-at org-table-hline-regexp))
12027 nil))
12029 (defun org-table-insert-column ()
12030 "Insert a new column into the table."
12031 (interactive)
12032 (if (not (org-at-table-p))
12033 (error "Not at a table"))
12034 (org-table-find-dataline)
12035 (let* ((col (max 1 (org-table-current-column)))
12036 (beg (org-table-begin))
12037 (end (org-table-end))
12038 ;; Current cursor position
12039 (linepos (org-current-line))
12040 (colpos col))
12041 (goto-char beg)
12042 (while (< (point) end)
12043 (if (org-at-table-hline-p)
12045 (org-table-goto-column col t)
12046 (insert "| "))
12047 (beginning-of-line 2))
12048 (move-marker end nil)
12049 (goto-line linepos)
12050 (org-table-goto-column colpos)
12051 (org-table-align)
12052 (org-table-modify-formulas 'insert col)))
12054 (defun org-table-find-dataline ()
12055 "Find a dataline in the current table, which is needed for column commands."
12056 (if (and (org-at-table-p)
12057 (not (org-at-table-hline-p)))
12059 (let ((col (current-column))
12060 (end (org-table-end)))
12061 (move-to-column col)
12062 (while (and (< (point) end)
12063 (or (not (= (current-column) col))
12064 (org-at-table-hline-p)))
12065 (beginning-of-line 2)
12066 (move-to-column col))
12067 (if (and (org-at-table-p)
12068 (not (org-at-table-hline-p)))
12070 (error
12071 "Please position cursor in a data line for column operations")))))
12073 (defun org-table-delete-column ()
12074 "Delete a column from the table."
12075 (interactive)
12076 (if (not (org-at-table-p))
12077 (error "Not at a table"))
12078 (org-table-find-dataline)
12079 (org-table-check-inside-data-field)
12080 (let* ((col (org-table-current-column))
12081 (beg (org-table-begin))
12082 (end (org-table-end))
12083 ;; Current cursor position
12084 (linepos (org-current-line))
12085 (colpos col))
12086 (goto-char beg)
12087 (while (< (point) end)
12088 (if (org-at-table-hline-p)
12090 (org-table-goto-column col t)
12091 (and (looking-at "|[^|\n]+|")
12092 (replace-match "|")))
12093 (beginning-of-line 2))
12094 (move-marker end nil)
12095 (goto-line linepos)
12096 (org-table-goto-column colpos)
12097 (org-table-align)
12098 (org-table-modify-formulas 'remove col)))
12100 (defun org-table-move-column-right ()
12101 "Move column to the right."
12102 (interactive)
12103 (org-table-move-column nil))
12104 (defun org-table-move-column-left ()
12105 "Move column to the left."
12106 (interactive)
12107 (org-table-move-column 'left))
12109 (defun org-table-move-column (&optional left)
12110 "Move the current column to the right. With arg LEFT, move to the left."
12111 (interactive "P")
12112 (if (not (org-at-table-p))
12113 (error "Not at a table"))
12114 (org-table-find-dataline)
12115 (org-table-check-inside-data-field)
12116 (let* ((col (org-table-current-column))
12117 (col1 (if left (1- col) col))
12118 (beg (org-table-begin))
12119 (end (org-table-end))
12120 ;; Current cursor position
12121 (linepos (org-current-line))
12122 (colpos (if left (1- col) (1+ col))))
12123 (if (and left (= col 1))
12124 (error "Cannot move column further left"))
12125 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
12126 (error "Cannot move column further right"))
12127 (goto-char beg)
12128 (while (< (point) end)
12129 (if (org-at-table-hline-p)
12131 (org-table-goto-column col1 t)
12132 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
12133 (replace-match "|\\2|\\1|")))
12134 (beginning-of-line 2))
12135 (move-marker end nil)
12136 (goto-line linepos)
12137 (org-table-goto-column colpos)
12138 (org-table-align)
12139 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
12141 (defun org-table-move-row-down ()
12142 "Move table row down."
12143 (interactive)
12144 (org-table-move-row nil))
12145 (defun org-table-move-row-up ()
12146 "Move table row up."
12147 (interactive)
12148 (org-table-move-row 'up))
12150 (defun org-table-move-row (&optional up)
12151 "Move the current table line down. With arg UP, move it up."
12152 (interactive "P")
12153 (let ((col (current-column))
12154 (pos (point))
12155 (tonew (if up 0 2))
12156 txt)
12157 (beginning-of-line tonew)
12158 (if (not (org-at-table-p))
12159 (progn
12160 (goto-char pos)
12161 (error "Cannot move row further")))
12162 (goto-char pos)
12163 (beginning-of-line 1)
12164 (setq pos (point))
12165 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
12166 (delete-region (point) (1+ (point-at-eol)))
12167 (beginning-of-line tonew)
12168 (insert txt)
12169 (beginning-of-line 0)
12170 (move-to-column col)))
12172 (defun org-table-insert-row (&optional arg)
12173 "Insert a new row above the current line into the table.
12174 With prefix ARG, insert below the current line."
12175 (interactive "P")
12176 (if (not (org-at-table-p))
12177 (error "Not at a table"))
12178 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
12179 (new (org-table-clean-line line)))
12180 ;; Fix the first field if necessary
12181 (if (string-match "^[ \t]*| *[#$] *|" line)
12182 (setq new (replace-match (match-string 0 line) t t new)))
12183 (beginning-of-line (if arg 2 1))
12184 (let (org-table-may-need-update) (insert-before-markers new "\n"))
12185 (beginning-of-line 0)
12186 (re-search-forward "| ?" (point-at-eol) t)
12187 (and org-table-may-need-update (org-table-align))))
12189 (defun org-table-insert-hline (&optional arg)
12190 "Insert a horizontal-line below the current line into the table.
12191 With prefix ARG, insert above the current line."
12192 (interactive "P")
12193 (if (not (org-at-table-p))
12194 (error "Not at a table"))
12195 (let ((line (org-table-clean-line
12196 (buffer-substring (point-at-bol) (point-at-eol))))
12197 (col (current-column)))
12198 (while (string-match "|\\( +\\)|" line)
12199 (setq line (replace-match
12200 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
12201 ?-) "|") t t line)))
12202 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
12203 (beginning-of-line (if arg 1 2))
12204 (insert line "\n")
12205 (beginning-of-line (if arg 1 -1))
12206 (move-to-column col)))
12208 (defun org-table-clean-line (s)
12209 "Convert a table line S into a string with only \"|\" and space.
12210 In particular, this does handle wide and invisible characters."
12211 (if (string-match "^[ \t]*|-" s)
12212 ;; It's a hline, just map the characters
12213 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
12214 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
12215 (setq s (replace-match
12216 (concat "|" (make-string (org-string-width (match-string 1 s))
12217 ?\ ) "|")
12218 t t s)))
12221 (defun org-table-kill-row ()
12222 "Delete the current row or horizontal line from the table."
12223 (interactive)
12224 (if (not (org-at-table-p))
12225 (error "Not at a table"))
12226 (let ((col (current-column)))
12227 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
12228 (if (not (org-at-table-p)) (beginning-of-line 0))
12229 (move-to-column col)))
12231 (defun org-table-sort-lines (beg end numericp)
12232 "Sort table lines in region.
12233 Point and mark define the first and last line to include. Both point and
12234 mark should be in the column that is used for sorting. For example, to
12235 sort according to column 3, put the mark in the first line to sort, in
12236 table column 3. Put point into the last line to be included in the sorting,
12237 also in table column 3. The command will prompt for the sorting method
12238 \(n for numerical, a for alphanumeric)."
12239 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
12240 (setq numericp (string-match "[nN]" numericp))
12241 (org-table-align) ;; Just to be safe
12242 (let* (bcol ecol cmp column lns)
12243 (goto-char beg)
12244 (org-table-check-inside-data-field)
12245 (setq column (org-table-current-column)
12246 beg (move-marker (make-marker) (point-at-bol)))
12247 (goto-char end)
12248 (org-table-check-inside-data-field)
12249 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
12250 (untabify beg end)
12251 (goto-char beg)
12252 (org-table-goto-column column)
12253 (skip-chars-backward "^|")
12254 (setq bcol (current-column))
12255 (org-table-goto-column (1+ column))
12256 (skip-chars-backward "^|")
12257 (setq ecol (1- (current-column)))
12258 (setq cmp (if numericp
12259 (lambda (a b) (< (car a) (car b)))
12260 (lambda (a b) (string< (car a) (car b)))))
12261 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
12262 (org-split-string (buffer-substring beg end) "\n")))
12263 (if numericp
12264 (setq lns (mapcar (lambda(x)
12265 (cons (string-to-number (car x)) (cdr x)))
12266 lns)))
12267 (delete-region beg end)
12268 (move-marker beg nil)
12269 (move-marker end nil)
12270 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
12271 (message "%d lines sorted %s based on column %d"
12272 (length lns)
12273 (if numericp "numerically" "alphabetically") column)))
12275 (defun org-table-cut-region (beg end)
12276 "Copy region in table to the clipboard and blank all relevant fields."
12277 (interactive "r")
12278 (org-table-copy-region beg end 'cut))
12280 (defun org-table-copy-region (beg end &optional cut)
12281 "Copy rectangular region in table to clipboard.
12282 A special clipboard is used which can only be accessed
12283 with `org-table-paste-rectangle'."
12284 (interactive "rP")
12285 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
12286 region cols
12287 (rpl (if cut " " nil)))
12288 (goto-char beg)
12289 (org-table-check-inside-data-field)
12290 (setq l01 (count-lines (point-min) (point))
12291 c01 (org-table-current-column))
12292 (goto-char end)
12293 (org-table-check-inside-data-field)
12294 (setq l02 (count-lines (point-min) (point))
12295 c02 (org-table-current-column))
12296 (setq l1 (min l01 l02) l2 (max l01 l02)
12297 c1 (min c01 c02) c2 (max c01 c02))
12298 (catch 'exit
12299 (while t
12300 (catch 'nextline
12301 (if (> l1 l2) (throw 'exit t))
12302 (goto-line l1)
12303 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
12304 (setq cols nil ic1 c1 ic2 c2)
12305 (while (< ic1 (1+ ic2))
12306 (push (org-table-get-field ic1 rpl) cols)
12307 (setq ic1 (1+ ic1)))
12308 (push (nreverse cols) region)
12309 (setq l1 (1+ l1)))))
12310 (setq org-table-clip (nreverse region))
12311 (if cut (org-table-align))
12312 org-table-clip))
12314 (defun org-table-paste-rectangle ()
12315 "Paste a rectangular region into a table.
12316 The upper right corner ends up in the current field. All involved fields
12317 will be overwritten. If the rectangle does not fit into the present table,
12318 the table is enlarged as needed. The process ignores horizontal separator
12319 lines."
12320 (interactive)
12321 (unless (and org-table-clip (listp org-table-clip))
12322 (error "First cut/copy a region to paste!"))
12323 (org-table-check-inside-data-field)
12324 (let* ((clip org-table-clip)
12325 (line (count-lines (point-min) (point)))
12326 (col (org-table-current-column))
12327 (org-enable-table-editor t)
12328 (org-table-automatic-realign nil)
12329 c cols field)
12330 (while (setq cols (pop clip))
12331 (while (org-at-table-hline-p) (beginning-of-line 2))
12332 (if (not (org-at-table-p))
12333 (progn (end-of-line 0) (org-table-next-field)))
12334 (setq c col)
12335 (while (setq field (pop cols))
12336 (org-table-goto-column c nil 'force)
12337 (org-table-get-field nil field)
12338 (setq c (1+ c)))
12339 (beginning-of-line 2))
12340 (goto-line line)
12341 (org-table-goto-column col)
12342 (org-table-align)))
12344 (defun org-table-convert ()
12345 "Convert from `org-mode' table to table.el and back.
12346 Obviously, this only works within limits. When an Org-mode table is
12347 converted to table.el, all horizontal separator lines get lost, because
12348 table.el uses these as cell boundaries and has no notion of horizontal lines.
12349 A table.el table can be converted to an Org-mode table only if it does not
12350 do row or column spanning. Multiline cells will become multiple cells.
12351 Beware, Org-mode does not test if the table can be successfully converted - it
12352 blindly applies a recipe that works for simple tables."
12353 (interactive)
12354 (require 'table)
12355 (if (org-at-table.el-p)
12356 ;; convert to Org-mode table
12357 (let ((beg (move-marker (make-marker) (org-table-begin t)))
12358 (end (move-marker (make-marker) (org-table-end t))))
12359 (table-unrecognize-region beg end)
12360 (goto-char beg)
12361 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
12362 (replace-match ""))
12363 (goto-char beg))
12364 (if (org-at-table-p)
12365 ;; convert to table.el table
12366 (let ((beg (move-marker (make-marker) (org-table-begin)))
12367 (end (move-marker (make-marker) (org-table-end))))
12368 ;; first, get rid of all horizontal lines
12369 (goto-char beg)
12370 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
12371 (replace-match ""))
12372 ;; insert a hline before first
12373 (goto-char beg)
12374 (org-table-insert-hline 'above)
12375 (beginning-of-line -1)
12376 ;; insert a hline after each line
12377 (while (progn (beginning-of-line 3) (< (point) end))
12378 (org-table-insert-hline))
12379 (goto-char beg)
12380 (setq end (move-marker end (org-table-end)))
12381 ;; replace "+" at beginning and ending of hlines
12382 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
12383 (replace-match "\\1+-"))
12384 (goto-char beg)
12385 (while (re-search-forward "-|[ \t]*$" end t)
12386 (replace-match "-+"))
12387 (goto-char beg)))))
12389 (defun org-table-wrap-region (arg)
12390 "Wrap several fields in a column like a paragraph.
12391 This is useful if you'd like to spread the contents of a field over several
12392 lines, in order to keep the table compact.
12394 If there is an active region, and both point and mark are in the same column,
12395 the text in the column is wrapped to minimum width for the given number of
12396 lines. Generally, this makes the table more compact. A prefix ARG may be
12397 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
12398 formats the selected text to two lines. If the region was longer than two
12399 lines, the remaining lines remain empty. A negative prefix argument reduces
12400 the current number of lines by that amount. The wrapped text is pasted back
12401 into the table. If you formatted it to more lines than it was before, fields
12402 further down in the table get overwritten - so you might need to make space in
12403 the table first.
12405 If there is no region, the current field is split at the cursor position and
12406 the text fragment to the right of the cursor is prepended to the field one
12407 line down.
12409 If there is no region, but you specify a prefix ARG, the current field gets
12410 blank, and the content is appended to the field above."
12411 (interactive "P")
12412 (org-table-check-inside-data-field)
12413 (if (org-region-active-p)
12414 ;; There is a region: fill as a paragraph
12415 (let ((beg (region-beginning))
12416 nlines)
12417 (org-table-cut-region (region-beginning) (region-end))
12418 (if (> (length (car org-table-clip)) 1)
12419 (error "Region must be limited to single column"))
12420 (setq nlines (if arg
12421 (if (< arg 1)
12422 (+ (length org-table-clip) arg)
12423 arg)
12424 (length org-table-clip)))
12425 (setq org-table-clip
12426 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
12427 nil nlines)))
12428 (goto-char beg)
12429 (org-table-paste-rectangle))
12430 ;; No region, split the current field at point
12431 (if arg
12432 ;; combine with field above
12433 (let ((s (org-table-blank-field))
12434 (col (org-table-current-column)))
12435 (beginning-of-line 0)
12436 (while (org-at-table-hline-p) (beginning-of-line 0))
12437 (org-table-goto-column col)
12438 (skip-chars-forward "^|")
12439 (skip-chars-backward " ")
12440 (insert " " (org-trim s))
12441 (org-table-align))
12442 ;; split field
12443 (when (looking-at "\\([^|]+\\)+|")
12444 (let ((s (match-string 1)))
12445 (replace-match " |")
12446 (goto-char (match-beginning 0))
12447 (org-table-next-row)
12448 (insert (org-trim s) " ")
12449 (org-table-align))))))
12451 (defvar org-field-marker nil)
12453 (defun org-table-edit-field (arg)
12454 "Edit table field in a different window.
12455 This is mainly useful for fields that contain hidden parts.
12456 When called with a \\[universal-argument] prefix, just make the full field visible so that
12457 it can be edited in place."
12458 (interactive "P")
12459 (if arg
12460 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
12461 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
12462 (remove-text-properties b e '(org-cwidth t invisible t
12463 display t intangible t))
12464 (if (and (boundp 'font-lock-mode) font-lock-mode)
12465 (font-lock-fontify-block)))
12466 (let ((pos (move-marker (make-marker) (point)))
12467 (field (org-table-get-field))
12468 (cw (current-window-configuration))
12470 (switch-to-buffer-other-window "*Org tmp*")
12471 (erase-buffer)
12472 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
12473 (org-mode)
12474 (goto-char (setq p (point-max)))
12475 (insert (org-trim field))
12476 (remove-text-properties p (point-max)
12477 '(invisible t org-cwidth t display t
12478 intangible t))
12479 (goto-char p)
12480 (org-set-local 'org-finish-function
12481 'org-table-finish-edit-field)
12482 (org-set-local 'org-window-configuration cw)
12483 (org-set-local 'org-field-marker pos)
12484 (message "Edit and finish with C-c C-c"))))
12486 (defun org-table-finish-edit-field ()
12487 "Finish editing a table data field.
12488 Remove all newline characters, insert the result into the table, realign
12489 the table and kill the editing buffer."
12490 (let ((pos org-field-marker)
12491 (cw org-window-configuration)
12492 (cb (current-buffer))
12493 text)
12494 (goto-char (point-min))
12495 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
12496 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
12497 (replace-match " "))
12498 (setq text (org-trim (buffer-string)))
12499 (set-window-configuration cw)
12500 (kill-buffer cb)
12501 (select-window (get-buffer-window (marker-buffer pos)))
12502 (goto-char pos)
12503 (move-marker pos nil)
12504 (org-table-check-inside-data-field)
12505 (org-table-get-field nil text)
12506 (org-table-align)
12507 (message "New field value inserted")))
12509 (defun org-trim (s)
12510 "Remove whitespace at beginning and end of string."
12511 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
12512 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
12515 (defun org-wrap (string &optional width lines)
12516 "Wrap string to either a number of lines, or a width in characters.
12517 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12518 that costs. If there is a word longer than WIDTH, the text is actually
12519 wrapped to the length of that word.
12520 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12521 many lines, whatever width that takes.
12522 The return value is a list of lines, without newlines at the end."
12523 (let* ((words (org-split-string string "[ \t\n]+"))
12524 (maxword (apply 'max (mapcar 'org-string-width words)))
12525 w ll)
12526 (cond (width
12527 (org-do-wrap words (max maxword width)))
12528 (lines
12529 (setq w maxword)
12530 (setq ll (org-do-wrap words maxword))
12531 (if (<= (length ll) lines)
12533 (setq ll words)
12534 (while (> (length ll) lines)
12535 (setq w (1+ w))
12536 (setq ll (org-do-wrap words w)))
12537 ll))
12538 (t (error "Cannot wrap this")))))
12541 (defun org-do-wrap (words width)
12542 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12543 (let (lines line)
12544 (while words
12545 (setq line (pop words))
12546 (while (and words (< (+ (length line) (length (car words))) width))
12547 (setq line (concat line " " (pop words))))
12548 (setq lines (push line lines)))
12549 (nreverse lines)))
12551 (defun org-split-string (string &optional separators)
12552 "Splits STRING into substrings at SEPARATORS.
12553 No empty strings are returned if there are matches at the beginning
12554 and end of string."
12555 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12556 (start 0)
12557 notfirst
12558 (list nil))
12559 (while (and (string-match rexp string
12560 (if (and notfirst
12561 (= start (match-beginning 0))
12562 (< start (length string)))
12563 (1+ start) start))
12564 (< (match-beginning 0) (length string)))
12565 (setq notfirst t)
12566 (or (eq (match-beginning 0) 0)
12567 (and (eq (match-beginning 0) (match-end 0))
12568 (eq (match-beginning 0) start))
12569 (setq list
12570 (cons (substring string start (match-beginning 0))
12571 list)))
12572 (setq start (match-end 0)))
12573 (or (eq start (length string))
12574 (setq list
12575 (cons (substring string start)
12576 list)))
12577 (nreverse list)))
12579 (defun org-table-map-tables (function)
12580 "Apply FUNCTION to the start of all tables in the buffer."
12581 (save-excursion
12582 (save-restriction
12583 (widen)
12584 (goto-char (point-min))
12585 (while (re-search-forward org-table-any-line-regexp nil t)
12586 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
12587 (beginning-of-line 1)
12588 (if (looking-at org-table-line-regexp)
12589 (save-excursion (funcall function)))
12590 (re-search-forward org-table-any-border-regexp nil 1))))
12591 (message "Mapping tables: done"))
12593 (defun org-table-sum (&optional beg end nlast)
12594 "Sum numbers in region of current table column.
12595 The result will be displayed in the echo area, and will be available
12596 as kill to be inserted with \\[yank].
12598 If there is an active region, it is interpreted as a rectangle and all
12599 numbers in that rectangle will be summed. If there is no active
12600 region and point is located in a table column, sum all numbers in that
12601 column.
12603 If at least one number looks like a time HH:MM or HH:MM:SS, all other
12604 numbers are assumed to be times as well (in decimal hours) and the
12605 numbers are added as such.
12607 If NLAST is a number, only the NLAST fields will actually be summed."
12608 (interactive)
12609 (save-excursion
12610 (let (col (timecnt 0) diff h m s org-table-clip)
12611 (cond
12612 ((and beg end)) ; beg and end given explicitly
12613 ((org-region-active-p)
12614 (setq beg (region-beginning) end (region-end)))
12616 (setq col (org-table-current-column))
12617 (goto-char (org-table-begin))
12618 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
12619 (error "No table data"))
12620 (org-table-goto-column col)
12621 ;not needed? (skip-chars-backward "^|")
12622 (setq beg (point))
12623 (goto-char (org-table-end))
12624 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
12625 (error "No table data"))
12626 (org-table-goto-column col)
12627 ;not needed? (skip-chars-forward "^|")
12628 (setq end (point))))
12629 (let* ((items (apply 'append (org-table-copy-region beg end)))
12630 (items1 (cond ((not nlast) items)
12631 ((>= nlast (length items)) items)
12632 (t (setq items (reverse items))
12633 (setcdr (nthcdr (1- nlast) items) nil)
12634 (nreverse items))))
12635 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
12636 items1)))
12637 (res (apply '+ numbers))
12638 (sres (if (= timecnt 0)
12639 (format "%g" res)
12640 (setq diff (* 3600 res)
12641 h (floor (/ diff 3600)) diff (mod diff 3600)
12642 m (floor (/ diff 60)) diff (mod diff 60)
12643 s diff)
12644 (format "%d:%02d:%02d" h m s))))
12645 (kill-new sres)
12646 (if (interactive-p)
12647 (message "%s"
12648 (substitute-command-keys
12649 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
12650 (length numbers) sres))))
12651 sres))))
12653 (defun org-table-get-number-for-summing (s)
12654 (let (n)
12655 (if (string-match "^ *|? *" s)
12656 (setq s (replace-match "" nil nil s)))
12657 (if (string-match " *|? *$" s)
12658 (setq s (replace-match "" nil nil s)))
12659 (setq n (string-to-number s))
12660 (cond
12661 ((and (string-match "0" s)
12662 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
12663 ((string-match "\\`[ \t]+\\'" s) nil)
12664 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
12665 (let ((h (string-to-number (or (match-string 1 s) "0")))
12666 (m (string-to-number (or (match-string 2 s) "0")))
12667 (s (string-to-number (or (match-string 4 s) "0"))))
12668 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
12669 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
12670 ((equal n 0) nil)
12671 (t n))))
12673 (defun org-table-get-vertical-vector (desc &optional tbeg col)
12674 "Get a calc vector from a column, accorting to descriptor DESC.
12675 Optional arguments TBEG and COL can give the beginning of the table and
12676 the current column, to avoid unnecessary parsing."
12677 (save-excursion
12678 (or tbeg (setq tbeg (org-table-begin)))
12679 (or col (setq col (org-table-current-column)))
12680 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
12681 (cond
12682 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
12683 (setq n1 (- (match-end 1) (match-beginning 1)))
12684 (if (match-beginning 3)
12685 (setq n2 (- (match-end 2) (match-beginning 3))))
12686 (setq n (if n2 (max n1 n2) n1))
12687 (setq n1 (if n2 (min n1 n2)))
12688 (setq nn n)
12689 (while (and (> nn 0)
12690 (re-search-backward org-table-hline-regexp tbeg t))
12691 (push (org-current-line) hline-list)
12692 (setq nn (1- nn)))
12693 (setq hline-list (nreverse hline-list))
12694 (goto-line (nth (1- n) hline-list))
12695 (when (re-search-forward org-table-dataline-regexp)
12696 (org-table-goto-column col)
12697 (setq beg (point)))
12698 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
12699 (when (re-search-backward org-table-dataline-regexp)
12700 (org-table-goto-column col)
12701 (setq end (point)))
12702 (setq l (apply 'append (org-table-copy-region beg end)))
12703 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
12704 (if (equal x "") "0" x))
12705 l ",") "]"))
12706 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
12707 (setq n1 (string-to-number (match-string 1 desc))
12708 n2 (string-to-number (match-string 2 desc)))
12709 (beginning-of-line 1)
12710 (save-excursion
12711 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
12712 (org-table-goto-column col)
12713 (setq beg (point))))
12714 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
12715 (org-table-goto-column col)
12716 (setq end (point)))
12717 (setq l (apply 'append (org-table-copy-region beg end)))
12718 (concat "[" (mapconcat
12719 (lambda (x) (setq x (org-trim x))
12720 (if (equal x "") "0" x))
12721 l ",") "]"))
12722 ((string-match "\\([0-9]+\\)" desc)
12723 (beginning-of-line 1)
12724 (when (re-search-backward org-table-dataline-regexp tbeg t
12725 (string-to-number (match-string 0 desc)))
12726 (org-table-goto-column col)
12727 (org-trim (org-table-get-field))))))))
12729 (defvar org-table-formula-history nil)
12731 (defvar org-table-column-names nil
12732 "Alist with column names, derived from the `!' line.")
12733 (defvar org-table-column-name-regexp nil
12734 "Regular expression matching the current column names.")
12735 (defvar org-table-local-parameters nil
12736 "Alist with parameter names, derived from the `$' line.")
12737 (defvar org-table-named-field-locations nil
12738 "Alist with locations of named fields.")
12740 (defun org-table-get-formula (&optional equation named)
12741 "Read a formula from the minibuffer, offer stored formula as default."
12742 (let* ((name (car (rassoc (list (org-current-line)
12743 (org-table-current-column))
12744 org-table-named-field-locations)))
12745 (scol (if named
12746 (if name name
12747 (error "Not in a named field"))
12748 (int-to-string (org-table-current-column))))
12749 (dummy (and name (not named)
12750 (not (y-or-n-p "Replace named-field formula with column equation? " ))
12751 (error "Abort")))
12752 (org-table-may-need-update nil)
12753 (stored-list (org-table-get-stored-formulas))
12754 (stored (cdr (assoc scol stored-list)))
12755 (eq (cond
12756 ((and stored equation (string-match "^ *=? *$" equation))
12757 stored)
12758 ((stringp equation)
12759 equation)
12760 (t (read-string
12761 (format "%s formula $%s=" (if named "Field" "Column") scol)
12762 (or stored "") 'org-table-formula-history
12763 ;stored
12764 ))))
12765 mustsave)
12766 (when (not (string-match "\\S-" eq))
12767 ;; remove formula
12768 (setq stored-list (delq (assoc scol stored-list) stored-list))
12769 (org-table-store-formulas stored-list)
12770 (error "Formula removed"))
12771 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
12772 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
12773 (if (and name (not named))
12774 ;; We set the column equation, delete the named one.
12775 (setq stored-list (delq (assoc name stored-list) stored-list)
12776 mustsave t))
12777 (if stored
12778 (setcdr (assoc scol stored-list) eq)
12779 (setq stored-list (cons (cons scol eq) stored-list)))
12780 (if (or mustsave (not (equal stored eq)))
12781 (org-table-store-formulas stored-list))
12782 eq))
12784 (defun org-table-store-formulas (alist)
12785 "Store the list of formulas below the current table."
12786 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
12787 (save-excursion
12788 (goto-char (org-table-end))
12789 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
12790 (delete-region (point) (match-end 0)))
12791 (insert "#+TBLFM: "
12792 (mapconcat (lambda (x)
12793 (concat "$" (car x) "=" (cdr x)))
12794 alist "::")
12795 "\n")))
12797 (defun org-table-get-stored-formulas ()
12798 "Return an alist with the stored formulas directly after current table."
12799 (interactive)
12800 (let (scol eq eq-alist strings string seen)
12801 (save-excursion
12802 (goto-char (org-table-end))
12803 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
12804 (setq strings (org-split-string (match-string 2) " *:: *"))
12805 (while (setq string (pop strings))
12806 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
12807 (setq scol (match-string 1 string)
12808 eq (match-string 2 string)
12809 eq-alist (cons (cons scol eq) eq-alist))
12810 (if (member scol seen)
12811 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
12812 (push scol seen))))))
12813 (nreverse eq-alist)))
12815 (defun org-table-modify-formulas (action &rest columns)
12816 "Modify the formulas stored below the current table.
12817 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
12818 expected, for the other actions only a single column number is needed."
12819 (let ((list (org-table-get-stored-formulas))
12820 (nmax (length (org-split-string
12821 (buffer-substring (point-at-bol) (point-at-eol))
12822 "|")))
12823 col col1 col2 scol si sc1 sc2)
12824 (cond
12825 ((null list)) ; No action needed if there are no stored formulas
12826 ((eq action 'remove)
12827 (setq col (car columns)
12828 scol (int-to-string col))
12829 (org-table-replace-in-formulas list scol "INVALID")
12830 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
12831 (loop for i from (1+ col) upto nmax by 1 do
12832 (setq si (int-to-string i))
12833 (org-table-replace-in-formulas list si (int-to-string (1- i)))
12834 (if (assoc si list) (setcar (assoc si list)
12835 (int-to-string (1- i))))))
12836 ((eq action 'insert)
12837 (setq col (car columns))
12838 (loop for i from nmax downto col by 1 do
12839 (setq si (int-to-string i))
12840 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
12841 (if (assoc si list) (setcar (assoc si list)
12842 (int-to-string (1+ i))))))
12843 ((eq action 'swap)
12844 (setq col1 (car columns) col2 (nth 1 columns)
12845 sc1 (int-to-string col1) sc2 (int-to-string col2))
12846 ;; Hopefully, ZqZtZ will never be a name in a table
12847 (org-table-replace-in-formulas list sc1 "ZqZtZ")
12848 (org-table-replace-in-formulas list sc2 sc1)
12849 (org-table-replace-in-formulas list "ZqZtZ" sc2)
12850 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
12851 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
12852 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
12853 (t (error "Invalid action in `org-table-modify-formulas'")))
12854 (if list (org-table-store-formulas list))))
12856 (defun org-table-replace-in-formulas (list s1 s2)
12857 (let (elt re s)
12858 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
12859 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
12860 re (concat (regexp-quote s1) "\\>"))
12861 (while (setq elt (pop list))
12862 (setq s (cdr elt))
12863 (while (string-match re s)
12864 (setq s (replace-match s2 t t s)))
12865 (setcdr elt s))))
12867 (defun org-table-get-specials ()
12868 "Get the column names and local parameters for this table."
12869 (save-excursion
12870 (let ((beg (org-table-begin)) (end (org-table-end))
12871 names name fields fields1 field cnt c v line col)
12872 (setq org-table-column-names nil
12873 org-table-local-parameters nil
12874 org-table-named-field-locations nil)
12875 (goto-char beg)
12876 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
12877 (setq names (org-split-string (match-string 1) " *| *")
12878 cnt 1)
12879 (while (setq name (pop names))
12880 (setq cnt (1+ cnt))
12881 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
12882 (push (cons name (int-to-string cnt)) org-table-column-names))))
12883 (setq org-table-column-names (nreverse org-table-column-names))
12884 (setq org-table-column-name-regexp
12885 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
12886 (goto-char beg)
12887 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
12888 (setq fields (org-split-string (match-string 1) " *| *"))
12889 (while (setq field (pop fields))
12890 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
12891 (push (cons (match-string 1 field) (match-string 2 field))
12892 org-table-local-parameters))))
12893 (goto-char beg)
12894 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
12895 (setq c (match-string 1)
12896 fields (org-split-string (match-string 2) " *| *"))
12897 (save-excursion
12898 (beginning-of-line (if (equal c "_") 2 0))
12899 (setq line (org-current-line) col 1)
12900 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
12901 (setq fields1 (org-split-string (match-string 1) " *| *"))))
12902 (while (and fields1 (setq field (pop fields)))
12903 (setq v (pop fields1) col (1+ col))
12904 (when (and (stringp field) (stringp v)
12905 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
12906 (push (cons field v) org-table-local-parameters)
12907 (push (list field line col) org-table-named-field-locations)))))))
12909 (defun org-this-word ()
12910 ;; Get the current word
12911 (save-excursion
12912 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
12913 (end (progn (skip-chars-forward "^ \t\n") (point))))
12914 (buffer-substring-no-properties beg end))))
12916 (defun org-table-maybe-eval-formula ()
12917 "Check if the current field starts with \"=\" or \":=\".
12918 If yes, store the formula and apply it."
12919 ;; We already know we are in a table. Get field will only return a formula
12920 ;; when appropriate. It might return a separator line, but no problem.
12921 (when org-table-formula-evaluate-inline
12922 (let* ((field (org-trim (or (org-table-get-field) "")))
12923 named eq)
12924 (when (string-match "^:?=\\(.*\\)" field)
12925 (setq named (equal (string-to-char field) ?:)
12926 eq (match-string 1 field))
12927 (if (fboundp 'calc-eval)
12928 (org-table-eval-formula (if named '(4) nil) eq))))))
12930 (defvar org-recalc-commands nil
12931 "List of commands triggering the recalculation of a line.
12932 Will be filled automatically during use.")
12934 (defvar org-recalc-marks
12935 '((" " . "Unmarked: no special line, no automatic recalculation")
12936 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
12937 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
12938 ("!" . "Column name definition line. Reference in formula as $name.")
12939 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
12940 ("_" . "Names for values in row below this one.")
12941 ("^" . "Names for values in row above this one.")))
12943 (defun org-table-rotate-recalc-marks (&optional newchar)
12944 "Rotate the recalculation mark in the first column.
12945 If in any row, the first field is not consistent with a mark,
12946 insert a new column for the markers.
12947 When there is an active region, change all the lines in the region,
12948 after prompting for the marking character.
12949 After each change, a message will be displayed indicating the meaning
12950 of the new mark."
12951 (interactive)
12952 (unless (org-at-table-p) (error "Not at a table"))
12953 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
12954 (beg (org-table-begin))
12955 (end (org-table-end))
12956 (l (org-current-line))
12957 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
12958 (l2 (if (org-region-active-p) (org-current-line (region-end))))
12959 (have-col
12960 (save-excursion
12961 (goto-char beg)
12962 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
12963 (col (org-table-current-column))
12964 (forcenew (car (assoc newchar org-recalc-marks)))
12965 epos new)
12966 (when l1
12967 (message "Change region to what mark? Type # * ! $ or SPC: ")
12968 (setq newchar (char-to-string (read-char-exclusive))
12969 forcenew (car (assoc newchar org-recalc-marks))))
12970 (if (and newchar (not forcenew))
12971 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
12972 newchar))
12973 (if l1 (goto-line l1))
12974 (save-excursion
12975 (beginning-of-line 1)
12976 (unless (looking-at org-table-dataline-regexp)
12977 (error "Not at a table data line")))
12978 (unless have-col
12979 (org-table-goto-column 1)
12980 (org-table-insert-column)
12981 (org-table-goto-column (1+ col)))
12982 (setq epos (point-at-eol))
12983 (save-excursion
12984 (beginning-of-line 1)
12985 (org-table-get-field
12986 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
12987 (concat " "
12988 (setq new (or forcenew
12989 (cadr (member (match-string 1) marks))))
12990 " ")
12991 " # ")))
12992 (if (and l1 l2)
12993 (progn
12994 (goto-line l1)
12995 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
12996 (and (looking-at org-table-dataline-regexp)
12997 (org-table-get-field 1 (concat " " new " "))))
12998 (goto-line l1)))
12999 (if (not (= epos (point-at-eol))) (org-table-align))
13000 (goto-line l)
13001 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
13003 (defun org-table-maybe-recalculate-line ()
13004 "Recompute the current line if marked for it, and if we haven't just done it."
13005 (interactive)
13006 (and org-table-allow-automatic-line-recalculation
13007 (not (and (memq last-command org-recalc-commands)
13008 (equal org-last-recalc-line (org-current-line))))
13009 (save-excursion (beginning-of-line 1)
13010 (looking-at org-table-auto-recalculate-regexp))
13011 (fboundp 'calc-eval)
13012 (org-table-recalculate) t))
13014 (defvar org-table-formula-debug nil
13015 "Non-nil means, debug table formulas.
13016 When nil, simply write \"#ERROR\" in corrupted fields.")
13018 (defvar modes)
13019 (defsubst org-set-calc-mode (var &optional value)
13020 (if (stringp var)
13021 (setq var (assoc var '(("D" calc-angle-mode deg)
13022 ("R" calc-angle-mode rad)
13023 ("F" calc-prefer-frac t)
13024 ("S" calc-symbolic-mode t)))
13025 value (nth 2 var) var (nth 1 var)))
13026 (if (memq var modes)
13027 (setcar (cdr (memq var modes)) value)
13028 (cons var (cons value modes)))
13029 modes)
13031 (defun org-table-eval-formula (&optional arg equation
13032 suppress-align suppress-const
13033 suppress-store)
13034 "Replace the table field value at the cursor by the result of a calculation.
13036 This function makes use of Dave Gillespie's Calc package, in my view the
13037 most exciting program ever written for GNU Emacs. So you need to have Calc
13038 installed in order to use this function.
13040 In a table, this command replaces the value in the current field with the
13041 result of a formula. It also installs the formula as the \"current\" column
13042 formula, by storing it in a special line below the table. When called
13043 with a `C-u' prefix, the current field must ba a named field, and the
13044 formula is installed as valid in only this specific field.
13046 When called, the command first prompts for a formula, which is read in
13047 the minibuffer. Previously entered formulas are available through the
13048 history list, and the last used formula is offered as a default.
13049 These stored formulas are adapted correctly when moving, inserting, or
13050 deleting columns with the corresponding commands.
13052 The formula can be any algebraic expression understood by the Calc package.
13053 For details, see the Org-mode manual.
13055 This function can also be called from Lisp programs and offers
13056 additional arguments: EQUATION can be the formula to apply. If this
13057 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
13058 used to speed-up recursive calls by by-passing unnecessary aligns.
13059 SUPPRESS-CONST suppresses the interpretation of constants in the
13060 formula, assuming that this has been done already outside the function.
13061 SUPPRESS-STORE means the formula should not be stored, either because
13062 it is already stored, or because it is a modified equation that should
13063 not overwrite the stored one."
13064 (interactive "P")
13065 (require 'calc)
13066 (org-table-check-inside-data-field)
13067 (org-table-get-specials)
13068 (let* (fields
13069 (ndown (if (integerp arg) arg 1))
13070 (org-table-automatic-realign nil)
13071 (case-fold-search nil)
13072 (down (> ndown 1))
13073 (formula (if (and equation suppress-store)
13074 equation
13075 (org-table-get-formula equation (equal arg '(4)))))
13076 (n0 (org-table-current-column))
13077 (modes (copy-sequence org-calc-default-modes))
13078 n form fmt x ev orig c lispp)
13079 ;; Parse the format string. Since we have a lot of modes, this is
13080 ;; a lot of work. However, I think calc still uses most of the time.
13081 (if (string-match ";" formula)
13082 (let ((tmp (org-split-string formula ";")))
13083 (setq formula (car tmp)
13084 fmt (concat (cdr (assoc "%" org-table-local-parameters))
13085 (nth 1 tmp)))
13086 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
13087 (setq c (string-to-char (match-string 1 fmt))
13088 n (string-to-number (match-string 2 fmt)))
13089 (if (= c ?p)
13090 (setq modes (org-set-calc-mode 'calc-internal-prec n))
13091 (setq modes (org-set-calc-mode
13092 'calc-float-format
13093 (list (cdr (assoc c '((?n . float) (?f . fix)
13094 (?s . sci) (?e . eng))))
13095 n))))
13096 (setq fmt (replace-match "" t t fmt)))
13097 (while (string-match "[DRFS]" fmt)
13098 (setq modes (org-set-calc-mode (match-string 0 fmt)))
13099 (setq fmt (replace-match "" t t fmt)))
13100 (unless (string-match "\\S-" fmt)
13101 (setq fmt nil))))
13102 (if (and (not suppress-const) org-table-formula-use-constants)
13103 (setq formula (org-table-formula-substitute-names formula)))
13104 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
13105 (while (> ndown 0)
13106 (setq fields (org-split-string
13107 (buffer-substring
13108 (point-at-bol) (point-at-eol)) " *| *"))
13109 (if org-table-formula-numbers-only
13110 (setq fields (mapcar
13111 (lambda (x) (number-to-string (string-to-number x)))
13112 fields)))
13113 (setq ndown (1- ndown))
13114 (setq form (copy-sequence formula)
13115 lispp (equal (substring form 0 2) "'("))
13116 ;; Insert the references to fields in same row
13117 (while (string-match "\\$\\([0-9]+\\)?" form)
13118 (setq n (if (match-beginning 1)
13119 (string-to-number (match-string 1 form))
13121 x (nth (1- n) fields))
13122 (unless x (error "Invalid field specifier \"%s\""
13123 (match-string 0 form)))
13124 (if (equal x "") (setq x "0"))
13125 (setq form (replace-match
13126 (if lispp x (concat "(" x ")"))
13127 t t form)))
13128 ;; Insert ranges in current column
13129 (while (string-match "\\&[-I0-9]+" form)
13130 (setq form (replace-match
13131 (save-match-data
13132 (org-table-get-vertical-vector (match-string 0 form)
13133 nil n0))
13134 t t form)))
13135 (if lispp
13136 (setq ev (eval (eval (read form)))
13137 ev (if (numberp ev) (number-to-string ev) ev))
13138 (setq ev (calc-eval (cons form modes)
13139 (if org-table-formula-numbers-only 'num))))
13141 (when org-table-formula-debug
13142 (with-output-to-temp-buffer "*Help*"
13143 (princ (format "Substitution history of formula
13144 Orig: %s
13145 $xyz-> %s
13146 $1-> %s\n" orig formula form))
13147 (if (listp ev)
13148 (princ (format " %s^\nError: %s"
13149 (make-string (car ev) ?\-) (nth 1 ev)))
13150 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
13151 ev (or fmt "NONE")
13152 (if fmt (format fmt (string-to-number ev)) ev)))))
13153 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
13154 (unless (and (interactive-p) (not ndown))
13155 (unless (let (inhibit-redisplay)
13156 (y-or-n-p "Debugging Formula. Continue to next? "))
13157 (org-table-align)
13158 (error "Abort"))
13159 (delete-window (get-buffer-window "*Help*"))
13160 (message "")))
13161 (if (listp ev) (setq fmt nil ev "#ERROR"))
13162 (org-table-justify-field-maybe
13163 (if fmt (format fmt (string-to-number ev)) ev))
13164 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
13165 (call-interactively 'org-return)
13166 (setq ndown 0)))
13167 (and down (org-table-maybe-recalculate-line))
13168 (or suppress-align (and org-table-may-need-update
13169 (org-table-align)))))
13171 (defun org-table-recalculate (&optional all noalign)
13172 "Recalculate the current table line by applying all stored formulas.
13173 With prefix arg ALL, do this for all lines in the table."
13174 (interactive "P")
13175 (or (memq this-command org-recalc-commands)
13176 (setq org-recalc-commands (cons this-command org-recalc-commands)))
13177 (unless (org-at-table-p) (error "Not at a table"))
13178 (org-table-get-specials)
13179 (let* ((eqlist (sort (org-table-get-stored-formulas)
13180 (lambda (a b) (string< (car a) (car b)))))
13181 (inhibit-redisplay t)
13182 (line-re org-table-dataline-regexp)
13183 (thisline (org-current-line))
13184 (thiscol (org-table-current-column))
13185 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
13186 ;; Insert constants in all formulas
13187 (setq eqlist
13188 (mapcar (lambda (x)
13189 (setcdr x (org-table-formula-substitute-names (cdr x)))
13191 eqlist))
13192 ;; Split the equation list
13193 (while (setq eq (pop eqlist))
13194 (if (<= (string-to-char (car eq)) ?9)
13195 (push eq eqlnum)
13196 (push eq eqlname)))
13197 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
13198 (if all
13199 (progn
13200 (setq end (move-marker (make-marker) (1+ (org-table-end))))
13201 (goto-char (setq beg (org-table-begin)))
13202 (if (re-search-forward org-table-calculate-mark-regexp end t)
13203 ;; This is a table with marked lines, only compute selected lines
13204 (setq line-re org-table-recalculate-regexp)
13205 ;; Move forward to the first non-header line
13206 (if (and (re-search-forward org-table-dataline-regexp end t)
13207 (re-search-forward org-table-hline-regexp end t)
13208 (re-search-forward org-table-dataline-regexp end t))
13209 (setq beg (match-beginning 0))
13210 nil))) ;; just leave beg where it is
13211 (setq beg (point-at-bol)
13212 end (move-marker (make-marker) (1+ (point-at-eol)))))
13213 (goto-char beg)
13214 (and all (message "Re-applying formulas to full table..."))
13215 (while (re-search-forward line-re end t)
13216 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
13217 ;; Unprotected line, recalculate
13218 (and all (message "Re-applying formulas to full table...(line %d)"
13219 (setq cnt (1+ cnt))))
13220 (setq org-last-recalc-line (org-current-line))
13221 (setq eql eqlnum)
13222 (while (setq entry (pop eql))
13223 (goto-line org-last-recalc-line)
13224 (org-table-goto-column (string-to-number (car entry)) nil 'force)
13225 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
13226 (goto-line thisline)
13227 (org-table-goto-column thiscol)
13228 (or noalign (and org-table-may-need-update (org-table-align))
13229 (and all (message "Re-applying formulas to %d lines...done" cnt)))
13230 ;; Now do the names fields
13231 (while (setq eq (pop eqlname))
13232 (setq name (car eq)
13233 a (assoc name org-table-named-field-locations))
13234 (when a
13235 (message "Re-applying formula to named field: %s" name)
13236 (goto-line (nth 1 a))
13237 (org-table-goto-column (nth 2 a))
13238 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
13239 ;; back to initial position
13240 (goto-line thisline)
13241 (org-table-goto-column thiscol)
13242 (or noalign (and org-table-may-need-update (org-table-align))
13243 (and all (message "Re-applying formulas...done")))))
13245 (defun org-table-formula-substitute-names (f)
13246 "Replace $const with values in string F."
13247 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
13248 ;; First, check for column names
13249 (while (setq start (string-match org-table-column-name-regexp f start))
13250 (setq start (1+ start))
13251 (setq a (assoc (match-string 1 f) org-table-column-names))
13252 (setq f (replace-match (concat "$" (cdr a)) t t f)))
13253 ;; Expand ranges to vectors
13254 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
13255 (setq n1 (string-to-number (match-string 1 f))
13256 n2 (string-to-number (match-string 2 f))
13257 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
13258 s (concat "[($" (number-to-string (1- nn1)) ")"))
13259 (loop for i from nn1 upto nn2 do
13260 (setq s (concat s ",($" (int-to-string i) ")")))
13261 (setq s (concat s "]"))
13262 (if (< n2 n1) (setq s (concat "rev(" s ")")))
13263 (setq f (replace-match s t t f)))
13264 ;; Parameters and constants
13265 (setq start 0)
13266 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
13267 (setq start (1+ start))
13268 (if (setq a (save-match-data
13269 (org-table-get-constant (match-string 1 f))))
13270 (setq f (replace-match (concat "(" a ")") t t f))))
13271 (if org-table-formula-debug
13272 (put-text-property 0 (length f) :orig-formula f1 f))
13275 (defun org-table-get-constant (const)
13276 "Find the value for a parameter or constant in a formula.
13277 Parameters get priority."
13278 (or (cdr (assoc const org-table-local-parameters))
13279 (cdr (assoc const org-table-formula-constants))
13280 (and (fboundp 'constants-get) (constants-get const))
13281 "#UNDEFINED_NAME"))
13283 (defvar org-edit-formulas-map (make-sparse-keymap))
13284 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
13285 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
13286 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
13288 (defvar org-pos)
13290 (defun org-table-edit-formulas ()
13291 "Edit the formulas of the current table in a separate buffer."
13292 (interactive)
13293 (unless (org-at-table-p)
13294 (error "Not at a table"))
13295 (org-table-get-specials)
13296 (let ((eql (org-table-get-stored-formulas))
13297 (pos (move-marker (make-marker) (point)))
13298 (wc (current-window-configuration))
13299 entry loc s)
13300 (switch-to-buffer-other-window "*Edit Formulas*")
13301 (erase-buffer)
13302 (fundamental-mode)
13303 (org-set-local 'org-pos pos)
13304 (org-set-local 'org-window-configuration wc)
13305 (use-local-map org-edit-formulas-map)
13306 (setq s "# Edit formulas and finish with `C-c C-c'.
13307 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
13308 # Use `C-c ?' to get information about $name at point.
13309 # To cancel editing, press `C-c C-q'.\n")
13310 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
13311 (insert s)
13312 (while (setq entry (pop eql))
13313 (when (setq loc (assoc (car entry) org-table-named-field-locations))
13314 (setq s (format "# Named formula, referring to column %d in line %d\n"
13315 (nth 2 loc) (nth 1 loc)))
13316 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
13317 (insert s))
13318 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
13319 (remove-text-properties 0 (length s) '(face nil) s)
13320 (insert s))
13321 (goto-char (point-min))
13322 (message "Edit formulas and finish with `C-c C-c'.")))
13324 (defun org-show-variable ()
13325 "Show the location/value of the $ expression at point."
13326 (interactive)
13327 (let (var (pos org-pos) (win (selected-window)) e)
13328 (save-excursion
13329 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
13330 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
13331 (setq var (match-string 1))
13332 (error "No variable at point")))
13333 (cond
13334 ((setq e (assoc var org-table-named-field-locations))
13335 (switch-to-buffer-other-window (marker-buffer pos))
13336 (goto-line (nth 1 e))
13337 (org-table-goto-column (nth 2 e))
13338 (select-window win)
13339 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
13340 ((setq e (assoc var org-table-column-names))
13341 (switch-to-buffer-other-window (marker-buffer pos))
13342 (goto-char pos)
13343 (goto-char (org-table-begin))
13344 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
13345 (org-table-end) t)
13346 (progn
13347 (goto-char (match-beginning 1))
13348 (message "Named column (column %s)" (cdr e)))
13349 (error "Column name not found"))
13350 (select-window win))
13351 ((string-match "^[0-9]$" var)
13352 ;; column number
13353 (switch-to-buffer-other-window (marker-buffer pos))
13354 (goto-char pos)
13355 (goto-char (org-table-begin))
13356 (recenter 1)
13357 (if (re-search-forward org-table-dataline-regexp
13358 (org-table-end) t)
13359 (progn
13360 (goto-char (match-beginning 0))
13361 (org-table-goto-column (string-to-number var))
13362 (message "Column %s" var))
13363 (error "Column name not found"))
13364 (select-window win))
13365 ((setq e (assoc var org-table-local-parameters))
13366 (switch-to-buffer-other-window (marker-buffer pos))
13367 (goto-char pos)
13368 (goto-char (org-table-begin))
13369 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
13370 (progn
13371 (goto-char (match-beginning 1))
13372 (message "Local parameter."))
13373 (error "Parameter not found"))
13374 (select-window win))
13376 (cond
13377 ((setq e (assoc var org-table-formula-constants))
13378 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
13379 ((setq e (and (fboundp 'constants-get) (constants-get var)))
13380 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
13381 (t (error "Undefined name $%s" var)))))))
13383 (defun org-finish-edit-formulas (&optional arg)
13384 "Parse the buffer for formula definitions and install them.
13385 With prefix ARG, apply the new formulas to the table."
13386 (interactive "P")
13387 (let ((pos org-pos) eql)
13388 (goto-char (point-min))
13389 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
13390 (push (cons (match-string 1) (match-string 2)) eql))
13391 (set-window-configuration org-window-configuration)
13392 (select-window (get-buffer-window (marker-buffer pos)))
13393 (goto-char pos)
13394 (unless (org-at-table-p)
13395 (error "Lost table position - cannot install formulae"))
13396 (org-table-store-formulas eql)
13397 (move-marker pos nil)
13398 (kill-buffer "*Edit Formulas*")
13399 (if arg
13400 (org-table-recalculate 'all)
13401 (message "New formulas installed - press C-u C-c C-c to apply."))))
13403 (defun org-abort-edit-formulas ()
13404 "Abort editing formulas, without installing the changes."
13405 (interactive)
13406 (let ((pos org-pos))
13407 (set-window-configuration org-window-configuration)
13408 (select-window (get-buffer-window (marker-buffer pos)))
13409 (goto-char pos)
13410 (message "Formula editing aborted without installing changes")))
13412 ;;; The orgtbl minor mode
13414 ;; Define a minor mode which can be used in other modes in order to
13415 ;; integrate the org-mode table editor.
13417 ;; This is really a hack, because the org-mode table editor uses several
13418 ;; keys which normally belong to the major mode, for example the TAB and
13419 ;; RET keys. Here is how it works: The minor mode defines all the keys
13420 ;; necessary to operate the table editor, but wraps the commands into a
13421 ;; function which tests if the cursor is currently inside a table. If that
13422 ;; is the case, the table editor command is executed. However, when any of
13423 ;; those keys is used outside a table, the function uses `key-binding' to
13424 ;; look up if the key has an associated command in another currently active
13425 ;; keymap (minor modes, major mode, global), and executes that command.
13426 ;; There might be problems if any of the keys used by the table editor is
13427 ;; otherwise used as a prefix key.
13429 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
13430 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
13431 ;; addresses this by checking explicitly for both bindings.
13433 ;; The optimized version (see variable `orgtbl-optimized') takes over
13434 ;; all keys which are bound to `self-insert-command' in the *global map*.
13435 ;; Some modes bind other commands to simple characters, for example
13436 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
13437 ;; active, this binding is ignored inside tables and replaced with a
13438 ;; modified self-insert.
13440 (defvar orgtbl-mode nil
13441 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
13442 table editor in arbitrary modes.")
13443 (make-variable-buffer-local 'orgtbl-mode)
13445 (defvar orgtbl-mode-map (make-keymap)
13446 "Keymap for `orgtbl-mode'.")
13448 ;;;###autoload
13449 (defun turn-on-orgtbl ()
13450 "Unconditionally turn on `orgtbl-mode'."
13451 (orgtbl-mode 1))
13453 ;;;###autoload
13454 (defun orgtbl-mode (&optional arg)
13455 "The `org-mode' table editor as a minor mode for use in other modes."
13456 (interactive)
13457 (if (org-mode-p)
13458 ;; Exit without error, in case some hook functions calls this
13459 ;; by accident in org-mode.
13460 (message "Orgtbl-mode is not useful in org-mode, command ignored")
13461 (setq orgtbl-mode
13462 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
13463 (if orgtbl-mode
13464 (progn
13465 (and (orgtbl-setup) (defun orgtbl-setup () nil))
13466 ;; Make sure we are first in minor-mode-map-alist
13467 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
13468 (and c (setq minor-mode-map-alist
13469 (cons c (delq c minor-mode-map-alist)))))
13470 (org-set-local (quote org-table-may-need-update) t)
13471 (org-add-hook 'before-change-functions 'org-before-change-function
13472 nil 'local)
13473 (org-set-local 'org-old-auto-fill-inhibit-regexp
13474 auto-fill-inhibit-regexp)
13475 (org-set-local 'auto-fill-inhibit-regexp
13476 (if auto-fill-inhibit-regexp
13477 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
13478 "[ \t]*|"))
13479 (org-add-to-invisibility-spec '(org-cwidth))
13480 (easy-menu-add orgtbl-mode-menu)
13481 (run-hooks 'orgtbl-mode-hook))
13482 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
13483 (org-cleanup-narrow-column-properties)
13484 (org-remove-from-invisibility-spec '(org-cwidth))
13485 (remove-hook 'before-change-functions 'org-before-change-function t)
13486 (easy-menu-remove orgtbl-mode-menu)
13487 (force-mode-line-update 'all))))
13489 (defun org-cleanup-narrow-column-properties ()
13490 "Remove all properties related to narrow-column invisibility."
13491 (let ((s 1))
13492 (while (setq s (text-property-any s (point-max)
13493 'display org-narrow-column-arrow))
13494 (remove-text-properties s (1+ s) '(display t)))
13495 (setq s 1)
13496 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
13497 (remove-text-properties s (1+ s) '(org-cwidth t)))
13498 (setq s 1)
13499 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
13500 (remove-text-properties s (1+ s) '(invisible t)))))
13502 ;; Install it as a minor mode.
13503 (put 'orgtbl-mode :included t)
13504 (put 'orgtbl-mode :menu-tag "Org Table Mode")
13505 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
13507 (defun orgtbl-make-binding (fun n &rest keys)
13508 "Create a function for binding in the table minor mode.
13509 FUN is the command to call inside a table. N is used to create a unique
13510 command name. KEYS are keys that should be checked in for a command
13511 to execute outside of tables."
13512 (eval
13513 (list 'defun
13514 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
13515 '(arg)
13516 (concat "In tables, run `" (symbol-name fun) "'.\n"
13517 "Outside of tables, run the binding of `"
13518 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
13519 "'.")
13520 '(interactive "p")
13521 (list 'if
13522 '(org-at-table-p)
13523 (list 'call-interactively (list 'quote fun))
13524 (list 'let '(orgtbl-mode)
13525 (list 'call-interactively
13526 (append '(or)
13527 (mapcar (lambda (k)
13528 (list 'key-binding k))
13529 keys)
13530 '('orgtbl-error))))))))
13532 (defun orgtbl-error ()
13533 "Error when there is no default binding for a table key."
13534 (interactive)
13535 (error "This key is has no function outside tables"))
13537 (defun orgtbl-setup ()
13538 "Setup orgtbl keymaps."
13539 (let ((nfunc 0)
13540 (bindings
13541 (list
13542 '([(meta shift left)] org-table-delete-column)
13543 '([(meta left)] org-table-move-column-left)
13544 '([(meta right)] org-table-move-column-right)
13545 '([(meta shift right)] org-table-insert-column)
13546 '([(meta shift up)] org-table-kill-row)
13547 '([(meta shift down)] org-table-insert-row)
13548 '([(meta up)] org-table-move-row-up)
13549 '([(meta down)] org-table-move-row-down)
13550 '("\C-c\C-w" org-table-cut-region)
13551 '("\C-c\M-w" org-table-copy-region)
13552 '("\C-c\C-y" org-table-paste-rectangle)
13553 '("\C-c-" org-table-insert-hline)
13554 ; '([(shift tab)] org-table-previous-field)
13555 '("\C-m" org-table-next-row)
13556 (list (org-key 'S-return) 'org-table-copy-down)
13557 '([(meta return)] org-table-wrap-region)
13558 '("\C-c\C-q" org-table-wrap-region)
13559 '("\C-c?" org-table-current-column)
13560 '("\C-c " org-table-blank-field)
13561 '("\C-c+" org-table-sum)
13562 '("\C-c=" org-table-eval-formula)
13563 '("\C-c'" org-table-edit-formulas)
13564 '("\C-c`" org-table-edit-field)
13565 '("\C-c*" org-table-recalculate)
13566 '("\C-c|" org-table-create-or-convert-from-region)
13567 '("\C-c^" org-table-sort-lines)
13568 '([(control ?#)] org-table-rotate-recalc-marks)))
13569 elt key fun cmd)
13570 (while (setq elt (pop bindings))
13571 (setq nfunc (1+ nfunc))
13572 (setq key (car elt)
13573 fun (nth 1 elt)
13574 cmd (orgtbl-make-binding fun nfunc key))
13575 (define-key orgtbl-mode-map key cmd))
13576 ;; Special treatment needed for TAB and RET
13577 (define-key orgtbl-mode-map [(return)]
13578 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
13579 (define-key orgtbl-mode-map "\C-m"
13580 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
13581 (define-key orgtbl-mode-map [(tab)]
13582 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
13583 (define-key orgtbl-mode-map "\C-i"
13584 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
13585 (define-key orgtbl-mode-map "\C-i"
13586 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
13587 (define-key orgtbl-mode-map "\C-c\C-c"
13588 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
13589 (when orgtbl-optimized
13590 ;; If the user wants maximum table support, we need to hijack
13591 ;; some standard editing functions
13592 (org-remap orgtbl-mode-map
13593 'self-insert-command 'orgtbl-self-insert-command
13594 'delete-char 'org-delete-char
13595 'delete-backward-char 'org-delete-backward-char)
13596 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
13597 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
13598 '("OrgTbl"
13599 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
13600 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
13601 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
13602 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
13603 "--"
13604 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
13605 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
13606 ["Copy Field from Above"
13607 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
13608 "--"
13609 ("Column"
13610 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
13611 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
13612 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
13613 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
13614 "--"
13615 ["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])
13616 ("Row"
13617 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
13618 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
13619 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
13620 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
13621 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
13622 "--"
13623 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
13624 ("Rectangle"
13625 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
13626 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
13627 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
13628 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
13629 "--"
13630 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
13631 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13632 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
13633 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
13634 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
13635 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
13636 ["Sum Column/Rectangle" org-table-sum
13637 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
13638 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
13639 ["Debug Formulas"
13640 (setq org-table-formula-debug (not org-table-formula-debug))
13641 :style toggle :selected org-table-formula-debug]
13645 (defun orgtbl-tab (arg)
13646 "Justification and field motion for `orgtbl-mode'."
13647 (interactive "P")
13648 (if arg (org-table-edit-field t)
13649 (org-table-justify-field-maybe)
13650 (org-table-next-field)))
13652 (defun orgtbl-ret ()
13653 "Justification and field motion for `orgtbl-mode'."
13654 (interactive)
13655 (org-table-justify-field-maybe)
13656 (org-table-next-row))
13658 (defun orgtbl-self-insert-command (N)
13659 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13660 If the cursor is in a table looking at whitespace, the whitespace is
13661 overwritten, and the table is not marked as requiring realignment."
13662 (interactive "p")
13663 (if (and (org-at-table-p)
13665 (and org-table-auto-blank-field
13666 (member last-command
13667 '(orgtbl-hijacker-command-100
13668 orgtbl-hijacker-command-101
13669 orgtbl-hijacker-command-102
13670 orgtbl-hijacker-command-103
13671 orgtbl-hijacker-command-104
13672 orgtbl-hijacker-command-105))
13673 (org-table-blank-field))
13675 (eq N 1)
13676 (looking-at "[^|\n]* +|"))
13677 (let (org-table-may-need-update)
13678 (goto-char (1- (match-end 0)))
13679 (delete-backward-char 1)
13680 (goto-char (match-beginning 0))
13681 (self-insert-command N))
13682 (setq org-table-may-need-update t)
13683 (let (orgtbl-mode)
13684 (call-interactively (key-binding (vector last-input-event))))))
13686 (defun org-force-self-insert (N)
13687 "Needed to enforce self-insert under remapping."
13688 (interactive "p")
13689 (self-insert-command N))
13691 ;;; Exporting
13693 (defconst org-level-max 20)
13695 (defvar org-export-html-preamble nil
13696 "Preamble, to be inserted just after <body>. Set by publishing functions.")
13697 (defvar org-export-html-postamble nil
13698 "Preamble, to be inserted just before </body>. Set by publishing functions.")
13699 (defvar org-export-html-auto-preamble t
13700 "Should default preamble be inserted? Set by publishing functions.")
13701 (defvar org-export-html-auto-postamble t
13702 "Should default postamble be inserted? Set by publishing functions.")
13704 (defconst org-export-plist-vars
13705 '((:language . org-export-default-language)
13706 (:headline-levels . org-export-headline-levels)
13707 (:section-numbers . org-export-with-section-numbers)
13708 (:table-of-contents . org-export-with-toc)
13709 (:archived-trees . org-export-with-archived-trees)
13710 (:emphasize . org-export-with-emphasize)
13711 (:sub-superscript . org-export-with-sub-superscripts)
13712 (:TeX-macros . org-export-with-TeX-macros)
13713 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
13714 (:fixed-width . org-export-with-fixed-width)
13715 (:timestamps . org-export-with-timestamps)
13716 (:tables . org-export-with-tables)
13717 (:table-auto-headline . org-export-highlight-first-table-line)
13718 (:style . org-export-html-style)
13719 (:convert-org-links . org-export-html-link-org-files-as-html)
13720 (:inline-images . org-export-html-inline-images)
13721 (:expand-quoted-html . org-export-html-expand)
13722 (:timestamp . org-export-html-with-timestamp)
13723 (:publishing-directory . org-export-publishing-directory)
13724 (:preamble . org-export-html-preamble)
13725 (:postamble . org-export-html-postamble)
13726 (:auto-preamble . org-export-html-auto-preamble)
13727 (:auto-postamble . org-export-html-auto-postamble)
13728 (:author . user-full-name)
13729 (:email . user-mail-address)))
13731 (defun org-default-export-plist ()
13732 "Return the property list with default settings for the export variables."
13733 (let ((l org-export-plist-vars) rtn e)
13734 (while (setq e (pop l))
13735 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
13736 rtn))
13738 (defun org-infile-export-plist ()
13739 "Return the property list with file-local settings for export."
13740 (save-excursion
13741 (goto-char 0)
13742 (let ((re (org-make-options-regexp
13743 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
13744 p key val text options)
13745 (while (re-search-forward re nil t)
13746 (setq key (org-match-string-no-properties 1)
13747 val (org-match-string-no-properties 2))
13748 (cond
13749 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
13750 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
13751 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
13752 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
13753 ((string-equal key "TEXT")
13754 (setq text (if text (concat text "\n" val) val)))
13755 ((string-equal key "OPTIONS") (setq options val))))
13756 (setq p (plist-put p :text text))
13757 (when options
13758 (let ((op '(("H" . :headline-levels)
13759 ("num" . :section-numbers)
13760 ("toc" . :table-of-contents)
13761 ("\\n" . :preserve-breaks)
13762 ("@" . :expand-quoted-html)
13763 (":" . :fixed-width)
13764 ("|" . :tables)
13765 ("^" . :sub-superscript)
13766 ("*" . :emphasize)
13767 ("TeX" . :TeX-macros)
13768 ("LaTeX" . :LaTeX-fragments)))
13770 (while (setq o (pop op))
13771 (if (string-match (concat (regexp-quote (car o))
13772 ":\\([^ \t\n\r;,.]*\\)")
13773 options)
13774 (setq p (plist-put p (cdr o)
13775 (car (read-from-string
13776 (match-string 1 options)))))))))
13777 p)))
13779 (defun org-combine-plists (&rest plists)
13780 "Create a single property list from all plists in PLISTS.
13781 The process starts by copying the last list, and then setting properties
13782 from the other lists. Settings in the first list are the most significant
13783 ones and overrule settings in the other lists."
13784 (let ((rtn (copy-sequence (pop plists)))
13785 p v ls)
13786 (while plists
13787 (setq ls (pop plists))
13788 (while ls
13789 (setq p (pop ls) v (pop ls))
13790 (setq rtn (plist-put rtn p v))))
13791 rtn))
13793 (defun org-export-directory (type plist)
13794 (let* ((val (plist-get plist :publishing-directory))
13795 (dir (if (listp val)
13796 (or (cdr (assoc type val)) ".")
13797 val)))
13798 dir))
13800 (defun org-export-find-first-heading-line (list)
13801 "Remove all lines from LIST which are before the first headline."
13802 (let ((orig-list list)
13803 (re (concat "^" outline-regexp)))
13804 (while (and list
13805 (not (string-match re (car list))))
13806 (pop list))
13807 (or list orig-list)))
13809 (defun org-skip-comments (lines)
13810 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
13811 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
13812 (re2 "^\\(\\*+\\)[ \t\n\r]")
13813 rtn line level)
13814 (while (setq line (pop lines))
13815 (cond
13816 ((and (string-match re1 line)
13817 (setq level (- (match-end 1) (match-beginning 1))))
13818 ;; Beginning of a COMMENT subtree. Skip it.
13819 (while (and (setq line (pop lines))
13820 (or (not (string-match re2 line))
13821 (> (- (match-end 1) (match-beginning 1)) level))))
13822 (setq lines (cons line lines)))
13823 ((string-match "^#" line)
13824 ;; an ordinary comment line
13826 ((and org-export-table-remove-special-lines
13827 (string-match "^[ \t]*|" line)
13828 (or (string-match "^[ \t]*| *[!_^] *|" line)
13829 (and (string-match "| *<[0-9]+> *|" line)
13830 (not (string-match "| *[^ <|]" line)))))
13831 ;; a special table line that should be removed
13833 (t (setq rtn (cons line rtn)))))
13834 (nreverse rtn)))
13836 (defun org-export (&optional arg)
13837 (interactive)
13838 (let ((help "[t] insert the export option template
13839 \[v] limit export to visible part of outline tree
13841 \[a] export as ASCII
13842 \[h] export as HTML
13843 \[b] export as HTML and browse immediately
13844 \[x] export as XOXO
13846 \[i] export current file as iCalendar file
13847 \[I] export all agenda files as iCalendar files
13848 \[c] export agenda files into combined iCalendar file
13850 \[F] publish current file
13851 \[P] publish current project
13852 \[X] publish... (project will be prompted for)
13853 \[A] publish all projects")
13854 (cmds
13855 '((?t . org-insert-export-options-template)
13856 (?v . org-export-visible)
13857 (?a . org-export-as-ascii)
13858 (?h . org-export-as-html)
13859 (?b . org-export-as-html-and-open)
13860 (?x . org-export-as-xoxo)
13861 (?i . org-export-icalendar-this-file)
13862 (?I . org-export-icalendar-all-agenda-files)
13863 (?c . org-export-icalendar-combine-agenda-files)
13864 (?F . org-publish-current-file)
13865 (?P . org-publish-current-project)
13866 (?X . org-publish)
13867 (?A . org-publish-all)))
13868 r1 r2 ass)
13869 (save-window-excursion
13870 (delete-other-windows)
13871 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
13872 (princ help))
13873 (message "Select command: ")
13874 (setq r1 (read-char-exclusive)))
13875 (setq r2 (if (< r1 27) (+ r1 96) r1))
13876 (if (setq ass (assq r2 cmds))
13877 (call-interactively (cdr ass))
13878 (error "No command associated with key %c" r1))))
13880 ;; ASCII
13882 (defconst org-html-entities
13883 '(("nbsp")
13884 ("iexcl")
13885 ("cent")
13886 ("pound")
13887 ("curren")
13888 ("yen")
13889 ("brvbar")
13890 ("sect")
13891 ("uml")
13892 ("copy")
13893 ("ordf")
13894 ("laquo")
13895 ("not")
13896 ("shy")
13897 ("reg")
13898 ("macr")
13899 ("deg")
13900 ("plusmn")
13901 ("sup2")
13902 ("sup3")
13903 ("acute")
13904 ("micro")
13905 ("para")
13906 ("middot")
13907 ("odot"."o")
13908 ("star"."*")
13909 ("cedil")
13910 ("sup1")
13911 ("ordm")
13912 ("raquo")
13913 ("frac14")
13914 ("frac12")
13915 ("frac34")
13916 ("iquest")
13917 ("Agrave")
13918 ("Aacute")
13919 ("Acirc")
13920 ("Atilde")
13921 ("Auml")
13922 ("Aring") ("AA"."&Aring;")
13923 ("AElig")
13924 ("Ccedil")
13925 ("Egrave")
13926 ("Eacute")
13927 ("Ecirc")
13928 ("Euml")
13929 ("Igrave")
13930 ("Iacute")
13931 ("Icirc")
13932 ("Iuml")
13933 ("ETH")
13934 ("Ntilde")
13935 ("Ograve")
13936 ("Oacute")
13937 ("Ocirc")
13938 ("Otilde")
13939 ("Ouml")
13940 ("times")
13941 ("Oslash")
13942 ("Ugrave")
13943 ("Uacute")
13944 ("Ucirc")
13945 ("Uuml")
13946 ("Yacute")
13947 ("THORN")
13948 ("szlig")
13949 ("agrave")
13950 ("aacute")
13951 ("acirc")
13952 ("atilde")
13953 ("auml")
13954 ("aring")
13955 ("aelig")
13956 ("ccedil")
13957 ("egrave")
13958 ("eacute")
13959 ("ecirc")
13960 ("euml")
13961 ("igrave")
13962 ("iacute")
13963 ("icirc")
13964 ("iuml")
13965 ("eth")
13966 ("ntilde")
13967 ("ograve")
13968 ("oacute")
13969 ("ocirc")
13970 ("otilde")
13971 ("ouml")
13972 ("divide")
13973 ("oslash")
13974 ("ugrave")
13975 ("uacute")
13976 ("ucirc")
13977 ("uuml")
13978 ("yacute")
13979 ("thorn")
13980 ("yuml")
13981 ("fnof")
13982 ("Alpha")
13983 ("Beta")
13984 ("Gamma")
13985 ("Delta")
13986 ("Epsilon")
13987 ("Zeta")
13988 ("Eta")
13989 ("Theta")
13990 ("Iota")
13991 ("Kappa")
13992 ("Lambda")
13993 ("Mu")
13994 ("Nu")
13995 ("Xi")
13996 ("Omicron")
13997 ("Pi")
13998 ("Rho")
13999 ("Sigma")
14000 ("Tau")
14001 ("Upsilon")
14002 ("Phi")
14003 ("Chi")
14004 ("Psi")
14005 ("Omega")
14006 ("alpha")
14007 ("beta")
14008 ("gamma")
14009 ("delta")
14010 ("epsilon")
14011 ("varepsilon"."&epsilon;")
14012 ("zeta")
14013 ("eta")
14014 ("theta")
14015 ("iota")
14016 ("kappa")
14017 ("lambda")
14018 ("mu")
14019 ("nu")
14020 ("xi")
14021 ("omicron")
14022 ("pi")
14023 ("rho")
14024 ("sigmaf") ("varsigma"."&sigmaf;")
14025 ("sigma")
14026 ("tau")
14027 ("upsilon")
14028 ("phi")
14029 ("chi")
14030 ("psi")
14031 ("omega")
14032 ("thetasym") ("vartheta"."&thetasym;")
14033 ("upsih")
14034 ("piv")
14035 ("bull") ("bullet"."&bull;")
14036 ("hellip") ("dots"."&hellip;")
14037 ("prime")
14038 ("Prime")
14039 ("oline")
14040 ("frasl")
14041 ("weierp")
14042 ("image")
14043 ("real")
14044 ("trade")
14045 ("alefsym")
14046 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
14047 ("uarr") ("uparrow"."&uarr;")
14048 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
14049 ("darr")("downarrow"."&darr;")
14050 ("harr") ("leftrightarrow"."&harr;")
14051 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
14052 ("lArr") ("Leftarrow"."&lArr;")
14053 ("uArr") ("Uparrow"."&uArr;")
14054 ("rArr") ("Rightarrow"."&rArr;")
14055 ("dArr") ("Downarrow"."&dArr;")
14056 ("hArr") ("Leftrightarrow"."&hArr;")
14057 ("forall")
14058 ("part") ("partial"."&part;")
14059 ("exist") ("exists"."&exist;")
14060 ("empty") ("emptyset"."&empty;")
14061 ("nabla")
14062 ("isin") ("in"."&isin;")
14063 ("notin")
14064 ("ni")
14065 ("prod")
14066 ("sum")
14067 ("minus")
14068 ("lowast") ("ast"."&lowast;")
14069 ("radic")
14070 ("prop") ("proptp"."&prop;")
14071 ("infin") ("infty"."&infin;")
14072 ("ang") ("angle"."&ang;")
14073 ("and") ("vee"."&and;")
14074 ("or") ("wedge"."&or;")
14075 ("cap")
14076 ("cup")
14077 ("int")
14078 ("there4")
14079 ("sim")
14080 ("cong") ("simeq"."&cong;")
14081 ("asymp")("approx"."&asymp;")
14082 ("ne") ("neq"."&ne;")
14083 ("equiv")
14084 ("le")
14085 ("ge")
14086 ("sub") ("subset"."&sub;")
14087 ("sup") ("supset"."&sup;")
14088 ("nsub")
14089 ("sube")
14090 ("supe")
14091 ("oplus")
14092 ("otimes")
14093 ("perp")
14094 ("sdot") ("cdot"."&sdot;")
14095 ("lceil")
14096 ("rceil")
14097 ("lfloor")
14098 ("rfloor")
14099 ("lang")
14100 ("rang")
14101 ("loz") ("Diamond"."&loz;")
14102 ("spades") ("spadesuit"."&spades;")
14103 ("clubs") ("clubsuit"."&clubs;")
14104 ("hearts") ("diamondsuit"."&hearts;")
14105 ("diams") ("diamondsuit"."&diams;")
14106 ("quot")
14107 ("amp")
14108 ("lt")
14109 ("gt")
14110 ("OElig")
14111 ("oelig")
14112 ("Scaron")
14113 ("scaron")
14114 ("Yuml")
14115 ("circ")
14116 ("tilde")
14117 ("ensp")
14118 ("emsp")
14119 ("thinsp")
14120 ("zwnj")
14121 ("zwj")
14122 ("lrm")
14123 ("rlm")
14124 ("ndash")
14125 ("mdash")
14126 ("lsquo")
14127 ("rsquo")
14128 ("sbquo")
14129 ("ldquo")
14130 ("rdquo")
14131 ("bdquo")
14132 ("dagger")
14133 ("Dagger")
14134 ("permil")
14135 ("lsaquo")
14136 ("rsaquo")
14137 ("euro")
14139 ("arccos"."arccos")
14140 ("arcsin"."arcsin")
14141 ("arctan"."arctan")
14142 ("arg"."arg")
14143 ("cos"."cos")
14144 ("cosh"."cosh")
14145 ("cot"."cot")
14146 ("coth"."coth")
14147 ("csc"."csc")
14148 ("deg"."deg")
14149 ("det"."det")
14150 ("dim"."dim")
14151 ("exp"."exp")
14152 ("gcd"."gcd")
14153 ("hom"."hom")
14154 ("inf"."inf")
14155 ("ker"."ker")
14156 ("lg"."lg")
14157 ("lim"."lim")
14158 ("liminf"."liminf")
14159 ("limsup"."limsup")
14160 ("ln"."ln")
14161 ("log"."log")
14162 ("max"."max")
14163 ("min"."min")
14164 ("Pr"."Pr")
14165 ("sec"."sec")
14166 ("sin"."sin")
14167 ("sinh"."sinh")
14168 ("sup"."sup")
14169 ("tan"."tan")
14170 ("tanh"."tanh")
14172 "Entities for TeX->HTML translation.
14173 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
14174 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
14175 In that case, \"\\ent\" will be translated to \"&other;\".
14176 The list contains HTML entities for Latin-1, Greek and other symbols.
14177 It is supplemented by a number of commonly used TeX macros with appropriate
14178 translations. There is currently no way for users to extend this.")
14180 (defun org-cleaned-string-for-export (string &rest parameters)
14181 "Cleanup a buffer substring so that links can be created safely."
14182 (interactive)
14183 (let* ((re-radio (and org-target-link-regexp
14184 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
14185 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
14186 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
14187 (re-archive (concat ":" org-archive-tag ":"))
14188 rtn)
14189 (save-excursion
14190 (set-buffer (get-buffer-create " org-mode-tmp"))
14191 (erase-buffer)
14192 (insert string)
14193 (let ((org-inhibit-startup t)) (org-mode))
14195 ;; Get rid of archived trees
14196 (when (not (eq org-export-with-archived-trees t))
14197 (goto-char (point-min))
14198 (while (re-search-forward re-archive nil t)
14199 (if (not (org-on-heading-p))
14200 (org-end-of-subtree t)
14201 (beginning-of-line 1)
14202 (delete-region
14203 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
14204 (org-end-of-subtree t)))))
14206 ;; Find targets in comments and move them out of comments,
14207 ;; but mark them as targets that should be invisible
14208 (goto-char (point-min))
14209 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
14210 (replace-match "\\1(INVISIBLE)"))
14212 ;; Remove comments
14213 (goto-char (point-min))
14214 (while (re-search-forward "^#.*\n?" nil t)
14215 (replace-match ""))
14217 ;; Find matches for radio targets and turn them into internal links
14218 (goto-char (point-min))
14219 (when re-radio
14220 (while (re-search-forward re-radio nil t)
14221 (replace-match "\\1[[\\2]]")))
14223 ;; Find all links that contain a newline and put them into a single line
14224 (goto-char (point-min))
14225 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
14226 (replace-match "\\1 \\3")
14227 (goto-char (match-beginning 0)))
14229 ;; Convert LaTeX fragments to images
14230 (when (memq :LaTeX-fragments parameters)
14231 (org-format-latex
14232 (concat "ltxpng/" (file-name-sans-extension
14233 (file-name-nondirectory
14234 org-current-export-file)))
14235 org-current-export-dir nil "Creating LaTeX image %s"))
14236 (message "Exporting...")
14238 ;; Normalize links: Convert angle and plain links into bracket links
14239 ;; Expand link abbreviations
14240 (goto-char (point-min))
14241 (while (re-search-forward re-plain-link nil t)
14242 (replace-match
14243 (concat
14244 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
14245 t t))
14246 (goto-char (point-min))
14247 (while (re-search-forward re-angle-link nil t)
14248 (replace-match
14249 (concat
14250 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
14251 t t))
14252 (goto-char (point-min))
14253 (while (re-search-forward org-bracket-link-regexp nil t)
14254 (replace-match
14255 (concat "[[" (save-match-data
14256 (org-link-expand-abbrev (match-string 1)))
14258 (if (match-end 3)
14259 (match-string 2)
14260 (concat "[" (match-string 1) "]"))
14261 "]")
14262 t t))
14264 ;; Find multiline emphasis and put them into single line
14265 (when (memq :emph-multiline parameters)
14266 (goto-char (point-min))
14267 (while (re-search-forward org-emph-re nil t)
14268 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
14269 (goto-char (1- (match-end 0)))))
14271 (setq rtn (buffer-string)))
14272 (kill-buffer " org-mode-tmp")
14273 rtn))
14275 (defun org-solidify-link-text (s &optional alist)
14276 "Take link text and make a safe target out of it."
14277 (save-match-data
14278 (let* ((rtn
14279 (mapconcat
14280 'identity
14281 (org-split-string s "[ \t\r\n]+") "--"))
14282 (a (assoc rtn alist)))
14283 (or (cdr a) rtn))))
14285 (defun org-convert-to-odd-levels ()
14286 "Convert an org-mode file with all levels allowed to one with odd levels.
14287 This will leave level 1 alone, convert level 2 to level 3, level 3 to
14288 level 5 etc."
14289 (interactive)
14290 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
14291 (let ((org-odd-levels-only nil) n)
14292 (save-excursion
14293 (goto-char (point-min))
14294 (while (re-search-forward "^\\*\\*+" nil t)
14295 (setq n (1- (length (match-string 0))))
14296 (while (>= (setq n (1- n)) 0)
14297 (org-demote))
14298 (end-of-line 1))))))
14301 (defun org-convert-to-oddeven-levels ()
14302 "Convert an org-mode file with only odd levels to one with odd and even levels.
14303 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
14304 section with an even level, conversion would destroy the structure of the file. An error
14305 is signaled in this case."
14306 (interactive)
14307 (goto-char (point-min))
14308 ;; First check if there are no even levels
14309 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
14310 (org-show-hierarchy-above t)
14311 (error "Not all levels are odd in this file. Conversion not possible."))
14312 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
14313 (let ((org-odd-levels-only nil) n)
14314 (save-excursion
14315 (goto-char (point-min))
14316 (while (re-search-forward "^\\*\\*+" nil t)
14317 (setq n (/ (length (match-string 0)) 2))
14318 (while (>= (setq n (1- n)) 0)
14319 (org-promote))
14320 (end-of-line 1))))))
14322 (defun org-tr-level (n)
14323 "Make N odd if required."
14324 (if org-odd-levels-only (1+ (/ n 2)) n))
14326 (defvar org-last-level nil) ; dynamically scoped variable
14327 (defvar org-ascii-current-indentation nil) ; For communication
14329 (defun org-export-as-ascii (arg)
14330 "Export the outline as a pretty ASCII file.
14331 If there is an active region, export only the region.
14332 The prefix ARG specifies how many levels of the outline should become
14333 underlined headlines. The default is 3."
14334 (interactive "P")
14335 (setq-default org-todo-line-regexp org-todo-line-regexp)
14336 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14337 (org-infile-export-plist)))
14338 (region
14339 (buffer-substring
14340 (if (org-region-active-p) (region-beginning) (point-min))
14341 (if (org-region-active-p) (region-end) (point-max))))
14342 (lines (org-export-find-first-heading-line
14343 (org-skip-comments
14344 (org-split-string
14345 (org-cleaned-string-for-export region)
14346 "[\r\n]"))))
14347 (org-ascii-current-indentation '(0 . 0))
14348 (org-startup-with-deadline-check nil)
14349 (level 0) line txt
14350 (umax nil)
14351 (case-fold-search nil)
14352 (filename (concat (file-name-as-directory
14353 (org-export-directory :ascii opt-plist))
14354 (file-name-sans-extension
14355 (file-name-nondirectory buffer-file-name))
14356 ".txt"))
14357 (buffer (find-file-noselect filename))
14358 (levels-open (make-vector org-level-max nil))
14359 (odd org-odd-levels-only)
14360 (date (format-time-string "%Y/%m/%d" (current-time)))
14361 (time (format-time-string "%X" (org-current-time)))
14362 (author (plist-get opt-plist :author))
14363 (title (or (plist-get opt-plist :title)
14364 (file-name-sans-extension
14365 (file-name-nondirectory buffer-file-name))))
14366 (email (plist-get opt-plist :email))
14367 (language (plist-get opt-plist :language))
14368 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
14369 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
14370 (text nil)
14371 (todo nil)
14372 (lang-words nil))
14374 (setq org-last-level 1)
14375 (org-init-section-numbers)
14377 (find-file-noselect filename)
14379 (setq lang-words (or (assoc language org-export-language-setup)
14380 (assoc "en" org-export-language-setup)))
14381 (if org-export-ascii-show-new-buffer
14382 (switch-to-buffer-other-window buffer)
14383 (set-buffer buffer))
14384 (erase-buffer)
14385 (fundamental-mode)
14386 ;; create local variables for all options, to make sure all called
14387 ;; functions get the correct information
14388 (mapcar (lambda (x)
14389 (set (make-local-variable (cdr x))
14390 (plist-get opt-plist (car x))))
14391 org-export-plist-vars)
14392 (org-set-local 'org-odd-levels-only odd)
14393 (setq umax (if arg (prefix-numeric-value arg)
14394 org-export-headline-levels))
14396 ;; File header
14397 (if title (org-insert-centered title ?=))
14398 (insert "\n")
14399 (if (or author email)
14400 (insert (concat (nth 1 lang-words) ": " (or author "")
14401 (if email (concat " <" email ">") "")
14402 "\n")))
14403 (if (and date time)
14404 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
14405 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
14407 (insert "\n\n")
14409 (if org-export-with-toc
14410 (progn
14411 (insert (nth 3 lang-words) "\n"
14412 (make-string (length (nth 3 lang-words)) ?=) "\n")
14413 (mapcar '(lambda (line)
14414 (if (string-match org-todo-line-regexp
14415 line)
14416 ;; This is a headline
14417 (progn
14418 (setq level (- (match-end 1) (match-beginning 1))
14419 level (org-tr-level level)
14420 txt (match-string 3 line)
14421 todo
14422 (or (and org-export-mark-todo-in-toc
14423 (match-beginning 2)
14424 (not (equal (match-string 2 line)
14425 org-done-string)))
14426 ; TODO, not DONE
14427 (and org-export-mark-todo-in-toc
14428 (= level umax)
14429 (org-search-todo-below
14430 line lines level))))
14431 (setq txt (org-html-expand-for-ascii txt))
14433 (if (and (memq org-export-with-tags '(not-in-toc nil))
14434 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
14435 (setq txt (replace-match "" t t txt)))
14436 (if (string-match quote-re0 txt)
14437 (setq txt (replace-match "" t t txt)))
14439 (if org-export-with-section-numbers
14440 (setq txt (concat (org-section-number level)
14441 " " txt)))
14442 (if (<= level umax)
14443 (progn
14444 (insert
14445 (make-string (* (1- level) 4) ?\ )
14446 (format (if todo "%s (*)\n" "%s\n") txt))
14447 (setq org-last-level level))
14448 ))))
14449 lines)))
14451 (org-init-section-numbers)
14452 (while (setq line (pop lines))
14453 ;; Remove the quoted HTML tags.
14454 (setq line (org-html-expand-for-ascii line))
14455 ;; Remove targets
14456 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
14457 (setq line (replace-match "" t t line)))
14458 ;; Replace internal links
14459 (while (string-match org-bracket-link-regexp line)
14460 (setq line (replace-match
14461 (if (match-end 3) "[\\3]" "[\\1]")
14462 t nil line)))
14463 (cond
14464 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14465 ;; a Headline
14466 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14467 txt (match-string 2 line))
14468 (org-ascii-level-start level txt umax lines))
14470 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
14471 (normal-mode)
14472 (save-buffer)
14473 ;; remove display and invisible chars
14474 (let (beg end)
14475 (goto-char (point-min))
14476 (while (setq beg (next-single-property-change (point) 'display))
14477 (setq end (next-single-property-change beg 'display))
14478 (delete-region beg end)
14479 (goto-char beg)
14480 (insert "=>"))
14481 (goto-char (point-min))
14482 (while (setq beg (next-single-property-change (point) 'org-cwidth))
14483 (setq end (next-single-property-change beg 'org-cwidth))
14484 (delete-region beg end)
14485 (goto-char beg)))
14486 (goto-char (point-min))))
14488 (defun org-search-todo-below (line lines level)
14489 "Search the subtree below LINE for any TODO entries."
14490 (let ((rest (cdr (memq line lines)))
14491 (re org-todo-line-regexp)
14492 line lv todo)
14493 (catch 'exit
14494 (while (setq line (pop rest))
14495 (if (string-match re line)
14496 (progn
14497 (setq lv (- (match-end 1) (match-beginning 1))
14498 todo (and (match-beginning 2)
14499 (not (equal (match-string 2 line)
14500 org-done-string))))
14501 ; TODO, not DONE
14502 (if (<= lv level) (throw 'exit nil))
14503 (if todo (throw 'exit t))))))))
14505 (defun org-html-expand-for-ascii (line)
14506 "Handle quoted HTML for ASCII export."
14507 (if org-export-html-expand
14508 (while (string-match "@<[^<>\n]*>" line)
14509 ;; We just remove the tags for now.
14510 (setq line (replace-match "" nil nil line))))
14511 line)
14513 (defun org-insert-centered (s &optional underline)
14514 "Insert the string S centered and underline it with character UNDERLINE."
14515 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
14516 (insert (make-string ind ?\ ) s "\n")
14517 (if underline
14518 (insert (make-string ind ?\ )
14519 (make-string (string-width s) underline)
14520 "\n"))))
14522 (defun org-ascii-level-start (level title umax &optional lines)
14523 "Insert a new level in ASCII export."
14524 (let (char (n (- level umax 1)) (ind 0))
14525 (if (> level umax)
14526 (progn
14527 (insert (make-string (* 2 n) ?\ )
14528 (char-to-string (nth (% n (length org-export-ascii-bullets))
14529 org-export-ascii-bullets))
14530 " " title "\n")
14531 ;; find the indentation of the next non-empty line
14532 (catch 'stop
14533 (while lines
14534 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
14535 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
14536 (throw 'stop (setq ind (org-get-indentation (car lines)))))
14537 (pop lines)))
14538 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
14539 (if (or (not (equal (char-before) ?\n))
14540 (not (equal (char-before (1- (point))) ?\n)))
14541 (insert "\n"))
14542 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
14543 (unless org-export-with-tags
14544 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14545 (setq title (replace-match "" t t title))))
14546 (if org-export-with-section-numbers
14547 (setq title (concat (org-section-number level) " " title)))
14548 (insert title "\n" (make-string (string-width title) char) "\n")
14549 (setq org-ascii-current-indentation '(0 . 0)))))
14551 (defun org-export-visible (type arg)
14552 "Create a copy of the visible part of the current buffer, and export it.
14553 The copy is created in a temporary buffer and removed after use.
14554 TYPE is the final key (as a string) that also select the export command in
14555 the `C-c C-e' export dispatcher.
14556 As a special case, if the you type SPC at the prompt, the temporary
14557 org-mode file will not be removed but presented to you so that you can
14558 continue to use it. The prefix arg ARG is passed through to the exporting
14559 command."
14560 (interactive
14561 (list (progn
14562 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
14563 (read-char-exclusive))
14564 current-prefix-arg))
14565 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
14566 (error "Invalid export key"))
14567 (let* ((binding (cdr (assoc type
14568 '((?a . org-export-as-ascii)
14569 (?\C-a . org-export-as-ascii)
14570 (?b . org-export-as-html-and-open)
14571 (?\C-b . org-export-as-html-and-open)
14572 (?h . org-export-as-html)
14573 (?x . org-export-as-xoxo)))))
14574 (keepp (equal type ?\ ))
14575 (file buffer-file-name)
14576 (buffer (get-buffer-create "*Org Export Visible*"))
14577 s e)
14578 (with-current-buffer buffer (erase-buffer))
14579 (save-excursion
14580 (setq s (goto-char (point-min)))
14581 (while (not (= (point) (point-max)))
14582 (goto-char (org-find-invisible))
14583 (append-to-buffer buffer s (point))
14584 (setq s (goto-char (org-find-visible))))
14585 (goto-char (point-min))
14586 (unless keepp
14587 ;; Copy all comment lines to the end, to make sure #+ settings are
14588 ;; still available for the second export step. Kind of a hack, but
14589 ;; does do the trick.
14590 (if (looking-at "#[^\r\n]*")
14591 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
14592 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
14593 (append-to-buffer buffer (1+ (match-beginning 0))
14594 (min (point-max) (1+ (match-end 0))))))
14595 (set-buffer buffer)
14596 (let ((buffer-file-name file)
14597 (org-inhibit-startup t))
14598 (org-mode)
14599 (show-all)
14600 (unless keepp (funcall binding arg))))
14601 (if (not keepp)
14602 (kill-buffer buffer)
14603 (switch-to-buffer-other-window buffer)
14604 (goto-char (point-min)))))
14606 (defun org-find-visible ()
14607 (let ((s (point)))
14608 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
14609 (get-char-property s 'invisible)))
14611 (defun org-find-invisible ()
14612 (let ((s (point)))
14613 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
14614 (not (get-char-property s 'invisible))))
14617 ;; HTML
14619 (defun org-get-current-options ()
14620 "Return a string with current options as keyword options.
14621 Does include HTML export options as well as TODO and CATEGORY stuff."
14622 (format
14623 "#+TITLE: %s
14624 #+AUTHOR: %s
14625 #+EMAIL: %s
14626 #+LANGUAGE: %s
14627 #+TEXT: Some descriptive text to be emitted. Several lines OK.
14628 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
14629 #+CATEGORY: %s
14630 #+SEQ_TODO: %s
14631 #+TYP_TODO: %s
14632 #+STARTUP: %s %s %s %s %s %s
14633 #+TAGS: %s
14634 #+ARCHIVE: %s
14636 (buffer-name) (user-full-name) user-mail-address org-export-default-language
14637 org-export-headline-levels
14638 org-export-with-section-numbers
14639 org-export-with-toc
14640 org-export-preserve-breaks
14641 org-export-html-expand
14642 org-export-with-fixed-width
14643 org-export-with-tables
14644 org-export-with-sub-superscripts
14645 org-export-with-emphasize
14646 org-export-with-TeX-macros
14647 org-export-with-LaTeX-fragments
14648 (file-name-nondirectory buffer-file-name)
14649 (if (equal org-todo-interpretation 'sequence)
14650 (mapconcat 'identity org-todo-keywords " ")
14651 "TODO FEEDBACK VERIFY DONE")
14652 (if (equal org-todo-interpretation 'type)
14653 (mapconcat 'identity org-todo-keywords " ")
14654 "Me Jason Marie DONE")
14655 (cdr (assoc org-startup-folded
14656 '((nil . "showall") (t . "overview") (content . "content"))))
14657 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
14658 (if org-odd-levels-only "odd" "oddeven")
14659 (if org-hide-leading-stars "hidestars" "showstars")
14660 (if org-startup-align-all-tables "align" "noalign")
14661 (if org-log-done "logging" "nologging")
14662 (or (mapconcat (lambda (x)
14663 (cond
14664 ((equal '(:startgroup) x) "{")
14665 ((equal '(:endgroup) x) "}")
14666 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
14667 (t (car x))))
14668 (or org-tag-alist (org-get-buffer-tags)) " ") "")
14669 org-archive-location
14672 (defun org-insert-export-options-template ()
14673 "Insert into the buffer a template with information for exporting."
14674 (interactive)
14675 (if (not (bolp)) (newline))
14676 (let ((s (org-get-current-options)))
14677 (and (string-match "#\\+CATEGORY" s)
14678 (setq s (substring s 0 (match-beginning 0))))
14679 (insert s)))
14681 (defun org-toggle-fixed-width-section (arg)
14682 "Toggle the fixed-width export.
14683 If there is no active region, the QUOTE keyword at the current headline is
14684 inserted or removed. When present, it causes the text between this headline
14685 and the next to be exported as fixed-width text, and unmodified.
14686 If there is an active region, this command adds or removes a colon as the
14687 first character of this line. If the first character of a line is a colon,
14688 this line is also exported in fixed-width font."
14689 (interactive "P")
14690 (let* ((cc 0)
14691 (regionp (org-region-active-p))
14692 (beg (if regionp (region-beginning) (point)))
14693 (end (if regionp (region-end)))
14694 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14695 (re "[ \t]*\\(:\\)")
14696 off)
14697 (if regionp
14698 (save-excursion
14699 (goto-char beg)
14700 (setq cc (current-column))
14701 (beginning-of-line 1)
14702 (setq off (looking-at re))
14703 (while (> nlines 0)
14704 (setq nlines (1- nlines))
14705 (beginning-of-line 1)
14706 (cond
14707 (arg
14708 (move-to-column cc t)
14709 (insert ":\n")
14710 (forward-line -1))
14711 ((and off (looking-at re))
14712 (replace-match "" t t nil 1))
14713 ((not off) (move-to-column cc t) (insert ":")))
14714 (forward-line 1)))
14715 (save-excursion
14716 (org-back-to-heading)
14717 (if (looking-at (concat outline-regexp
14718 "\\( +\\<" org-quote-string "\\>\\)"))
14719 (replace-match "" t t nil 1)
14720 (if (looking-at outline-regexp)
14721 (progn
14722 (goto-char (match-end 0))
14723 (insert " " org-quote-string))))))))
14725 (defun org-export-as-html-and-open (arg)
14726 "Export the outline as HTML and immediately open it with a browser.
14727 If there is an active region, export only the region.
14728 The prefix ARG specifies how many levels of the outline should become
14729 headlines. The default is 3. Lower levels will become bulleted lists."
14730 (interactive "P")
14731 (org-export-as-html arg 'hidden)
14732 (org-open-file buffer-file-name))
14734 (defun org-export-as-html-batch ()
14735 "Call `org-export-as-html', may be used in batch processing as
14736 emacs --batch
14737 --load=$HOME/lib/emacs/org.el
14738 --eval \"(setq org-export-headline-levels 2)\"
14739 --visit=MyFile --funcall org-export-as-html-batch"
14740 (org-export-as-html org-export-headline-levels 'hidden))
14742 (defun org-export-as-html (arg &optional hidden ext-plist)
14743 "Export the outline as a pretty HTML file.
14744 If there is an active region, export only the region.
14745 The prefix ARG specifies how many levels of the outline should become
14746 headlines. The default is 3. Lower levels will become bulleted lists.
14747 When HIDDEN is non-nil, don't display the HTML buffer.
14748 EXT-PLIST is a property list with external parameters overriding
14749 org-mode's default settings, but still inferior to file-local settings."
14750 (interactive "P")
14751 (message "Exporting...")
14752 (setq-default org-todo-line-regexp org-todo-line-regexp)
14753 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
14754 (setq-default org-done-string org-done-string)
14755 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14756 ext-plist
14757 (org-infile-export-plist)))
14759 (style (plist-get opt-plist :style))
14760 (link-validate (plist-get opt-plist :link-validation-function))
14761 valid
14762 (odd org-odd-levels-only)
14763 (region-p (org-region-active-p))
14764 (region
14765 (buffer-substring
14766 (if region-p (region-beginning) (point-min))
14767 (if region-p (region-end) (point-max))))
14768 ;; The following two are dynamically scoped into other
14769 ;; routines below.
14770 (org-current-export-dir (org-export-directory :html opt-plist))
14771 (org-current-export-file buffer-file-name)
14772 (all_lines
14773 (org-skip-comments (org-split-string
14774 (org-cleaned-string-for-export
14775 region :emph-multiline
14776 (if (plist-get opt-plist :LaTeX-fragments)
14777 :LaTeX-fragments))
14778 "[\r\n]")))
14779 (lines (org-export-find-first-heading-line all_lines))
14780 (level 0) (line "") (origline "") txt todo
14781 (umax nil)
14782 (filename (concat (file-name-as-directory
14783 (org-export-directory :html opt-plist))
14784 (file-name-sans-extension
14785 (file-name-nondirectory buffer-file-name))
14786 ".html"))
14787 (current-dir (file-name-directory buffer-file-name))
14788 (buffer (find-file-noselect filename))
14789 (levels-open (make-vector org-level-max nil))
14790 (date (format-time-string "%Y/%m/%d" (current-time)))
14791 (time (format-time-string "%X" (org-current-time)))
14792 (author (plist-get opt-plist :author))
14793 (title (or (plist-get opt-plist :title)
14794 (file-name-sans-extension
14795 (file-name-nondirectory buffer-file-name))))
14796 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
14797 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
14798 (inquote nil)
14799 (infixed nil)
14800 (in-local-list nil)
14801 (local-list-num nil)
14802 (local-list-indent nil)
14803 (llt org-plain-list-ordered-item-terminator)
14804 (email (plist-get opt-plist :email))
14805 (language (plist-get opt-plist :language))
14806 (text (plist-get opt-plist :text))
14807 (lang-words nil)
14808 (target-alist nil) tg
14809 (head-count 0) cnt
14810 (start 0)
14811 (coding-system (and (boundp 'buffer-file-coding-system)
14812 buffer-file-coding-system))
14813 (coding-system-for-write coding-system)
14814 (save-buffer-coding-system coding-system)
14815 (charset (and coding-system
14816 (fboundp 'coding-system-get)
14817 (coding-system-get coding-system 'mime-charset)))
14818 table-open type
14819 table-buffer table-orig-buffer
14820 ind start-is-num starter
14821 rpl path desc descp desc1 desc2 link
14823 (message "Exporting...")
14825 (setq org-last-level 1)
14826 (org-init-section-numbers)
14828 ;; Get the language-dependent settings
14829 (setq lang-words (or (assoc language org-export-language-setup)
14830 (assoc "en" org-export-language-setup)))
14832 ;; Switch to the output buffer
14833 (if (or hidden (not org-export-html-show-new-buffer))
14834 (set-buffer buffer)
14835 (switch-to-buffer-other-window buffer))
14836 (erase-buffer)
14837 (fundamental-mode)
14838 (let ((case-fold-search nil)
14839 (org-odd-levels-only odd))
14840 ;; create local variables for all options, to make sure all called
14841 ;; functions get the correct information
14842 (mapcar (lambda (x)
14843 (set (make-local-variable (cdr x))
14844 (plist-get opt-plist (car x))))
14845 org-export-plist-vars)
14846 (setq umax (if arg (prefix-numeric-value arg)
14847 org-export-headline-levels))
14849 ;; File header
14850 (insert (format
14851 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
14852 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
14853 <html xmlns=\"http://www.w3.org/1999/xhtml\"
14854 lang=\"%s\" xml:lang=\"%s\">
14855 <head>
14856 <title>%s</title>
14857 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
14858 <meta name=\"generator\" content=\"Org-mode\"/>
14859 <meta name=\"generated\" content=\"%s %s\"/>
14860 <meta name=\"author\" content=\"%s\"/>
14862 </head><body>
14864 language language (org-html-expand title) (or charset "iso-8859-1")
14865 date time author style))
14868 (insert (or (plist-get opt-plist :preamble) ""))
14870 (when (plist-get opt-plist :auto-preamble)
14871 (if title (insert (format org-export-html-title-format
14872 (org-html-expand title))))
14873 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
14875 (if org-export-with-toc
14876 (progn
14877 (insert (format "<h%d>%s</h%d>\n"
14878 org-export-html-toplevel-hlevel
14879 (nth 3 lang-words)
14880 org-export-html-toplevel-hlevel))
14881 (insert "<ul>\n<li>")
14882 (setq lines
14883 (mapcar '(lambda (line)
14884 (if (string-match org-todo-line-regexp line)
14885 ;; This is a headline
14886 (progn
14887 (setq level (- (match-end 1) (match-beginning 1))
14888 level (org-tr-level level)
14889 txt (save-match-data
14890 (org-html-expand
14891 (org-export-cleanup-toc-line
14892 (match-string 3 line))))
14893 todo
14894 (or (and org-export-mark-todo-in-toc
14895 (match-beginning 2)
14896 (not (equal (match-string 2 line)
14897 org-done-string)))
14898 ; TODO, not DONE
14899 (and org-export-mark-todo-in-toc
14900 (= level umax)
14901 (org-search-todo-below
14902 line lines level))))
14903 (if (and (memq org-export-with-tags '(not-in-toc nil))
14904 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
14905 (setq txt (replace-match "" t t txt)))
14906 (if (string-match quote-re0 txt)
14907 (setq txt (replace-match "" t t txt)))
14908 (if org-export-with-section-numbers
14909 (setq txt (concat (org-section-number level)
14910 " " txt)))
14911 (if (<= level umax)
14912 (progn
14913 (setq head-count (+ head-count 1))
14914 (if (> level org-last-level)
14915 (progn
14916 (setq cnt (- level org-last-level))
14917 (while (>= (setq cnt (1- cnt)) 0)
14918 (insert "\n<ul>\n<li>"))
14919 (insert "\n")))
14920 (if (< level org-last-level)
14921 (progn
14922 (setq cnt (- org-last-level level))
14923 (while (>= (setq cnt (1- cnt)) 0)
14924 (insert "</li>\n</ul>"))
14925 (insert "\n")))
14926 ;; Check for targets
14927 (while (string-match org-target-regexp line)
14928 (setq tg (match-string 1 line)
14929 line (replace-match
14930 (concat "@<span class=\"target\">" tg "@</span> ")
14931 t t line))
14932 (push (cons (org-solidify-link-text tg)
14933 (format "sec-%d" head-count))
14934 target-alist))
14935 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
14936 (setq txt (replace-match "" t t txt)))
14937 (insert
14938 (format
14939 (if todo
14940 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
14941 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
14942 head-count txt))
14944 (setq org-last-level level))
14946 line)
14947 lines))
14948 (while (> org-last-level 0)
14949 (setq org-last-level (1- org-last-level))
14950 (insert "</li>\n</ul>\n"))
14952 (setq head-count 0)
14953 (org-init-section-numbers)
14955 (while (setq line (pop lines) origline line)
14956 (catch 'nextline
14958 ;; end of quote section?
14959 (when (and inquote (string-match "^\\*+" line))
14960 (insert "</pre>\n")
14961 (setq inquote nil))
14962 ;; inside a quote section?
14963 (when inquote
14964 (insert (org-html-protect line) "\n")
14965 (throw 'nextline nil))
14967 ;; verbatim lines
14968 (when (and org-export-with-fixed-width
14969 (string-match "^[ \t]*:\\(.*\\)" line))
14970 (when (not infixed)
14971 (setq infixed t)
14972 (insert "<pre>\n"))
14973 (insert (org-html-protect (match-string 1 line)) "\n")
14974 (when (and lines
14975 (not (string-match "^[ \t]*\\(:.*\\)"
14976 (car lines))))
14977 (setq infixed nil)
14978 (insert "</pre>\n"))
14979 (throw 'nextline nil))
14982 ;; make targets to anchors
14983 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
14984 (cond
14985 ((match-end 2)
14986 (setq line (replace-match
14987 (concat "@<a name=\""
14988 (org-solidify-link-text (match-string 1 line))
14989 "\">\\nbsp@</a>")
14990 t t line)))
14991 ((and org-export-with-toc (equal (string-to-char line) ?*))
14992 (setq line (replace-match
14993 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
14994 ; (concat "@<i>" (match-string 1 line) "@</i> ")
14995 t t line)))
14997 (setq line (replace-match
14998 (concat "@<a name=\""
14999 (org-solidify-link-text (match-string 1 line))
15000 "\" class=\"target\">" (match-string 1 line) "@</a> ")
15001 t t line)))))
15003 (setq line (org-html-handle-time-stamps line))
15005 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
15006 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
15007 ;; Also handle sub_superscripts and checkboxes
15008 (setq line (org-html-expand line))
15010 ;; Format the links
15011 (setq start 0)
15012 (while (string-match org-bracket-link-analytic-regexp line start)
15013 (setq start (match-beginning 0))
15014 (setq type (if (match-end 2) (match-string 2 line) "internal"))
15015 (setq path (match-string 3 line))
15016 (setq desc1 (if (match-end 5) (match-string 5 line))
15017 desc2 (if (match-end 2) (concat type ":" path) path)
15018 descp (and desc1 (not (equal desc1 desc2)))
15019 desc (or desc1 desc2))
15020 ;; FIXME: do we need to unescape here somewhere?
15021 (cond
15022 ((equal type "internal")
15023 (setq rpl
15024 (concat
15025 "<a href=\"#"
15026 (org-solidify-link-text path target-alist)
15027 "\">" desc "</a>")))
15028 ((member type '("http" "https" "ftp" "mailto" "news"))
15029 ;; standard URL
15030 (setq link (concat type ":" path))
15031 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
15032 ((string= type "file")
15033 ;; FILE link
15034 (let* ((filename path)
15035 (abs-p (file-name-absolute-p filename))
15036 thefile file-is-image-p search)
15037 (save-match-data
15038 (if (string-match "::\\(.*\\)" filename)
15039 (setq search (match-string 1 filename)
15040 filename (replace-match "" t nil filename)))
15041 (setq valid
15042 (if (functionp link-validate)
15043 (funcall link-validate filename current-dir)
15044 t))
15045 (setq file-is-image-p
15046 (string-match (org-image-file-name-regexp) filename))
15047 (setq thefile (if abs-p (expand-file-name filename) filename))
15048 (when (and org-export-html-link-org-files-as-html
15049 (string-match "\\.org$" thefile))
15050 (setq thefile (concat (substring thefile 0
15051 (match-beginning 0))
15052 ".html"))
15053 (if (and search
15054 ;; make sure this is can be used as target search
15055 (not (string-match "^[0-9]*$" search))
15056 (not (string-match "^\\*" search))
15057 (not (string-match "^/.*/$" search)))
15058 (setq thefile (concat thefile "#"
15059 (org-solidify-link-text
15060 (org-link-unescape search)))))
15061 (when (string-match "^file:" desc)
15062 (setq desc (replace-match "" t t desc))
15063 (if (string-match "\\.org$" desc)
15064 (setq desc (replace-match "" t t desc))))))
15065 (setq rpl (if (and file-is-image-p
15066 (or (eq t org-export-html-inline-images)
15067 (and org-export-html-inline-images
15068 (not descp))))
15069 (concat "<img src=\"" thefile "\"/>")
15070 (concat "<a href=\"" thefile "\">" desc "</a>")))
15071 (if (not valid) (setq rpl desc))))
15072 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
15073 (setq rpl (concat "<i>&lt;" type ":"
15074 (save-match-data (org-link-unescape path))
15075 "&gt;</i>"))))
15076 (setq line (replace-match rpl t t line)
15077 start (+ start (length rpl))))
15078 ;; TODO items
15079 (if (and (string-match org-todo-line-regexp line)
15080 (match-beginning 2))
15081 (if (equal (match-string 2 line) org-done-string)
15082 (setq line (replace-match
15083 "<span class=\"done\">\\2</span>"
15084 t nil line 2))
15085 (setq line (replace-match "<span class=\"todo\">\\2</span>"
15086 t nil line 2))))
15088 (cond
15089 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
15090 ;; This is a headline
15091 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
15092 txt (match-string 2 line))
15093 (if (string-match quote-re0 txt)
15094 (setq txt (replace-match "" t t txt)))
15095 (if (<= level umax) (setq head-count (+ head-count 1)))
15096 (when in-local-list
15097 ;; Close any local lists before inserting a new header line
15098 (while local-list-num
15099 (org-close-li)
15100 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
15101 (pop local-list-num))
15102 (setq local-list-indent nil
15103 in-local-list nil))
15104 (org-html-level-start level txt umax
15105 (and org-export-with-toc (<= level umax))
15106 head-count)
15107 ;; QUOTES
15108 (when (string-match quote-re line)
15109 (insert "<pre>")
15110 (setq inquote t)))
15112 ((and org-export-with-tables
15113 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
15114 (if (not table-open)
15115 ;; New table starts
15116 (setq table-open t table-buffer nil table-orig-buffer nil))
15117 ;; Accumulate lines
15118 (setq table-buffer (cons line table-buffer)
15119 table-orig-buffer (cons origline table-orig-buffer))
15120 (when (or (not lines)
15121 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
15122 (car lines))))
15123 (setq table-open nil
15124 table-buffer (nreverse table-buffer)
15125 table-orig-buffer (nreverse table-orig-buffer))
15126 (org-close-par-maybe)
15127 (insert (org-format-table-html table-buffer table-orig-buffer))))
15129 ;; Normal lines
15130 (when (string-match
15131 (cond
15132 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
15133 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
15134 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
15135 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
15136 line)
15137 (setq ind (org-get-string-indentation line)
15138 start-is-num (match-beginning 4)
15139 starter (if (match-beginning 2)
15140 (substring (match-string 2 line) 0 -1))
15141 line (substring line (match-beginning 5)))
15142 (unless (string-match "[^ \t]" line)
15143 ;; empty line. Pretend indentation is large.
15144 (setq ind (1+ (or (car local-list-indent) 1))))
15145 (while (and in-local-list
15146 (or (and (= ind (car local-list-indent))
15147 (not starter))
15148 (< ind (car local-list-indent))))
15149 (org-close-li)
15150 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
15151 (pop local-list-num) (pop local-list-indent)
15152 (setq in-local-list local-list-indent))
15153 (cond
15154 ((and starter
15155 (or (not in-local-list)
15156 (> ind (car local-list-indent))))
15157 ;; Start new (level of ) list
15158 (org-close-par-maybe)
15159 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
15160 (push start-is-num local-list-num)
15161 (push ind local-list-indent)
15162 (setq in-local-list t))
15163 (starter
15164 ;; continue current list
15165 (org-close-li)
15166 (insert "<li>\n")))
15167 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
15168 (setq line
15169 (replace-match
15170 (if (equal (match-string 1 line) "X")
15171 "<b>[X]</b>"
15172 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
15173 t t line))))
15175 ;; Empty lines start a new paragraph. If hand-formatted lists
15176 ;; are not fully interpreted, lines starting with "-", "+", "*"
15177 ;; also start a new paragraph.
15178 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
15180 ;; Check if the line break needs to be conserved
15181 (cond
15182 ((string-match "\\\\\\\\[ \t]*$" line)
15183 (setq line (replace-match "<br/>" t t line)))
15184 (org-export-preserve-breaks
15185 (setq line (concat line "<br/>"))))
15187 (insert line "\n")))))
15189 ;; Properly close all local lists and other lists
15190 (when inquote (insert "</pre>\n"))
15191 (when in-local-list
15192 ;; Close any local lists before inserting a new header line
15193 (while local-list-num
15194 (org-close-li)
15195 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
15196 (pop local-list-num))
15197 (setq local-list-indent nil
15198 in-local-list nil))
15199 (org-html-level-start 1 nil umax
15200 (and org-export-with-toc (<= level umax))
15201 head-count)
15203 (when (plist-get opt-plist :auto-postamble)
15204 (when author
15205 (insert "<p class=\"author\"> "
15206 (nth 1 lang-words) ": " author "\n")
15207 (when email
15208 (insert "<a href=\"mailto:" email "\">&lt;"
15209 email "&gt;</a>\n"))
15210 (insert "</p>\n"))
15211 (when (and date time)
15212 (insert "<p class=\"date\"> "
15213 (nth 2 lang-words) ": "
15214 date " " time "</p>\n")))
15216 (if org-export-html-with-timestamp
15217 (insert org-export-html-html-helper-timestamp))
15218 (insert (or (plist-get opt-plist :postamble) ""))
15219 (insert "</body>\n</html>\n")
15220 (normal-mode)
15221 ;; remove empty paragraphs and lists
15222 (goto-char (point-min))
15223 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
15224 (replace-match ""))
15225 (goto-char (point-min))
15226 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
15227 (replace-match ""))
15228 (save-buffer)
15229 (goto-char (point-min))
15230 (message "Exporting... done"))))
15233 (defun org-format-table-html (lines olines)
15234 "Find out which HTML converter to use and return the HTML code."
15235 (if (string-match "^[ \t]*|" (car lines))
15236 ;; A normal org table
15237 (org-format-org-table-html lines)
15238 ;; Table made by table.el - test for spanning
15239 (let* ((hlines (delq nil (mapcar
15240 (lambda (x)
15241 (if (string-match "^[ \t]*\\+-" x) x
15242 nil))
15243 lines)))
15244 (first (car hlines))
15245 (ll (and (string-match "\\S-+" first)
15246 (match-string 0 first)))
15247 (re (concat "^[ \t]*" (regexp-quote ll)))
15248 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
15249 hlines))))
15250 (if (and (not spanning)
15251 (not org-export-prefer-native-exporter-for-tables))
15252 ;; We can use my own converter with HTML conversions
15253 (org-format-table-table-html lines)
15254 ;; Need to use the code generator in table.el, with the original text.
15255 (org-format-table-table-html-using-table-generate-source olines)))))
15257 (defun org-format-org-table-html (lines)
15258 "Format a table into HTML."
15259 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
15260 (setq lines (nreverse lines))
15261 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
15262 (setq lines (nreverse lines))
15263 (when org-export-table-remove-special-lines
15264 ;; Check if the table has a marking column. If yes remove the
15265 ;; column and the special lines
15266 (let* ((special
15267 (not
15268 (memq nil
15269 (mapcar
15270 (lambda (x)
15271 (or (string-match "^[ \t]*|-" x)
15272 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
15273 lines)))))
15274 (if special
15275 (setq lines
15276 (delq nil
15277 (mapcar
15278 (lambda (x)
15279 (if (string-match "^[ \t]*| *[!_^] *|" x)
15280 nil ; ignore this line
15281 (and (or (string-match "^[ \t]*|-+\\+" x)
15282 (string-match "^[ \t]*|[^|]*|" x))
15283 (replace-match "|" t t x))))
15284 lines))))))
15286 (let ((head (and org-export-highlight-first-table-line
15287 (delq nil (mapcar
15288 (lambda (x) (string-match "^[ \t]*|-" x))
15289 (cdr lines)))))
15290 line fields html)
15291 (setq html (concat org-export-html-table-tag "\n"))
15292 (while (setq line (pop lines))
15293 (catch 'next-line
15294 (if (string-match "^[ \t]*|-" line)
15295 (progn
15296 (setq head nil) ;; head ends here, first time around
15297 ;; ignore this line
15298 (throw 'next-line t)))
15299 ;; Break the line into fields
15300 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
15301 (setq html (concat
15302 html
15303 "<tr>"
15304 (mapconcat (lambda (x)
15305 (if head
15306 (concat "<th>" x "</th>")
15307 (concat "<td>" x "</td>")))
15308 fields "")
15309 "</tr>\n"))))
15310 (setq html (concat html "</table>\n"))
15311 html))
15313 (defun org-fake-empty-table-line (line)
15314 "Replace everything except \"|\" with spaces."
15315 (let ((i (length line))
15316 (newstr (copy-sequence line)))
15317 (while (> i 0)
15318 (setq i (1- i))
15319 (if (not (eq (aref newstr i) ?|))
15320 (aset newstr i ?\ )))
15321 newstr))
15323 (defun org-format-table-table-html (lines)
15324 "Format a table generated by table.el into HTML.
15325 This conversion does *not* use `table-generate-source' from table.el.
15326 This has the advantage that Org-mode's HTML conversions can be used.
15327 But it has the disadvantage, that no cell- or row-spanning is allowed."
15328 (let (line field-buffer
15329 (head org-export-highlight-first-table-line)
15330 fields html empty)
15331 (setq html (concat org-export-html-table-tag "\n"))
15332 (while (setq line (pop lines))
15333 (setq empty "&nbsp;")
15334 (catch 'next-line
15335 (if (string-match "^[ \t]*\\+-" line)
15336 (progn
15337 (if field-buffer
15338 (progn
15339 (setq html (concat
15340 html
15341 "<tr>"
15342 (mapconcat
15343 (lambda (x)
15344 (if (equal x "") (setq x empty))
15345 (if head
15346 (concat "<th>" x "</th>\n")
15347 (concat "<td>" x "</td>\n")))
15348 field-buffer "\n")
15349 "</tr>\n"))
15350 (setq head nil)
15351 (setq field-buffer nil)))
15352 ;; Ignore this line
15353 (throw 'next-line t)))
15354 ;; Break the line into fields and store the fields
15355 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
15356 (if field-buffer
15357 (setq field-buffer (mapcar
15358 (lambda (x)
15359 (concat x "<br/>" (pop fields)))
15360 field-buffer))
15361 (setq field-buffer fields))))
15362 (setq html (concat html "</table>\n"))
15363 html))
15365 (defun org-format-table-table-html-using-table-generate-source (lines)
15366 "Format a table into html, using `table-generate-source' from table.el.
15367 This has the advantage that cell- or row-spanning is allowed.
15368 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
15369 (require 'table)
15370 (with-current-buffer (get-buffer-create " org-tmp1 ")
15371 (erase-buffer)
15372 (insert (mapconcat 'identity lines "\n"))
15373 (goto-char (point-min))
15374 (if (not (re-search-forward "|[^+]" nil t))
15375 (error "Error processing table"))
15376 (table-recognize-table)
15377 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
15378 (table-generate-source 'html " org-tmp2 ")
15379 (set-buffer " org-tmp2 ")
15380 (buffer-substring (point-min) (point-max))))
15382 (defun org-html-handle-time-stamps (s)
15383 "Format time stamps in string S, or remove them."
15384 (catch 'exit
15385 (let (r b)
15386 (while (string-match org-maybe-keyword-time-regexp s)
15387 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
15388 ;; never export CLOCK
15389 (throw 'exit ""))
15390 (or b (setq b (substring s 0 (match-beginning 0))))
15391 (if (not org-export-with-timestamps)
15392 (setq r (concat r (substring s 0 (match-beginning 0)))
15393 s (substring s (match-end 0)))
15394 (setq r (concat
15395 r (substring s 0 (match-beginning 0))
15396 (if (match-end 1)
15397 (format "@<span class=\"timestamp-kwd\">%s @</span>"
15398 (match-string 1 s)))
15399 (format " @<span class=\"timestamp\">%s@</span>"
15400 (substring (match-string 3 s) 1 -1)))
15401 s (substring s (match-end 0)))))
15402 ;; Line break if line started and ended with time stamp stuff
15403 (if (not r)
15405 (setq r (concat r s))
15406 (unless (string-match "\\S-" (concat b s))
15407 (setq r (concat r "@<br/>")))
15408 r))))
15410 (defun org-html-protect (s)
15411 ;; convert & to &amp;, < to &lt; and > to &gt;
15412 (let ((start 0))
15413 (while (string-match "&" s start)
15414 (setq s (replace-match "&amp;" t t s)
15415 start (1+ (match-beginning 0))))
15416 (while (string-match "<" s)
15417 (setq s (replace-match "&lt;" t t s)))
15418 (while (string-match ">" s)
15419 (setq s (replace-match "&gt;" t t s))))
15422 (defun org-export-cleanup-toc-line (s)
15423 "Remove tags and time staps from lines going into the toc."
15424 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
15425 (setq s (replace-match "" t t s)))
15426 (when org-export-remove-timestamps-from-toc
15427 (while (string-match org-maybe-keyword-time-regexp s)
15428 (setq s (replace-match "" t t s))))
15431 (defun org-html-expand (string)
15432 "Prepare STRING for HTML export. Applies all active conversions.
15433 If there are links in the string, don't modify these."
15434 (let* (m s l res)
15435 (while (setq m (string-match org-bracket-link-regexp string))
15436 (setq s (substring string 0 m)
15437 l (match-string 0 string)
15438 string (substring string (match-end 0)))
15439 (push (org-html-do-expand s) res)
15440 (push l res))
15441 (push (org-html-do-expand string) res)
15442 (apply 'concat (nreverse res))))
15444 (defun org-html-do-expand (s)
15445 "Apply all active conversions to translate special ASCII to HTML."
15446 (setq s (org-html-protect s))
15447 (if org-export-html-expand
15448 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
15449 (setq s (replace-match "<\\1>" t nil s))))
15450 (if org-export-with-emphasize
15451 (setq s (org-export-html-convert-emphasize s)))
15452 (if org-export-with-sub-superscripts
15453 (setq s (org-export-html-convert-sub-super s)))
15454 (if org-export-with-TeX-macros
15455 (let ((start 0) wd ass)
15456 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
15457 (setq wd (match-string 1 s))
15458 (if (setq ass (assoc wd org-html-entities))
15459 (setq s (replace-match (or (cdr ass)
15460 (concat "&" (car ass) ";"))
15461 t t s))
15462 (setq start (+ start (length wd)))))))
15465 (defun org-create-multibrace-regexp (left right n)
15466 "Create a regular expression which will match a balanced sexp.
15467 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
15468 as single character strings.
15469 The regexp returned will match the entire expression including the
15470 delimiters. It will also define a single group which contains the
15471 match except for the outermost delimiters. The maximum depth of
15472 stacked delimiters is N. Escaping delimiters is not possible."
15473 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
15474 (or "\\|")
15475 (re nothing)
15476 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
15477 (while (> n 1)
15478 (setq n (1- n)
15479 re (concat re or next)
15480 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
15481 (concat left "\\(" re "\\)" right)))
15483 (defvar org-match-substring-regexp
15484 (concat
15485 "\\([^\\]\\)\\([_^]\\)\\("
15486 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
15487 "\\|"
15488 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
15489 "\\|"
15490 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
15491 "The regular expression matching a sub- or superscript.")
15493 (defun org-export-html-convert-sub-super (string)
15494 "Convert sub- and superscripts in STRING to HTML."
15495 (let (key c)
15496 (while (string-match org-match-substring-regexp string)
15497 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
15498 (setq c (or (match-string 8 string)
15499 (match-string 6 string)
15500 (match-string 5 string)))
15501 (setq string (replace-match
15502 (concat (match-string 1 string)
15503 "<" key ">" c "</" key ">")
15504 t t string)))
15505 (while (string-match "\\\\\\([_^]\\)" string)
15506 (setq string (replace-match (match-string 1 string) t t string))))
15507 string)
15509 (defun org-export-html-convert-emphasize (string)
15510 "Apply emphasis."
15511 (while (string-match org-emph-re string)
15512 (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)))
15513 string)
15515 (defvar org-par-open nil)
15516 (defun org-open-par ()
15517 "Insert <p>, but first close previous paragraph if any."
15518 (org-close-par-maybe)
15519 (insert "\n<p>")
15520 (setq org-par-open t))
15521 (defun org-close-par-maybe ()
15522 "Close paragraph if there is one open."
15523 (when org-par-open
15524 (insert "</p>")
15525 (setq org-par-open nil)))
15526 (defun org-close-li ()
15527 "Close <li> if necessary."
15528 (org-close-par-maybe)
15529 (insert "</li>\n"))
15530 ; (when (save-excursion
15531 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
15532 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
15533 ; (insert "</li>"))))
15535 (defun org-html-level-start (level title umax with-toc head-count)
15536 "Insert a new level in HTML export.
15537 When TITLE is nil, just close all open levels."
15538 (org-close-par-maybe)
15539 (let ((l (1+ (max level umax))))
15540 (while (<= l org-level-max)
15541 (if (aref levels-open (1- l))
15542 (progn
15543 (org-html-level-close l)
15544 (aset levels-open (1- l) nil)))
15545 (setq l (1+ l)))
15546 (when title
15547 ;; If title is nil, this means this function is called to close
15548 ;; all levels, so the rest is done only if title is given
15549 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
15550 (setq title (replace-match
15551 (if org-export-with-tags
15552 (save-match-data
15553 (concat
15554 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
15555 (mapconcat 'identity (org-split-string
15556 (match-string 1 title) ":")
15557 "&nbsp;")
15558 "</span>"))
15560 t t title)))
15561 (if (> level umax)
15562 (progn
15563 (if (aref levels-open (1- level))
15564 (progn
15565 (org-close-li)
15566 (insert "<li>" title "<br/>\n"))
15567 (aset levels-open (1- level) t)
15568 (org-close-par-maybe)
15569 (insert "<ul>\n<li>" title "<br/>\n")))
15570 (if org-export-with-section-numbers
15571 (setq title (concat (org-section-number level) " " title)))
15572 (setq level (+ level org-export-html-toplevel-hlevel -1))
15573 (if with-toc
15574 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
15575 level head-count title level))
15576 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
15577 (org-open-par)))))
15579 (defun org-html-level-close (&rest args)
15580 "Terminate one level in HTML export."
15581 (org-close-li)
15582 (insert "</ul>"))
15584 ;; Variable holding the vector with section numbers
15585 (defvar org-section-numbers (make-vector org-level-max 0))
15587 (defun org-init-section-numbers ()
15588 "Initialize the vector for the section numbers."
15589 (let* ((level -1)
15590 (numbers (nreverse (org-split-string "" "\\.")))
15591 (depth (1- (length org-section-numbers)))
15592 (i depth) number-string)
15593 (while (>= i 0)
15594 (if (> i level)
15595 (aset org-section-numbers i 0)
15596 (setq number-string (or (car numbers) "0"))
15597 (if (string-match "\\`[A-Z]\\'" number-string)
15598 (aset org-section-numbers i
15599 (- (string-to-char number-string) ?A -1))
15600 (aset org-section-numbers i (string-to-number number-string)))
15601 (pop numbers))
15602 (setq i (1- i)))))
15604 (defun org-section-number (&optional level)
15605 "Return a string with the current section number.
15606 When LEVEL is non-nil, increase section numbers on that level."
15607 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
15608 (when level
15609 (when (> level -1)
15610 (aset org-section-numbers
15611 level (1+ (aref org-section-numbers level))))
15612 (setq idx (1+ level))
15613 (while (<= idx depth)
15614 (if (not (= idx 1))
15615 (aset org-section-numbers idx 0))
15616 (setq idx (1+ idx))))
15617 (setq idx 0)
15618 (while (<= idx depth)
15619 (setq n (aref org-section-numbers idx))
15620 (setq string (concat string (if (not (string= string "")) "." "")
15621 (int-to-string n)))
15622 (setq idx (1+ idx)))
15623 (save-match-data
15624 (if (string-match "\\`\\([@0]\\.\\)+" string)
15625 (setq string (replace-match "" t nil string)))
15626 (if (string-match "\\(\\.0\\)+\\'" string)
15627 (setq string (replace-match "" t nil string))))
15628 string))
15631 ;;;###autoload
15632 (defun org-export-icalendar-this-file ()
15633 "Export current file as an iCalendar file.
15634 The iCalendar file will be located in the same directory as the Org-mode
15635 file, but with extension `.ics'."
15636 (interactive)
15637 (org-export-icalendar nil buffer-file-name))
15639 (defun org-export-as-xoxo-insert-into (buffer &rest output)
15640 (with-current-buffer buffer
15641 (apply 'insert output)))
15642 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
15644 (defun org-export-as-xoxo (&optional buffer)
15645 "Export the org buffer as XOXO.
15646 The XOXO buffer is named *xoxo-<source buffer name>*"
15647 (interactive (list (current-buffer)))
15648 ;; A quickie abstraction
15650 ;; Output everything as XOXO
15651 (with-current-buffer (get-buffer buffer)
15652 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
15653 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
15654 (org-infile-export-plist)))
15655 (filename (concat (file-name-as-directory
15656 (org-export-directory :xoxo opt-plist))
15657 (file-name-sans-extension
15658 (file-name-nondirectory buffer-file-name))
15659 ".html"))
15660 (out (find-file-noselect filename))
15661 (last-level 1)
15662 (hanging-li nil))
15663 ;; Check the output buffer is empty.
15664 (with-current-buffer out (erase-buffer))
15665 ;; Kick off the output
15666 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
15667 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
15668 (let* ((hd (match-string-no-properties 1))
15669 (level (length hd))
15670 (text (concat
15671 (match-string-no-properties 2)
15672 (save-excursion
15673 (goto-char (match-end 0))
15674 (let ((str ""))
15675 (catch 'loop
15676 (while 't
15677 (forward-line)
15678 (if (looking-at "^[ \t]\\(.*\\)")
15679 (setq str (concat str (match-string-no-properties 1)))
15680 (throw 'loop str)))))))))
15682 ;; Handle level rendering
15683 (cond
15684 ((> level last-level)
15685 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
15687 ((< level last-level)
15688 (dotimes (- (- last-level level) 1)
15689 (if hanging-li
15690 (org-export-as-xoxo-insert-into out "</li>\n"))
15691 (org-export-as-xoxo-insert-into out "</ol>\n"))
15692 (when hanging-li
15693 (org-export-as-xoxo-insert-into out "</li>\n")
15694 (setq hanging-li nil)))
15696 ((equal level last-level)
15697 (if hanging-li
15698 (org-export-as-xoxo-insert-into out "</li>\n")))
15701 (setq last-level level)
15703 ;; And output the new li
15704 (setq hanging-li 't)
15705 (if (equal ?+ (elt text 0))
15706 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
15707 (org-export-as-xoxo-insert-into out "<li>" text))))
15709 ;; Finally finish off the ol
15710 (dotimes (- last-level 1)
15711 (if hanging-li
15712 (org-export-as-xoxo-insert-into out "</li>\n"))
15713 (org-export-as-xoxo-insert-into out "</ol>\n"))
15715 ;; Finish the buffer off and clean it up.
15716 (switch-to-buffer-other-window out)
15717 (indent-region (point-min) (point-max) nil)
15718 (save-buffer)
15719 (goto-char (point-min))
15722 ;;;###autoload
15723 (defun org-export-icalendar-all-agenda-files ()
15724 "Export all files in `org-agenda-files' to iCalendar .ics files.
15725 Each iCalendar file will be located in the same directory as the Org-mode
15726 file, but with extension `.ics'."
15727 (interactive)
15728 (apply 'org-export-icalendar nil (org-agenda-files t)))
15730 ;;;###autoload
15731 (defun org-export-icalendar-combine-agenda-files ()
15732 "Export all files in `org-agenda-files' to a single combined iCalendar file.
15733 The file is stored under the name `org-combined-agenda-icalendar-file'."
15734 (interactive)
15735 (apply 'org-export-icalendar t (org-agenda-files t)))
15737 (defun org-export-icalendar (combine &rest files)
15738 "Create iCalendar files for all elements of FILES.
15739 If COMBINE is non-nil, combine all calendar entries into a single large
15740 file and store it under the name `org-combined-agenda-icalendar-file'."
15741 (save-excursion
15742 (let* ((dir (org-export-directory
15743 :ical (list :publishing-directory
15744 org-export-publishing-directory)))
15745 file ical-file ical-buffer category started org-agenda-new-buffers)
15747 (when combine
15748 (setq ical-file
15749 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
15750 org-combined-agenda-icalendar-file
15751 (expand-file-name org-combined-agenda-icalendar-file dir))
15752 ical-buffer (org-get-agenda-file-buffer ical-file))
15753 (set-buffer ical-buffer) (erase-buffer))
15754 (while (setq file (pop files))
15755 (catch 'nextfile
15756 (org-check-agenda-file file)
15757 (set-buffer (org-get-agenda-file-buffer file))
15758 (unless combine
15759 (setq ical-file (concat (file-name-as-directory dir)
15760 (file-name-sans-extension
15761 (file-name-nondirectory buffer-file-name))
15762 ".ics"))
15763 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
15764 (with-current-buffer ical-buffer (erase-buffer)))
15765 (setq category (or org-category
15766 (file-name-sans-extension
15767 (file-name-nondirectory buffer-file-name))))
15768 (if (symbolp category) (setq category (symbol-name category)))
15769 (let ((standard-output ical-buffer))
15770 (if combine
15771 (and (not started) (setq started t)
15772 (org-start-icalendar-file org-icalendar-combined-name))
15773 (org-start-icalendar-file category))
15774 (org-print-icalendar-entries combine category)
15775 (when (or (and combine (not files)) (not combine))
15776 (org-finish-icalendar-file)
15777 (set-buffer ical-buffer)
15778 (save-buffer)
15779 (run-hooks 'org-after-save-iCalendar-file-hook)))))
15780 (org-release-buffers org-agenda-new-buffers))))
15782 (defvar org-after-save-iCalendar-file-hook nil
15783 "Hook run after an iCalendar file has been saved.
15784 The iCalendar buffer is still current when this hook is run.
15785 A good way to use this is to tell a desktop calenndar application to re-read
15786 the iCalendar file.")
15788 (defun org-print-icalendar-entries (&optional combine category)
15789 "Print iCalendar entries for the current Org-mode file to `standard-output'.
15790 When COMBINE is non nil, add the category to each line."
15791 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
15792 (dts (org-ical-ts-to-string
15793 (format-time-string (cdr org-time-stamp-formats) (current-time))
15794 "DTSTART"))
15795 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
15796 (save-excursion
15797 (goto-char (point-min))
15798 (while (re-search-forward org-ts-regexp nil t)
15799 (setq pos (match-beginning 0)
15800 ts (match-string 0)
15801 inc t
15802 hd (org-get-heading))
15803 (if (looking-at re2)
15804 (progn
15805 (goto-char (match-end 0))
15806 (setq ts2 (match-string 1) inc nil))
15807 (setq ts2 ts
15808 tmp (buffer-substring (max (point-min)
15809 (- pos org-ds-keyword-length))
15810 pos)
15811 deadlinep (string-match org-deadline-regexp tmp)
15812 scheduledp (string-match org-scheduled-regexp tmp)
15813 ;; donep (org-entry-is-done-p)
15815 (if (or (string-match org-tr-regexp hd)
15816 (string-match org-ts-regexp hd))
15817 (setq hd (replace-match "" t t hd)))
15818 (if combine
15819 (setq hd (concat hd " (category " category ")")))
15820 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
15821 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
15822 (princ (format "BEGIN:VEVENT
15825 SUMMARY:%s
15826 END:VEVENT\n"
15827 (org-ical-ts-to-string ts "DTSTART")
15828 (org-ical-ts-to-string ts2 "DTEND" inc)
15829 hd)))
15830 (when org-icalendar-include-todo
15831 (goto-char (point-min))
15832 (while (re-search-forward org-todo-line-regexp nil t)
15833 (setq state (match-string 1))
15834 (unless (equal state org-done-string)
15835 (setq hd (match-string 3))
15836 (if (string-match org-priority-regexp hd)
15837 (setq pri (string-to-char (match-string 2 hd))
15838 hd (concat (substring hd 0 (match-beginning 1))
15839 (substring hd (- (match-end 1)))))
15840 (setq pri org-default-priority))
15841 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
15842 (- org-lowest-priority ?A))))))
15844 (princ (format "BEGIN:VTODO
15846 SUMMARY:%s
15847 SEQUENCE:1
15848 PRIORITY:%d
15849 END:VTODO\n"
15850 dts hd pri))))))))
15852 (defun org-start-icalendar-file (name)
15853 "Start an iCalendar file by inserting the header."
15854 (let ((user user-full-name)
15855 (name (or name "unknown"))
15856 (timezone (cadr (current-time-zone))))
15857 (princ
15858 (format "BEGIN:VCALENDAR
15859 VERSION:2.0
15860 X-WR-CALNAME:%s
15861 PRODID:-//%s//Emacs with Org-mode//EN
15862 X-WR-TIMEZONE:%s
15863 CALSCALE:GREGORIAN\n" name user timezone))))
15865 (defun org-finish-icalendar-file ()
15866 "Finish an iCalendar file by inserting the END statement."
15867 (princ "END:VCALENDAR\n"))
15869 (defun org-ical-ts-to-string (s keyword &optional inc)
15870 "Take a time string S and convert it to iCalendar format.
15871 KEYWORD is added in front, to make a complete line like DTSTART....
15872 When INC is non-nil, increase the hour by two (if time string contains
15873 a time), or the day by one (if it does not contain a time)."
15874 (let ((t1 (org-parse-time-string s 'nodefault))
15875 t2 fmt have-time time)
15876 (if (and (car t1) (nth 1 t1) (nth 2 t1))
15877 (setq t2 t1 have-time t)
15878 (setq t2 (org-parse-time-string s)))
15879 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
15880 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
15881 (when inc
15882 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
15883 (setq time (encode-time s mi h d m y)))
15884 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
15885 (concat keyword (format-time-string fmt time))))
15887 ;;; LaTeX stuff
15889 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15890 "Keymap for the minor `org-cdlatex-mode'.")
15892 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15893 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15894 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15895 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15896 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15898 (defvar org-cdlatex-texmathp-advice-is-done nil
15899 "Flag remembering if we have applied the advice to texmathp already.")
15901 (define-minor-mode org-cdlatex-mode
15902 "Toggle the minor `org-cdlatex-mode'.
15903 This mode supports entering LaTeX environment and math in LaTeX fragments
15904 in Org-mode.
15905 \\{org-cdlatex-mode-map}"
15906 nil " OCDL" nil
15907 (when org-cdlatex-mode (require 'cdlatex))
15908 (unless org-cdlatex-texmathp-advice-is-done
15909 (setq org-cdlatex-texmathp-advice-is-done t)
15910 (defadvice texmathp (around org-math-always-on activate)
15911 "Always return t in org-mode buffers.
15912 This is because we want to insert math symbols without dollars even outside
15913 the LaTeX math segments. If Orgmode thinks that point is actually inside
15914 en embedded LaTeX fragement, let texmathp do its job.
15915 \\[org-cdlatex-mode-map]"
15916 (interactive)
15917 (let (p)
15918 (cond
15919 ((not (org-mode-p)) ad-do-it)
15920 ((eq this-command 'cdlatex-math-symbol)
15921 (setq ad-return-value t
15922 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15924 (let ((p (org-inside-LaTeX-fragment-p)))
15925 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15926 (setq ad-return-value t
15927 texmathp-why '("Org-mode embedded math" . 0))
15928 (if p ad-do-it)))))))))
15930 (defun turn-on-org-cdlatex ()
15931 "Unconditionally turn on `org-cdlatex-mode'."
15932 (org-cdlatex-mode 1))
15934 (defun org-inside-LaTeX-fragment-p ()
15935 "Test if point is inside a LaTeX fragment.
15936 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15937 sequence appearing also before point.
15938 Even though the matchers for math are configurable, this function assumes
15939 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15940 delimiters are skipped when they have been removed by customization.
15941 The return value is nil, or a cons cell with the delimiter and
15942 and the position of this delimiter.
15944 This function does a reasonably good job, but can locally be fooled by
15945 for example currency specifications. For example it will assume being in
15946 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15947 fragments that are properly closed, but during editing, we have to live
15948 with the uncertainty caused by missing closing delimiters. This function
15949 looks only before point, not after."
15950 (catch 'exit
15951 (let ((pos (point))
15952 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15953 (lim (progn
15954 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15955 (point)))
15956 dd-on str (start 0) m re)
15957 (goto-char pos)
15958 (when dodollar
15959 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15960 re (nth 1 (assoc "$" org-latex-regexps)))
15961 (while (string-match re str start)
15962 (cond
15963 ((= (match-end 0) (length str))
15964 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
15965 ((= (match-end 0) (- (length str) 5))
15966 (throw 'exit nil))
15967 (t (setq start (match-end 0))))))
15968 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15969 (goto-char pos)
15970 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15971 (and (match-beginning 2) (throw 'exit nil))
15972 ;; count $$
15973 (while (re-search-backward "\\$\\$" lim t)
15974 (setq dd-on (not dd-on)))
15975 (goto-char pos)
15976 (if dd-on (cons "$$" m))))))
15979 (defun org-try-cdlatex-tab ()
15980 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15981 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15982 - inside a LaTeX fragment, or
15983 - after the first word in a line, where an abbreviation expansion could
15984 insert a LaTeX environment."
15985 (when org-cdlatex-mode
15986 (cond
15987 ((save-excursion
15988 (skip-chars-backward "a-zA-Z0-9*")
15989 (skip-chars-backward " \t")
15990 (bolp))
15991 (cdlatex-tab) t)
15992 ((org-inside-LaTeX-fragment-p)
15993 (cdlatex-tab) t)
15994 (t nil))))
15996 (defun org-cdlatex-underscore-caret (&optional arg)
15997 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15998 Revert to the normal definition outside of these fragments."
15999 (interactive "P")
16000 (if (org-inside-LaTeX-fragment-p)
16001 (call-interactively 'cdlatex-sub-superscript)
16002 (let (org-cdlatex-mode)
16003 (call-interactively (key-binding (vector last-input-event))))))
16005 (defun org-cdlatex-math-modify (&optional arg)
16006 "Execute `cdlatex-math-modify' in LaTeX fragments.
16007 Revert to the normal definition outside of these fragments."
16008 (interactive "P")
16009 (if (org-inside-LaTeX-fragment-p)
16010 (call-interactively 'cdlatex-math-modify)
16011 (let (org-cdlatex-mode)
16012 (call-interactively (key-binding (vector last-input-event))))))
16014 (defvar org-latex-fragment-image-overlays nil
16015 "List of overlays carrying the images of latex fragments.")
16016 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16018 (defun org-remove-latex-fragment-image-overlays ()
16019 "Remove all overlays with LaTeX fragment images in current buffer."
16020 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
16021 (setq org-latex-fragment-image-overlays nil))
16023 (defun org-preview-latex-fragment (&optional subtree)
16024 "Preview the LaTeX fragment at point, or all locally or globally.
16025 If the cursor is in a LaTeX fragment, create the image and overlay
16026 it over the source code. If there is no fragment at point, display
16027 all fragments in the current text, from one headline to the next. With
16028 prefix SUBTREE, display all fragments in the current subtree. With a
16029 double prefix `C-u C-u', or when the cursor is before the first headline,
16030 display all fragments in the buffer.
16031 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16032 (interactive "P")
16033 (org-remove-latex-fragment-image-overlays)
16034 (save-excursion
16035 (save-restriction
16036 (let (beg end at msg)
16037 (cond
16038 ((or (equal subtree '(16))
16039 (not (save-excursion
16040 (re-search-backward (concat "^" outline-regexp) nil t))))
16041 (setq beg (point-min) end (point-max)
16042 msg "Creating images for buffer...%s"))
16043 ((equal subtree '(4))
16044 (org-back-to-heading)
16045 (setq beg (point) end (org-end-of-subtree t)
16046 msg "Creating images for subtree...%s"))
16048 (if (setq at (org-inside-LaTeX-fragment-p))
16049 (goto-char (max (point-min) (- (cdr at) 2)))
16050 (org-back-to-heading))
16051 (setq beg (point) end (progn (outline-next-heading) (point))
16052 msg (if at "Creating image...%s"
16053 "Creating images for entry...%s"))))
16054 (message msg "")
16055 (narrow-to-region beg end)
16056 (org-format-latex
16057 (concat "ltxpng/" (file-name-sans-extension
16058 (file-name-nondirectory
16059 buffer-file-name)))
16060 default-directory 'overlays msg at)
16061 (message msg "done. Use `C-c C-c' to remove images.")))))
16063 (defvar org-latex-regexps
16064 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16065 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16066 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16067 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
16068 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16069 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
16070 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
16071 "Regular expressions for matching embedded LaTeX.")
16073 (defun org-format-latex (prefix &optional dir overlays msg at)
16074 "Replace LaTeX fragments with links to an image, and produce images."
16075 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16076 (let* ((prefixnodir (file-name-nondirectory prefix))
16077 (absprefix (expand-file-name prefix dir))
16078 (todir (file-name-directory absprefix))
16079 (opt org-format-latex-options)
16080 (matchers (plist-get opt :matchers))
16081 (re-list org-latex-regexps)
16082 (cnt 0) txt link beg end re e oldfiles
16083 m n block linkfile movefile ov)
16084 ;; Make sure the directory exists
16085 (or (file-directory-p todir) (make-directory todir))
16086 ;; Check if there are old images files with this prefix, and remove them
16087 (setq oldfiles (directory-files
16088 todir 'full
16089 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
16090 (while oldfiles (delete-file (pop oldfiles)))
16091 ;; Check the different regular expressions
16092 (while (setq e (pop re-list))
16093 (setq m (car e) re (nth 1 e) n (nth 2 e)
16094 block (if (nth 3 e) "\n\n" ""))
16095 (when (member m matchers)
16096 (goto-char (point-min))
16097 (while (re-search-forward re nil t)
16098 (when (or (not at) (equal (cdr at) (match-beginning n)))
16099 (setq txt (match-string n)
16100 beg (match-beginning n) end (match-end n)
16101 cnt (1+ cnt)
16102 linkfile (format "%s_%04d.png" prefix cnt)
16103 movefile (format "%s_%04d.png" absprefix cnt)
16104 link (concat block "[[file:" linkfile "]]" block))
16105 (if msg (message msg cnt))
16106 (goto-char beg)
16107 (org-create-formula-image
16108 txt movefile opt)
16109 (if overlays
16110 (progn
16111 (setq ov (org-make-overlay beg end))
16112 (if (featurep 'xemacs)
16113 (progn
16114 (org-overlay-put ov 'invisible t)
16115 (org-overlay-put
16116 ov 'end-glyph
16117 (make-glyph (vector 'png :file movefile))))
16118 (org-overlay-put
16119 ov 'display
16120 (list 'image :type 'png :file movefile :ascent 'center)))
16121 (push ov org-latex-fragment-image-overlays)
16122 (goto-char end))
16123 (delete-region beg end)
16124 (insert link))))))))
16126 ;; This function borrows from Ganesh Swami's latex2png.el
16127 (defun org-create-formula-image (string tofile options)
16128 (let* ((tmpdir (if (featurep 'xemacs)
16129 (temp-directory)
16130 temporary-file-directory))
16131 (texfilebase (make-temp-name
16132 (expand-file-name "orgtex" tmpdir)))
16134 ;(texfilebase (make-temp-file "orgtex"))
16135 ; (dummy (delete-file texfilebase))
16136 (texfile (concat texfilebase ".tex"))
16137 (dvifile (concat texfilebase ".dvi"))
16138 (pngfile (concat texfilebase ".png"))
16139 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
16140 (fg (or (plist-get options :foreground) "Black"))
16141 (bg (or (plist-get options :background) "Transparent")))
16142 (with-temp-file texfile
16143 (insert "\\documentclass{article}
16144 \\usepackage{fullpage}
16145 \\usepackage{amssymb}
16146 \\usepackage[usenames]{color}
16147 \\usepackage{amsmath}
16148 \\usepackage{latexsym}
16149 \\usepackage[mathscr]{eucal}
16150 \\pagestyle{empty}
16151 \\begin{document}\n" string "\n\\end{document}\n"))
16152 (let ((dir default-directory))
16153 (condition-case nil
16154 (progn
16155 (cd tmpdir)
16156 (call-process "latex" nil nil nil texfile))
16157 (error nil))
16158 (cd dir))
16159 (if (not (file-exists-p dvifile))
16160 (progn (message "Failed to create dvi file from %s" texfile) nil)
16161 (call-process "dvipng" nil nil nil
16162 "-E" "-fg" fg "-bg" bg
16163 "-x" scale "-y" scale "-T" "tight"
16164 "-o" pngfile
16165 dvifile)
16166 (if (not (file-exists-p pngfile))
16167 (progn (message "Failed to create png file from %s" texfile) nil)
16168 ;; Use the requested file name and clean up
16169 (copy-file pngfile tofile 'replace)
16170 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16171 (delete-file (concat texfilebase e)))
16172 pngfile))))
16174 ;;; Key bindings
16176 ;; - Bindings in Org-mode map are currently
16177 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
16178 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
16179 ;; e (?) useful from outline-mode
16180 ;; i k @ expendable from outline-mode
16181 ;; 0123456789 % & ()_{} " ` free
16183 ;; Make `C-c C-x' a prefix key
16184 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
16186 ;; TAB key with modifiers
16187 (define-key org-mode-map "\C-i" 'org-cycle)
16188 (define-key org-mode-map [(tab)] 'org-cycle)
16189 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
16190 (define-key org-mode-map [(meta tab)] 'org-complete)
16191 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
16192 ;; The following line is necessary under Suse GNU/Linux
16193 (unless (featurep 'xemacs)
16194 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
16195 (define-key org-mode-map [(shift tab)] 'org-shifttab)
16197 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
16198 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
16199 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16200 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
16201 (define-key org-mode-map [(meta return)] 'org-meta-return)
16202 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
16203 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
16205 ;; Cursor keys with modifiers
16206 (define-key org-mode-map [(meta left)] 'org-metaleft)
16207 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
16208 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
16209 (define-key org-mode-map [(meta right)] 'org-metaright)
16210 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
16211 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
16212 (define-key org-mode-map [(meta up)] 'org-metaup)
16213 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
16214 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
16215 (define-key org-mode-map [(meta down)] 'org-metadown)
16216 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
16217 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
16219 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16220 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
16221 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
16222 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
16223 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
16224 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
16225 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
16226 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
16227 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
16228 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
16229 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
16230 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
16231 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
16232 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
16233 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
16234 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
16236 ;; All the other keys
16238 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16239 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
16240 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
16241 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
16242 (define-key org-mode-map "\C-c\C-j" 'org-goto)
16243 (define-key org-mode-map "\C-c\C-t" 'org-todo)
16244 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
16245 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
16246 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
16247 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
16248 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
16249 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
16250 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
16251 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
16252 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
16253 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
16254 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
16255 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
16256 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
16257 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
16258 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16259 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16260 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16261 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16262 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
16263 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
16264 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16265 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
16266 (define-key org-mode-map "\C-c]" 'org-remove-file)
16267 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
16268 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
16269 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16270 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
16271 (define-key org-mode-map "\C-m" 'org-return)
16272 (define-key org-mode-map "\C-c?" 'org-table-current-column)
16273 (define-key org-mode-map "\C-c " 'org-table-blank-field)
16274 (define-key org-mode-map "\C-c+" 'org-table-sum)
16275 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
16276 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
16277 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
16278 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16279 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
16280 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16281 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
16282 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
16283 (define-key org-mode-map "\C-c\C-e" 'org-export)
16284 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16286 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
16287 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16288 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16289 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16291 (define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16292 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16293 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16294 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16295 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16296 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16297 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16298 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16299 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16301 (when (featurep 'xemacs)
16302 (define-key org-mode-map 'button3 'popup-mode-menu))
16304 (defsubst org-table-p () (org-at-table-p))
16306 (defun org-self-insert-command (N)
16307 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16308 If the cursor is in a table looking at whitespace, the whitespace is
16309 overwritten, and the table is not marked as requiring realignment."
16310 (interactive "p")
16311 (if (and (org-table-p)
16312 (progn
16313 ;; check if we blank the field, and if that triggers align
16314 (and org-table-auto-blank-field
16315 (member last-command
16316 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
16317 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16318 ;; got extra space, this field does not determine column width
16319 (let (org-table-may-need-update) (org-table-blank-field))
16320 ;; no extra space, this field may determine column width
16321 (org-table-blank-field)))
16323 (eq N 1)
16324 (looking-at "[^|\n]* |"))
16325 (let (org-table-may-need-update)
16326 (goto-char (1- (match-end 0)))
16327 (delete-backward-char 1)
16328 (goto-char (match-beginning 0))
16329 (self-insert-command N))
16330 (setq org-table-may-need-update t)
16331 (self-insert-command N)))
16333 (defun org-delete-backward-char (N)
16334 "Like `delete-backward-char', insert whitespace at field end in tables.
16335 When deleting backwards, in tables this function will insert whitespace in
16336 front of the next \"|\" separator, to keep the table aligned. The table will
16337 still be marked for re-alignment if the field did fill the entire column,
16338 because, in this case the deletion might narrow the column."
16339 (interactive "p")
16340 (if (and (org-table-p)
16341 (eq N 1)
16342 (string-match "|" (buffer-substring (point-at-bol) (point)))
16343 (looking-at ".*?|"))
16344 (let ((pos (point))
16345 (noalign (looking-at "[^|\n\r]* |"))
16346 (c org-table-may-need-update))
16347 (backward-delete-char N)
16348 (skip-chars-forward "^|")
16349 (insert " ")
16350 (goto-char (1- pos))
16351 ;; noalign: if there were two spaces at the end, this field
16352 ;; does not determine the width of the column.
16353 (if noalign (setq org-table-may-need-update c)))
16354 (backward-delete-char N)))
16356 (defun org-delete-char (N)
16357 "Like `delete-char', but insert whitespace at field end in tables.
16358 When deleting characters, in tables this function will insert whitespace in
16359 front of the next \"|\" separator, to keep the table aligned. The table will
16360 still be marked for re-alignment if the field did fill the entire column,
16361 because, in this case the deletion might narrow the column."
16362 (interactive "p")
16363 (if (and (org-table-p)
16364 (not (bolp))
16365 (not (= (char-after) ?|))
16366 (eq N 1))
16367 (if (looking-at ".*?|")
16368 (let ((pos (point))
16369 (noalign (looking-at "[^|\n\r]* |"))
16370 (c org-table-may-need-update))
16371 (replace-match (concat
16372 (substring (match-string 0) 1 -1)
16373 " |"))
16374 (goto-char pos)
16375 ;; noalign: if there were two spaces at the end, this field
16376 ;; does not determine the width of the column.
16377 (if noalign (setq org-table-may-need-update c)))
16378 (delete-char N))
16379 (delete-char N)))
16381 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16382 (put 'org-self-insert-command 'delete-selection t)
16383 (put 'orgtbl-self-insert-command 'delete-selection t)
16384 (put 'org-delete-char 'delete-selection 'supersede)
16385 (put 'org-delete-backward-char 'delete-selection 'supersede)
16387 ;; How to do this: Measure non-white length of current string
16388 ;; If equal to column width, we should realign.
16390 (defun org-remap (map &rest commands)
16391 "In MAP, remap the functions given in COMMANDS.
16392 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16393 (let (new old)
16394 (while commands
16395 (setq old (pop commands) new (pop commands))
16396 (if (fboundp 'command-remapping)
16397 (define-key map (vector 'remap old) new)
16398 (substitute-key-definition old new map global-map)))))
16400 (when (eq org-enable-table-editor 'optimized)
16401 ;; If the user wants maximum table support, we need to hijack
16402 ;; some standard editing functions
16403 (org-remap org-mode-map
16404 'self-insert-command 'org-self-insert-command
16405 'delete-char 'org-delete-char
16406 'delete-backward-char 'org-delete-backward-char)
16407 (define-key org-mode-map "|" 'org-force-self-insert))
16409 (defun org-shiftcursor-error ()
16410 "Throw an error because Shift-Cursor command was applied in wrong context."
16411 (error "This command is active in special context like tables, headlines or timestamps"))
16413 (defun org-shifttab (&optional arg)
16414 "Global visibility cycling or move to previous table field.
16415 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16416 on context.
16417 See the individual commands for more information."
16418 (interactive "P")
16419 (cond
16420 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16421 (t (call-interactively 'org-global-cycle))))
16423 (defun org-shiftmetaleft ()
16424 "Promote subtree or delete table column.
16425 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
16426 See the individual commands for more information."
16427 (interactive)
16428 (cond
16429 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16430 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16431 ((org-at-item-p) (call-interactively 'org-outdent-item))
16432 (t (org-shiftcursor-error))))
16434 (defun org-shiftmetaright ()
16435 "Demote subtree or insert table column.
16436 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
16437 See the individual commands for more information."
16438 (interactive)
16439 (cond
16440 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16441 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16442 ((org-at-item-p) (call-interactively 'org-indent-item))
16443 (t (org-shiftcursor-error))))
16445 (defun org-shiftmetaup (&optional arg)
16446 "Move subtree up or kill table row.
16447 Calls `org-move-subtree-up' or `org-table-kill-row' or
16448 `org-move-item-up' depending on context. See the individual commands
16449 for more information."
16450 (interactive "P")
16451 (cond
16452 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16453 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16454 ((org-at-item-p) (call-interactively 'org-move-item-up))
16455 (t (org-shiftcursor-error))))
16456 (defun org-shiftmetadown (&optional arg)
16457 "Move subtree down or insert table row.
16458 Calls `org-move-subtree-down' or `org-table-insert-row' or
16459 `org-move-item-down', depending on context. See the individual
16460 commands for more information."
16461 (interactive "P")
16462 (cond
16463 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16464 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16465 ((org-at-item-p) (call-interactively 'org-move-item-down))
16466 (t (org-shiftcursor-error))))
16468 (defun org-metaleft (&optional arg)
16469 "Promote heading or move table column to left.
16470 Calls `org-do-promote' or `org-table-move-column', depending on context.
16471 With no specific context, calls the Emacs default `backward-word'.
16472 See the individual commands for more information."
16473 (interactive "P")
16474 (cond
16475 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16476 ((or (org-on-heading-p) (org-region-active-p))
16477 (call-interactively 'org-do-promote))
16478 (t (call-interactively 'backward-word))))
16480 (defun org-metaright (&optional arg)
16481 "Demote subtree or move table column to right.
16482 Calls `org-do-demote' or `org-table-move-column', depending on context.
16483 With no specific context, calls the Emacs default `forward-word'.
16484 See the individual commands for more information."
16485 (interactive "P")
16486 (cond
16487 ((org-at-table-p) (call-interactively 'org-table-move-column))
16488 ((or (org-on-heading-p) (org-region-active-p))
16489 (call-interactively 'org-do-demote))
16490 (t (call-interactively 'forward-word))))
16492 (defun org-metaup (&optional arg)
16493 "Move subtree up or move table row up.
16494 Calls `org-move-subtree-up' or `org-table-move-row' or
16495 `org-move-item-up', depending on context. See the individual commands
16496 for more information."
16497 (interactive "P")
16498 (cond
16499 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16500 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16501 ((org-at-item-p) (call-interactively 'org-move-item-up))
16502 (t (org-shiftcursor-error))))
16504 (defun org-metadown (&optional arg)
16505 "Move subtree down or move table row down.
16506 Calls `org-move-subtree-down' or `org-table-move-row' or
16507 `org-move-item-down', depending on context. See the individual
16508 commands for more information."
16509 (interactive "P")
16510 (cond
16511 ((org-at-table-p) (call-interactively 'org-table-move-row))
16512 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16513 ((org-at-item-p) (call-interactively 'org-move-item-down))
16514 (t (org-shiftcursor-error))))
16516 (defun org-shiftup (&optional arg)
16517 "Increase item in timestamp or increase priority of current headline.
16518 Calls `org-timestamp-up' or `org-priority-up', depending on context.
16519 See the individual commands for more information."
16520 (interactive "P")
16521 (cond
16522 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
16523 ((org-on-heading-p) (call-interactively 'org-priority-up))
16524 ((org-at-item-p) (call-interactively 'org-previous-item))
16525 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
16527 (defun org-shiftdown (&optional arg)
16528 "Decrease item in timestamp or decrease priority of current headline.
16529 Calls `org-timestamp-down' or `org-priority-down', depending on context.
16530 See the individual commands for more information."
16531 (interactive "P")
16532 (cond
16533 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
16534 ((org-on-heading-p) (call-interactively 'org-priority-down))
16535 (t (call-interactively 'org-next-item))))
16537 (defun org-shiftright ()
16538 "Next TODO keyword or timestamp one day later, depending on context."
16539 (interactive)
16540 (cond
16541 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16542 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
16543 (t (org-shiftcursor-error))))
16545 (defun org-shiftleft ()
16546 "Previous TODO keyword or timestamp one day earlier, depending on context."
16547 (interactive)
16548 (cond
16549 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16550 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
16551 (t (org-shiftcursor-error))))
16553 (defun org-copy-special ()
16554 "Copy region in table or copy current subtree.
16555 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16556 See the individual commands for more information."
16557 (interactive)
16558 (call-interactively
16559 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16561 (defun org-cut-special ()
16562 "Cut region in table or cut current subtree.
16563 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16564 See the individual commands for more information."
16565 (interactive)
16566 (call-interactively
16567 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16569 (defun org-paste-special (arg)
16570 "Paste rectangular region into table, or past subtree relative to level.
16571 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16572 See the individual commands for more information."
16573 (interactive "P")
16574 (if (org-at-table-p)
16575 (org-table-paste-rectangle)
16576 (org-paste-subtree arg)))
16578 (defun org-ctrl-c-ctrl-c (&optional arg)
16579 "Set tags in headline, or update according to changed information at point.
16581 This command does many different things, depending on context:
16583 - If the cursor is in a headline, prompt for tags and insert them
16584 into the current line, aligned to `org-tags-column'. When called
16585 with prefix arg, realign all tags in the current buffer.
16587 - If the cursor is in one of the special #+KEYWORD lines, this
16588 triggers scanning the buffer for these lines and updating the
16589 information.
16591 - If the cursor is inside a table, realign the table. This command
16592 works even if the automatic table editor has been turned off.
16594 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16595 the entire table.
16597 - If the cursor is inside a table created by the table.el package,
16598 activate that table.
16600 - If the current buffer is a remember buffer, close note and file it.
16601 with a prefix argument, file it without further interaction to the default
16602 location.
16604 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16605 links in this buffer.
16607 - If the cursor is on a numbered item in a plain list, renumber the
16608 ordered list."
16609 (interactive "P")
16610 (let ((org-enable-table-editor t))
16611 (cond
16612 ((or org-clock-overlays
16613 org-occur-highlights
16614 org-latex-fragment-image-overlays)
16615 (org-remove-clock-overlays)
16616 (org-remove-occur-highlights)
16617 (org-remove-latex-fragment-image-overlays)
16618 (message "Temporary highlights/overlays removed from current buffer"))
16619 ((and (local-variable-p 'org-finish-function (current-buffer))
16620 (fboundp org-finish-function))
16621 (funcall org-finish-function))
16622 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16623 ((org-on-heading-p) (call-interactively 'org-set-tags))
16624 ((org-at-table.el-p)
16625 (require 'table)
16626 (beginning-of-line 1)
16627 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
16628 (call-interactively 'table-recognize-table))
16629 ((org-at-table-p)
16630 (org-table-maybe-eval-formula)
16631 (if arg
16632 (call-interactively 'org-table-recalculate)
16633 (org-table-maybe-recalculate-line))
16634 (call-interactively 'org-table-align))
16635 ((org-at-item-checkbox-p)
16636 (call-interactively 'org-toggle-checkbox))
16637 ((org-at-item-p)
16638 (call-interactively 'org-renumber-ordered-list))
16639 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
16640 (cond
16641 ((equal (match-string 1) "TBLFM")
16642 ;; Recalculate the table before this line
16643 (save-excursion
16644 (beginning-of-line 1)
16645 (skip-chars-backward " \r\n\t")
16646 (if (org-at-table-p)
16647 (org-call-with-arg 'org-table-recalculate t))))
16649 (call-interactively 'org-mode-restart))))
16650 (t (error "C-c C-c can do nothing useful at this location.")))))
16652 (defun org-mode-restart ()
16653 "Restart Org-mode, to scan again for special lines.
16654 Also updates the keyword regular expressions."
16655 (interactive)
16656 (let ((org-inhibit-startup t)) (org-mode))
16657 (message "Org-mode restarted to refresh keyword and special line setup"))
16659 (defun org-return ()
16660 "Goto next table row or insert a newline.
16661 Calls `org-table-next-row' or `newline', depending on context.
16662 See the individual commands for more information."
16663 (interactive)
16664 (cond
16665 ((org-at-table-p)
16666 (org-table-justify-field-maybe)
16667 (call-interactively 'org-table-next-row))
16668 (t (newline))))
16670 (defun org-meta-return (&optional arg)
16671 "Insert a new heading or wrap a region in a table.
16672 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16673 See the individual commands for more information."
16674 (interactive "P")
16675 (cond
16676 ((org-at-table-p)
16677 (call-interactively 'org-table-wrap-region))
16678 (t (call-interactively 'org-insert-heading))))
16680 ;;; Menu entries
16682 ;; Define the Org-mode menus
16683 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16684 '("Tbl"
16685 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
16686 ["Next Field" org-cycle (org-at-table-p)]
16687 ["Previous Field" org-shifttab (org-at-table-p)]
16688 ["Next Row" org-return (org-at-table-p)]
16689 "--"
16690 ["Blank Field" org-table-blank-field (org-at-table-p)]
16691 ["Edit Field" org-table-edit-field (org-at-table-p)]
16692 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16693 "--"
16694 ("Column"
16695 ["Move Column Left" org-metaleft (org-at-table-p)]
16696 ["Move Column Right" org-metaright (org-at-table-p)]
16697 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16698 ["Insert Column" org-shiftmetaright (org-at-table-p)]
16699 "--"
16700 ["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])
16701 ("Row"
16702 ["Move Row Up" org-metaup (org-at-table-p)]
16703 ["Move Row Down" org-metadown (org-at-table-p)]
16704 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16705 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16706 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16707 "--"
16708 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
16709 ("Rectangle"
16710 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16711 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16712 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16713 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16714 "--"
16715 ("Calculate"
16716 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16717 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16718 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
16719 "--"
16720 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16721 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16722 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16723 "--"
16724 ["Sum Column/Rectangle" org-table-sum
16725 (or (org-at-table-p) (org-region-active-p))]
16726 ["Which Column?" org-table-current-column (org-at-table-p)])
16727 ["Debug Formulas"
16728 (setq org-table-formula-debug (not org-table-formula-debug))
16729 :style toggle :selected org-table-formula-debug]
16730 "--"
16731 ["Create" org-table-create (and (not (org-at-table-p))
16732 org-enable-table-editor)]
16733 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16734 ["Import from File" org-table-import (not (org-at-table-p))]
16735 ["Export to File" org-table-export (org-at-table-p)]
16736 "--"
16737 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16739 (easy-menu-define org-org-menu org-mode-map "Org menu"
16740 '("Org"
16741 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
16742 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
16743 ["Sparse Tree" org-occur t]
16744 ["Show All" show-all t]
16745 "--"
16746 ["New Heading" org-insert-heading t]
16747 ("Navigate Headings"
16748 ["Up" outline-up-heading t]
16749 ["Next" outline-next-visible-heading t]
16750 ["Previous" outline-previous-visible-heading t]
16751 ["Next Same Level" outline-forward-same-level t]
16752 ["Previous Same Level" outline-backward-same-level t]
16753 "--"
16754 ["Jump" org-goto t])
16755 ("Edit Structure"
16756 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16757 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16758 "--"
16759 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16760 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16761 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16762 "--"
16763 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16764 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16765 ["Demote Heading" org-metaright (not (org-at-table-p))]
16766 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16767 "--"
16768 ["Convert to odd levels" org-convert-to-odd-levels t]
16769 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16770 ("Archive"
16771 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16772 ["Check and Tag Children" (org-toggle-archive-tag (4))
16773 :active t :keys "C-u C-c C-x C-a"]
16774 ["Sparse trees open ARCHIVE trees"
16775 (setq org-sparse-tree-open-archived-trees
16776 (not org-sparse-tree-open-archived-trees))
16777 :style toggle :selected org-sparse-tree-open-archived-trees]
16778 ["Cycling opens ARCHIVE trees"
16779 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
16780 :style toggle :selected org-cycle-open-archived-trees]
16781 ["Agenda includes ARCHIVE trees"
16782 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
16783 :style toggle :selected (not org-agenda-skip-archived-trees)]
16784 "--"
16785 ["Move Subtree to Archive" org-archive-subtree t]
16786 ["Check and Move Children" (org-archive-subtree '(4))
16787 :active t :keys "C-u C-c $"])
16788 "--"
16789 ("TODO Lists"
16790 ["TODO/DONE/-" org-todo t]
16791 ("Select keyword"
16792 ["Next keyword" org-shiftright (org-on-heading-p)]
16793 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16794 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
16795 ["Show TODO Tree" org-show-todo-tree t]
16796 ["Global TODO list" org-todo-list t]
16797 "--"
16798 ["Set Priority" org-priority t]
16799 ["Priority Up" org-shiftup t]
16800 ["Priority Down" org-shiftdown t]
16801 "--"
16802 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
16803 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
16804 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
16805 ; (or (org-on-heading-p) (org-at-item-p))]
16806 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
16807 ; (or (org-on-heading-p) (org-at-item-p))]
16808 ; ["Update Statistics" org-update-checkbox-count t]
16810 ("Dates and Scheduling"
16811 ["Timestamp" org-time-stamp t]
16812 ["Timestamp (inactive)" org-time-stamp-inactive t]
16813 ("Change Date"
16814 ["1 Day Later" org-timestamp-up-day t]
16815 ["1 Day Earlier" org-timestamp-down-day t]
16816 ["1 ... Later" org-shiftup t]
16817 ["1 ... Earlier" org-shiftdown t])
16818 ["Compute Time Range" org-evaluate-time-range t]
16819 ["Schedule Item" org-schedule t]
16820 ["Deadline" org-deadline t]
16821 "--"
16822 ["Custom time format" org-toggle-time-stamp-overlays
16823 :style radio :selected org-display-custom-times]
16824 "--"
16825 ["Goto Calendar" org-goto-calendar t]
16826 ["Date from Calendar" org-date-from-calendar t])
16827 ("Logging work"
16828 ["Clock in" org-clock-in t]
16829 ["Clock out" org-clock-out t]
16830 ["Clock cancel" org-clock-cancel t]
16831 ["Display times" org-clock-display t]
16832 ["Create clock table" org-clock-report t]
16833 "--"
16834 ["Record DONE time"
16835 (progn (setq org-log-done (not org-log-done))
16836 (message "Switching to %s will %s record a timestamp"
16837 org-done-string
16838 (if org-log-done "automatically" "not")))
16839 :style toggle :selected org-log-done])
16840 "--"
16841 ["Agenda Command..." org-agenda t]
16842 ("File List for Agenda")
16843 ("Special views current file"
16844 ["TODO Tree" org-show-todo-tree t]
16845 ["Check Deadlines" org-check-deadlines t]
16846 ["Timeline" org-timeline t]
16847 ["Tags Tree" org-tags-sparse-tree t])
16848 "--"
16849 ("Hyperlinks"
16850 ["Store Link (Global)" org-store-link t]
16851 ["Insert Link" org-insert-link t]
16852 ["Follow Link" org-open-at-point t]
16853 "--"
16854 ["Descriptive Links"
16855 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16856 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
16857 ["Literal Links"
16858 (progn
16859 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16860 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
16861 "--"
16862 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
16863 (save-excursion (goto-char (point-min))
16864 (re-search-forward "<[a-z]+:" nil t))])
16865 "--"
16866 ["Export/Publish..." org-export t]
16867 ("LaTeX"
16868 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16869 :selected org-cdlatex-mode]
16870 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16871 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16872 ["Modify math symbol" org-cdlatex-math-modify
16873 (org-inside-LaTeX-fragment-p)]
16874 ["Export LaTeX fragments as images"
16875 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
16876 :style toggle :selected org-export-with-LaTeX-fragments])
16877 "--"
16878 ("Documentation"
16879 ["Show Version" org-version t]
16880 ["Info Documentation" org-info t])
16881 ("Customize"
16882 ["Browse Org Group" org-customize t]
16883 "--"
16884 ["Expand This Menu" org-create-customize-menu
16885 (fboundp 'customize-menu-create)])
16886 "--"
16887 ["Refresh setup" org-mode-restart t]
16890 (defun org-info (&optional node)
16891 "Read documentation for Org-mode in the info system.
16892 With optional NODE, go directly to that node."
16893 (interactive)
16894 (require 'info)
16895 (Info-goto-node (format "(org)%s" (or node ""))))
16897 (defun org-install-agenda-files-menu ()
16898 (let ((bl (buffer-list)))
16899 (save-excursion
16900 (while bl
16901 (set-buffer (pop bl))
16902 (if (org-mode-p) (setq bl nil)))
16903 (when (org-mode-p)
16904 (easy-menu-change
16905 '("Org") "File List for Agenda"
16906 (append
16907 (list
16908 ["Edit File List" (org-edit-agenda-file-list) t]
16909 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16910 ["Remove Current File from List" org-remove-file t]
16911 ["Cycle through agenda files" org-cycle-agenda-files t]
16912 "--")
16913 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16915 ;;; Documentation
16917 (defun org-customize ()
16918 "Call the customize function with org as argument."
16919 (interactive)
16920 (customize-browse 'org))
16922 (defun org-create-customize-menu ()
16923 "Create a full customization menu for Org-mode, insert it into the menu."
16924 (interactive)
16925 (if (fboundp 'customize-menu-create)
16926 (progn
16927 (easy-menu-change
16928 '("Org") "Customize"
16929 `(["Browse Org group" org-customize t]
16930 "--"
16931 ,(customize-menu-create 'org)
16932 ["Set" Custom-set t]
16933 ["Save" Custom-save t]
16934 ["Reset to Current" Custom-reset-current t]
16935 ["Reset to Saved" Custom-reset-saved t]
16936 ["Reset to Standard Settings" Custom-reset-standard t]))
16937 (message "\"Org\"-menu now contains full customization menu"))
16938 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16940 ;;; Miscellaneous stuff
16942 (defun org-context ()
16943 "Return a list of contexts of the current cursor position.
16944 If several contexts apply, all are returned.
16945 Each context entry is a list with a symbol naming the context, and
16946 two positions indicating start and end of the context. Possible
16947 contexts are:
16949 :headline anywhere in a headline
16950 :headline-stars on the leading stars in a headline
16951 :todo-keyword on a TODO keyword (including DONE) in a headline
16952 :tags on the TAGS in a headline
16953 :priority on the priority cookie in a headline
16954 :item on the first line of a plain list item
16955 :item-bullet on the bullet/number of a plain list item
16956 :checkbox on the checkbox in a plain list item
16957 :table in an org-mode table
16958 :table-special on a special filed in a table
16959 :table-table in a table.el table
16960 :link on a hyperline
16961 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16962 :target on a <<target>>
16963 :radio-target on a <<<radio-target>>>
16964 :latex-fragment on a LaTeX fragment
16965 :latex-preview on a LaTeX fragment with overlayed preview image
16967 This function expects the position to be visible because it uses font-lock
16968 faces as a help to recognize the following contexts: :table-special, :link,
16969 and :keyword."
16970 (let* ((f (get-text-property (point) 'face))
16971 (faces (if (listp f) f (list f)))
16972 (p (point)) clist o)
16973 ;; First the large context
16974 (cond
16975 ((org-on-heading-p)
16976 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16977 (when (progn
16978 (beginning-of-line 1)
16979 (looking-at org-todo-line-tags-regexp))
16980 (push (org-point-in-group p 1 :headline-stars) clist)
16981 (push (org-point-in-group p 2 :todo-keyword) clist)
16982 (push (org-point-in-group p 4 :tags) clist))
16983 (goto-char p)
16984 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
16985 (if (looking-at "\\[#[A-Z]\\]")
16986 (push (org-point-in-group p 0 :priority) clist)))
16988 ((org-at-item-p)
16989 (push (org-point-in-group p 2 :item-bullet) clist)
16990 (push (list :item (point-at-bol)
16991 (save-excursion (org-end-of-item) (point)))
16992 clist)
16993 (and (org-at-item-checkbox-p)
16994 (push (org-point-in-group p 0 :checkbox) clist)))
16996 ((org-at-table-p)
16997 (push (list :table (org-table-begin) (org-table-end)) clist)
16998 (if (memq 'org-formula faces)
16999 (push (list :table-special
17000 (previous-single-property-change p 'face)
17001 (next-single-property-change p 'face)) clist)))
17002 ((org-at-table-p 'any)
17003 (push (list :table-table) clist)))
17004 (goto-char p)
17006 ;; Now the small context
17007 (cond
17008 ((org-at-timestamp-p)
17009 (push (org-point-in-group p 0 :timestamp) clist))
17010 ((memq 'org-link faces)
17011 (push (list :link
17012 (previous-single-property-change p 'face)
17013 (next-single-property-change p 'face)) clist))
17014 ((memq 'org-special-keyword faces)
17015 (push (list :keyword
17016 (previous-single-property-change p 'face)
17017 (next-single-property-change p 'face)) clist))
17018 ((org-on-target-p)
17019 (push (org-point-in-group p 0 :target) clist)
17020 (goto-char (1- (match-beginning 0)))
17021 (if (looking-at org-radio-target-regexp)
17022 (push (org-point-in-group p 0 :radio-target) clist))
17023 (goto-char p))
17024 ((setq o (car (delq nil
17025 (mapcar
17026 (lambda (x)
17027 (if (memq x org-latex-fragment-image-overlays) x))
17028 (org-overlays-at (point))))))
17029 (push (list :latex-fragment
17030 (org-overlay-start o) (org-overlay-end o)) clist)
17031 (push (list :latex-preview
17032 (org-overlay-start o) (org-overlay-end o)) clist))
17033 ((org-inside-LaTeX-fragment-p)
17034 ;; FIXME: positions wrong.
17035 (push (list :latex-fragment (point) (point)) clist)))
17037 (setq clist (nreverse (delq nil clist)))
17038 clist))
17040 (defun org-point-in-group (point group &optional context)
17041 "Check if POINT is in match-group GROUP.
17042 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17043 match. If the match group does ot exist or point is not inside it,
17044 return nil."
17045 (and (match-beginning group)
17046 (>= point (match-beginning group))
17047 (<= point (match-end group))
17048 (if context
17049 (list context (match-beginning group) (match-end group))
17050 t)))
17052 (defun org-move-line-down (arg)
17053 "Move the current line down. With prefix argument, move it past ARG lines."
17054 (interactive "p")
17055 (let ((col (current-column))
17056 beg end pos)
17057 (beginning-of-line 1) (setq beg (point))
17058 (beginning-of-line 2) (setq end (point))
17059 (beginning-of-line (+ 1 arg))
17060 (setq pos (move-marker (make-marker) (point)))
17061 (insert (delete-and-extract-region beg end))
17062 (goto-char pos)
17063 (move-to-column col)))
17065 (defun org-move-line-up (arg)
17066 "Move the current line up. With prefix argument, move it past ARG lines."
17067 (interactive "p")
17068 (let ((col (current-column))
17069 beg end pos)
17070 (beginning-of-line 1) (setq beg (point))
17071 (beginning-of-line 2) (setq end (point))
17072 (beginning-of-line (- arg))
17073 (setq pos (move-marker (make-marker) (point)))
17074 (insert (delete-and-extract-region beg end))
17075 (goto-char pos)
17076 (move-to-column col)))
17078 ;; Paragraph filling stuff.
17079 ;; We want this to be just right, so use the full arsenal.
17081 (defun org-set-autofill-regexps ()
17082 (interactive)
17083 ;; In the paragraph separator we include headlines, because filling
17084 ;; text in a line directly attached to a headline would otherwise
17085 ;; fill the headline as well.
17086 (org-set-local 'comment-start-skip "^#+[ \t]*")
17087 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
17088 ;; The paragraph starter includes hand-formatted lists.
17089 (org-set-local 'paragraph-start
17090 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
17091 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17092 ;; But only if the user has not turned off tables or fixed-width regions
17093 (org-set-local
17094 'auto-fill-inhibit-regexp
17095 (concat "\\*\\|#"
17096 "\\|[ \t]*" org-keyword-time-regexp
17097 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17098 (concat
17099 "\\|[ \t]*["
17100 (if org-enable-table-editor "|" "")
17101 (if org-enable-fixed-width-editor ":" "")
17102 "]"))))
17103 ;; We use our own fill-paragraph function, to make sure that tables
17104 ;; and fixed-width regions are not wrapped. That function will pass
17105 ;; through to `fill-paragraph' when appropriate.
17106 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17107 ; Adaptive filling: To get full control, first make sure that
17108 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17109 (org-set-local 'adaptive-fill-regexp "\000")
17110 (org-set-local 'adaptive-fill-function
17111 'org-adaptive-fill-function))
17113 (defun org-fill-paragraph (&optional justify)
17114 "Re-align a table, pass through to fill-paragraph if no table."
17115 (let ((table-p (org-at-table-p))
17116 (table.el-p (org-at-table.el-p)))
17117 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
17118 (table.el-p t) ; skip table.el tables
17119 (table-p (org-table-align) t) ; align org-mode tables
17120 (t nil)))) ; call paragraph-fill
17122 ;; For reference, this is the default value of adaptive-fill-regexp
17123 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17125 (defun org-adaptive-fill-function ()
17126 "Return a fill prefix for org-mode files.
17127 In particular, this makes sure hanging paragraphs for hand-formatted lists
17128 work correctly."
17129 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
17130 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
17132 ;; Functions needed for Emacs/XEmacs region compatibility
17134 (defun org-add-hook (hook function &optional append local)
17135 "Add-hook, compatible with both Emacsen."
17136 (if (and local (featurep 'xemacs))
17137 (add-local-hook hook function append)
17138 (add-hook hook function append local)))
17140 (defun org-region-active-p ()
17141 "Is `transient-mark-mode' on and the region active?
17142 Works on both Emacs and XEmacs."
17143 (if org-ignore-region
17145 (if (featurep 'xemacs)
17146 (and zmacs-regions (region-active-p))
17147 (and transient-mark-mode mark-active))))
17149 (defun org-add-to-invisibility-spec (arg)
17150 "Add elements to `buffer-invisibility-spec'.
17151 See documentation for `buffer-invisibility-spec' for the kind of elements
17152 that can be added."
17153 (cond
17154 ((fboundp 'add-to-invisibility-spec)
17155 (add-to-invisibility-spec arg))
17156 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
17157 (setq buffer-invisibility-spec (list arg)))
17159 (setq buffer-invisibility-spec
17160 (cons arg buffer-invisibility-spec)))))
17162 (defun org-remove-from-invisibility-spec (arg)
17163 "Remove elements from `buffer-invisibility-spec'."
17164 (if (fboundp 'remove-from-invisibility-spec)
17165 (remove-from-invisibility-spec arg)
17166 (if (consp buffer-invisibility-spec)
17167 (setq buffer-invisibility-spec
17168 (delete arg buffer-invisibility-spec)))))
17170 (defun org-in-invisibility-spec-p (arg)
17171 "Is ARG a member of `buffer-invisibility-spec'?"
17172 (if (consp buffer-invisibility-spec)
17173 (member arg buffer-invisibility-spec)
17174 nil))
17176 (defun org-image-file-name-regexp ()
17177 "Return regexp matching the file names of images."
17178 (if (fboundp 'image-file-name-regexp)
17179 (image-file-name-regexp)
17180 (let ((image-file-name-extensions
17181 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17182 "xbm" "xpm" "pbm" "pgm" "ppm")))
17183 (concat "\\."
17184 (regexp-opt (nconc (mapcar 'upcase
17185 image-file-name-extensions)
17186 image-file-name-extensions)
17188 "\\'"))))
17190 ;; Functions extending outline functionality
17192 ;; C-a should go to the beginning of a *visible* line, also in the
17193 ;; new outline.el. I guess this should be patched into Emacs?
17194 (defun org-beginning-of-line ()
17195 "Go to the beginning of the current line. If that is invisible, continue
17196 to a visible line beginning. This makes the function of C-a more intuitive."
17197 (interactive)
17198 (beginning-of-line 1)
17199 (if (bobp)
17201 (backward-char 1)
17202 (if (org-invisible-p)
17203 (while (and (not (bobp)) (org-invisible-p))
17204 (backward-char 1)
17205 (beginning-of-line 1))
17206 (forward-char 1))))
17208 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17210 (defun org-invisible-p ()
17211 "Check if point is at a character currently not visible."
17212 ;; Early versions of noutline don't have `outline-invisible-p'.
17213 (if (fboundp 'outline-invisible-p)
17214 (outline-invisible-p)
17215 (get-char-property (point) 'invisible)))
17217 (defun org-invisible-p2 ()
17218 "Check if point is at a character currently not visible."
17219 (save-excursion
17220 (if (and (eolp) (not (bobp))) (backward-char 1))
17221 ;; Early versions of noutline don't have `outline-invisible-p'.
17222 (if (fboundp 'outline-invisible-p)
17223 (outline-invisible-p)
17224 (get-char-property (point) 'invisible))))
17226 (defalias 'org-back-to-heading 'outline-back-to-heading)
17227 (defalias 'org-on-heading-p 'outline-on-heading-p)
17229 (defun org-on-target-p ()
17230 (let ((pos (point)))
17231 (save-excursion
17232 (skip-chars-forward "<")
17233 (and (re-search-backward "<<" nil t)
17234 (or (looking-at org-radio-target-regexp)
17235 (looking-at org-target-regexp))
17236 (<= (match-beginning 0) pos)
17237 (>= (1+ (match-end 0)) pos)))))
17239 (defun org-up-heading-all (arg)
17240 "Move to the heading line of which the present line is a subheading.
17241 This function considers both visible and invisible heading lines.
17242 With argument, move up ARG levels."
17243 (if (fboundp 'outline-up-heading-all)
17244 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17245 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17247 (defun org-show-hidden-entry ()
17248 "Show an entry where even the heading is hidden."
17249 (save-excursion
17250 (org-show-entry)))
17252 (defun org-flag-heading (flag &optional entry)
17253 "Flag the current heading. FLAG non-nil means make invisible.
17254 When ENTRY is non-nil, show the entire entry."
17255 (save-excursion
17256 (org-back-to-heading t)
17257 ;; Check if we should show the entire entry
17258 (if entry
17259 (progn
17260 (org-show-entry)
17261 (save-excursion
17262 (and (outline-next-heading)
17263 (org-flag-heading nil))))
17264 (outline-flag-region (max 1 (1- (point)))
17265 (save-excursion (outline-end-of-heading) (point))
17266 flag))))
17268 (defun org-end-of-subtree (&optional invisible-OK)
17269 ;; This is an exact copy of the original function, but it uses
17270 ;; `org-back-to-heading', to make it work also in invisible
17271 ;; trees. And is uses an invisible-OK argument.
17272 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17273 (org-back-to-heading invisible-OK)
17274 (let ((first t)
17275 (level (funcall outline-level)))
17276 (while (and (not (eobp))
17277 (or first (> (funcall outline-level) level)))
17278 (setq first nil)
17279 (outline-next-heading))
17280 (if (memq (preceding-char) '(?\n ?\^M))
17281 (progn
17282 ;; Go to end of line before heading
17283 (forward-char -1)
17284 (if (memq (preceding-char) '(?\n ?\^M))
17285 ;; leave blank line before heading
17286 (forward-char -1)))))
17287 (point))
17289 (defun org-show-subtree ()
17290 "Show everything after this heading at deeper levels."
17291 (outline-flag-region
17292 (point)
17293 (save-excursion
17294 (outline-end-of-subtree) (outline-next-heading) (point))
17295 nil))
17297 (defun org-show-entry ()
17298 "Show the body directly following this heading.
17299 Show the heading too, if it is currently invisible."
17300 (interactive)
17301 (save-excursion
17302 (org-back-to-heading t)
17303 (outline-flag-region
17304 (max 1 (1- (point)))
17305 (save-excursion
17306 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
17307 (or (match-beginning 1) (point-max)))
17308 nil)))
17310 (defun org-make-options-regexp (kwds)
17311 "Make a regular expression for keyword lines."
17312 (concat
17314 "#?[ \t]*\\+\\("
17315 (mapconcat 'regexp-quote kwds "\\|")
17316 "\\):[ \t]*"
17317 "\\(.+\\)"))
17319 ;; Make `bookmark-jump' show the jump location if it was hidden.
17320 (eval-after-load "bookmark"
17321 '(if (boundp 'bookmark-after-jump-hook)
17322 ;; We can use the hook
17323 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17324 ;; Hook not available, use advice
17325 (defadvice bookmark-jump (after org-make-visible activate)
17326 "Make the position visible."
17327 (org-bookmark-jump-unhide))))
17329 (defun org-bookmark-jump-unhide ()
17330 "Unhide the current position, to show the bookmark location."
17331 (and (org-mode-p)
17332 (or (org-invisible-p)
17333 (save-excursion (goto-char (max (point-min) (1- (point))))
17334 (org-invisible-p)))
17335 (org-show-hierarchy-above 'bookmark-jump)))
17337 ;; Make session.el ignore our circular variable
17338 (eval-after-load "session"
17339 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17341 ;;; Experimental code
17344 ;;; Finish up
17346 (provide 'org)
17348 (run-hooks 'org-load-hook)
17350 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17351 ;;; org.el ends here