Release 4.59
[org-mode.git] / org.el
blob0d165d4ae170e28381e3681e9b492febfdc943fd
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.59
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.59
65 ;; - Cleanup code, bug fixes.
67 ;; Version 4.58
68 ;; - Full undo support in the agenda buffer.
69 ;; - Listing stuck GTD projects (projects without any NEXT ACTIONS).
70 ;; Configure `org-stuck-projects' before using it.
71 ;; - C-c C-x b shows the current subtree in an indirect buffer, in
72 ;; another, dedicated frame.
73 ;; - Custom agenda commands take precedence over builtin commands.
74 ;; - auto-fill for comments works on the Emacs side, XEmacs not yet.
76 ;; Version 4.57
77 ;; - Sorting of outline items on same level.
78 ;; - Sorting tables automatically selects line range between hlines.
79 ;; - Changes in Agenda buffer
80 ;; - `C-c C-o' follows a link in the current line.
81 ;; - `C-c $' archives the subtree corresponding to the line.
82 ;; - Changing dates with S-left and S-right show new date in agenda,
83 ;; but still do not move the entry to the new date.
84 ;; - new option `org-agenda-skip-scheduled-if-done'.
85 ;; - Agenda and sparse tree construction using tag matches can now
86 ;; use regular expressions.
87 ;; - When prompted for a date/time, entering "+7" indicates a date
88 ;; 7 days from now - but only this is the only thing you give.
89 ;; - Custom time formats also apply to exported html and ascii.
90 ;; - Bug fixes.
92 ;; Version 4.56
93 ;; - `C-k' in agenda kills current line and corresponding subtree in file.
94 ;; - XEmacs compatibility issues fixed, in particular tag alignment.
95 ;; - M-left/right now in/outdents plain list items, no Shift needed.
96 ;; - Bug fixes.
98 ;; Version 4.55
99 ;; - Bug fixes.
101 ;; Version 4.54
102 ;; - Improvements to fast tag selection
103 ;; + show status also in target line.
104 ;; + option to auto-exit after first change to tags list (see manual).
105 ;; - Tags sparse trees now also respect the settings in
106 ;; `org-show-hierarchy-above' and `org-show-following-heading'.
107 ;; - Bug fixes.
109 ;; Version 4.53
110 ;; - Custom time formats can be overlayed over time stamps.
111 ;; - New option `org-agenda-todo-ignore-deadlines'.
112 ;; - Work-around for flyspell bug (CVS Emacs has this fixed in flyspell.el).
113 ;; - Work-around for session.el problem with circular data structures.
114 ;; - Bug fixes.
116 ;; Version 4.52
117 ;; - TAG matches can also specify conditions on TODO keywords.
118 ;; - The fast tag interface allows setting tags that are not in the
119 ;; predefined list.
120 ;; - Bug fixes.
122 ;; Version 4.51
123 ;; - Link abbreviations (manual section 4.5).
124 ;; - More control over how agenda is displayed. See the new variables
125 ;; `org-agenda-window-setup', `org-agenda-restore-windows-after-quit'.
126 ;; - Bug fixes.
128 ;;; Code:
130 ;;;; Require other packages
132 (eval-when-compile
133 (require 'cl)
134 (require 'gnus-sum)
135 (require 'calendar))
136 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
137 ;; the file noutline.el being loaded.
138 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
139 ;; We require noutline, which might be provided in outline.el
140 (require 'outline) (require 'noutline)
141 ;; Other stuff we need.
142 (require 'time-date)
143 (require 'easymenu)
145 ;;;; Customization variables
147 ;;; Version
149 (defvar org-version "4.58"
150 "The version number of the file org.el.")
151 (defun org-version ()
152 (interactive)
153 (message "Org-mode version %s" org-version))
155 ;;; Compatibility constants
156 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
157 (defconst org-format-transports-properties-p
158 (let ((x "a"))
159 (add-text-properties 0 1 '(test t) x)
160 (get-text-property 0 'test (format "%s" x)))
161 "Does format transport text properties?")
163 ;;; The custom variables
165 (defgroup org nil
166 "Outline-based notes management and organizer."
167 :tag "Org"
168 :group 'outlines
169 :group 'hypermedia
170 :group 'calendar)
172 (defgroup org-startup nil
173 "Options concerning startup of Org-mode."
174 :tag "Org Startup"
175 :group 'org)
177 (defcustom org-startup-folded t
178 "Non-nil means, entering Org-mode will switch to OVERVIEW.
179 This can also be configured on a per-file basis by adding one of
180 the following lines anywhere in the buffer:
182 #+STARTUP: fold
183 #+STARTUP: nofold
184 #+STARTUP: content"
185 :group 'org-startup
186 :type '(choice
187 (const :tag "nofold: show all" nil)
188 (const :tag "fold: overview" t)
189 (const :tag "content: all headlines" content)))
191 (defcustom org-startup-truncated t
192 "Non-nil means, entering Org-mode will set `truncate-lines'.
193 This is useful since some lines containing links can be very long and
194 uninteresting. Also tables look terrible when wrapped."
195 :group 'org-startup
196 :type 'boolean)
198 (defcustom org-startup-align-all-tables nil
199 "Non-nil means, align all tables when visiting a file.
200 This is useful when the column width in tables is forced with <N> cookies
201 in table fields. Such tables will look correct only after the first re-align.
202 This can also be configured on a per-file basis by adding one of
203 the following lines anywhere in the buffer:
204 #+STARTUP: align
205 #+STARTUP: noalign"
206 :group 'org-startup
207 :type 'boolean)
209 (defcustom org-startup-with-deadline-check nil
210 "Non-nil means, entering Org-mode will run the deadline check.
211 This means, if you start editing an org file, you will get an
212 immediate reminder of any due deadlines.
213 This can also be configured on a per-file basis by adding one of
214 the following lines anywhere in the buffer:
215 #+STARTUP: dlcheck
216 #+STARTUP: nodlcheck"
217 :group 'org-startup
218 :type 'boolean)
220 (defcustom org-insert-mode-line-in-empty-file nil
221 "Non-nil means insert the first line setting Org-mode in empty files.
222 When the function `org-mode' is called interactively in an empty file, this
223 normally means that the file name does not automatically trigger Org-mode.
224 To ensure that the file will always be in Org-mode in the future, a
225 line enforcing Org-mode will be inserted into the buffer, if this option
226 has been set."
227 :group 'org-startup
228 :type 'boolean)
230 (defcustom org-CUA-compatible nil
231 "Non-nil means use alternative key bindings for S-<cursor movement>.
232 Org-mode used S-<cursor movement> for changing timestamps and priorities.
233 S-<cursor movement> is also used for example by `CUA-mode' to select text.
234 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
235 alternative bindings. Setting this variable to t will replace the following
236 keys both in Org-mode and in the Org-agenda buffer.
238 S-RET -> C-S-RET
239 S-up -> M-p
240 S-down -> M-n
241 S-left -> M--
242 S-right -> M-+
244 If you do not like the alternative keys, take a look at the variable
245 `org-disputed-keys'.
247 This option is only relevant at load-time of Org-mode. Changing it requires
248 a restart of Emacs to become effective."
249 :group 'org-startup
250 :type 'boolean)
252 (defvar org-disputed-keys
253 '((S-up [(shift up)] [(meta ?p)])
254 (S-down [(shift down)] [(meta ?n)])
255 (S-left [(shift left)] [(meta ?-)])
256 (S-right [(shift right)] [(meta ?+)])
257 (S-return [(shift return)] [(control shift return)]))
258 "Keys for which Org-mode and other modes compete.
259 This is an alist, cars are symbols for lookup, 1st element is the default key,
260 second element will be used when `org-CUA-compatible' is t.")
262 (defun org-key (key)
263 "Select a key according to `org-CUA-compatible'."
264 (nth (if org-CUA-compatible 2 1)
265 (or (assq key org-disputed-keys)
266 (error "Invalid Key %s in `org-key'" key))))
268 (defcustom org-ellipsis nil
269 "The ellipsis to use in the Org-mode outline.
270 When nil, just use the standard three dots. When a string, use that instead,
271 and just in Org-mode (which will then use its own display table).
272 Changing this requires executing `M-x org-mode' in a buffer to become
273 effective."
274 :group 'org-startup
275 :type '(choice (const :tag "Default" nil)
276 (string :tag "String" :value "...#")))
278 (defvar org-display-table nil
279 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
281 (defgroup org-keywords nil
282 "Keywords in Org-mode."
283 :tag "Org Keywords"
284 :group 'org)
286 (defcustom org-deadline-string "DEADLINE:"
287 "String to mark deadline entries.
288 A deadline is this string, followed by a time stamp. Should be a word,
289 terminated by a colon. You can insert a schedule keyword and
290 a timestamp with \\[org-deadline].
291 Changes become only effective after restarting Emacs."
292 :group 'org-keywords
293 :type 'string)
295 (defcustom org-scheduled-string "SCHEDULED:"
296 "String to mark scheduled TODO entries.
297 A schedule is this string, followed by a time stamp. Should be a word,
298 terminated by a colon. You can insert a schedule keyword and
299 a timestamp with \\[org-schedule].
300 Changes become only effective after restarting Emacs."
301 :group 'org-keywords
302 :type 'string)
304 (defcustom org-closed-string "CLOSED:"
305 "String used as the prefix for timestamps logging closing a TODO entry."
306 :group 'org-keywords
307 :type 'string)
309 (defcustom org-clock-string "CLOCK:"
310 "String used as prefix for timestamps clocking work hours on an item."
311 :group 'org-keywords
312 :type 'string)
314 (defcustom org-comment-string "COMMENT"
315 "Entries starting with this keyword will never be exported.
316 An entry can be toggled between COMMENT and normal with
317 \\[org-toggle-comment].
318 Changes become only effective after restarting Emacs."
319 :group 'org-keywords
320 :type 'string)
322 (defcustom org-quote-string "QUOTE"
323 "Entries starting with this keyword will be exported in fixed-width font.
324 Quoting applies only to the text in the entry following the headline, and does
325 not extend beyond the next headline, even if that is lower level.
326 An entry can be toggled between QUOTE and normal with
327 \\[org-toggle-fixed-width-section]."
328 :group 'org-keywords
329 :type 'string)
331 (defgroup org-structure nil
332 "Options concerning the general structure of Org-mode files."
333 :tag "Org Structure"
334 :group 'org)
336 (defgroup org-cycle nil
337 "Options concerning visibility cycling in Org-mode."
338 :tag "Org Cycle"
339 :group 'org-structure)
341 (defcustom org-cycle-global-at-bob t
342 "Cycle globally if cursor is at beginning of buffer and not at a headline.
343 This makes it possible to do global cycling without having to use S-TAB or
344 C-u TAB. For this special case to work, the first line of the buffer
345 must not be a headline - it may be empty ot some other text. When used in
346 this way, `org-cycle-hook' is disables temporarily, to make sure the
347 cursor stays at the beginning of the buffer.
348 When this option is nil, don't do anything special at the beginning
349 of the buffer."
350 :group 'org-cycle
351 :type 'boolean)
353 (defcustom org-cycle-emulate-tab t
354 "Where should `org-cycle' emulate TAB.
355 nil Never
356 white Only in completely white lines
357 whitestart Only at the beginning of lines, before the first non-white char.
358 t Everywhere except in headlines
359 If TAB is used in a place where it does not emulate TAB, the current subtree
360 visibility is cycled."
361 :group 'org-cycle
362 :type '(choice (const :tag "Never" nil)
363 (const :tag "Only in completely white lines" white)
364 (const :tag "Before first char in a line" whitestart)
365 (const :tag "Everywhere except in headlines" t)
368 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
369 org-optimize-window-after-visibility-change)
370 "Hook that is run after `org-cycle' has changed the buffer visibility.
371 The function(s) in this hook must accept a single argument which indicates
372 the new state that was set by the most recent `org-cycle' command. The
373 argument is a symbol. After a global state change, it can have the values
374 `overview', `content', or `all'. After a local state change, it can have
375 the values `folded', `children', or `subtree'."
376 :group 'org-cycle
377 :type 'hook)
380 (defgroup org-edit-structure nil
381 "Options concerning structure editing in Org-mode."
382 :tag "Org Edit Structure"
383 :group 'org-structure)
385 (defcustom org-odd-levels-only nil
386 "Non-nil means, skip even levels and only use odd levels for the outline.
387 This has the effect that two stars are being added/taken away in
388 promotion/demotion commands. It also influences how levels are
389 handled by the exporters.
390 Changing it requires restart of `font-lock-mode' to become effective
391 for fontification also in regions already fontified.
392 You may also set this on a per-file basis by adding one of the following
393 lines to the buffer:
395 #+STARTUP: odd
396 #+STARTUP: oddeven"
397 :group 'org-edit-structure
398 :group 'org-font-lock
399 :type 'boolean)
401 (defcustom org-adapt-indentation t
402 "Non-nil means, adapt indentation when promoting and demoting.
403 When this is set and the *entire* text in an entry is indented, the
404 indentation is increased by one space in a demotion command, and
405 decreased by one in a promotion command. If any line in the entry
406 body starts at column 0, indentation is not changed at all."
407 :group 'org-edit-structure
408 :type 'boolean)
410 (defcustom org-blank-before-new-entry '((heading . nil)
411 (plain-list-item . nil))
412 "Should `org-insert-heading' leave a blank line before new heading/item?
413 The value is an alist, with `heading' and `plain-list-item' as car,
414 and a boolean flag as cdr."
415 :group 'org-edit-structure
416 :type '(list
417 (cons (const heading) (boolean))
418 (cons (const plain-list-item) (boolean))))
420 (defcustom org-insert-heading-hook nil
421 "Hook being run after inserting a new heading."
422 :group 'org-edit-structure
423 :type 'boolean)
425 (defcustom org-enable-fixed-width-editor t
426 "Non-nil means, lines starting with \":\" are treated as fixed-width.
427 This currently only means, they are never auto-wrapped.
428 When nil, such lines will be treated like ordinary lines.
429 See also the QUOTE keyword."
430 :group 'org-edit-structure
431 :type 'boolean)
433 (defgroup org-sparse-trees nil
434 "Options concerning sparse trees in Org-mode."
435 :tag "Org Sparse Trees"
436 :group 'org-structure)
438 (defcustom org-highlight-sparse-tree-matches t
439 "Non-nil means, highlight all matches that define a sparse tree.
440 The highlights will automatically disappear the next time the buffer is
441 changed by an edit command."
442 :group 'org-sparse-trees
443 :type 'boolean)
445 (defcustom org-remove-highlights-with-change t
446 "Non-nil means, any change to the buffer will remove temporary highlights.
447 Such highlights are created by `org-occur' and `org-clock-display'.
448 When nil, `C-c C-c needs to be used to get rid of the highlights.
449 The highlights created by `org-preview-latex-fragment' always need
450 `C-c C-c' to be removed."
451 :group 'org-sparse-trees
452 :group 'org-time
453 :type 'boolean)
455 (defcustom org-show-hierarchy-above '((default . t))
456 "Non-nil means, show full hierarchy when showing a spot in the tree.
457 Turning this off makes sparse trees more compact, but also less clear.
458 Instead of t, this can also be an alist specifying this option for different
459 contexts. Valid contexts are
460 agenda when exposing an entry from the agenda
461 org-goto when using the command `org-goto' on key C-c C-j
462 occur-tree when using the command `org-occur' on key C-c /
463 tags-tree when constructing a sparse tree based on tags matches
464 link-search when exposing search matches associated with a link
465 mark-goto when exposing the jump goal of a mark
466 bookmark-jump when exposing a bookmark location
467 default default for all contexts not set explicitly"
468 :group 'org-sparse-trees
469 :type '(choice
470 (const :tag "Always" t)
471 (const :tag "Never" nil)
472 (repeat :greedy t :tag "Individual contexts"
473 (cons
474 (choice :tag "Context"
475 (const agenda)
476 (const org-goto)
477 (const occur-tree)
478 (const tags-tree)
479 (const link-search)
480 (const mark-goto)
481 (const bookmark-jump)
482 (const default))
483 (boolean)))))
485 (defcustom org-show-following-heading '((default . t))
486 "Non-nil means, show heading following match in `org-occur'.
487 When doing an `org-occur' it is useful to show the headline which
488 follows the match, even if they do not match the regexp. This makes it
489 easier to edit directly inside the sparse tree. However, if you use
490 `org-occur' mainly as an overview, the following headlines are
491 unnecessary clutter.
492 Instead of t, this can also be an alist specifying this option for different
493 contexts. See `org-show-hierarchy-above' for valid contexts."
494 :group 'org-sparse-trees
495 :type '(choice
496 (const :tag "Always" t)
497 (const :tag "Never" nil)
498 (repeat :greedy t :tag "Individual contexts"
499 (cons
500 (choice :tag "Context"
501 (const agenda)
502 (const org-goto)
503 (const occur-tree)
504 (const tags-tree)
505 (const link-search)
506 (const mark-goto)
507 (const bookmark-jump)
508 (const default))
509 (boolean)))))
511 (defcustom org-occur-hook '(org-first-headline-recenter)
512 "Hook that is run after `org-occur' has constructed a sparse tree.
513 This can be used to recenter the window to show as much of the structure
514 as possible."
515 :group 'org-sparse-trees
516 :type 'hook)
518 (defgroup org-plain-lists nil
519 "Options concerning plain lists in Org-mode."
520 :tag "Org Plain lists"
521 :group 'org-structure)
523 (defcustom org-cycle-include-plain-lists nil
524 "Non-nil means, include plain lists into visibility cycling.
525 This means that during cycling, plain list items will *temporarily* be
526 interpreted as outline headlines with a level given by 1000+i where i is the
527 indentation of the bullet. In all other operations, plain list items are
528 not seen as headlines. For example, you cannot assign a TODO keyword to
529 such an item."
530 :group 'org-plain-lists
531 :type 'boolean)
533 (defcustom org-plain-list-ordered-item-terminator t
534 "The character that makes a line with leading number an ordered list item.
535 Valid values are ?. and ?\). To get both terminators, use t. While
536 ?. may look nicer, it creates the danger that a line with leading
537 number may be incorrectly interpreted as an item. ?\) therefore is
538 the safe choice."
539 :group 'org-plain-lists
540 :type '(choice (const :tag "dot like in \"2.\"" ?.)
541 (const :tag "paren like in \"2)\"" ?\))
542 (const :tab "both" t)))
544 (defcustom org-auto-renumber-ordered-lists t
545 "Non-nil means, automatically renumber ordered plain lists.
546 Renumbering happens when the sequence have been changed with
547 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
548 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
549 :group 'org-plain-lists
550 :type 'boolean)
552 (defcustom org-provide-checkbox-statistics t
553 "Non-nil means, update checkbox statistics after insert and toggle.
554 When this is set, checkbox statistics is updated each time you either insert
555 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
556 with \\[org-ctrl-c-ctrl-c\\]."
557 :group 'org-plain-lists
558 :type 'boolean)
560 (defgroup org-archive nil
561 "Options concerning archiving in Org-mode."
562 :tag "Org Archive"
563 :group 'org-structure)
565 (defcustom org-archive-tag "ARCHIVE"
566 "The tag that marks a subtree as archived.
567 An archived subtree does not open during visibility cycling, and does
568 not contribute to the agenda listings."
569 :group 'org-archive
570 :group 'org-keywords
571 :type 'string)
573 (defcustom org-agenda-skip-archived-trees t
574 "Non-nil means, the agenda will skip any items located in archived trees.
575 An archived tree is a tree marked with the tag ARCHIVE."
576 :group 'org-archive
577 :group 'org-agenda-skip
578 :type 'boolean)
580 (defcustom org-cycle-open-archived-trees nil
581 "Non-nil means, `org-cycle' will open archived trees.
582 An archived tree is a tree marked with the tag ARCHIVE.
583 When nil, archived trees will stay folded. You can still open them with
584 normal outline commands like `show-all', but not with the cycling commands."
585 :group 'org-archive
586 :group 'org-cycle
587 :type 'boolean)
589 (defcustom org-sparse-tree-open-archived-trees nil
590 "Non-nil means sparse tree construction shows matches in archived trees.
591 When nil, matches in these trees are highlighted, but the trees are kept in
592 collapsed state."
593 :group 'org-archive
594 :group 'org-sparse-trees
595 :type 'boolean)
597 (defcustom org-archive-location "%s_archive::"
598 "The location where subtrees should be archived.
599 This string consists of two parts, separated by a double-colon.
601 The first part is a file name - when omitted, archiving happens in the same
602 file. %s will be replaced by the current file name (without directory part).
603 Archiving to a different file is useful to keep archived entries from
604 contributing to the Org-mode Agenda.
606 The part after the double colon is a headline. The archived entries will be
607 filed under that headline. When omitted, the subtrees are simply filed away
608 at the end of the file, as top-level entries.
610 Here are a few examples:
611 \"%s_archive::\"
612 If the current file is Projects.org, archive in file
613 Projects.org_archive, as top-level trees. This is the default.
615 \"::* Archived Tasks\"
616 Archive in the current file, under the top-level headline
617 \"* Archived Tasks\".
619 \"~/org/archive.org::\"
620 Archive in file ~/org/archive.org (absolute path), as top-level trees.
622 \"basement::** Finished Tasks\"
623 Archive in file ./basement (relative path), as level 3 trees
624 below the level 2 heading \"** Finished Tasks\".
626 You may set this option on a per-file basis by adding to the buffer a
627 line like
629 #+ARCHIVE: basement::** Finished Tasks"
630 :group 'org-archive
631 :type 'string)
633 (defcustom org-archive-mark-done t
634 "Non-nil means, mark entries as DONE when they are moved to the archive file."
635 :group 'org-archive
636 :type 'boolean)
638 (defcustom org-archive-stamp-time t
639 "Non-nil means, add a time stamp to entries moved to an archive file.
640 The time stamp will be added directly after the TODO state keyword in the
641 first line, so it is probably best to use this in combinations with
642 `org-archive-mark-done'."
643 :group 'org-archive
644 :type 'boolean)
646 (defgroup org-table nil
647 "Options concerning tables in Org-mode."
648 :tag "Org Table"
649 :group 'org)
651 (defcustom org-enable-table-editor 'optimized
652 "Non-nil means, lines starting with \"|\" are handled by the table editor.
653 When nil, such lines will be treated like ordinary lines.
655 When equal to the symbol `optimized', the table editor will be optimized to
656 do the following:
657 - Automatic overwrite mode in front of whitespace in table fields.
658 This makes the structure of the table stay in tact as long as the edited
659 field does not exceed the column width.
660 - Minimize the number of realigns. Normally, the table is aligned each time
661 TAB or RET are pressed to move to another field. With optimization this
662 happens only if changes to a field might have changed the column width.
663 Optimization requires replacing the functions `self-insert-command',
664 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
665 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
666 very good at guessing when a re-align will be necessary, but you can always
667 force one with \\[org-ctrl-c-ctrl-c].
669 If you would like to use the optimized version in Org-mode, but the
670 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
672 This variable can be used to turn on and off the table editor during a session,
673 but in order to toggle optimization, a restart is required.
675 See also the variable `org-table-auto-blank-field'."
676 :group 'org-table
677 :type '(choice
678 (const :tag "off" nil)
679 (const :tag "on" t)
680 (const :tag "on, optimized" optimized)))
682 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
683 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
684 In the optimized version, the table editor takes over all simple keys that
685 normally just insert a character. In tables, the characters are inserted
686 in a way to minimize disturbing the table structure (i.e. in overwrite mode
687 for empty fields). Outside tables, the correct binding of the keys is
688 restored.
690 The default for this option is t if the optimized version is also used in
691 Org-mode. See the variable `org-enable-table-editor' for details. Changing
692 this variable requires a restart of Emacs to become effective."
693 :group 'org-table
694 :type 'boolean)
696 (defgroup org-table-settings nil
697 "Settings for tables in Org-mode."
698 :tag "Org Table Settings"
699 :group 'org-table)
701 (defcustom org-table-default-size "5x2"
702 "The default size for newly created tables, Columns x Rows."
703 :group 'org-table-settings
704 :type 'string)
706 ;; FIXME: I am no longer sure if including HEX is a good idea.
707 (defcustom org-table-number-regexp
708 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)?[0-9a-fA-F]+\\)$"
709 "Regular expression for recognizing numbers in table columns.
710 If a table column contains mostly numbers, it will be aligned to the
711 right. If not, it will be aligned to the left.
713 The default value of this option is a regular expression which allows
714 anything which looks remotely like a number as used in scientific
715 context. For example, all of the following will be considered a
716 number:
717 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
719 Other options offered by the customize interface are more restrictive."
720 :group 'org-table-settings
721 :type '(choice
722 (const :tag "Positive Integers"
723 "^[0-9]+$")
724 (const :tag "Integers"
725 "^[-+]?[0-9]+$")
726 (const :tag "Floating Point Numbers"
727 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
728 (const :tag "Floating Point Number or Integer"
729 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
730 (const :tag "Exponential, Floating point, Integer"
731 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
732 (const :tag "Very General Number-Like, including hex"
733 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)?[0-9a-fA-F]+\\)$")
734 (string :tag "Regexp:")))
736 (defcustom org-table-number-fraction 0.5
737 "Fraction of numbers in a column required to make the column align right.
738 In a column all non-white fields are considered. If at least this
739 fraction of fields is matched by `org-table-number-fraction',
740 alignment to the right border applies."
741 :group 'org-table-settings
742 :type 'number)
744 (defgroup org-table-editing nil
745 "Bahavior of tables during editing in Org-mode."
746 :tag "Org Table Editing"
747 :group 'org-table)
749 (defcustom org-table-automatic-realign t
750 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
751 When nil, aligning is only done with \\[org-table-align], or after column
752 removal/insertion."
753 :group 'org-table-editing
754 :type 'boolean)
756 (defcustom org-table-limit-column-width t ;kw
757 "Non-nil means, allow to limit the width of table columns with <N> fields."
758 :group 'org-table-editing
759 :type 'boolean)
761 (defcustom org-table-auto-blank-field t
762 "Non-nil means, automatically blank table field when starting to type into it.
763 This only happens when typing immediately after a field motion
764 command (TAB, S-TAB or RET).
765 Only relevant when `org-enable-table-editor' is equal to `optimized'."
766 :group 'org-table-editing
767 :type 'boolean)
769 (defcustom org-table-tab-jumps-over-hlines t
770 "Non-nil means, tab in the last column of a table with jump over a hline.
771 If a horizontal separator line is following the current line,
772 `org-table-next-field' can either create a new row before that line, or jump
773 over the line. When this option is nil, a new line will be created before
774 this line."
775 :group 'org-table-editing
776 :type 'boolean)
778 (defcustom org-table-tab-recognizes-table.el t
779 "Non-nil means, TAB will automatically notice a table.el table.
780 When it sees such a table, it moves point into it and - if necessary -
781 calls `table-recognize-table'."
782 :group 'org-table-editing
783 :type 'boolean)
785 (defgroup org-table-calculation nil
786 "Options concerning tables in Org-mode."
787 :tag "Org Table Calculation"
788 :group 'org-table)
790 (defcustom org-table-copy-increment t
791 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
792 :group 'org-table-calculation
793 :type 'boolean)
795 (defcustom org-calc-default-modes
796 '(calc-internal-prec 12
797 calc-float-format (float 5)
798 calc-angle-mode deg
799 calc-prefer-frac nil
800 calc-symbolic-mode nil
801 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
802 calc-display-working-message t
804 "List with Calc mode settings for use in calc-eval for table formulas.
805 The list must contain alternating symbols (Calc modes variables and values).
806 Don't remove any of the default settings, just change the values. Org-mode
807 relies on the variables to be present in the list."
808 :group 'org-table-calculation
809 :type 'plist)
811 (defcustom org-table-formula-evaluate-inline t
812 "Non-nil means, TAB and RET evaluate a formula in current table field.
813 If the current field starts with an equal sign, it is assumed to be a formula
814 which should be evaluated as described in the manual and in the documentation
815 string of the command `org-table-eval-formula'. This feature requires the
816 Emacs calc package.
817 When this variable is nil, formula calculation is only available through
818 the command \\[org-table-eval-formula]."
819 :group 'org-table-calculation
820 :type 'boolean)
823 (defcustom org-table-formula-use-constants t
824 "Non-nil means, interpret constants in formulas in tables.
825 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
826 by the value given in `org-table-formula-constants', or by a value obtained
827 from the `constants.el' package."
828 :group 'org-table-calculation
829 :type 'boolean)
831 (defcustom org-table-formula-constants nil
832 "Alist with constant names and values, for use in table formulas.
833 The car of each element is a name of a constant, without the `$' before it.
834 The cdr is the value as a string. For example, if you'd like to use the
835 speed of light in a formula, you would configure
837 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
839 and then use it in an equation like `$1*$c'."
840 :group 'org-table-calculation
841 :type '(repeat
842 (cons (string :tag "name")
843 (string :tag "value"))))
845 (defcustom org-table-formula-numbers-only nil
846 "Non-nil means, calculate only with numbers in table formulas.
847 Then all input fields will be converted to a number, and the result
848 must also be a number. When nil, calc's full potential is available
849 in table calculations, including symbolics etc."
850 :group 'org-table-calculation
851 :type 'boolean)
853 (defcustom org-table-allow-automatic-line-recalculation t
854 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
855 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
856 :group 'org-table-calculation
857 :type 'boolean)
859 (defgroup org-link nil
860 "Options concerning links in Org-mode."
861 :tag "Org Link"
862 :group 'org)
864 (defvar org-link-abbrev-alist-local nil
865 "buffer-local version of `org-link-abbrev-alist', which see.
866 The value of this is taken from the #+LINK lines.")
867 (make-variable-buffer-local 'org-link-abbrev-alist-local)
869 (defcustom org-link-abbrev-alist nil
870 "Alist of link abbreviations.
871 The car of each element is a string, to be replaced at the start of a link.
872 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
873 links in Org-mode buffers can have an optional tag after a double colon, e.g.
875 [[linkkey::tag][description]]
877 If REPLACE is a string, the tag will simply be appended to create the link.
878 If the string contains \"%s\", the tag will be inserted there. REPLACE may
879 also be a function that will be called with the tag as the only argument to
880 create the link. See the manual for examples."
881 :group 'org-link
882 :type 'alist)
884 (defcustom org-descriptive-links t
885 "Non-nil means, hide link part and only show description of bracket links.
886 Bracket links are like [[link][descritpion]]. This variable sets the initial
887 state in new org-mode buffers. The setting can then be toggled on a
888 per-buffer basis from the Org->Hyperlinks menu."
889 :group 'org-link
890 :type 'boolean)
892 (defcustom org-link-style 'bracket
893 "The style of links to be inserted with \\[org-insert-link].
894 Possible values are:
895 bracket [[link][description]]. This is recommended
896 plain Description \\n link. The old way, no longer recommended."
897 :group 'org-link
898 :type '(choice
899 (const :tag "Bracket (recommended)" bracket)
900 (const :tag "Plain (no longer recommended)" plain)))
902 (defcustom org-link-format "%s"
903 "Default format for external, URL-like linkes in the buffer.
904 This is a format string for printf, %s will be replaced by the link text.
905 The recommended value is just \"%s\", since links will be protected by
906 enclosing them in double brackets. If you prefer plain links (see variable
907 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
908 additional URL: prefix, so the format would be \"<URL:%s>\"."
909 :group 'org-link
910 :type '(choice
911 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
912 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
913 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
914 (string :tag "Other" :value "<%s>")))
916 (defcustom org-link-file-path-type 'adaptive
917 "How the path name in file links should be stored.
918 Valid values are:
920 relative relative to the current directory, i.e. the directory of the file
921 into which the link is being inserted.
922 absolute absolute path, if possible with ~ for home directory.
923 noabbrev absolute path, no abbreviation of home directory.
924 adaptive Use relative path for files in the current directory and sub-
925 directories of it. For other files, use an absolute path."
926 :group 'org-link
927 :type '(choice
928 (const relative)
929 (const absolute)
930 (const noabbrev)
931 (const adaptive)))
933 (defcustom org-activate-links '(bracket angle plain radio tag date)
934 "Types of links that should be activated in Org-mode files.
935 This is a list of symbols, each leading to the activation of a certain link
936 type. In principle, it does not hurt to turn on most link types - there may
937 be a small gain when turning off unused link types. The types are:
939 bracket The recommended [[link][description]] or [[link]] links with hiding.
940 angular Links in angular brackes that may contain whitespace like
941 <bbdb:Carsten Dominik>.
942 plain Plain links in normal text, no whitespace, like http://google.com.
943 radio Text that is matched by a radio target, see manual for details.
944 tag Tag settings in a headline (link to tag search).
945 date Time stamps (link to calendar).
946 camel CamelCase words defining text searches.
948 Changing this variable requires a restart of Emacs to become effective."
949 :group 'org-link
950 :type '(set (const :tag "Double bracket links (new style)" bracket)
951 (const :tag "Angular bracket links (old style)" angular)
952 (const :tag "plain text links" plain)
953 (const :tag "Radio target matches" radio)
954 (const :tag "Tags" tag)
955 (const :tag "Timestamps" date)
956 (const :tag "CamelCase words" camel)))
958 (defgroup org-link-store nil
959 "Options concerning storing links in Org-mode"
960 :tag "Org Store Link"
961 :group 'org-link)
963 (defcustom org-context-in-file-links t
964 "Non-nil means, file links from `org-store-link' contain context.
965 A search string will be added to the file name with :: as separator and
966 used to find the context when the link is activated by the command
967 `org-open-at-point'.
968 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
969 negates this setting for the duration of the command."
970 :group 'org-link-store
971 :type 'boolean)
973 (defcustom org-file-link-context-use-camel-case nil
974 "Non-nil means, use CamelCase to store a search context in a file link.
975 When nil, the search string simply consists of the words of the string.
976 CamelCase is deprecated, and support for it may be dropped in the future."
977 :group 'org-link-store
978 :type 'boolean)
980 (defcustom org-keep-stored-link-after-insertion nil
981 "Non-nil means, keep link in list for entire session.
983 The command `org-store-link' adds a link pointing to the current
984 location to an internal list. These links accumulate during a session.
985 The command `org-insert-link' can be used to insert links into any
986 Org-mode file (offering completion for all stored links). When this
987 option is nil, every link which has been inserted once using \\[org-insert-link]
988 will be removed from the list, to make completing the unused links
989 more efficient."
990 :group 'org-link-store
991 :type 'boolean)
993 (defcustom org-usenet-links-prefer-google nil
994 "Non-nil means, `org-store-link' will create web links to Google groups.
995 When nil, Gnus will be used for such links.
996 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
997 negates this setting for the duration of the command."
998 :group 'org-link-store
999 :type 'boolean)
1001 (defgroup org-link-follow nil
1002 "Options concerning following links in Org-mode"
1003 :tag "Org Follow Link"
1004 :group 'org-link)
1006 (defcustom org-tab-follows-link nil
1007 "Non-nil means, on links TAB will follow the link.
1008 Needs to be set before org.el is loaded."
1009 :group 'org-link-follow
1010 :type 'boolean)
1012 (defcustom org-return-follows-link nil
1013 "Non-nil means, on links RET 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-mouse-1-follows-link t
1019 "Non-nil means, mouse-1 on a link will follow the link.
1020 A longer mouse click will still set point. Does not wortk on XEmacs.
1021 Needs to be set before org.el is loaded."
1022 :group 'org-link-follow
1023 :type 'boolean)
1025 (defcustom org-mark-ring-length 4
1026 "Number of different positions to be recorded in the ring
1027 Changing this requires a restart of Emacs to work correctly."
1028 :group 'org-link-follow
1029 :type 'interger)
1031 (defcustom org-link-frame-setup
1032 '((vm . vm-visit-folder-other-frame)
1033 (gnus . gnus-other-frame)
1034 (file . find-file-other-window))
1035 "Setup the frame configuration for following links.
1036 When following a link with Emacs, it may often be useful to display
1037 this link in another window or frame. This variable can be used to
1038 set this up for the different types of links.
1039 For VM, use any of
1040 `vm-visit-folder'
1041 `vm-visit-folder-other-frame'
1042 For Gnus, use any of
1043 `gnus'
1044 `gnus-other-frame'
1045 For FILE, use any of
1046 `find-file'
1047 `find-file-other-window'
1048 `find-file-other-frame'
1049 For the calendar, use the variable `calendar-setup'.
1050 For BBDB, it is currently only possible to display the matches in
1051 another window."
1052 :group 'org-link-follow
1053 :type '(list
1054 (cons (const vm)
1055 (choice
1056 (const vm-visit-folder)
1057 (const vm-visit-folder-other-window)
1058 (const vm-visit-folder-other-frame)))
1059 (cons (const gnus)
1060 (choice
1061 (const gnus)
1062 (const gnus-other-frame)))
1063 (cons (const file)
1064 (choice
1065 (const find-file)
1066 (const find-file-other-window)
1067 (const find-file-other-frame)))))
1069 (defcustom org-display-internal-link-with-indirect-buffer nil
1070 "Non-nil means, use indirect buffer to display infile links.
1071 Activating internal links (from one location in a file to another location
1072 in the same file) normally just jumps to the location. When the link is
1073 activated with a C-u prefix (or with mouse-3), the link is displayed in
1074 another window. When this option is set, the other window actually displays
1075 an indirect buffer clone of the current buffer, to avoid any visibility
1076 changes to the current buffer."
1077 :group 'org-link-follow
1078 :type 'boolean)
1081 (defcustom org-open-non-existing-files nil
1082 "Non-nil means, `org-open-file' will open non-existing file.
1083 When nil, an error will be generated."
1084 :group 'org-link-follow
1085 :type 'boolean)
1087 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1088 "Function and arguments to call for following mailto links.
1089 This is a list with the first element being a lisp function, and the
1090 remaining elements being arguments to the function. In string arguments,
1091 %a will be replaced by the address, and %s will be replaced by the subject
1092 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1093 :group 'org-link-follow
1094 :type '(choice
1095 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1096 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1097 (const :tag "message-mail" (message-mail "%a" "%s"))
1098 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1100 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1101 "Non-nil means, ask for confirmation before executing shell links.
1102 Shell links can be dangerous, just thing about a link
1104 [[shell:rm -rf ~/*][Google Search]]
1106 This link would show up in your Org-mode document as \"Google Search\"
1107 but really it would remove your entire home directory.
1108 Therefore I *definitely* advise against setting this variable to nil.
1109 Just change it to `y-or-n-p' of you want to confirm with a single key press
1110 rather than having to type \"yes\"."
1111 :group 'org-link-follow
1112 :type '(choice
1113 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1114 (const :tag "with y-or-n (faster)" y-or-n-p)
1115 (const :tag "no confirmation (dangerous)" nil)))
1117 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1118 "Non-nil means, ask for confirmation before executing elisp links.
1119 Elisp links can be dangerous, just think about a link
1121 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1123 This link would show up in your Org-mode document as \"Google Search\"
1124 but really it would remove your entire home directory.
1125 Therefore I *definitely* advise against setting this variable to nil.
1126 Just change it to `y-or-n-p' of you want to confirm with a single key press
1127 rather than having to type \"yes\"."
1128 :group 'org-link-follow
1129 :type '(choice
1130 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1131 (const :tag "with y-or-n (faster)" y-or-n-p)
1132 (const :tag "no confirmation (dangerous)" nil)))
1134 (defconst org-file-apps-defaults-gnu
1135 '((remote . emacs)
1136 (t . mailcap))
1137 "Default file applications on a UNIX or GNU/Linux system.
1138 See `org-file-apps'.")
1140 (defconst org-file-apps-defaults-macosx
1141 '((remote . emacs)
1142 (t . "open %s")
1143 ("ps" . "gv %s")
1144 ("ps.gz" . "gv %s")
1145 ("eps" . "gv %s")
1146 ("eps.gz" . "gv %s")
1147 ("dvi" . "xdvi %s")
1148 ("fig" . "xfig %s"))
1149 "Default file applications on a MacOS X system.
1150 The system \"open\" is known as a default, but we use X11 applications
1151 for some files for which the OS does not have a good default.
1152 See `org-file-apps'.")
1154 (defconst org-file-apps-defaults-windowsnt
1155 (list
1156 '(remote . emacs)
1157 (cons t
1158 (list (if (featurep 'xemacs)
1159 'mswindows-shell-execute
1160 'w32-shell-execute)
1161 "open" 'file)))
1162 "Default file applications on a Windows NT system.
1163 The system \"open\" is used for most files.
1164 See `org-file-apps'.")
1166 (defcustom org-file-apps
1168 ("txt" . emacs)
1169 ("tex" . emacs)
1170 ("ltx" . emacs)
1171 ("org" . emacs)
1172 ("el" . emacs)
1173 ("bib" . emacs)
1175 "External applications for opening `file:path' items in a document.
1176 Org-mode uses system defaults for different file types, but
1177 you can use this variable to set the application for a given file
1178 extension. The entries in this list are cons cells where the car identifies
1179 files and the cdr the corresponding command. Possible values for the
1180 file identifier are
1181 \"ext\" A string identifying an extension
1182 `directory' Matches a directory
1183 `remote' Matches a remote file, accessible through tramp or efs.
1184 Remote files most likely should be visited through Emacs
1185 because external applications cannot handle such paths.
1186 t Default for all remaining files
1188 Possible values for the command are:
1189 `emacs' The file will be visited by the current Emacs process.
1190 `default' Use the default application for this file type.
1191 string A command to be executed by a shell; %s will be replaced
1192 by the path to the file.
1193 sexp A Lisp form which will be evaluated. The file path will
1194 be available in the Lisp variable `file'.
1195 For more examples, see the system specific constants
1196 `org-file-apps-defaults-macosx'
1197 `org-file-apps-defaults-windowsnt'
1198 `org-file-apps-defaults-gnu'."
1199 :group 'org-link-follow
1200 :type '(repeat
1201 (cons (choice :value ""
1202 (string :tag "Extension")
1203 (const :tag "Default for unrecognized files" t)
1204 (const :tag "Remote file" remote)
1205 (const :tag "Links to a directory" directory))
1206 (choice :value ""
1207 (const :tag "Visit with Emacs" emacs)
1208 (const :tag "Use system default" default)
1209 (string :tag "Command")
1210 (sexp :tag "Lisp form")))))
1212 (defcustom org-mhe-search-all-folders nil
1213 "Non-nil means, that the search for the mh-message will be extended to
1214 all folders if the message cannot be found in the folder given in the link.
1215 Searching all folders is very effective with one of the search engines
1216 supported by MH-E, but will be slow with pick."
1217 :group 'org-link-follow
1218 :type 'boolean)
1220 (defgroup org-remember nil
1221 "Options concerning interaction with remember.el."
1222 :tag "Org Remember"
1223 :group 'org)
1225 (defcustom org-directory "~/org"
1226 "Directory with org files.
1227 This directory will be used as default to prompt for org files.
1228 Used by the hooks for remember.el."
1229 :group 'org-remember
1230 :type 'directory)
1232 (defcustom org-default-notes-file "~/.notes"
1233 "Default target for storing notes.
1234 Used by the hooks for remember.el. This can be a string, or nil to mean
1235 the value of `remember-data-file'."
1236 :group 'org-remember
1237 :type '(choice
1238 (const :tag "Default from remember-data-file" nil)
1239 file))
1241 (defcustom org-remember-templates nil
1242 "Templates for the creation of remember buffers.
1243 When nil, just let remember make the buffer.
1244 When not nil, this is a list of 3-element lists. In each entry, the first
1245 element is a character, a unique key to select this template.
1246 The second element is the template. The third element is optional and can
1247 specify a destination file for remember items created with this template.
1248 The default file is given by `org-default-notes-file'.
1250 The template specifies the structure of the remember buffer. It should have
1251 a first line starting with a star, to act as the org-mode headline.
1252 Furthermore, the following %-escapes will be replaced with content:
1253 %t time stamp, date only
1254 %T time stamp with date and time
1255 %u inactive time stamp, date only
1256 %U inactive time stamp with date and time
1257 %n user name
1258 %a annotation, normally the link created with org-store-link
1259 %i initial content, the region when remember is called with C-u.
1260 If %i is indented, the entire inserted text will be indented as well.
1261 %? This will be removed, and the cursor placed at this position."
1262 :group 'org-remember
1263 :type '(repeat :tag "enabled"
1264 (list :value (?a "\n" nil)
1265 (character :tag "Selection Key")
1266 (string :tag "Template")
1267 (file :tag "Destination file (optional)"))))
1269 (defcustom org-reverse-note-order nil
1270 "Non-nil means, store new notes at the beginning of a file or entry.
1271 When nil, new notes will be filed to the end of a file or entry."
1272 :group 'org-remember
1273 :type '(choice
1274 (const :tag "Reverse always" t)
1275 (const :tag "Reverse never" nil)
1276 (repeat :tag "By file name regexp"
1277 (cons regexp boolean))))
1279 (defgroup org-todo nil
1280 "Options concerning TODO items in Org-mode."
1281 :tag "Org TODO"
1282 :group 'org)
1284 (defcustom org-todo-keywords '("TODO" "DONE")
1285 "List of TODO entry keywords.
1286 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1287 considered to mean that the entry is \"done\". All the other mean that
1288 action is required, and will make the entry show up in todo lists, diaries
1289 etc.
1290 The command \\[org-todo] cycles an entry through these states, and an
1291 additional state where no keyword is present. For details about this
1292 cycling, see also the variable `org-todo-interpretation'
1293 Changes become only effective after restarting Emacs."
1294 :group 'org-todo
1295 :group 'org-keywords
1296 :type '(repeat (string :tag "Keyword")))
1298 (defcustom org-todo-interpretation 'sequence
1299 "Controls how TODO keywords are interpreted.
1300 This variable is only relevant if `org-todo-keywords' contains more than two
1301 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1303 When `sequence', \\[org-todo] will always switch to the next state in the
1304 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1305 to state when executed several times in direct succession. Otherwise, it
1306 switches directly to DONE from any state.
1307 See the manual for more information."
1308 :group 'org-todo
1309 :group 'org-keywords
1310 :type '(choice (const sequence)
1311 (const type)))
1313 (defcustom org-after-todo-state-change-hook nil
1314 "Hook which is run after the state of a TODO item was changed.
1315 The new state (a string with a TODO keyword, or nil) is available in the
1316 Lisp variable `state'."
1317 :group 'org-todo
1318 :type 'hook)
1320 (defcustom org-log-done nil
1321 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1322 When the state of an entry is changed from nothing to TODO, remove a previous
1323 closing date.
1325 This can also be a list of symbols indicating under which conditions
1326 the time stamp recording the action should be annotated with a short note.
1327 Valid members of this list are
1329 done Offer to record a note when marking entries done
1330 clock-out Offer to record a note when clocking out of an item.
1332 A separate window will then pop up and allow you to type a note.
1333 After finishing with C-c C-c, the note will be added directly after the
1334 timestamp, as a plain list item. See also the variable
1335 `org-log-note-headings'.
1337 Logging can also be configured on a per-file basis by adding one of
1338 the following lines anywhere in the buffer:
1340 #+STARTUP: logging
1341 #+STARTUP: nologging"
1342 ;; FIXME: in-buffer words for notes???????
1343 :group 'org-todo
1344 :type '(choice
1345 (const :tag "off" nil)
1346 (const :tag "on" t)
1347 (set :tag "on, with notes" :greedy t :value (done)
1348 (const done) (const clock-out))))
1350 (defcustom org-log-note-headings '((done . "CLOSING NOTE %t") (clock-out . ""))
1351 "Headings for notes added when clocking out or closing TODO items.
1352 The value is an alist, with the car being a sympol indicating the note
1353 context, and the cdr is the heading to be used. The heading may also be the
1354 empty string.
1355 %t in the heading will be replaced by a time stamp
1356 %u will be replaced by the user name
1357 %U will be replaced by the full user name."
1358 :group 'org-todo
1359 :type '(list :greedy t
1360 (cons (const :tag "Heading when closing an item" done) string)
1361 (cons (const :tag "Heading when clocking out" clock-out) string)))
1363 (defgroup org-priorities nil
1364 "Priorities in Org-mode."
1365 :tag "Org Priorities"
1366 :group 'org-todo)
1368 (defcustom org-default-priority ?B
1369 "The default priority of TODO items.
1370 This is the priority an item get if no explicit priority is given."
1371 :group 'org-priorities
1372 :type 'character)
1374 (defcustom org-lowest-priority ?C
1375 "The lowest priority of TODO items. A character like ?A, ?B etc."
1376 :group 'org-priorities
1377 :type 'character)
1379 (defgroup org-time nil
1380 "Options concerning time stamps and deadlines in Org-mode."
1381 :tag "Org Time"
1382 :group 'org)
1384 (defcustom org-insert-labeled-timestamps-at-point nil
1385 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1386 When nil, these labeled time stamps are forces into the second line of an
1387 entry, just after the headline. When scheduling from the global TODO list,
1388 the time stamp will always be forced into the second line."
1389 :group 'org-time
1390 :type 'boolean)
1392 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1393 "Formats for `format-time-string' which are used for time stamps.
1394 It is not recommended to change this constant.")
1396 (defcustom org-time-stamp-rounding-minutes 0
1397 "Number of minutes to round time stamps to upon insertion.
1398 When zero, insert the time unmodified. Useful rounding numbers
1399 should be factors of 60, so for example 5, 10, 15.
1400 When this is not zero, you can still force an exact time-stamp by using
1401 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1402 :group 'org-time
1403 :type 'integer)
1405 (defcustom org-display-custom-times nil
1406 "Non-nil means, overlay custom formats over all time stamps.
1407 The formats are defined through the variable `org-time-stamp-custom-formats'.
1408 To turn this on on a per-file basis, insert anywhere in the file:
1409 #+STARTUP: customtime"
1410 :group 'org-time
1411 :set 'set-default
1412 :type 'sexp)
1413 (make-variable-buffer-local 'org-display-custom-times)
1415 (defcustom org-time-stamp-custom-formats
1416 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1417 "Custom formats for time stamps. See `format-time-string' for the syntax.
1418 These are overlayed over the default ISO format if the variable
1419 `org-display-custom-times' is set."
1420 :group 'org-time
1421 :type 'sexp)
1423 (defun org-time-stamp-format (&optional long inactive)
1424 "Get the right format for a time string."
1425 (let ((f (if long (cdr org-time-stamp-formats)
1426 (car org-time-stamp-formats))))
1427 (if inactive
1428 (concat "[" (substring f 1 -1) "]")
1429 f)))
1431 (defcustom org-deadline-warning-days 30
1432 "No. of days before expiration during which a deadline becomes active.
1433 This variable governs the display in sparse trees and in the agenda."
1434 :group 'org-time
1435 :type 'number)
1437 (defcustom org-popup-calendar-for-date-prompt t
1438 "Non-nil means, pop up a calendar when prompting for a date.
1439 In the calendar, the date can be selected with mouse-1. However, the
1440 minibuffer will also be active, and you can simply enter the date as well.
1441 When nil, only the minibuffer will be available."
1442 :group 'org-time
1443 :type 'boolean)
1445 (defcustom org-calendar-follow-timestamp-change t
1446 "Non-nil means, make the calendar window follow timestamp changes.
1447 When a timestamp is modified and the calendar window is visible, it will be
1448 moved to the new date."
1449 :group 'org-time
1450 :type 'boolean)
1452 (defgroup org-tags nil
1453 "Options concerning tags in Org-mode."
1454 :tag "Org Tags"
1455 :group 'org)
1457 (defcustom org-tag-alist nil
1458 "List of tags allowed in Org-mode files.
1459 When this list is nil, Org-mode will base TAG input on what is already in the
1460 buffer.
1461 The value of this variable is an alist, the car may be (and should) be a
1462 character that is used to select that tag through the fast-tag-selection
1463 interface. See the manual for details."
1464 :group 'org-tags
1465 :type '(repeat
1466 (choice
1467 (cons (string :tag "Tag name")
1468 (character :tag "Access char"))
1469 (const :tag "Start radio group" (:startgroup))
1470 (const :tag "End radio group" (:endgroup)))))
1472 (defcustom org-use-fast-tag-selection 'auto
1473 "Non-nil means, use fast tag selection scheme.
1474 This is a special interface to select and deselect tags with single keys.
1475 When nil, fast selection is never used.
1476 When the symbol `auto', fast selection is used if and only if selection
1477 characters for tags have been configured, either through the variable
1478 `org-tag-alist' or through a #+TAGS line in the buffer.
1479 When t, fast selection is always used and selection keys are assigned
1480 automatically if necessary."
1481 :group 'org-tags
1482 :type '(choice
1483 (const :tag "Always" t)
1484 (const :tag "Never" nil)
1485 (const :tag "When selection characters are configured" 'auto)))
1487 (defcustom org-fast-tag-selection-single-key nil
1488 "Non-nil means, fast tag selection exits after first change.
1489 When nil, you have to press RET to exit it.
1490 During fast tag selection, you can toggle this flag with `C-c'."
1491 :group 'org-tags
1492 :type 'boolean)
1494 (defcustom org-tags-column 48
1495 "The column to which tags should be indented in a headline.
1496 If this number is positive, it specifies the column. If it is negative,
1497 it means that the tags should be flushright to that column. For example,
1498 -79 works well for a normal 80 character screen."
1499 :group 'org-tags
1500 :type 'integer)
1502 (defcustom org-auto-align-tags t
1503 "Non-nil means, realign tags after pro/demotion of TODO state change.
1504 These operations change the length of a headline and therefore shift
1505 the tags around. With this options turned on, after each such operation
1506 the tags are again aligned to `org-tags-column'."
1507 :group 'org-tags
1508 :type 'boolean)
1510 (defcustom org-use-tag-inheritance t
1511 "Non-nil means, tags in levels apply also for sublevels.
1512 When nil, only the tags directly given in a specific line apply there.
1513 If you turn off this option, you very likely want to turn on the
1514 companion option `org-tags-match-list-sublevels'."
1515 :group 'org-tags
1516 :type 'boolean)
1518 (defcustom org-tags-match-list-sublevels nil
1519 "Non-nil means list also sublevels of headlines matching tag search.
1520 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1521 the sublevels of a headline matching a tag search often also match
1522 the same search. Listing all of them can create very long lists.
1523 Setting this variable to nil causes subtrees of a match to be skipped.
1524 This option is off by default, because inheritance in on. If you turn
1525 inheritance off, you very likely want to turn this option on.
1527 As a special case, if the tag search is restricted to TODO items, the
1528 value of this variable is ignored and sublevels are always checked, to
1529 make sure all corresponding TODO items find their way into the list."
1530 :group 'org-tags
1531 :type 'boolean)
1533 (defvar org-tags-history nil
1534 "History of minibuffer reads for tags.")
1535 (defvar org-last-tags-completion-table nil
1536 "The last used completion table for tags.")
1538 (defgroup org-agenda nil
1539 "Options concerning agenda views in Org-mode."
1540 :tag "Org Agenda"
1541 :group 'org)
1543 (defvar org-category nil
1544 "Variable used by org files to set a category for agenda display.
1545 Such files should use a file variable to set it, for example
1547 -*- mode: org; org-category: \"ELisp\"
1549 or contain a special line
1551 #+CATEGORY: ELisp
1553 If the file does not specify a category, then file's base name
1554 is used instead.")
1555 (make-variable-buffer-local 'org-category)
1557 (defcustom org-agenda-files nil
1558 "The files to be used for agenda display.
1559 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1560 \\[org-remove-file]. You can also use customize to edit the list.
1562 If the value of the variable is not a list but a single file name, then
1563 the list of agenda files is actually stored and maintained in that file, one
1564 agenda file per line."
1565 :group 'org-agenda
1566 :type '(choice
1567 (repeat :tag "List of files" file)
1568 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1571 (defcustom org-agenda-confirm-kill 1
1572 "When set, remote killing from the agenda buffer needs confirmation.
1573 When t, a confirmation is always needed. When a number N, confirmation is
1574 only needed when the text to be killed contains more than N non-white lines."
1575 :group 'org-agenda
1576 :type '(choice
1577 (const :tag "Never" nil)
1578 (const :tag "Always" t)
1579 (number :tag "When more than N lines")))
1581 (defcustom org-calendar-to-agenda-key [?c]
1582 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1583 The command `org-calendar-goto-agenda' will be bound to this key. The
1584 default is the character `c' because then `c' can be used to switch back and
1585 forth between agenda and calendar."
1586 :group 'org-agenda
1587 :type 'sexp)
1589 (defgroup org-agenda-custom-commands nil
1590 "Options concerning agenda views in Org-mode."
1591 :tag "Org Agenda Custom Commands"
1592 :group 'org-agenda)
1594 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1595 "Custom commands for the agenda.
1596 These commands will be offered on the splash screen displayed by the
1597 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1599 (key type match options)
1601 key The key (a single char as a string) to be associated with the command.
1602 type The command type, any of the following symbols:
1603 todo Entries with a specific TODO keyword, in all agenda files.
1604 tags Tags match in all agenda files.
1605 tags-todo Tags match in all agenda files, TODO entries only.
1606 todo-tree Sparse tree of specific TODO keyword in *current* file.
1607 tags-tree Sparse tree with all tags matches in *current* file.
1608 occur-tree Occur sparse tree for *current* file.
1609 match What to search for:
1610 - a single keyword for TODO keyword searches
1611 - a tags match expression for tags searches
1612 - a regular expression for occur searches
1613 options A list of option setttings, similar to that in a let form, so like
1614 this: ((opt1 val1) (opt2 val2) ...)
1616 You can also define a set of commands, to create a composite agenda buffer.
1617 In this case, an entry looks like this:
1619 (key desc (cmd1 cmd2 ...) general-options)
1621 where
1623 desc A description string to be displayed in the dispatcher menu.
1624 cmd An agenda command, similar to the above. However, tree commands
1625 are no allowed, but instead you can get agenda and global todo list.
1626 So valid commands for a set are:
1627 (agenda)
1628 (alltodo)
1629 (todo \"match\" options)
1630 (tags \"match\" options )
1631 (tags-todo \"match\" options)
1633 Each command can carry a list of options, and another set of options can be
1634 given for the whole set of commands. Individual command options take
1635 precedence over the general options."
1636 :group 'org-agenda-custom-commands
1637 :type '(repeat
1638 (choice
1639 (list :tag "Single command"
1640 (string :tag "Key")
1641 (choice
1642 (const :tag "Tags search (all agenda files)" tags)
1643 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1644 (const :tag "TODO keyword search (all agenda files)" todo)
1645 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1646 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1647 (const :tag "Occur tree (current buffer)" occur-tree)
1648 (symbol :tag "Other, user-defined function"))
1649 (string :tag "Match")
1650 (repeat :tag "Local options"
1651 (list (variable :tag "Option") (sexp :tag "Value"))))
1652 (list :tag "Command series, all agenda files"
1653 (string :tag "Key")
1654 (string :tag "Description")
1655 (repeat
1656 (choice
1657 (const :tag "Agenda" (agenda))
1658 (const :tag "TODO list" (alltodo))
1659 (list :tag "Tags search"
1660 (const :format "" tags)
1661 (string :tag "Match")
1662 (repeat :tag "Local options"
1663 (list (variable :tag "Option")
1664 (sexp :tag "Value"))))
1666 (list :tag "Tags search, TODO entries only"
1667 (const :format "" tags-todo)
1668 (string :tag "Match")
1669 (repeat :tag "Local options"
1670 (list (variable :tag "Option")
1671 (sexp :tag "Value"))))
1673 (list :tag "TODO keyword search"
1674 (const :format "" todo)
1675 (string :tag "Match")
1676 (repeat :tag "Local options"
1677 (list (variable :tag "Option")
1678 (sexp :tag "Value"))))
1680 (list :tag "Other, user-defined function" ; FIXME: untested
1681 (symbol :tag "function")
1682 (string :tag "Match")
1683 (repeat :tag "Local options"
1684 (list (variable :tag "Option")
1685 (sexp :tag "Value"))))))
1687 (repeat :tag "General options"
1688 (list (variable :tag "Option")
1689 (sexp :tag "Value")))))))
1691 (defcustom org-stuck-projects
1692 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil)
1693 "How to identify stuck projects.
1694 This is a list of three items:
1695 1. A tags/todo matcher string that is used to identify a project.
1696 The entire tree below a headline matched by this is considered a project.
1697 2. A list of TODO keywords itentifying non-stuck projects.
1698 If the project subtree contains any headline with one of these todo
1699 keywords, the project is consitered to be not stuck.
1700 3. A list of tags identifying non-stuck projects.
1701 If the project subtree contains any headline with one of these tags,
1702 the project is consitered to be not stuck.
1704 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
1705 or `C-c a #' to produce the list."
1706 :group 'org-agenda-custom-commands
1707 :type '(list
1708 (string :tag "Tags/TODO match to identify a project")
1709 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
1710 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))))
1713 (defgroup org-agenda-skip nil
1714 "Options concerning skipping parts of agenda files."
1715 :tag "Org Agenda Skip"
1716 :group 'org-agenda)
1718 (defcustom org-agenda-todo-list-sublevels t
1719 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1720 When nil, the sublevels of a TODO entry are not checked, resulting in
1721 potentially much shorter TODO lists."
1722 :group 'org-agenda-skip
1723 :group 'org-todo
1724 :type 'boolean)
1726 (defcustom org-agenda-todo-ignore-scheduled nil
1727 "Non-nil means, don't show scheduled entries in the global todo list.
1728 The idea behind this is that by scheduling it, you have already taken care
1729 of this item."
1730 :group 'org-agenda-skip
1731 :group 'org-todo
1732 :type 'boolean)
1734 (defcustom org-agenda-todo-ignore-deadlines nil
1735 "Non-nil means, don't show near deadline entries in the global todo list.
1736 Near means closer than `org-deadline-warning-days' days.
1737 The idea behind this is that such items will appear in the agenda anyway."
1738 :group 'org-agenda-skip
1739 :group 'org-todo
1740 :type 'boolean)
1742 (defcustom org-agenda-skip-scheduled-if-done nil
1743 "Non-nil means don't show scheduled items in agenda when they are done.
1744 This is relevant for the daily/weekly agenda, not for the TODO list."
1745 :group 'org-agenda-skip
1746 :type 'boolean)
1748 (defcustom org-timeline-show-empty-dates 3
1749 "Non-nil means, `org-timeline' also shows dates without an entry.
1750 When nil, only the days which actually have entries are shown.
1751 When t, all days between the first and the last date are shown.
1752 When an integer, show also empty dates, but if there is a gap of more than
1753 N days, just insert a special line indicating the size of the gap."
1754 :group 'org-agenda-skip ; FIXME: not quite the right group...
1755 :type '(choice
1756 (const :tag "None" nil)
1757 (const :tag "All" t)
1758 (number :tag "at most")))
1761 (defgroup org-agenda-startup nil
1762 "Options concerning initial settings in the Agenda in Org Mode."
1763 :tag "Org Agenda Startup"
1764 :group 'org-agenda)
1766 (defcustom org-finalize-agenda-hook nil
1767 "Hook run just before displaying an agenda buffer."
1768 :group 'org-agenda-startup
1769 :type 'hook)
1771 (defcustom org-agenda-mouse-1-follows-link nil
1772 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1773 A longer mouse click will still set point. Does not wortk on XEmacs.
1774 Needs to be set before org.el is loaded."
1775 :group 'org-agenda-startup
1776 :type 'boolean)
1778 (defcustom org-agenda-start-with-follow-mode nil
1779 "The initial value of follwo-mode in a newly created agenda window."
1780 :group 'org-agenda-startup
1781 :type 'boolean)
1783 (defgroup org-agenda-windows nil
1784 "Options concerning the windows used by the Agenda in Org Mode."
1785 :tag "Org Agenda Windows"
1786 :group 'org-agenda)
1788 (defcustom org-agenda-window-setup 'reorganize-frame
1789 "How the agenda buffer should be displayed.
1790 Possible values for this option are:
1792 current-window Show agenda in the current window, keeping all other windows.
1793 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1794 other-window Use `switch-to-buffer-other-window' to display agenda.
1795 reorganize-frame Show only two windows on the current frame, the current
1796 window and the agenda. Also, if the option
1797 `org-fit-agenda-window' is set, resize the agenda window to
1798 try to show as much as possible of the buffer content.
1799 See also the variable `org-agenda-restore-windows-after-quit'."
1800 :group 'org-agenda-windows
1801 :type '(choice
1802 (const current-window)
1803 (const other-frame)
1804 (const other-window)
1805 (const reorganize-frame)))
1807 (defcustom org-agenda-restore-windows-after-quit nil
1808 "Non-nil means, restore window configuration open exiting agenda.
1809 Before the window configuration is changed for displaying the agenda,
1810 the current status is recorded. When the agenda is exited with
1811 `q' or `x' and this option is set, the old state is restored. If
1812 `org-agenda-window-setup' is `other-frame', the value of this
1813 option will be ignored.."
1814 :group 'org-agenda-windows
1815 :type 'boolean)
1817 ;; FIXME: I think this variable could be removed, default set to t
1818 (defcustom org-select-agenda-window t
1819 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1820 When nil, cursor will remain in the current window."
1821 :group 'org-agenda-windows
1822 :type 'boolean)
1824 ;; FIXME: I think this variable could be removed, default set to t
1825 (defcustom org-fit-agenda-window t
1826 "Non-nil means, change window size of agenda to fit content.
1827 This is only effective if `org-agenda-window-setup' is `reorganize-frame'."
1828 :group 'org-agenda-windows
1829 :type 'boolean)
1831 (defcustom org-indirect-buffer-display 'other-window
1832 "How should indirect tree buffers be displayed?
1833 This applies to indirect buffers created with the commands
1834 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1835 Valid values are:
1836 current-window Display in the current window
1837 other-window Just display in another window.
1838 dedicated-frame Create one new frame, and re-use it each time.
1839 new-frame Make a new frame each time."
1840 :group 'org-structure
1841 :group 'org-agenda-windows
1842 :type '(choice
1843 (const :tag "In current window" current-window)
1844 (const :tag "In current frame, other window" other-window)
1845 (const :tag "Each time a new frame" new-frame)
1846 (const :tag "One dedicated frame" dedicated-frame)))
1848 (defgroup org-agenda-daily/weekly nil
1849 "Options concerning the daily/weekly agenda."
1850 :tag "Org Agenda Daily/Weekly"
1851 :group 'org-agenda)
1853 (defcustom org-agenda-ndays 7
1854 "Number of days to include in overview display.
1855 Should be 1 or 7."
1856 :group 'org-agenda-daily/weekly
1857 :type 'number)
1859 (defcustom org-agenda-start-on-weekday 1
1860 "Non-nil means, start the overview always on the specified weekday.
1861 0 denotes Sunday, 1 denotes Monday etc.
1862 When nil, always start on the current day."
1863 :group 'org-agenda-daily/weekly
1864 :type '(choice (const :tag "Today" nil)
1865 (number :tag "Weekday No.")))
1866 (defcustom org-agenda-show-all-dates t
1867 "Non-nil means, `org-agenda' shows every day in the selected range.
1868 When nil, only the days which actually have entries are shown."
1869 :group 'org-agenda-daily/weekly
1870 :type 'boolean)
1872 (defcustom org-agenda-include-diary nil
1873 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1874 :group 'org-agenda-daily/weekly
1875 :type 'boolean)
1877 ;; FIXME: This variable could be removed
1878 (defcustom org-agenda-include-all-todo nil
1879 "Set means weekly/daily agenda will always contain all TODO entries.
1880 The TODO entries will be listed at the top of the agenda, before
1881 the entries for specific days."
1882 :group 'org-agenda-daily/weekly
1883 :type 'boolean)
1885 (defgroup org-agenda-time-grid nil
1886 "Options concerning the time grid in the Org-mode Agenda."
1887 :tag "Org Agenda Time Grid"
1888 :group 'org-agenda)
1890 (defcustom org-agenda-use-time-grid t
1891 "Non-nil means, show a time grid in the agenda schedule.
1892 A time grid is a set of lines for specific times (like every two hours between
1893 8:00 and 20:00). The items scheduled for a day at specific times are
1894 sorted in between these lines.
1895 For details about when the grid will be shown, and what it will look like, see
1896 the variable `org-agenda-time-grid'."
1897 :group 'org-agenda-time-grid
1898 :type 'boolean)
1900 (defcustom org-agenda-time-grid
1901 '((daily today require-timed)
1902 "----------------"
1903 (800 1000 1200 1400 1600 1800 2000))
1905 "The settings for time grid for agenda display.
1906 This is a list of three items. The first item is again a list. It contains
1907 symbols specifying conditions when the grid should be displayed:
1909 daily if the agenda shows a single day
1910 weekly if the agenda shows an entire week
1911 today show grid on current date, independent of daily/weekly display
1912 require-timed show grid only if at least one item has a time specification
1914 The second item is a string which will be places behing the grid time.
1916 The third item is a list of integers, indicating the times that should have
1917 a grid line."
1918 :group 'org-agenda-time-grid
1919 :type
1920 '(list
1921 (set :greedy t :tag "Grid Display Options"
1922 (const :tag "Show grid in single day agenda display" daily)
1923 (const :tag "Show grid in weekly agenda display" weekly)
1924 (const :tag "Always show grid for today" today)
1925 (const :tag "Show grid only if any timed entries are present"
1926 require-timed)
1927 (const :tag "Skip grid times already present in an entry"
1928 remove-match))
1929 (string :tag "Grid String")
1930 (repeat :tag "Grid Times" (integer :tag "Time"))))
1932 (defgroup org-agenda-sorting nil
1933 "Options concerning sorting in the Org-mode Agenda."
1934 :tag "Org Agenda Sorting"
1935 :group 'org-agenda)
1937 (let ((sorting-choice
1938 '(choice
1939 (const time-up) (const time-down)
1940 (const category-keep) (const category-up) (const category-down)
1941 (const tag-down) (const tag-up)
1942 (const priority-up) (const priority-down))))
1944 (defcustom org-agenda-sorting-strategy
1945 '((agenda time-up category-keep priority-down)
1946 (todo category-keep priority-down)
1947 (tags category-keep))
1948 "Sorting structure for the agenda items of a single day.
1949 This is a list of symbols which will be used in sequence to determine
1950 if an entry should be listed before another entry. The following
1951 symbols are recognized:
1953 time-up Put entries with time-of-day indications first, early first
1954 time-down Put entries with time-of-day indications first, late first
1955 category-keep Keep the default order of categories, corresponding to the
1956 sequence in `org-agenda-files'.
1957 category-up Sort alphabetically by category, A-Z.
1958 category-down Sort alphabetically by category, Z-A.
1959 tag-up Sort alphabetically by last tag, A-Z.
1960 tag-down Sort alphabetically by last tag, Z-A.
1961 priority-up Sort numerically by priority, high priority last.
1962 priority-down Sort numerically by priority, high priority first.
1964 The different possibilities will be tried in sequence, and testing stops
1965 if one comparison returns a \"not-equal\". For example, the default
1966 '(time-up category-keep priority-down)
1967 means: Pull out all entries having a specified time of day and sort them,
1968 in order to make a time schedule for the current day the first thing in the
1969 agenda listing for the day. Of the entries without a time indication, keep
1970 the grouped in categories, don't sort the categories, but keep them in
1971 the sequence given in `org-agenda-files'. Within each category sort by
1972 priority.
1974 Leaving out `category-keep' would mean that items will be sorted across
1975 categories by priority."
1976 :group 'org-agenda-sorting
1977 :type `(choice
1978 (repeat :tag "General" ,sorting-choice)
1979 (list :tag "Individually"
1980 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
1981 (repeat ,sorting-choice))
1982 (cons (const :tag "Strategy for TODO lists" todo)
1983 (repeat ,sorting-choice))
1984 (cons (const :tag "Strategy for Tags matches" tags)
1985 (repeat ,sorting-choice))))))
1987 (defcustom org-sort-agenda-notime-is-late t
1988 "Non-nil means, items without time are considered late.
1989 This is only relevant for sorting. When t, items which have no explicit
1990 time like 15:30 will be considered as 99:01, i.e. later than any items which
1991 do have a time. When nil, the default time is before 0:00. You can use this
1992 option to decide if the schedule for today should come before or after timeless
1993 agenda entries."
1994 :group 'org-agenda-sorting
1995 :type 'boolean)
1997 (defgroup org-agenda-prefix nil
1998 "Options concerning the entry prefix in the Org-mode agenda display."
1999 :tag "Org Agenda Prefix"
2000 :group 'org-agenda)
2002 (defcustom org-agenda-prefix-format
2003 '((agenda . " %-12:c%?-12t% s")
2004 (timeline . " % s")
2005 (todo . " %-12:c")
2006 (tags . " %-12:c"))
2007 "Format specifications for the prefix of items in the agenda views.
2008 An alist with four entries, for the different agenda types. The keys to the
2009 sublists are `agenda', `timeline', `todo', and `tags'. The values
2010 are format strings.
2011 This format works similar to a printf format, with the following meaning:
2013 %c the category of the item, \"Diary\" for entries from the diary, or
2014 as given by the CATEGORY keyword or derived from the file name.
2015 %T the *last* tag of the item. Last because inherited tags come
2016 first in the list.
2017 %t the time-of-day specification if one applies to the entry, in the
2018 format HH:MM
2019 %s Scheduling/Deadline information, a short string
2021 All specifiers work basically like the standard `%s' of printf, but may
2022 contain two additional characters: A question mark just after the `%' and
2023 a whitespace/punctuation character just before the final letter.
2025 If the first character after `%' is a question mark, the entire field
2026 will only be included if the corresponding value applies to the
2027 current entry. This is useful for fields which should have fixed
2028 width when present, but zero width when absent. For example,
2029 \"%?-12t\" will result in a 12 character time field if a time of the
2030 day is specified, but will completely disappear in entries which do
2031 not contain a time.
2033 If there is punctuation or whitespace character just before the final
2034 format letter, this character will be appended to the field value if
2035 the value is not empty. For example, the format \"%-12:c\" leads to
2036 \"Diary: \" if the category is \"Diary\". If the category were be
2037 empty, no additional colon would be interted.
2039 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2040 - Indent the line with two space characters
2041 - Give the category in a 12 chars wide field, padded with whitespace on
2042 the right (because of `-'). Append a colon if there is a category
2043 (because of `:').
2044 - If there is a time-of-day, put it into a 12 chars wide field. If no
2045 time, don't put in an empty field, just skip it (because of '?').
2046 - Finally, put the scheduling information and append a whitespace.
2048 As another example, if you don't want the time-of-day of entries in
2049 the prefix, you could use:
2051 (setq org-agenda-prefix-format \" %-11:c% s\")
2053 See also the variables `org-agenda-remove-times-when-in-prefix' and
2054 `org-agenda-remove-tags-when-in-prefix'."
2055 :type '(choice
2056 (string :tag "General format")
2057 (list :greedy t :tag "View dependent"
2058 (cons (const agenda) (string :tag "Format"))
2059 (cons (const timeline) (string :tag "Format"))
2060 (cons (const todo) (string :tag "Format"))
2061 (cons (const tags) (string :tag "Format"))))
2062 :group 'org-agenda-prefix)
2064 (defvar org-prefix-format-compiled nil
2065 "The compiled version of the most recently used prefix format.
2066 See the variable `org-agenda-prefix-format'.")
2068 (defcustom org-agenda-remove-times-when-in-prefix t
2069 "Non-nil means, remove duplicate time specifications in agenda items.
2070 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2071 time-of-day specification in a headline or diary entry is extracted and
2072 placed into the prefix. If this option is non-nil, the original specification
2073 \(a timestamp or -range, or just a plain time(range) specification like
2074 11:30-4pm) will be removed for agenda display. This makes the agenda less
2075 cluttered.
2076 The option can be t or nil. It may also be the symbol `beg', indicating
2077 that the time should only be removed what it is located at the beginning of
2078 the headline/diary entry."
2079 :group 'org-agenda-prefix
2080 :type '(choice
2081 (const :tag "Always" t)
2082 (const :tag "Never" nil)
2083 (const :tag "When at beginning of entry" beg)))
2085 (defcustom org-agenda-remove-tags-when-in-prefix nil
2086 "Non-nil means, remove the tags from the headline copy in the agenda.
2087 When this is the symbol `prefix', only remove tags when
2088 `org-agenda-prefix-format' contains a `%T' specifier."
2089 :group 'org-agenda-prefix
2090 :type '(choice
2091 (const :tag "Always" t)
2092 (const :tag "Never" nil)
2093 (const :tag "When prefix format contains %T" prefix)))
2095 (defcustom org-agenda-align-tags-to-column 65
2096 "Shift tags in agenda items to this column."
2097 :group 'org-agenda-prefix
2098 :type 'integer)
2100 (defgroup org-latex nil
2101 "Options for embedding LaTeX code into Org-mode"
2102 :tag "Org LaTeX"
2103 :group 'org)
2105 (defcustom org-format-latex-options
2106 '(:foreground "Black" :background "Transparent" :scale 1.0
2107 :matchers ("begin" "$" "$$" "\\(" "\\["))
2108 "Options for creating images from LaTeX fragments.
2109 This is a property list with the following properties:
2110 :foreground the foreground color, for example \"Black\".
2111 :background the background color, or \"Transparent\".
2112 :scale a scaling factor for the size of the images
2113 :matchers a list indicating which matchers should be used to
2114 find LaTeX fragments. Valid members of this list are:
2115 \"begin\" find environments
2116 \"$\" find math expressions surrounded by $...$
2117 \"$$\" find math expressions surrounded by $$....$$
2118 \"\\(\" find math expressions surrounded by \\(...\\)
2119 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2120 :group 'org-latex
2121 :type 'plist)
2123 (defgroup org-export nil
2124 "Options for exporting org-listings."
2125 :tag "Org Export"
2126 :group 'org)
2128 (defgroup org-export-general nil
2129 "General options for exporting Org-mode files."
2130 :tag "Org Export General"
2131 :group 'org-export)
2133 (defcustom org-export-publishing-directory "."
2134 "Path to the location where exported files should be located.
2135 This path may be relative to the directory where the Org-mode file lives.
2136 The default is to put them into the same directory as the Org-mode file.
2137 The variable may also be an alist with export types `:html', `:ascii',
2138 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2139 is relative, it is interpreted relative to the directory where the exported
2140 Org-mode files lives."
2141 :group 'org-export-general
2142 :type '(choice
2143 (directory)
2144 (repeat
2145 (cons
2146 (choice :tag "Type"
2147 (const :html) (const :ascii) (const :ical) (const :xoxo))
2148 (directory)))))
2150 (defcustom org-export-language-setup
2151 '(("en" "Author" "Date" "Table of Contents")
2152 ("cs" "Autor" "Datum" "Obsah")
2153 ("da" "Ophavsmand" "Dato" "Indhold")
2154 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2155 ("es" "Autor" "Fecha" "\xccndice")
2156 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2157 ("it" "Autore" "Data" "Indice")
2158 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2159 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2160 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2161 "Terms used in export text, translated to different languages.
2162 Use the variable `org-export-default-language' to set the language,
2163 or use the +OPTION lines for a per-file setting."
2164 :group 'org-export-general
2165 :type '(repeat
2166 (list
2167 (string :tag "HTML language tag")
2168 (string :tag "Author")
2169 (string :tag "Date")
2170 (string :tag "Table of Contents"))))
2172 (defcustom org-export-default-language "en"
2173 "The default language of HTML export, as a string.
2174 This should have an association in `org-export-language-setup'."
2175 :group 'org-export-general
2176 :type 'string)
2178 (defcustom org-export-headline-levels 3
2179 "The last level which is still exported as a headline.
2180 Inferior levels will produce itemize lists when exported.
2181 Note that a numeric prefix argument to an exporter function overrides
2182 this setting.
2184 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2185 :group 'org-export-general
2186 :type 'number)
2188 (defcustom org-export-with-section-numbers t
2189 "Non-nil means, add section numbers to headlines when exporting.
2191 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2192 :group 'org-export-general
2193 :type 'boolean)
2195 (defcustom org-export-with-toc t
2196 "Non-nil means, create a table of contents in exported files.
2197 The TOC contains headlines with levels up to`org-export-headline-levels'.
2199 Headlines which contain any TODO items will be marked with \"(*)\" in
2200 ASCII export, and with red color in HTML output.
2202 In HTML output, the TOC will be clickable.
2204 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
2205 :group 'org-export-general
2206 :type 'boolean)
2208 (defcustom org-export-mark-todo-in-toc nil
2209 "Non-nil means, mark TOC lines that contain any open TODO items."
2210 :group 'org-export-general
2211 :type 'boolean)
2213 (defcustom org-export-preserve-breaks nil
2214 "Non-nil means, preserve all line breaks when exporting.
2215 Normally, in HTML output paragraphs will be reformatted. In ASCII
2216 export, line breaks will always be preserved, regardless of this variable.
2218 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2219 :group 'org-export-general
2220 :type 'boolean)
2222 (defcustom org-export-with-archived-trees 'headline
2223 "Whether subtrees with the ARCHIVE tag should be exported.
2224 This can have three different values
2225 nil Do not export, pretend this tree is not present
2226 t Do export the entire tree
2227 headline Only export the headline, but skip the tree below it."
2228 :group 'org-export-general
2229 :group 'org-archive
2230 :type '(choice
2231 (const :tag "not at all" nil)
2232 (const :tag "headline only" 'headline)
2233 (const :tag "entirely" t)))
2235 (defcustom org-export-with-timestamps t
2236 "If nil, do not export time stamps and associated keywords."
2237 :group 'org-export-general
2238 :type 'boolean)
2240 (defcustom org-export-remove-timestamps-from-toc t
2241 "If nil, remove timestamps from the table of contents entries."
2242 :group 'org-export-general
2243 :type 'boolean)
2245 (defcustom org-export-with-tags 'not-in-toc
2246 "If nil, do not export tags, just remove them from headlines.
2247 If this is the symbol `not-in-toc', tags will be removed from table of
2248 contents entries, but still be shown in the headlines of the document."
2249 :group 'org-export-general
2250 :type '(choice
2251 (const :tag "Off" nil)
2252 (const :tag "Not in TOC" not-in-toc)
2253 (const :tag "On" t)))
2255 (defgroup org-export-translation nil
2256 "Options for translating special ascii sequences for the export backends."
2257 :tag "Org Export Translation"
2258 :group 'org-export)
2260 (defcustom org-export-with-emphasize t
2261 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2262 If the export target supports emphasizing text, the word will be
2263 typeset in bold, italic, or underlined, respectively. Works only for
2264 single words, but you can say: I *really* *mean* *this*.
2265 Not all export backends support this.
2267 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2268 :group 'org-export-translation
2269 :type 'boolean)
2271 (defcustom org-export-with-sub-superscripts t
2272 "Non-nil means, interpret \"_\" and \"^\" for export.
2273 When this option is turned on, you can use TeX-like syntax for sub- and
2274 superscripts. Several characters after \"_\" or \"^\" will be
2275 considered as a single item - so grouping with {} is normally not
2276 needed. For example, the following things will be parsed as single
2277 sub- or superscripts.
2279 10^24 or 10^tau several digits will be considered 1 item.
2280 10^-12 or 10^-tau a leading sign with digits or a word
2281 x^2-y^3 will be read as x^2 - y^3, because items are
2282 terminated by almost any nonword/nondigit char.
2283 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2285 Still, ambiguity is possible - so when in doubt use {} to enclose the
2286 sub/superscript.
2287 Not all export backends support this, but HTML does.
2289 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2290 :group 'org-export-translation
2291 :type 'boolean)
2293 (defcustom org-export-with-TeX-macros t
2294 "Non-nil means, interpret simple TeX-like macros when exporting.
2295 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2296 No only real TeX macros will work here, but the standard HTML entities
2297 for math can be used as macro names as well. For a list of supported
2298 names in HTML export, see the constant `org-html-entities'.
2299 Not all export backends support this.
2301 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2302 :group 'org-export-translation
2303 :group 'org-latex
2304 :type 'boolean)
2306 (defcustom org-export-with-LaTeX-fragments nil
2307 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2308 When set, the exporter will find LaTeX environments if the \\begin line is
2309 the first non-white thing on a line. It will also find the math delimiters
2310 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2311 display math.
2313 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2314 :group 'org-export-translation
2315 :group 'org-latex
2316 :type 'boolean)
2318 (defcustom org-export-with-fixed-width t
2319 "Non-nil means, lines starting with \":\" will be in fixed width font.
2320 This can be used to have pre-formatted text, fragments of code etc. For
2321 example:
2322 : ;; Some Lisp examples
2323 : (while (defc cnt)
2324 : (ding))
2325 will be looking just like this in also HTML. See also the QUOTE keyword.
2326 Not all export backends support this.
2328 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2329 :group 'org-export-translation
2330 :type 'boolean)
2332 (defcustom org-match-sexp-depth 3
2333 "Number of stacked braces for sub/superscript matching.
2334 This has to be set before loading org.el to be effective."
2335 :group 'org-export-translation
2336 :type 'integer)
2338 (defgroup org-export-tables nil
2339 "Options for exporting tables in Org-mode."
2340 :tag "Org Export Tables"
2341 :group 'org-export)
2343 (defcustom org-export-with-tables t
2344 "If non-nil, lines starting with \"|\" define a table.
2345 For example:
2347 | Name | Address | Birthday |
2348 |-------------+----------+-----------|
2349 | Arthur Dent | England | 29.2.2100 |
2351 Not all export backends support this.
2353 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2354 :group 'org-export-tables
2355 :type 'boolean)
2357 (defcustom org-export-highlight-first-table-line t
2358 "Non-nil means, highlight the first table line.
2359 In HTML export, this means use <th> instead of <td>.
2360 In tables created with table.el, this applies to the first table line.
2361 In Org-mode tables, all lines before the first horizontal separator
2362 line will be formatted with <th> tags."
2363 :group 'org-export-tables
2364 :type 'boolean)
2366 (defcustom org-export-table-remove-special-lines t
2367 "Remove special lines and marking characters in calculating tables.
2368 This removes the special marking character column from tables that are set
2369 up for spreadsheet calculations. It also removes the entire lines
2370 marked with `!', `_', or `^'. The lines with `$' are kept, because
2371 the values of constants may be useful to have."
2372 :group 'org-export-tables
2373 :type 'boolean)
2375 (defcustom org-export-prefer-native-exporter-for-tables nil
2376 "Non-nil means, always export tables created with table.el natively.
2377 Natively means, use the HTML code generator in table.el.
2378 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2379 the table does not use row- or column-spanning). This has the
2380 advantage, that the automatic HTML conversions for math symbols and
2381 sub/superscripts can be applied. Org-mode's HTML generator is also
2382 much faster."
2383 :group 'org-export-tables
2384 :type 'boolean)
2386 (defgroup org-export-ascii nil
2387 "Options specific for ASCII export of Org-mode files."
2388 :tag "Org Export ASCII"
2389 :group 'org-export)
2391 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2392 "Characters for underlining headings in ASCII export.
2393 In the given sequence, these characters will be used for level 1, 2, ..."
2394 :group 'org-export-ascii
2395 :type '(repeat character))
2397 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2398 "Bullet characters for headlines converted to lists in ASCII export.
2399 The first character is is used for the first lest level generated in this
2400 way, and so on. If there are more levels than characters given here,
2401 the list will be repeated.
2402 Note that plain lists will keep the same bullets as the have in the
2403 Org-mode file."
2404 :group 'org-export-ascii
2405 :type '(repeat character))
2407 (defcustom org-export-ascii-show-new-buffer t
2408 "Non-nil means, popup buffer containing the exported ASCII text.
2409 Otherwise the buffer will just be saved to a file and stay hidden."
2410 :group 'org-export-ascii
2411 :type 'boolean)
2413 (defgroup org-export-xml nil
2414 "Options specific for XML export of Org-mode files."
2415 :tag "Org Export XML"
2416 :group 'org-export)
2418 (defgroup org-export-html nil
2419 "Options specific for HTML export of Org-mode files."
2420 :tag "Org Export HTML"
2421 :group 'org-export)
2423 (defcustom org-export-html-style
2424 "<style type=\"text/css\">
2425 html {
2426 font-family: Times, serif;
2427 font-size: 12pt;
2429 .title { text-align: center; }
2430 .todo { color: red; }
2431 .done { color: green; }
2432 .timestamp { color: grey }
2433 .timestamp-kwd { color: CadetBlue }
2434 .tag { background-color:lightblue; font-weight:normal }
2435 .target { background-color: lavender; }
2436 pre {
2437 border: 1pt solid #AEBDCC;
2438 background-color: #F3F5F7;
2439 padding: 5pt;
2440 font-family: courier, monospace;
2442 table { border-collapse: collapse; }
2443 td, th {
2444 vertical-align: top;
2445 border: 1pt solid #ADB9CC;
2447 </style>"
2448 "The default style specification for exported HTML files.
2449 Since there are different ways of setting style information, this variable
2450 needs to contain the full HTML structure to provide a style, including the
2451 surrounding HTML tags. The style specifications should include definitions
2452 for new classes todo, done, title, and deadline. For example, legal values
2453 would be:
2455 <style type=\"text/css\">
2456 p { font-weight: normal; color: gray; }
2457 h1 { color: black; }
2458 .title { text-align: center; }
2459 .todo, .deadline { color: red; }
2460 .done { color: green; }
2461 </style>
2463 or, if you want to keep the style in a file,
2465 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2467 As the value of this option simply gets inserted into the HTML <head> header,
2468 you can \"misuse\" it to add arbitrary text to the header."
2469 :group 'org-export-html
2470 :type 'string)
2472 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2473 "Format for typesetting the document title in HTML export."
2474 :group 'org-export-html
2475 :type 'string)
2477 (defcustom org-export-html-toplevel-hlevel 2
2478 "The <H> level for level 1 headings in HTML export."
2479 :group 'org-export-html
2480 :type 'string)
2482 (defcustom org-export-html-link-org-files-as-html t
2483 "Non-nil means, make file links to `file.org' point to `file.html'.
2484 When org-mode is exporting an org-mode file to HTML, links to
2485 non-html files are directly put into a href tag in HTML.
2486 However, links to other Org-mode files (recognized by the
2487 extension `.org.) should become links to the corresponding html
2488 file, assuming that the linked org-mode file will also be
2489 converted to HTML.
2490 When nil, the links still point to the plain `.org' file."
2491 :group 'org-export-html
2492 :type 'boolean)
2494 (defcustom org-export-html-inline-images 'maybe
2495 "Non-nil means, inline images into exported HTML pages.
2496 This is done using an <img> tag. When nil, an anchor with href is used to
2497 link to the image. If this option is `maybe', then images in links with
2498 an empty description will be inlined, while images with a description will
2499 be linked only."
2500 :group 'org-export-html
2501 :type '(choice (const :tag "Never" nil)
2502 (const :tag "Always" t)
2503 (const :tag "When there is no description" maybe)))
2505 (defcustom org-export-html-expand t
2506 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2507 When nil, these tags will be exported as plain text and therefore
2508 not be interpreted by a browser.
2510 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2511 :group 'org-export-html
2512 :type 'boolean)
2514 (defcustom org-export-html-table-tag
2515 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2516 "The HTML tag used to start a table.
2517 This must be a <table> tag, but you may change the options like
2518 borders and spacing."
2519 :group 'org-export-html
2520 :type 'string)
2522 (defcustom org-export-html-with-timestamp nil
2523 "If non-nil, write `org-export-html-html-helper-timestamp'
2524 into the exported HTML text. Otherwise, the buffer will just be saved
2525 to a file."
2526 :group 'org-export-html
2527 :type 'boolean)
2529 (defcustom org-export-html-html-helper-timestamp
2530 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2531 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2532 :group 'org-export-html
2533 :type 'string)
2535 (defcustom org-export-html-show-new-buffer nil
2536 "Non-nil means, popup buffer containing the exported html text.
2537 Otherwise, the buffer will just be saved to a file and stay hidden."
2538 :group 'org-export-html
2539 :type 'boolean)
2541 (defgroup org-export-icalendar nil
2542 "Options specific for iCalendar export of Org-mode files."
2543 :tag "Org Export iCalendar"
2544 :group 'org-export)
2546 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2547 "The file name for the iCalendar file covering all agenda files.
2548 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2549 The file name should be absolute."
2550 :group 'org-export-icalendar
2551 :type 'file)
2553 (defcustom org-icalendar-include-todo nil
2554 "Non-nil means, export to iCalendar files should also cover TODO items."
2555 :group 'org-export-icalendar
2556 :type 'boolean)
2558 (defcustom org-icalendar-combined-name "OrgMode"
2559 "Calendar name for the combined iCalendar representing all agenda files."
2560 :group 'org-export-icalendar
2561 :type 'string)
2563 (defgroup org-font-lock nil
2564 "Font-lock settings for highlighting in Org-mode."
2565 :tag "Org Font Lock"
2566 :group 'org)
2568 (defcustom org-level-color-stars-only nil
2569 "Non-nil means fontify only the stars in each headline.
2570 When nil, the entire headline is fontified.
2571 Changing it requires restart of `font-lock-mode' to become effective
2572 also in regions already fontified."
2573 :group 'org-font-lock
2574 :type 'boolean)
2576 (defcustom org-hide-leading-stars nil
2577 "Non-nil means, hide the first N-1 stars in a headline.
2578 This works by using the face `org-hide' for these stars. This
2579 face is white for a light background, and black for a dark
2580 background. You may have to customize the face `org-hide' to
2581 make this work.
2582 Changing it requires restart of `font-lock-mode' to become effective
2583 also in regions already fontified.
2584 You may also set this on a per-file basis by adding one of the following
2585 lines to the buffer:
2587 #+STARTUP: hidestars
2588 #+STARTUP: showstars"
2589 :group 'org-font-lock
2590 :type 'boolean)
2592 (defcustom org-fontify-done-headline nil
2593 "Non-nil means, change the face of a headline if it is marked DONE.
2594 Normally, only the TODO/DONE keyword indicates the state of a headline.
2595 When this is non-nil, the headline after the keyword is set to the
2596 `org-headline-done' as an additional indication."
2597 :group 'org-font-lock
2598 :type 'boolean)
2600 (defcustom org-fontify-emphasized-text t
2601 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2602 Changing this variable requires a restart of Emacs to take effect."
2603 :group 'org-font-lock
2604 :type 'boolean)
2606 (defvar org-emph-re nil
2607 "Regular expression for matching emphasis.")
2608 (defvar org-emphasis-regexp-components) ; defined just below
2609 (defvar org-emphasis-alist) ; defined just below
2610 (defun org-set-emph-re (var val)
2611 "Set variable and compute the emphasis regular expression."
2612 (set var val)
2613 (when (and (boundp 'org-emphasis-alist)
2614 (boundp 'org-emphasis-regexp-components)
2615 org-emphasis-alist org-emphasis-regexp-components)
2616 (let* ((e org-emphasis-regexp-components)
2617 (pre (car e))
2618 (post (nth 1 e))
2619 (border (nth 2 e))
2620 (body (nth 3 e))
2621 (nl (nth 4 e))
2622 (stacked (nth 5 e))
2623 (body1 (concat body "*?"))
2624 (markers (mapconcat 'car org-emphasis-alist "")))
2625 ;; make sure special characters appear at the right position in the class
2626 (if (string-match "\\^" markers)
2627 (setq markers (concat (replace-match "" t t markers) "^")))
2628 (if (string-match "-" markers)
2629 (setq markers (concat (replace-match "" t t markers) "-")))
2630 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2631 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2632 (if (> nl 0)
2633 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2634 (int-to-string nl) "\\}")))
2635 ;; Make the regexp
2636 (setq org-emph-re
2637 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2638 "\\("
2639 "\\([" markers "]\\)"
2640 "\\("
2641 "[^" border markers "]"
2642 body1
2643 "[^" border markers "]"
2644 "\\)"
2645 "\\3\\)"
2646 "\\([" post (if stacked markers) "]\\|$\\)")))))
2648 (defcustom org-emphasis-regexp-components
2649 '(" \t('\"" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2650 "Components used to build the reqular expression for emphasis.
2651 This is a list with 6 entries. Terminology: In an emphasis string
2652 like \" *strong word* \", we call the initial space PREMATCH, the final
2653 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2654 and \"trong wor\" is the body. The different components in this variable
2655 specify what is allowed/forbidden in each part:
2657 pre Chars allowed as prematch. Beginning of line will be allowed too.
2658 post Chars allowed as postmatch. End of line will be allowed too.
2659 border The chars *forbidden* as border characters. In addition to the
2660 characters given here, all marker characters are forbidden too.
2661 body-regexp A regexp like \".\" to match a body character. Don't use
2662 non-shy groups here, and don't allow newline here.
2663 newline The maximum number of newlines allowed in an emphasis exp.
2664 stacked Non-nil means, allow stacked styles. This works only in HTML
2665 export. When this is set, all marker characters (as given in
2666 `org-emphasis-alist') will be allowed as pre/post, aiding
2667 inside-out matching.
2668 Use customize to modify this, or restart Emacs after changing it."
2669 :group 'org-font-lock
2670 :set 'org-set-emph-re
2671 :type '(list
2672 (sexp :tag "Allowed chars in pre ")
2673 (sexp :tag "Allowed chars in post ")
2674 (sexp :tag "Forbidden chars in border ")
2675 (sexp :tag "Regexp for body ")
2676 (integer :tag "number of newlines allowed")
2677 (boolean :tag "Stacking allowed ")))
2679 (defcustom org-emphasis-alist
2680 '(("*" bold "<b>" "</b>")
2681 ("/" italic "<i>" "</i>")
2682 ("_" underline "<u>" "</u>")
2683 ("=" shadow "<code>" "</code>")
2684 ("+" (:strike-through t) "<del>" "</del>")
2686 "Special syntax for emphasized text.
2687 Text starting and ending with a special character will be emphasized, for
2688 example *bold*, _underlined_ and /italic/. This variable sets the marker
2689 characters, the face to bbe used by font-lock for highlighting in Org-mode
2690 Emacs buffers, and the HTML tags to be used for this.
2691 Use customize to modify this, or restart Emacs after changing it."
2692 :group 'org-font-lock
2693 :set 'org-set-emph-re
2694 :type '(repeat
2695 (list
2696 (string :tag "Marker character")
2697 (choice
2698 (face :tag "Font-lock-face")
2699 (plist :tag "Face property list"))
2700 (string :tag "HTML start tag")
2701 (string :tag "HTML end tag"))))
2703 ;;; The faces
2705 (defgroup org-faces nil
2706 "Faces in Org-mode."
2707 :tag "Org Faces"
2708 :group 'org-font-lock)
2710 (defun org-compatible-face (specs)
2711 "Make a compatible face specification.
2712 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2713 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2714 to the top of the list. The `min-colors' attribute will be removed from
2715 any other entries, and any resulting duplicates will be removed entirely."
2716 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2717 (let (r e a)
2718 (while (setq e (pop specs))
2719 (cond
2720 ((memq (car e) '(t default)) (push e r))
2721 ((setq a (member '(min-colors 8) (car e)))
2722 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2723 (cdr e)))))
2724 ((setq a (assq 'min-colors (car e)))
2725 (setq e (cons (delq a (car e)) (cdr e)))
2726 (or (assoc (car e) r) (push e r)))
2727 (t (or (assoc (car e) r) (push e r)))))
2728 (nreverse r))
2729 specs))
2731 (defface org-hide
2732 '((((background light)) (:foreground "white"))
2733 (((background dark)) (:foreground "black")))
2734 "Face used to hide leading stars in headlines.
2735 The forground color of this face should be equal to the background
2736 color of the frame."
2737 :group 'org-faces)
2739 (defface org-level-1 ;; font-lock-function-name-face
2740 (org-compatible-face
2741 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2742 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2743 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2744 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2745 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2746 (t (:bold t))))
2747 "Face used for level 1 headlines."
2748 :group 'org-faces)
2750 (defface org-level-2 ;; font-lock-variable-name-face
2751 (org-compatible-face
2752 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2753 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2754 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2755 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2756 (t (:bold t))))
2757 "Face used for level 2 headlines."
2758 :group 'org-faces)
2760 (defface org-level-3 ;; font-lock-keyword-face
2761 (org-compatible-face
2762 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2763 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2764 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2765 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2766 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2767 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2768 (t (:bold t))))
2769 "Face used for level 3 headlines."
2770 :group 'org-faces)
2772 (defface org-level-4 ;; font-lock-comment-face
2773 (org-compatible-face
2774 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2775 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2776 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2777 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2778 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2779 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2780 (t (:bold t))))
2781 "Face used for level 4 headlines."
2782 :group 'org-faces)
2784 (defface org-level-5 ;; font-lock-type-face
2785 (org-compatible-face
2786 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2787 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2788 (((class color) (min-colors 8)) (:foreground "green"))))
2789 "Face used for level 5 headlines."
2790 :group 'org-faces)
2792 (defface org-level-6 ;; font-lock-constant-face
2793 (org-compatible-face
2794 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2795 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2796 (((class color) (min-colors 8)) (:foreground "magenta"))))
2797 "Face used for level 6 headlines."
2798 :group 'org-faces)
2800 (defface org-level-7 ;; font-lock-builtin-face
2801 (org-compatible-face
2802 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2803 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2804 (((class color) (min-colors 8)) (:foreground "blue"))))
2805 "Face used for level 7 headlines."
2806 :group 'org-faces)
2808 (defface org-level-8 ;; font-lock-string-face
2809 (org-compatible-face
2810 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2811 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2812 (((class color) (min-colors 8)) (:foreground "green"))))
2813 "Face used for level 8 headlines."
2814 :group 'org-faces)
2816 (defface org-special-keyword ;; font-lock-string-face
2817 (org-compatible-face
2818 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2819 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2820 (t (:italic t))))
2821 "Face used for special keywords."
2822 :group 'org-faces)
2824 (defface org-warning ;; font-lock-warning-face
2825 (org-compatible-face
2826 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2827 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2828 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2829 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2830 (t (:bold t))))
2831 "Face for deadlines and TODO keywords."
2832 :group 'org-faces)
2834 (defface org-headline-done ;; font-lock-string-face
2835 (org-compatible-face
2836 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2837 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2838 (((class color) (min-colors 8) (background light)) (:bold nil))))
2839 "Face used to indicate that a headline is DONE.
2840 This face is only used if `org-fontify-done-headline' is set."
2841 :group 'org-faces)
2843 (defface org-archived ; similar to shadow
2844 (org-compatible-face
2845 '((((class color grayscale) (min-colors 88) (background light))
2846 (:foreground "grey50"))
2847 (((class color grayscale) (min-colors 88) (background dark))
2848 (:foreground "grey70"))
2849 (((class color) (min-colors 8) (background light))
2850 (:foreground "green"))
2851 (((class color) (min-colors 8) (background dark))
2852 (:foreground "yellow"))))
2853 "Face for headline with the ARCHIVE tag."
2854 :group 'org-faces)
2856 (defface org-link
2857 '((((class color) (background light)) (:foreground "Purple" :underline t))
2858 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2859 (t (:underline t)))
2860 "Face for links."
2861 :group 'org-faces)
2863 (defface org-date
2864 '((((class color) (background light)) (:foreground "Purple" :underline t))
2865 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2866 (t (:underline t)))
2867 "Face for links."
2868 :group 'org-faces)
2870 (defface org-tag
2871 '((t (:bold t)))
2872 "Face for tags."
2873 :group 'org-faces)
2875 (defface org-todo ;; font-lock-warning-face
2876 (org-compatible-face
2877 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2878 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2879 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2880 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2881 (t (:inverse-video t :bold t))))
2882 "Face for TODO keywords."
2883 :group 'org-faces)
2885 (defface org-done ;; font-lock-type-face
2886 (org-compatible-face
2887 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2888 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2889 (((class color) (min-colors 8)) (:foreground "green"))
2890 (t (:bold t))))
2891 "Face used for DONE."
2892 :group 'org-faces)
2894 (defface org-table ;; font-lock-function-name-face
2895 (org-compatible-face
2896 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2897 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2898 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2899 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2900 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2901 (((class color) (min-colors 8) (background dark)))))
2902 "Face used for tables."
2903 :group 'org-faces)
2905 (defface org-formula
2906 (org-compatible-face
2907 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2908 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2909 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2910 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2911 (t (:bold t :italic t))))
2912 "Face for formulas."
2913 :group 'org-faces)
2915 (defface org-scheduled-today
2916 (org-compatible-face
2917 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2918 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2919 (((class color) (min-colors 8)) (:foreground "green"))
2920 (t (:bold t :italic t))))
2921 "Face for items scheduled for a certain day."
2922 :group 'org-faces)
2924 (defface org-scheduled-previously
2925 (org-compatible-face
2926 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2927 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2928 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2929 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2930 (t (:bold t))))
2931 "Face for items scheduled previously, and not yet done."
2932 :group 'org-faces)
2934 (defface org-upcoming-deadline
2935 (org-compatible-face
2936 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2937 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2938 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2939 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2940 (t (:bold t))))
2941 "Face for items scheduled previously, and not yet done."
2942 :group 'org-faces)
2944 (defface org-time-grid ;; font-lock-variable-name-face
2945 (org-compatible-face
2946 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2947 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2948 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2949 "Face used for time grids."
2950 :group 'org-faces)
2952 (defconst org-level-faces
2953 '(org-level-1 org-level-2 org-level-3 org-level-4
2954 org-level-5 org-level-6 org-level-7 org-level-8
2956 (defconst org-n-levels (length org-level-faces))
2959 ;;; Variables for pre-computed regular expressions, all buffer local
2961 (defvar org-done-string nil
2962 "The last string in `org-todo-keywords', indicating an item is DONE.")
2963 (make-variable-buffer-local 'org-done-string)
2964 (defvar org-todo-regexp nil
2965 "Matches any of the TODO state keywords.")
2966 (make-variable-buffer-local 'org-todo-regexp)
2967 (defvar org-not-done-regexp nil
2968 "Matches any of the TODO state keywords except the last one.")
2969 (make-variable-buffer-local 'org-not-done-regexp)
2970 (defvar org-todo-line-regexp nil
2971 "Matches a headline and puts TODO state into group 2 if present.")
2972 (make-variable-buffer-local 'org-todo-line-regexp)
2973 (defvar org-todo-line-tags-regexp nil
2974 "Matches a headline and puts TODO state into group 2 if present.
2975 Also put tags into group 4 if tags are present.")
2976 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2977 (defvar org-nl-done-regexp nil
2978 "Matches newline followed by a headline with the DONE keyword.")
2979 (make-variable-buffer-local 'org-nl-done-regexp)
2980 (defvar org-looking-at-done-regexp nil
2981 "Matches the DONE keyword a point.")
2982 (make-variable-buffer-local 'org-looking-at-done-regexp)
2983 (defvar org-todo-kwd-priority-p nil
2984 "Do TODO items have priorities?")
2985 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2986 (defvar org-todo-kwd-max-priority nil
2987 "Maximum priority of TODO items.")
2988 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2989 (defvar org-ds-keyword-length 12
2990 "Maximum length of the Deadline and SCHEDULED keywords.")
2991 (make-variable-buffer-local 'org-ds-keyword-length)
2992 (defvar org-deadline-regexp nil
2993 "Matches the DEADLINE keyword.")
2994 (make-variable-buffer-local 'org-deadline-regexp)
2995 (defvar org-deadline-time-regexp nil
2996 "Matches the DEADLINE keyword together with a time stamp.")
2997 (make-variable-buffer-local 'org-deadline-time-regexp)
2998 (defvar org-deadline-line-regexp nil
2999 "Matches the DEADLINE keyword and the rest of the line.")
3000 (make-variable-buffer-local 'org-deadline-line-regexp)
3001 (defvar org-scheduled-regexp nil
3002 "Matches the SCHEDULED keyword.")
3003 (make-variable-buffer-local 'org-scheduled-regexp)
3004 (defvar org-scheduled-time-regexp nil
3005 "Matches the SCHEDULED keyword together with a time stamp.")
3006 (make-variable-buffer-local 'org-scheduled-time-regexp)
3007 (defvar org-closed-time-regexp nil
3008 "Matches the CLOSED keyword together with a time stamp.")
3009 (make-variable-buffer-local 'org-closed-time-regexp)
3011 (defvar org-keyword-time-regexp nil
3012 "Matches any of the 3 keywords, together with the time stamp.")
3013 (make-variable-buffer-local 'org-keyword-time-regexp)
3014 (defvar org-maybe-keyword-time-regexp nil
3015 "Matches a timestamp, possibly preceeded by a keyword.")
3016 (make-variable-buffer-local 'org-keyword-time-regexp)
3018 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3019 rear-nonsticky t mouse-map t)
3020 "Properties to remove when a string without properties is wanted.")
3022 (defsubst org-match-string-no-properties (num &optional string)
3023 (if (featurep 'xemacs)
3024 (let ((s (match-string num string)))
3025 (remove-text-properties 0 (length s) org-rm-props s)
3027 (match-string-no-properties num string)))
3029 (defsubst org-no-properties (s)
3030 (remove-text-properties 0 (length s) org-rm-props s)
3033 (defsubst org-get-alist-option (option key)
3034 (cond ((eq key t) t)
3035 ((eq option t) t)
3036 ((assoc key option) (cdr (assoc key option)))
3037 (t (cdr (assq 'default option)))))
3039 (defsubst org-set-local (var value)
3040 "Make VAR local in current buffer and set it to VALUE."
3041 (set (make-variable-buffer-local var) value))
3043 (defsubst org-mode-p ()
3044 "Check if the current buffer is in Org-mode."
3045 (eq major-mode 'org-mode))
3047 (defsubst org-last (list)
3048 "Return the last element of LIST."
3049 (car (last list)))
3051 (defun org-let (list &rest body)
3052 (eval (cons 'let (cons list body))))
3053 (put 'org-let 'lisp-indent-function 1)
3055 (defun org-let2 (list1 list2 &rest body)
3056 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3057 (put 'org-let2 'lisp-indent-function 2)
3059 (defconst org-startup-options
3060 '(("fold" org-startup-folded t)
3061 ("overview" org-startup-folded t)
3062 ("nofold" org-startup-folded nil)
3063 ("showall" org-startup-folded nil)
3064 ("content" org-startup-folded content)
3065 ("hidestars" org-hide-leading-stars t)
3066 ("showstars" org-hide-leading-stars nil)
3067 ("odd" org-odd-levels-only t)
3068 ("oddeven" org-odd-levels-only nil)
3069 ("align" org-startup-align-all-tables t)
3070 ("noalign" org-startup-align-all-tables nil)
3071 ("customtime" org-display-custom-times t)
3072 ("logging" org-log-done t)
3073 ("nologging" org-log-done nil)
3074 ("dlcheck" org-startup-with-deadline-check t)
3075 ("nodlcheck" org-startup-with-deadline-check nil)))
3077 (defun org-set-regexps-and-options ()
3078 "Precompute regular expressions for current buffer."
3079 (when (org-mode-p)
3080 (let ((re (org-make-options-regexp
3081 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
3082 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
3083 (splitre "[ \t]+")
3084 kwds int key value cat arch tags links)
3085 (save-excursion
3086 (save-restriction
3087 (widen)
3088 (goto-char (point-min))
3089 (while (re-search-forward re nil t)
3090 (setq key (match-string 1) value (org-match-string-no-properties 2))
3091 (cond
3092 ((equal key "CATEGORY")
3093 (if (string-match "[ \t]+$" value)
3094 (setq value (replace-match "" t t value)))
3095 (setq cat (intern value)))
3096 ((equal key "SEQ_TODO")
3097 (setq int 'sequence
3098 kwds (append kwds (org-split-string value splitre))))
3099 ((equal key "PRI_TODO")
3100 (setq int 'priority
3101 kwds (append kwds (org-split-string value splitre))))
3102 ((equal key "TYP_TODO")
3103 (setq int 'type
3104 kwds (append kwds (org-split-string value splitre))))
3105 ((equal key "TAGS")
3106 (setq tags (append tags (org-split-string value splitre))))
3107 ((equal key "LINK")
3108 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3109 (push (cons (match-string 1 value)
3110 (org-trim (match-string 2 value)))
3111 links)))
3112 ((equal key "STARTUP")
3113 (let ((opts (org-split-string value splitre))
3114 l var val)
3115 (while (setq l (assoc (pop opts) org-startup-options))
3116 (setq var (nth 1 l) val (nth 2 l))
3117 (set (make-local-variable var) val))))
3118 ((equal key "ARCHIVE")
3119 (string-match " *$" value)
3120 (setq arch (replace-match "" t t value))
3121 (remove-text-properties 0 (length arch)
3122 '(face t fontified t) arch)))
3124 (and cat (org-set-local 'org-category cat))
3125 (and kwds (org-set-local 'org-todo-keywords kwds))
3126 (and arch (org-set-local 'org-archive-location arch))
3127 (and int (org-set-local 'org-todo-interpretation int))
3128 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3129 (when tags
3130 (let (e tgs)
3131 (while (setq e (pop tags))
3132 (cond
3133 ((equal e "{") (push '(:startgroup) tgs))
3134 ((equal e "}") (push '(:endgroup) tgs))
3135 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3136 (push (cons (match-string 1 e)
3137 (string-to-char (match-string 2 e)))
3138 tgs))
3139 (t (push (list e) tgs))))
3140 (org-set-local 'org-tag-alist nil)
3141 (while (setq e (pop tgs))
3142 (or (and (stringp (car e))
3143 (assoc (car e) org-tag-alist))
3144 (push e org-tag-alist))))))
3146 ;; Compute the regular expressions and other local variables
3147 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
3148 org-todo-kwd-max-priority (1- (length org-todo-keywords))
3149 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3150 (length org-scheduled-string)))
3151 org-done-string
3152 (nth (1- (length org-todo-keywords)) org-todo-keywords)
3153 org-todo-regexp
3154 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
3155 "\\|") "\\)\\>")
3156 org-not-done-regexp
3157 (concat "\\<\\("
3158 (mapconcat 'regexp-quote
3159 (nreverse (cdr (reverse org-todo-keywords)))
3160 "\\|")
3161 "\\)\\>")
3162 org-todo-line-regexp
3163 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3164 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3165 "\\)\\>\\)? *\\(.*\\)")
3166 org-nl-done-regexp
3167 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
3168 org-todo-line-tags-regexp
3169 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3170 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3171 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3172 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
3173 org-deadline-regexp (concat "\\<" org-deadline-string)
3174 org-deadline-time-regexp
3175 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3176 org-deadline-line-regexp
3177 (concat "\\<\\(" org-deadline-string "\\).*")
3178 org-scheduled-regexp
3179 (concat "\\<" org-scheduled-string)
3180 org-scheduled-time-regexp
3181 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3182 org-closed-time-regexp
3183 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3184 org-keyword-time-regexp
3185 (concat "\\<\\(" org-scheduled-string
3186 "\\|" org-deadline-string
3187 "\\|" org-closed-string
3188 "\\|" org-clock-string "\\)"
3189 " *[[<]\\([^]>]+\\)[]>]")
3190 org-maybe-keyword-time-regexp
3191 (concat "\\(\\<\\(" org-scheduled-string
3192 "\\|" org-deadline-string
3193 "\\|" org-closed-string
3194 "\\|" org-clock-string "\\)\\)?"
3195 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3197 (org-set-font-lock-defaults)))
3200 ;;; Some variables ujsed in various places
3202 (defvar org-window-configuration nil
3203 "Used in various places to store a window configuration.")
3204 (defvar org-finish-function nil
3205 "Function to be called when `C-c C-c' is used.
3206 This is for getting out of special buffers like remember.")
3208 ;;; Foreign variables, to inform the compiler
3210 ;; XEmacs only
3211 (defvar outline-mode-menu-heading)
3212 (defvar outline-mode-menu-show)
3213 (defvar outline-mode-menu-hide)
3214 (defvar zmacs-regions) ; XEmacs regions
3215 ;; Emacs only
3216 (defvar mark-active)
3218 ;; Packages that org-mode interacts with
3219 (defvar calc-embedded-close-formula)
3220 (defvar calc-embedded-open-formula)
3221 (defvar font-lock-unfontify-region-function)
3222 (defvar org-goto-start-pos)
3223 (defvar vm-message-pointer)
3224 (defvar vm-folder-directory)
3225 (defvar wl-summary-buffer-elmo-folder)
3226 (defvar wl-summary-buffer-folder-name)
3227 (defvar gnus-other-frame-object)
3228 (defvar gnus-group-name)
3229 (defvar gnus-article-current)
3230 (defvar w3m-current-url)
3231 (defvar w3m-current-title)
3232 (defvar mh-progs)
3233 (defvar mh-current-folder)
3234 (defvar mh-show-folder-buffer)
3235 (defvar mh-index-folder)
3236 (defvar mh-searcher)
3237 (defvar calendar-mode-map)
3238 (defvar Info-current-file)
3239 (defvar Info-current-node)
3240 (defvar texmathp-why)
3241 (defvar remember-save-after-remembering)
3242 (defvar remember-data-file)
3243 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3244 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3245 (defvar org-latex-regexps)
3247 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3249 ;; FIXME: Occasionally check by commenting these, to make sure
3250 ;; no other functions uses these, forgetting to let-bind them.
3251 (defvar entry)
3252 (defvar state)
3253 (defvar date)
3254 (defvar description)
3257 ;; Defined somewhere in this file, but used before definition.
3258 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3259 (defvar org-agenda-undo-list)
3260 (defvar org-agenda-pending-undo-list)
3261 (defvar org-agenda-overriding-header)
3262 (defvar orgtbl-mode)
3263 (defvar org-html-entities)
3264 (defvar org-struct-menu)
3265 (defvar org-org-menu)
3266 (defvar org-tbl-menu)
3267 (defvar org-agenda-keymap)
3268 (defvar org-category-table)
3270 ;;;; Emacs/XEmacs compatibility
3272 ;; Overlay compatibility functions
3273 (defun org-make-overlay (beg end &optional buffer)
3274 (if (featurep 'xemacs)
3275 (make-extent beg end buffer)
3276 (make-overlay beg end buffer)))
3277 (defun org-delete-overlay (ovl)
3278 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3279 (defun org-detach-overlay (ovl)
3280 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3281 (defun org-move-overlay (ovl beg end &optional buffer)
3282 (if (featurep 'xemacs)
3283 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3284 (move-overlay ovl beg end buffer)))
3285 (defun org-overlay-put (ovl prop value)
3286 (if (featurep 'xemacs)
3287 (set-extent-property ovl prop value)
3288 (overlay-put ovl prop value)))
3289 (defun org-overlay-display (ovl text &optional face)
3290 "Make overlay OVL display TEXT with face FACE."
3291 (if (featurep 'xemacs)
3292 (let ((gl (make-glyph text)))
3293 (and face (set-glyph-face gl face))
3294 (set-extent-property ovl 'invisible t)
3295 (set-extent-property ovl 'end-glyph gl))
3296 (overlay-put ovl 'display text)
3297 (if face (overlay-put ovl 'face face))))
3298 (defun org-overlay-get (ovl prop)
3299 (if (featurep 'xemacs)
3300 (extent-property ovl prop)
3301 (overlay-get ovl prop)))
3302 (defun org-overlays-at (pos)
3303 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
3304 (defun org-overlays-in (&optional start end)
3305 (if (featurep 'xemacs)
3306 (extent-list nil start end)
3307 (overlays-in start end)))
3308 (defun org-overlay-start (o)
3309 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
3310 (defun org-overlay-end (o)
3311 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
3312 (defun org-find-overlays (prop &optional pos delete)
3313 "Find all overlays specifying PROP at POS or point.
3314 If DELETE is non-nil, delete all those overlays."
3315 (let ((overlays (org-overlays-at (or pos (point))))
3316 ov found)
3317 (while (setq ov (pop overlays))
3318 (if (org-overlay-get ov prop)
3319 (if delete (org-delete-overlay ov) (push ov found))))
3320 found))
3322 ;; Region compatibility
3324 (defun org-add-hook (hook function &optional append local)
3325 "Add-hook, compatible with both Emacsen."
3326 (if (and local (featurep 'xemacs))
3327 (add-local-hook hook function append)
3328 (add-hook hook function append local)))
3330 (defvar org-ignore-region nil
3331 "To temporarily disable the active region.")
3333 (defun org-region-active-p ()
3334 "Is `transient-mark-mode' on and the region active?
3335 Works on both Emacs and XEmacs."
3336 (if org-ignore-region
3338 (if (featurep 'xemacs)
3339 (and zmacs-regions (region-active-p))
3340 (and transient-mark-mode mark-active))))
3342 ;; Invisibility compatibility
3344 (defun org-add-to-invisibility-spec (arg)
3345 "Add elements to `buffer-invisibility-spec'.
3346 See documentation for `buffer-invisibility-spec' for the kind of elements
3347 that can be added."
3348 (cond
3349 ((fboundp 'add-to-invisibility-spec)
3350 (add-to-invisibility-spec arg))
3351 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
3352 (setq buffer-invisibility-spec (list arg)))
3354 (setq buffer-invisibility-spec
3355 (cons arg buffer-invisibility-spec)))))
3357 (defun org-remove-from-invisibility-spec (arg)
3358 "Remove elements from `buffer-invisibility-spec'."
3359 (if (fboundp 'remove-from-invisibility-spec)
3360 (remove-from-invisibility-spec arg)
3361 (if (consp buffer-invisibility-spec)
3362 (setq buffer-invisibility-spec
3363 (delete arg buffer-invisibility-spec)))))
3365 (defun org-in-invisibility-spec-p (arg)
3366 "Is ARG a member of `buffer-invisibility-spec'?"
3367 (if (consp buffer-invisibility-spec)
3368 (member arg buffer-invisibility-spec)
3369 nil))
3371 ;;;; Define the Org-mode
3373 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3374 (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."))
3377 ;; We use a before-change function to check if a table might need
3378 ;; an update.
3379 (defvar org-table-may-need-update t
3380 "Indicates that a table might need an update.
3381 This variable is set by `org-before-change-function'.
3382 `org-table-align' sets it back to nil.")
3383 (defvar org-mode-map)
3384 (defvar org-mode-hook nil)
3385 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3386 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3389 ;;;###autoload
3390 (define-derived-mode org-mode outline-mode "Org"
3391 "Outline-based notes management and organizer, alias
3392 \"Carsten's outline-mode for keeping track of everything.\"
3394 Org-mode develops organizational tasks around a NOTES file which
3395 contains information about projects as plain text. Org-mode is
3396 implemented on top of outline-mode, which is ideal to keep the content
3397 of large files well structured. It supports ToDo items, deadlines and
3398 time stamps, which magically appear in the diary listing of the Emacs
3399 calendar. Tables are easily created with a built-in table editor.
3400 Plain text URL-like links connect to websites, emails (VM), Usenet
3401 messages (Gnus), BBDB entries, and any files related to the project.
3402 For printing and sharing of notes, an Org-mode file (or a part of it)
3403 can be exported as a structured ASCII or HTML file.
3405 The following commands are available:
3407 \\{org-mode-map}"
3409 ;; Get rid of Outline menus, they are not needed
3410 ;; Need to do this here because define-derived-mode sets up
3411 ;; the keymap so late. Still, it is a waste to call this each time
3412 ;; we switch another buffer into org-mode.
3413 (if (featurep 'xemacs)
3414 (when (boundp 'outline-mode-menu-heading)
3415 ;; Assume this is Greg's port, it used easymenu
3416 (easy-menu-remove outline-mode-menu-heading)
3417 (easy-menu-remove outline-mode-menu-show)
3418 (easy-menu-remove outline-mode-menu-hide))
3419 (define-key org-mode-map [menu-bar headings] 'undefined)
3420 (define-key org-mode-map [menu-bar hide] 'undefined)
3421 (define-key org-mode-map [menu-bar show] 'undefined))
3423 (easy-menu-add org-org-menu)
3424 (easy-menu-add org-tbl-menu)
3425 (org-install-agenda-files-menu)
3426 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3427 (org-add-to-invisibility-spec '(org-cwidth))
3428 (when (featurep 'xemacs)
3429 (org-set-local 'line-move-ignore-invisible t))
3430 (setq outline-regexp "\\*+")
3431 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
3432 (setq outline-level 'org-outline-level)
3433 (when (and org-ellipsis (stringp org-ellipsis))
3434 (unless org-display-table
3435 (setq org-display-table (make-display-table)))
3436 (set-display-table-slot org-display-table
3437 4 (string-to-vector org-ellipsis))
3438 (setq buffer-display-table org-display-table))
3439 (org-set-regexps-and-options)
3440 ;; Calc embedded
3441 (org-set-local 'calc-embedded-open-mode "# ")
3442 (modify-syntax-entry ?# "<")
3443 (if org-startup-truncated (setq truncate-lines t))
3444 (org-set-local 'font-lock-unfontify-region-function
3445 'org-unfontify-region)
3446 ;; Activate before-change-function
3447 (org-set-local 'org-table-may-need-update t)
3448 (org-add-hook 'before-change-functions 'org-before-change-function nil
3449 'local)
3450 ;; Check for running clock before killing a buffer
3451 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3452 ;; Paragraphs and auto-filling
3453 (org-set-autofill-regexps)
3454 (org-update-radio-target-regexp)
3456 (if (and org-insert-mode-line-in-empty-file
3457 (interactive-p)
3458 (= (point-min) (point-max)))
3459 (insert " -*- mode: org -*-\n\n"))
3461 (unless org-inhibit-startup
3462 (when org-startup-align-all-tables
3463 (let ((bmp (buffer-modified-p)))
3464 (org-table-map-tables 'org-table-align)
3465 (set-buffer-modified-p bmp)))
3466 (if org-startup-with-deadline-check
3467 (call-interactively 'org-check-deadlines)
3468 (cond
3469 ((eq org-startup-folded t)
3470 (org-cycle '(4)))
3471 ((eq org-startup-folded 'content)
3472 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3473 (org-cycle '(4)) (org-cycle '(4))))))))
3475 (defsubst org-call-with-arg (command arg)
3476 "Call COMMAND interactively, but pretend prefix are was ARG."
3477 (let ((current-prefix-arg arg)) (call-interactively command)))
3479 (defsubst org-current-line (&optional pos)
3480 (save-excursion
3481 (and pos (goto-char pos))
3482 (+ (if (bolp) 1 0) (count-lines (point-min) (point)))))
3484 (defun org-current-time ()
3485 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3486 (if (> org-time-stamp-rounding-minutes 0)
3487 (let ((r org-time-stamp-rounding-minutes)
3488 (time (decode-time)))
3489 (apply 'encode-time
3490 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3491 (nthcdr 2 time))))
3492 (current-time)))
3494 (defun org-add-props (string plist &rest props)
3495 "Add text properties to entire string, from beginning to end.
3496 PLIST may be a list of properties, PROPS are individual properties and values
3497 that will be added to PLIST. Returns the string that was modified."
3498 (add-text-properties
3499 0 (length string) (if props (append plist props) plist) string)
3500 string)
3501 (put 'org-add-props 'lisp-indent-function 2)
3504 ;;;; Font-Lock stuff, including the activators
3506 (defvar org-mouse-map (make-sparse-keymap))
3507 (define-key org-mouse-map
3508 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3509 (define-key org-mouse-map
3510 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3511 (when org-mouse-1-follows-link
3512 (define-key org-mouse-map [follow-link] 'mouse-face))
3513 (when org-tab-follows-link
3514 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3515 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3516 (when org-return-follows-link
3517 (define-key org-mouse-map [(return)] 'org-open-at-point)
3518 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3520 (require 'font-lock)
3522 (defconst org-non-link-chars "]\t\n\r<>")
3523 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3524 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3525 (defconst org-link-re-with-space
3526 (concat
3527 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3528 "\\([^" org-non-link-chars " ]"
3529 "[^" org-non-link-chars "]*"
3530 "[^" org-non-link-chars " ]\\)>?")
3531 "Matches a link with spaces, optional angular brackets around it.")
3533 (defconst org-link-re-with-space2
3534 (concat
3535 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3536 "\\([^" org-non-link-chars " ]"
3537 "[^]\t\n\r]*"
3538 "[^" org-non-link-chars " ]\\)>?")
3539 "Matches a link with spaces, optional angular brackets around it.")
3541 (defconst org-angle-link-re
3542 (concat
3543 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3544 "\\([^" org-non-link-chars " ]"
3545 "[^" org-non-link-chars "]*"
3546 "\\)>")
3547 "Matches link with angular brackets, spaces are allowed.")
3548 (defconst org-plain-link-re
3549 (concat
3550 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3551 "\\([^]\t\n\r<>,;() ]+\\)")
3552 "Matches plain link, without spaces.")
3554 (defconst org-bracket-link-regexp
3555 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3556 "Matches a link in double brackets.")
3558 (defconst org-bracket-link-analytic-regexp
3559 (concat
3560 "\\[\\["
3561 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3562 "\\([^]]+\\)"
3563 "\\]"
3564 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3565 "\\]"))
3566 ; 1: http:
3567 ; 2: http
3568 ; 3: path
3569 ; 4: [desc]
3570 ; 5: desc
3572 (defconst org-ts-lengths
3573 (cons (length (format-time-string (car org-time-stamp-formats)))
3574 (length (format-time-string (cdr org-time-stamp-formats))))
3575 "This holds the lengths of the two different time formats.")
3576 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3577 "Regular expression for fast time stamp matching.")
3578 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3579 "Regular expression for fast time stamp matching.")
3580 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3581 "Regular expression matching time strings for analysis.")
3582 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3583 "Regular expression matching time stamps, with groups.")
3584 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3585 "Regular expression matching time stamps (also [..]), with groups.")
3586 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3587 "Regular expression matching a time stamp range.")
3588 (defconst org-tr-regexp-both
3589 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3590 "Regular expression matching a time stamp range.")
3591 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3592 org-ts-regexp "\\)?")
3593 "Regular expression matching a time stamp or time stamp range.")
3594 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3595 org-ts-regexp-both "\\)?")
3596 "Regular expression matching a time stamp or time stamp range.
3597 The time stamps may be either active or inactive.")
3599 (defvar org-emph-face nil)
3601 (defun org-do-emphasis-faces (limit)
3602 "Run through the buffer and add overlays to links."
3603 (if (re-search-forward org-emph-re limit t)
3604 (progn
3605 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3606 'face
3607 (nth 1 (assoc (match-string 3)
3608 org-emphasis-alist)))
3609 (add-text-properties (match-beginning 2) (match-end 2)
3610 '(font-lock-multiline t))
3611 (backward-char 1)
3612 t)))
3614 (defun org-activate-plain-links (limit)
3615 "Run through the buffer and add overlays to links."
3616 (if (re-search-forward org-plain-link-re limit t)
3617 (progn
3618 (add-text-properties (match-beginning 0) (match-end 0)
3619 (list 'mouse-face 'highlight
3620 'rear-nonsticky t
3621 'keymap org-mouse-map
3623 t)))
3625 (defun org-activate-angle-links (limit)
3626 "Run through the buffer and add overlays to links."
3627 (if (re-search-forward org-angle-link-re limit t)
3628 (progn
3629 (add-text-properties (match-beginning 0) (match-end 0)
3630 (list 'mouse-face 'highlight
3631 'rear-nonsticky t
3632 'keymap org-mouse-map
3634 t)))
3636 (defmacro org-maybe-intangible (props)
3637 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3638 In emacs 21, invisible text is not avoided by the command loop, so the
3639 intangible property is needed to make sure point skips this text.
3640 In Emacs 22, this is not necessary. The intangible text property has
3641 led to problems with flyspell. These problems are fixed in flyspell.el,
3642 but we still avoid setting the property in Emacs 22 and later.
3643 We use a macro so that the test can happen at compilation time."
3644 (if (< emacs-major-version 22)
3645 `(append '(intangible t) ,props)
3646 props))
3648 (defun org-activate-bracket-links (limit)
3649 "Run through the buffer and add overlays to bracketed links."
3650 (if (re-search-forward org-bracket-link-regexp limit t)
3651 (let* ((help (concat "LINK: "
3652 (org-match-string-no-properties 1)))
3653 ;; FIXME: above we should remove the escapes.
3654 ;; but that requires another match, protecting match data,
3655 ;; a lot of overhead for font-lock.
3656 (ip (org-maybe-intangible
3657 (list 'invisible 'org-link 'rear-nonsticky t
3658 'keymap org-mouse-map 'mouse-face 'highlight
3659 'help-echo help)))
3660 (vp (list 'rear-nonsticky t
3661 'keymap org-mouse-map 'mouse-face 'highlight
3662 'help-echo help)))
3663 ;; We need to remove the invisible property here. Table narrowing
3664 ;; may have made some of this invisible.
3665 (remove-text-properties (match-beginning 0) (match-end 0)
3666 '(invisible nil))
3667 (if (match-end 3)
3668 (progn
3669 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3670 (add-text-properties (match-beginning 3) (match-end 3) vp)
3671 (add-text-properties (match-end 3) (match-end 0) ip))
3672 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3673 (add-text-properties (match-beginning 1) (match-end 1) vp)
3674 (add-text-properties (match-end 1) (match-end 0) ip))
3675 t)))
3677 (defun org-activate-dates (limit)
3678 "Run through the buffer and add overlays to dates."
3679 (if (re-search-forward org-tsr-regexp-both limit t)
3680 (progn
3681 (add-text-properties (match-beginning 0) (match-end 0)
3682 (list 'mouse-face 'highlight
3683 'rear-nonsticky t
3684 'keymap org-mouse-map))
3685 (when org-display-custom-times
3686 (if (match-end 3)
3687 (org-display-custom-time (match-beginning 3) (match-end 3)))
3688 (org-display-custom-time (match-beginning 1) (match-end 1)))
3689 t)))
3691 (defvar org-target-link-regexp nil
3692 "Regular expression matching radio targets in plain text.")
3693 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3694 "Regular expression matching a link target.")
3695 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3696 "Regular expression matching a link target.")
3698 (defun org-activate-target-links (limit)
3699 "Run through the buffer and add overlays to target matches."
3700 (when org-target-link-regexp
3701 (let ((case-fold-search t))
3702 (if (re-search-forward org-target-link-regexp limit t)
3703 (progn
3704 (add-text-properties (match-beginning 0) (match-end 0)
3705 (list 'mouse-face 'highlight
3706 'rear-nonsticky t
3707 'keymap org-mouse-map
3708 'help-echo "Radio target link"
3709 'org-linked-text t))
3710 t)))))
3712 (defun org-update-radio-target-regexp ()
3713 "Find all radio targets in this file and update the regular expression."
3714 (interactive)
3715 (when (memq 'radio org-activate-links)
3716 (setq org-target-link-regexp
3717 (org-make-target-link-regexp (org-all-targets 'radio)))
3718 (org-restart-font-lock)))
3720 (defun org-hide-wide-columns (limit)
3721 (let (s e)
3722 (setq s (text-property-any (point) (or limit (point-max))
3723 'org-cwidth t))
3724 (when s
3725 (setq e (next-single-property-change s 'org-cwidth))
3726 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3727 (goto-char e)
3728 t)))
3730 (defun org-restart-font-lock ()
3731 "Restart font-lock-mode, to force refontification."
3732 (when (and (boundp 'font-lock-mode) font-lock-mode)
3733 (font-lock-mode -1)
3734 (font-lock-mode 1)))
3736 (defun org-all-targets (&optional radio)
3737 "Return a list of all targets in this file.
3738 With optional argument RADIO, only find radio targets."
3739 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3740 rtn)
3741 (save-excursion
3742 (goto-char (point-min))
3743 (while (re-search-forward re nil t)
3744 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3745 rtn)))
3747 (defun org-make-target-link-regexp (targets)
3748 "Make regular expression matching all strings in TARGETS.
3749 The regular expression finds the targets also if there is a line break
3750 between words."
3751 (and targets
3752 (concat
3753 "\\<\\("
3754 (mapconcat
3755 (lambda (x)
3756 (while (string-match " +" x)
3757 (setq x (replace-match "\\s-+" t t x)))
3759 targets
3760 "\\|")
3761 "\\)\\>")))
3763 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3764 "Matches CamelCase words, possibly with a star before it.")
3766 (defun org-activate-camels (limit)
3767 "Run through the buffer and add overlays to dates."
3768 (if (re-search-forward org-camel-regexp limit t)
3769 (progn
3770 (add-text-properties (match-beginning 0) (match-end 0)
3771 (list 'mouse-face 'highlight
3772 'rear-nonsticky t
3773 'keymap org-mouse-map))
3774 t)))
3776 (defun org-activate-tags (limit)
3777 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3778 (progn
3779 (add-text-properties (match-beginning 1) (match-end 1)
3780 (list 'mouse-face 'highlight
3781 'rear-nonsticky t
3782 'keymap org-mouse-map))
3783 t)))
3785 (defun org-font-lock-level ()
3786 (save-excursion
3787 (org-back-to-heading t)
3788 (- (match-end 0) (match-beginning 0))))
3790 (defun org-outline-level ()
3791 (save-excursion
3792 (looking-at outline-regexp)
3793 (if (match-beginning 1)
3794 (+ (org-get-string-indentation (match-string 1)) 1000)
3795 (- (match-end 0) (match-beginning 0)))))
3797 (defvar org-font-lock-keywords nil)
3799 (defun org-set-font-lock-defaults ()
3800 (let* ((em org-fontify-emphasized-text)
3801 (lk org-activate-links)
3802 (org-font-lock-extra-keywords
3803 ;; Headlines
3804 (list
3805 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3806 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3807 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3808 (1 'org-table))
3809 ;; Links
3810 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3811 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3812 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3813 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3814 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3815 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3816 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3817 (if org-table-limit-column-width
3818 '(org-hide-wide-columns (0 nil append)))
3819 ;; TODO lines
3820 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3821 '(1 'org-todo t))
3822 ;; Priorities
3823 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3824 ;; Special keywords
3825 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3826 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3827 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3828 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3829 ;; Emphasis
3830 (if em
3831 (if (featurep 'xemacs)
3832 '(org-do-emphasis-faces (0 nil append))
3833 '(org-do-emphasis-faces)))
3834 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3835 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3836 2 'bold prepend)
3837 (if org-provide-checkbox-statistics
3838 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3839 (0 (org-get-checkbox-statistics-face) t)))
3840 ;; COMMENT
3841 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3842 "\\|" org-quote-string "\\)\\>")
3843 '(1 'org-special-keyword t))
3844 '("^#.*" (0 'font-lock-comment-face t))
3845 ;; DONE
3846 (if org-fontify-done-headline
3847 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3848 '(1 'org-done t) '(2 'org-headline-done t))
3849 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3850 '(1 'org-done t)))
3851 ;; Table stuff
3852 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3853 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3854 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3855 (if org-format-transports-properties-p
3856 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3857 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3859 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3860 ;; Now set the full font-lock-keywords
3861 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3862 (org-set-local 'font-lock-defaults
3863 '(org-font-lock-keywords t nil nil backward-paragraph))
3864 (kill-local-variable 'font-lock-keywords) nil))
3866 (defvar org-m nil)
3867 (defvar org-l nil)
3868 (defvar org-f nil)
3869 (defun org-get-level-face (n)
3870 "Get the right face for match N in font-lock matching of healdines."
3871 (setq org-l (- (match-end 2) (match-beginning 1)))
3872 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3873 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3874 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3875 (cond
3876 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3877 ((eq n 2) org-f)
3878 (t (if org-level-color-stars-only nil org-f))))
3880 (defun org-unfontify-region (beg end &optional maybe_loudly)
3881 "Remove fontification and activation overlays from links."
3882 (font-lock-default-unfontify-region beg end)
3883 (let* ((buffer-undo-list t)
3884 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3885 (inhibit-modification-hooks t)
3886 deactivate-mark buffer-file-name buffer-file-truename)
3887 (remove-text-properties beg end
3888 '(mouse-face t keymap t org-linked-text t
3889 rear-nonsticky t
3890 invisible t intangible t))))
3892 ;;;; Visibility cycling, including org-goto and indirect buffer
3894 ;;; Cycling
3896 (defvar org-cycle-global-status nil)
3897 (make-variable-buffer-local 'org-cycle-global-status)
3898 (defvar org-cycle-subtree-status nil)
3899 (make-variable-buffer-local 'org-cycle-subtree-status)
3901 ;;;###autoload
3902 (defun org-cycle (&optional arg)
3903 "Visibility cycling for Org-mode.
3905 - When this function is called with a prefix argument, rotate the entire
3906 buffer through 3 states (global cycling)
3907 1. OVERVIEW: Show only top-level headlines.
3908 2. CONTENTS: Show all headlines of all levels, but no body text.
3909 3. SHOW ALL: Show everything.
3911 - When point is at the beginning of a headline, rotate the subtree started
3912 by this line through 3 different states (local cycling)
3913 1. FOLDED: Only the main headline is shown.
3914 2. CHILDREN: The main headline and the direct children are shown.
3915 From this state, you can move to one of the children
3916 and zoom in further.
3917 3. SUBTREE: Show the entire subtree, including body text.
3919 - When there is a numeric prefix, go up to a heading with level ARG, do
3920 a `show-subtree' and return to the previous cursor position. If ARG
3921 is negative, go up that many levels.
3923 - When point is not at the beginning of a headline, execute
3924 `indent-relative', like TAB normally does. See the option
3925 `org-cycle-emulate-tab' for details.
3927 - Special case: if point is the the beginning of the buffer and there is
3928 no headline in line 1, this function will act as if called with prefix arg."
3929 (interactive "P")
3930 (let* ((outline-regexp
3931 (if (and (org-mode-p) org-cycle-include-plain-lists)
3932 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3933 outline-regexp))
3934 (bob-special (and org-cycle-global-at-bob (bobp)
3935 (not (looking-at outline-regexp))))
3936 (org-cycle-hook
3937 (if bob-special
3938 (delq 'org-optimize-window-after-visibility-change
3939 (copy-sequence org-cycle-hook))
3940 org-cycle-hook))
3941 (pos (point)))
3943 (if (or bob-special (equal arg '(4)))
3944 ;; special case: use global cycling
3945 (setq arg t))
3947 (cond
3949 ((org-at-table-p 'any)
3950 ;; Enter the table or move to the next field in the table
3951 (or (org-table-recognize-table.el)
3952 (progn
3953 (if arg (org-table-edit-field t)
3954 (org-table-justify-field-maybe)
3955 (call-interactively 'org-table-next-field)))))
3957 ((eq arg t) ;; Global cycling
3959 (cond
3960 ((and (eq last-command this-command)
3961 (eq org-cycle-global-status 'overview))
3962 ;; We just created the overview - now do table of contents
3963 ;; This can be slow in very large buffers, so indicate action
3964 (message "CONTENTS...")
3965 (org-content)
3966 (message "CONTENTS...done")
3967 (setq org-cycle-global-status 'contents)
3968 (run-hook-with-args 'org-cycle-hook 'contents))
3970 ((and (eq last-command this-command)
3971 (eq org-cycle-global-status 'contents))
3972 ;; We just showed the table of contents - now show everything
3973 (show-all)
3974 (message "SHOW ALL")
3975 (setq org-cycle-global-status 'all)
3976 (run-hook-with-args 'org-cycle-hook 'all))
3979 ;; Default action: go to overview
3980 (org-overview)
3981 (message "OVERVIEW")
3982 (setq org-cycle-global-status 'overview)
3983 (run-hook-with-args 'org-cycle-hook 'overview))))
3985 ((integerp arg)
3986 ;; Show-subtree, ARG levels up from here.
3987 (save-excursion
3988 (org-back-to-heading)
3989 (outline-up-heading (if (< arg 0) (- arg)
3990 (- (funcall outline-level) arg)))
3991 (org-show-subtree)))
3993 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3994 ;; At a heading: rotate between three different views
3995 (org-back-to-heading)
3996 (let ((goal-column 0) eoh eol eos)
3997 ;; First, some boundaries
3998 (save-excursion
3999 (org-back-to-heading)
4000 (save-excursion
4001 (beginning-of-line 2)
4002 (while (and (not (eobp)) ;; this is like `next-line'
4003 (get-char-property (1- (point)) 'invisible))
4004 (beginning-of-line 2)) (setq eol (point)))
4005 (outline-end-of-heading) (setq eoh (point))
4006 (org-end-of-subtree t) (setq eos (point))
4007 (outline-next-heading))
4008 ;; Find out what to do next and set `this-command'
4009 (cond
4010 ((and (= eos eoh)
4011 ;; Nothing is hidden behind this heading
4012 (message "EMPTY ENTRY")
4013 (setq org-cycle-subtree-status nil)))
4014 ((>= eol eos)
4015 ;; Entire subtree is hidden in one line: open it
4016 (org-show-entry)
4017 (show-children)
4018 (message "CHILDREN")
4019 (setq org-cycle-subtree-status 'children)
4020 (run-hook-with-args 'org-cycle-hook 'children))
4021 ((and (eq last-command this-command)
4022 (eq org-cycle-subtree-status 'children))
4023 ;; We just showed the children, now show everything.
4024 (org-show-subtree)
4025 (message "SUBTREE")
4026 (setq org-cycle-subtree-status 'subtree)
4027 (run-hook-with-args 'org-cycle-hook 'subtree))
4029 ;; Default action: hide the subtree.
4030 (hide-subtree)
4031 (message "FOLDED")
4032 (setq org-cycle-subtree-status 'folded)
4033 (run-hook-with-args 'org-cycle-hook 'folded)))))
4035 ;; TAB emulation
4036 (buffer-read-only (org-back-to-heading))
4038 ((org-try-cdlatex-tab))
4040 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4041 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4042 (or (and (eq org-cycle-emulate-tab 'white)
4043 (= (match-end 0) (point-at-eol)))
4044 (and (eq org-cycle-emulate-tab 'whitestart)
4045 (>= (match-end 0) pos))))
4047 (eq org-cycle-emulate-tab t))
4048 (if (and (looking-at "[ \n\r\t]")
4049 (string-match "^[ \t]*$" (buffer-substring
4050 (point-at-bol) (point))))
4051 (progn
4052 (beginning-of-line 1)
4053 (and (looking-at "[ \t]+") (replace-match ""))))
4054 (indent-relative))
4056 (t (save-excursion
4057 (org-back-to-heading)
4058 (org-cycle))))))
4060 ;;;###autoload
4061 (defun org-global-cycle (&optional arg)
4062 "Cycle the global visibility. For details see `org-cycle'."
4063 (interactive "P")
4064 (let ((org-cycle-include-plain-lists
4065 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4066 (if (integerp arg)
4067 (progn
4068 (show-all)
4069 (hide-sublevels arg)
4070 (setq org-cycle-global-status 'contents))
4071 (org-cycle '(4)))))
4073 (defun org-overview ()
4074 "Switch to overview mode, shoing only top-level headlines.
4075 Really, this shows all headlines with level equal or greater than the level
4076 of the first headline in the buffer. This is important, because if the
4077 first headline is not level one, then (hide-sublevels 1) gives confusing
4078 results."
4079 (interactive)
4080 (hide-sublevels (save-excursion
4081 (goto-char (point-min))
4082 (if (re-search-forward (concat "^" outline-regexp) nil t)
4083 (progn
4084 (goto-char (match-beginning 0))
4085 (funcall outline-level))
4086 1))))
4088 ;; FIXME: allow an argument to give a limiting level for this.
4089 (defun org-content ()
4090 "Show all headlines in the buffer, like a table of contents"
4091 (interactive)
4092 (save-excursion
4093 ;; Visit all headings and show their offspring
4094 (goto-char (point-max))
4095 (catch 'exit
4096 (while (and (progn (condition-case nil
4097 (outline-previous-visible-heading 1)
4098 (error (goto-char (point-min))))
4100 (looking-at outline-regexp))
4101 (show-branches)
4102 (if (bobp) (throw 'exit nil))))))
4105 (defun org-optimize-window-after-visibility-change (state)
4106 "Adjust the window after a change in outline visibility.
4107 This function is the default value of the hook `org-cycle-hook'."
4108 (when (get-buffer-window (current-buffer))
4109 (cond
4110 ((eq state 'overview) (org-first-headline-recenter 1))
4111 ((eq state 'content) nil)
4112 ((eq state 'all) nil)
4113 ((eq state 'folded) nil)
4114 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4115 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4117 (defun org-subtree-end-visible-p ()
4118 "Is the end of the current subtree visible?"
4119 (pos-visible-in-window-p
4120 (save-excursion (org-end-of-subtree t) (point))))
4122 (defun org-first-headline-recenter (&optional N)
4123 "Move cursor to the first headline and recenter the headline.
4124 Optional argument N means, put the headline into the Nth line of the window."
4125 (goto-char (point-min))
4126 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4127 (beginning-of-line)
4128 (recenter (prefix-numeric-value N))))
4130 ;;; Org-goto
4132 (defvar org-goto-window-configuration nil)
4133 (defvar org-goto-marker nil)
4134 (defvar org-goto-map (make-sparse-keymap))
4135 (let ((cmds '(isearch-forward isearch-backward)) cmd)
4136 (while (setq cmd (pop cmds))
4137 (substitute-key-definition cmd cmd org-goto-map global-map)))
4138 (define-key org-goto-map "\C-m" 'org-goto-ret)
4139 (define-key org-goto-map [(left)] 'org-goto-left)
4140 (define-key org-goto-map [(right)] 'org-goto-right)
4141 (define-key org-goto-map [(?q)] 'org-goto-quit)
4142 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
4143 (define-key org-goto-map "\C-i" 'org-cycle)
4144 (define-key org-goto-map [(tab)] 'org-cycle)
4145 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
4146 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
4147 (define-key org-goto-map "n" 'outline-next-visible-heading)
4148 (define-key org-goto-map "p" 'outline-previous-visible-heading)
4149 (define-key org-goto-map "f" 'outline-forward-same-level)
4150 (define-key org-goto-map "b" 'outline-backward-same-level)
4151 (define-key org-goto-map "u" 'outline-up-heading)
4152 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
4153 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
4154 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
4155 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
4156 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
4157 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4158 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
4160 (defconst org-goto-help
4161 "Select a location to jump to, press RET
4162 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
4164 (defun org-goto ()
4165 "Go to a different location of the document, keeping current visibility.
4167 When you want to go to a different location in a document, the fastest way
4168 is often to fold the entire buffer and then dive into the tree. This
4169 method has the disadvantage, that the previous location will be folded,
4170 which may not be what you want.
4172 This command works around this by showing a copy of the current buffer in
4173 overview mode. You can dive into the tree in that copy, to find the
4174 location you want to reach. When pressing RET, the command returns to the
4175 original buffer in which the visibility is still unchanged. It then jumps
4176 to the new location, making it and the headline hierarchy above it visible."
4177 (interactive)
4178 (let* ((org-goto-start-pos (point))
4179 (selected-point
4180 (org-get-location (current-buffer) org-goto-help)))
4181 (if selected-point
4182 (progn
4183 (org-mark-ring-push org-goto-start-pos)
4184 (goto-char selected-point)
4185 (if (or (org-invisible-p) (org-invisible-p2))
4186 (org-show-context 'org-goto)))
4187 (error "Quit"))))
4189 (defvar org-selected-point nil) ; dynamically scoped parameter
4191 (defun org-get-location (buf help)
4192 "Let the user select a location in the Org-mode buffer BUF.
4193 This function uses a recursive edit. It returns the selected position
4194 or nil."
4195 (let (org-selected-point)
4196 (save-excursion
4197 (save-window-excursion
4198 (delete-other-windows)
4199 (switch-to-buffer (get-buffer-create "*org-goto*"))
4200 (with-output-to-temp-buffer "*Help*"
4201 (princ help))
4202 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4203 (setq buffer-read-only nil)
4204 (erase-buffer)
4205 (insert-buffer-substring buf)
4206 (let ((org-startup-truncated t)
4207 (org-startup-folded t)
4208 (org-startup-align-all-tables nil)
4209 (org-startup-with-deadline-check nil))
4210 (org-mode))
4211 (setq buffer-read-only t)
4212 (if (boundp 'org-goto-start-pos)
4213 (goto-char org-goto-start-pos)
4214 (goto-char (point-min)))
4215 (org-beginning-of-line)
4216 (message "Select location and press RET")
4217 ;; now we make sure that during selection, ony very few keys work
4218 ;; and that it is impossible to switch to another window.
4219 (let ((gm (current-global-map))
4220 (overriding-local-map org-goto-map))
4221 (unwind-protect
4222 (progn
4223 (use-global-map org-goto-map)
4224 (recursive-edit))
4225 (use-global-map gm)))))
4226 (kill-buffer "*org-goto*")
4227 org-selected-point))
4229 (defun org-goto-ret (&optional arg)
4230 "Finish `org-goto' by going to the new location."
4231 (interactive "P")
4232 (setq org-selected-point (point)
4233 current-prefix-arg arg)
4234 (throw 'exit nil))
4236 (defun org-goto-left ()
4237 "Finish `org-goto' by going to the new location."
4238 (interactive)
4239 (if (org-on-heading-p)
4240 (progn
4241 (beginning-of-line 1)
4242 (setq org-selected-point (point)
4243 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4244 (throw 'exit nil))
4245 (error "Not on a heading")))
4247 (defun org-goto-right ()
4248 "Finish `org-goto' by going to the new location."
4249 (interactive)
4250 (if (org-on-heading-p)
4251 (progn
4252 (outline-end-of-subtree)
4253 (or (eobp) (forward-char 1))
4254 (setq org-selected-point (point)
4255 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4256 (throw 'exit nil))
4257 (error "Not on a heading")))
4259 (defun org-goto-quit ()
4260 "Finish `org-goto' without cursor motion."
4261 (interactive)
4262 (setq org-selected-point nil)
4263 (throw 'exit nil))
4265 ;;; Indirect buffer display of subtrees
4267 (defvar org-indirect-dedicated-frame nil
4268 "This is the frame being used for indirect tree display.")
4269 (defvar org-last-indirect-buffer nil)
4271 (defun org-tree-to-indirect-buffer (&optional arg)
4272 "Create indirect buffer and narrow it to current subtree.
4273 With numerical prefix ARG, go up to this level and then take that tree.
4274 If ARG is negative, go up that many levels.
4275 Normally this command removes the indirect buffer previously made
4276 with this command. However, when called with a C-u prefix, the last buffer
4277 is kept so that you can work with several indirect buffers at the same time.
4278 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4279 requests that a new frame be made for the new buffer, so that the dedicated
4280 frame is not changed."
4281 (interactive "P")
4282 (let ((cbuf (current-buffer))
4283 (cwin (selected-window))
4284 (pos (point))
4285 (bname (buffer-name (current-buffer)))
4286 beg end level heading ibuf)
4287 (save-excursion
4288 (org-back-to-heading t)
4289 (when (numberp arg)
4290 (setq level (org-outline-level))
4291 (if (< arg 0) (setq arg (+ level arg)))
4292 (while (> (setq level (org-outline-level)) arg)
4293 (outline-up-heading 1 t)))
4294 (setq beg (point)
4295 heading (org-get-heading))
4296 (org-end-of-subtree t) (setq end (point)))
4297 (if (and (not arg)
4298 (buffer-live-p org-last-indirect-buffer))
4299 (kill-buffer org-last-indirect-buffer))
4300 (setq ibuf (org-get-indirect-buffer cbuf)
4301 org-last-indirect-buffer ibuf)
4302 (cond
4303 ((or (eq org-indirect-buffer-display 'new-frame)
4304 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4305 (select-frame (make-frame))
4306 (delete-other-windows)
4307 (switch-to-buffer ibuf)
4308 (org-set-frame-title heading))
4309 ((eq org-indirect-buffer-display 'dedicated-frame)
4310 (raise-frame
4311 (select-frame (or (and org-indirect-dedicated-frame
4312 (frame-live-p org-indirect-dedicated-frame)
4313 org-indirect-dedicated-frame)
4314 (setq org-indirect-dedicated-frame (make-frame)))))
4315 (delete-other-windows)
4316 (switch-to-buffer ibuf)
4317 (org-set-frame-title (concat "Indirect: " heading)))
4318 ((eq org-indirect-buffer-display 'current-window)
4319 (switch-to-buffer ibuf))
4320 ((eq org-indirect-buffer-display 'other-window)
4321 (pop-to-buffer ibuf))
4322 (t (error "Invalid value.")))
4323 (if (featurep 'xemacs)
4324 (save-excursion (org-mode) (turn-on-font-lock)))
4325 (narrow-to-region beg end)
4326 (show-all)
4327 (goto-char pos)
4328 (debug)
4329 (and (window-live-p cwin) (select-window cwin))))
4331 (defun org-get-indirect-buffer (&optional buffer)
4332 (setq buffer (or buffer (current-buffer)))
4333 (let ((n 1) (base (buffer-name buffer)) bname)
4334 (while (buffer-live-p
4335 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4336 (setq n (1+ n)))
4337 (condition-case nil
4338 (make-indirect-buffer buffer bname 'clone)
4339 (error (make-indirect-buffer buffer bname)))))
4341 (defun org-set-frame-title (title)
4342 "Set the title of the current frame to the string TITLE."
4343 ;; FIXME: how to name a single frame in XEmacs???
4344 (unless (featurep 'xemacs)
4345 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4347 ;;;; Structure editing
4349 ;;; Inserting headlines
4351 (defun org-insert-heading (&optional force-heading)
4352 "Insert a new heading or item with same depth at point.
4353 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4354 If point is at the beginning of a headline, insert a sibling before the
4355 current headline. If point is in the middle of a headline, split the headline
4356 at that position and make the rest of the headline part of the sibling below
4357 the current headline."
4358 (interactive "P")
4359 (if (= (buffer-size) 0)
4360 (insert "\n* ")
4361 (when (or force-heading (not (org-insert-item)))
4362 (let* ((head (save-excursion
4363 (condition-case nil
4364 (progn
4365 (org-back-to-heading)
4366 (match-string 0))
4367 (error "*"))))
4368 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4369 pos)
4370 (cond
4371 ((and (org-on-heading-p) (bolp)
4372 (save-excursion (backward-char 1) (not (org-invisible-p))))
4373 (open-line (if blank 2 1)))
4374 ((and (bolp) (save-excursion
4375 (backward-char 1) (not (org-invisible-p))))
4376 nil)
4377 (t (newline (if blank 2 1))))
4378 (insert head) (just-one-space)
4379 (setq pos (point))
4380 (end-of-line 1)
4381 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4382 (run-hooks 'org-insert-heading-hook)))))
4385 (defun org-insert-todo-heading (arg)
4386 "Insert a new heading with the same level and TODO state as current heading.
4387 If the heading has no TODO state, or if the state is DONE, use the first
4388 state (TODO by default). Also with prefix arg, force first state."
4389 (interactive "P")
4390 (when (not (org-insert-item 'checkbox))
4391 (org-insert-heading)
4392 (save-excursion
4393 (org-back-to-heading)
4394 (outline-previous-heading)
4395 (looking-at org-todo-line-regexp))
4396 (if (or arg
4397 (not (match-beginning 2))
4398 (equal (match-string 2) org-done-string))
4399 (insert (car org-todo-keywords) " ")
4400 (insert (match-string 2) " "))))
4402 ;;; Promotion and Demotion
4404 (defun org-promote-subtree ()
4405 "Promote the entire subtree.
4406 See also `org-promote'."
4407 (interactive)
4408 (save-excursion
4409 (org-map-tree 'org-promote))
4410 (org-fix-position-after-promote))
4412 (defun org-demote-subtree ()
4413 "Demote the entire subtree. See `org-demote'.
4414 See also `org-promote'."
4415 (interactive)
4416 (save-excursion
4417 (org-map-tree 'org-demote))
4418 (org-fix-position-after-promote))
4421 (defun org-do-promote ()
4422 "Promote the current heading higher up the tree.
4423 If the region is active in `transient-mark-mode', promote all headings
4424 in the region."
4425 (interactive)
4426 (save-excursion
4427 (if (org-region-active-p)
4428 (org-map-region 'org-promote (region-beginning) (region-end))
4429 (org-promote)))
4430 (org-fix-position-after-promote))
4432 (defun org-do-demote ()
4433 "Demote the current heading lower down the tree.
4434 If the region is active in `transient-mark-mode', demote all headings
4435 in the region."
4436 (interactive)
4437 (save-excursion
4438 (if (org-region-active-p)
4439 (org-map-region 'org-demote (region-beginning) (region-end))
4440 (org-demote)))
4441 (org-fix-position-after-promote))
4443 (defun org-fix-position-after-promote ()
4444 "Make sure that after pro/demotion cursor position is right."
4445 (if (and (equal (char-after) ?\n)
4446 (save-excursion
4447 (skip-chars-backward "a-zA-Z0-9_@")
4448 (looking-at org-todo-regexp)))
4449 (insert " "))
4450 (and (equal (char-after) ?\ )
4451 (equal (char-before) ?*)
4452 (forward-char 1)))
4454 (defun org-get-legal-level (level &optional change)
4455 "Rectify a level change under the influence of `org-odd-levels-only'
4456 LEVEL is a current level, CHANGE is by how much the level should be
4457 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4458 even level numbers will become the next higher odd number."
4459 (if org-odd-levels-only
4460 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4461 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4462 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4463 (max 1 (+ level change))))
4465 (defun org-promote ()
4466 "Promote the current heading higher up the tree.
4467 If the region is active in `transient-mark-mode', promote all headings
4468 in the region."
4469 (org-back-to-heading t)
4470 (let* ((level (save-match-data (funcall outline-level)))
4471 (up-head (make-string (org-get-legal-level level -1) ?*))
4472 (diff (abs (- level (length up-head)))))
4473 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4474 (replace-match up-head nil t)
4475 ;; Fixup tag positioning
4476 (and org-auto-align-tags (org-set-tags nil t))
4477 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4479 (defun org-demote ()
4480 "Demote the current heading lower down the tree.
4481 If the region is active in `transient-mark-mode', demote all headings
4482 in the region."
4483 (org-back-to-heading t)
4484 (let* ((level (save-match-data (funcall outline-level)))
4485 (down-head (make-string (org-get-legal-level level 1) ?*))
4486 (diff (abs (- level (length down-head)))))
4487 (replace-match down-head nil t)
4488 ;; Fixup tag positioning
4489 (and org-auto-align-tags (org-set-tags nil t))
4490 (if org-adapt-indentation (org-fixup-indentation diff))))
4492 (defun org-map-tree (fun)
4493 "Call FUN for every heading underneath the current one."
4494 (org-back-to-heading)
4495 (let ((level (funcall outline-level)))
4496 (save-excursion
4497 (funcall fun)
4498 (while (and (progn
4499 (outline-next-heading)
4500 (> (funcall outline-level) level))
4501 (not (eobp)))
4502 (funcall fun)))))
4504 (defun org-map-region (fun beg end)
4505 "Call FUN for every heading between BEG and END."
4506 (let ((org-ignore-region t))
4507 (save-excursion
4508 (setq end (copy-marker end))
4509 (goto-char beg)
4510 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4511 (< (point) end))
4512 (funcall fun))
4513 (while (and (progn
4514 (outline-next-heading)
4515 (< (point) end))
4516 (not (eobp)))
4517 (funcall fun)))))
4519 (defun org-fixup-indentation (diff)
4520 "Change the indentation in the current entry by DIFF
4521 However, if any line in the current entry has no indentation, or if it
4522 would end up with no indentation after the change, nothing at all is done."
4523 (save-excursion
4524 (let ((end (save-excursion (outline-next-heading)
4525 (point-marker)))
4526 (prohibit (if (> diff 0)
4527 "^\\S-"
4528 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4529 col)
4530 (unless (save-excursion (re-search-forward prohibit end t))
4531 (while (re-search-forward "^[ \t]+" end t)
4532 (goto-char (match-end 0))
4533 (setq col (current-column))
4534 (if (< diff 0) (replace-match ""))
4535 (indent-to (+ diff col))))
4536 (move-marker end nil))))
4538 (defun org-convert-to-odd-levels ()
4539 "Convert an org-mode file with all levels allowed to one with odd levels.
4540 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4541 level 5 etc."
4542 (interactive)
4543 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4544 (let ((org-odd-levels-only nil) n)
4545 (save-excursion
4546 (goto-char (point-min))
4547 (while (re-search-forward "^\\*\\*+" nil t)
4548 (setq n (1- (length (match-string 0))))
4549 (while (>= (setq n (1- n)) 0)
4550 (org-demote))
4551 (end-of-line 1))))))
4554 (defun org-convert-to-oddeven-levels ()
4555 "Convert an org-mode file with only odd levels to one with odd and even levels.
4556 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4557 section with an even level, conversion would destroy the structure of the file. An error
4558 is signaled in this case."
4559 (interactive)
4560 (goto-char (point-min))
4561 ;; First check if there are no even levels
4562 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
4563 (org-show-context t)
4564 (error "Not all levels are odd in this file. Conversion not possible."))
4565 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4566 (let ((org-odd-levels-only nil) n)
4567 (save-excursion
4568 (goto-char (point-min))
4569 (while (re-search-forward "^\\*\\*+" nil t)
4570 (setq n (/ (length (match-string 0)) 2))
4571 (while (>= (setq n (1- n)) 0)
4572 (org-promote))
4573 (end-of-line 1))))))
4575 (defun org-tr-level (n)
4576 "Make N odd if required."
4577 (if org-odd-levels-only (1+ (/ n 2)) n))
4579 ;;; Vertical tree motion, cutting and pasting of subtrees
4581 (defun org-move-subtree-up (&optional arg)
4582 "Move the current subtree up past ARG headlines of the same level."
4583 (interactive "p")
4584 (org-move-subtree-down (- (prefix-numeric-value arg))))
4586 (defun org-move-subtree-down (&optional arg)
4587 "Move the current subtree down past ARG headlines of the same level."
4588 (interactive "p")
4589 (setq arg (prefix-numeric-value arg))
4590 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4591 'outline-get-last-sibling))
4592 (ins-point (make-marker))
4593 (cnt (abs arg))
4594 beg end txt folded)
4595 ;; Select the tree
4596 (org-back-to-heading)
4597 (setq beg (point))
4598 (save-match-data
4599 (save-excursion (outline-end-of-heading)
4600 (setq folded (org-invisible-p)))
4601 (outline-end-of-subtree))
4602 (outline-next-heading)
4603 (setq end (point))
4604 ;; Find insertion point, with error handling
4605 (goto-char beg)
4606 (while (> cnt 0)
4607 (or (and (funcall movfunc) (looking-at outline-regexp))
4608 (progn (goto-char beg)
4609 (error "Cannot move past superior level or buffer limit")))
4610 (setq cnt (1- cnt)))
4611 (if (> arg 0)
4612 ;; Moving forward - still need to move over subtree
4613 (progn (outline-end-of-subtree)
4614 (outline-next-heading)
4615 (if (not (or (looking-at (concat "^" outline-regexp))
4616 (bolp)))
4617 (newline))))
4618 (move-marker ins-point (point))
4619 (setq txt (buffer-substring beg end))
4620 (delete-region beg end)
4621 (insert txt)
4622 (goto-char ins-point)
4623 (if folded (hide-subtree))
4624 (move-marker ins-point nil)))
4626 (defvar org-subtree-clip ""
4627 "Clipboard for cut and paste of subtrees.
4628 This is actually only a copy of the kill, because we use the normal kill
4629 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4631 (defvar org-subtree-clip-folded nil
4632 "Was the last copied subtree folded?
4633 This is used to fold the tree back after pasting.")
4635 (defun org-cut-subtree ()
4636 "Cut the current subtree into the clipboard.
4637 This is a short-hand for marking the subtree and then cutting it."
4638 (interactive)
4639 (org-copy-subtree 'cut))
4641 (defun org-copy-subtree (&optional cut)
4642 "Cut the current subtree into the clipboard.
4643 This is a short-hand for marking the subtree and then copying it.
4644 If CUT is non-nil, actually cut the subtree."
4645 (interactive)
4646 (let (beg end folded)
4647 (org-back-to-heading)
4648 (setq beg (point))
4649 (save-match-data
4650 (save-excursion (outline-end-of-heading)
4651 (setq folded (org-invisible-p)))
4652 (outline-end-of-subtree))
4653 (if (equal (char-after) ?\n) (forward-char 1))
4654 (setq end (point))
4655 (goto-char beg)
4656 (when (> end beg)
4657 (setq org-subtree-clip-folded folded)
4658 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4659 (setq org-subtree-clip (current-kill 0))
4660 (message "%s: Subtree with %d characters"
4661 (if cut "Cut" "Copied")
4662 (length org-subtree-clip)))))
4664 (defun org-paste-subtree (&optional level tree)
4665 "Paste the clipboard as a subtree, with modification of headline level.
4666 The entire subtree is promoted or demoted in order to match a new headline
4667 level. By default, the new level is derived from the visible headings
4668 before and after the insertion point, and taken to be the inferior headline
4669 level of the two. So if the previous visible heading is level 3 and the
4670 next is level 4 (or vice versa), level 4 will be used for insertion.
4671 This makes sure that the subtree remains an independent subtree and does
4672 not swallow low level entries.
4674 You can also force a different level, either by using a numeric prefix
4675 argument, or by inserting the heading marker by hand. For example, if the
4676 cursor is after \"*****\", then the tree will be shifted to level 5.
4678 If you want to insert the tree as is, just use \\[yank].
4680 If optional TREE is given, use this text instead of the kill ring."
4681 (interactive "P")
4682 (unless (org-kill-is-subtree-p tree)
4683 (error
4684 (substitute-command-keys
4685 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4686 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4687 (^re (concat "^\\(" outline-regexp "\\)"))
4688 (re (concat "\\(" outline-regexp "\\)"))
4689 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4691 (old-level (if (string-match ^re txt)
4692 (- (match-end 0) (match-beginning 0))
4693 -1))
4694 (force-level (cond (level (prefix-numeric-value level))
4695 ((string-match
4696 ^re_ (buffer-substring (point-at-bol) (point)))
4697 (- (match-end 0) (match-beginning 0)))
4698 (t nil)))
4699 (previous-level (save-excursion
4700 (condition-case nil
4701 (progn
4702 (outline-previous-visible-heading 1)
4703 (if (looking-at re)
4704 (- (match-end 0) (match-beginning 0))
4706 (error 1))))
4707 (next-level (save-excursion
4708 (condition-case nil
4709 (progn
4710 (outline-next-visible-heading 1)
4711 (if (looking-at re)
4712 (- (match-end 0) (match-beginning 0))
4714 (error 1))))
4715 (new-level (or force-level (max previous-level next-level)))
4716 (shift (if (or (= old-level -1)
4717 (= new-level -1)
4718 (= old-level new-level))
4720 (- new-level old-level)))
4721 (shift1 shift)
4722 (delta (if (> shift 0) -1 1))
4723 (func (if (> shift 0) 'org-demote 'org-promote))
4724 (org-odd-levels-only nil)
4725 beg end)
4726 ;; Remove the forces level indicator
4727 (if force-level
4728 (delete-region (point-at-bol) (point)))
4729 ;; Make sure we start at the beginning of an empty line
4730 (if (not (bolp)) (insert "\n"))
4731 (if (not (looking-at "[ \t]*$"))
4732 (progn (insert "\n") (backward-char 1)))
4733 ;; Paste
4734 (setq beg (point))
4735 (if (string-match "[ \t\r\n]+\\'" txt)
4736 (setq txt (replace-match "\n" t t txt)))
4737 (insert txt)
4738 (setq end (point))
4739 (if (looking-at "[ \t\r\n]+")
4740 (replace-match "\n"))
4741 (goto-char beg)
4742 ;; Shift if necessary
4743 (if (= shift 0)
4744 (message "Pasted at level %d, without shift" new-level)
4745 (save-restriction
4746 (narrow-to-region beg end)
4747 (while (not (= shift 0))
4748 (org-map-region func (point-min) (point-max))
4749 (setq shift (+ delta shift)))
4750 (goto-char (point-min))
4751 (message "Pasted at level %d, with shift by %d levels"
4752 new-level shift1)))
4753 (if (and kill-ring
4754 (eq org-subtree-clip (current-kill 0))
4755 org-subtree-clip-folded)
4756 ;; The tree was folded before it was killed/copied
4757 (hide-subtree))))
4759 (defun org-kill-is-subtree-p (&optional txt)
4760 "Check if the current kill is an outline subtree, or a set of trees.
4761 Returns nil if kill does not start with a headline, or if the first
4762 headline level is not the largest headline level in the tree.
4763 So this will actually accept several entries of equal levels as well,
4764 which is OK for `org-paste-subtree'.
4765 If optional TXT is given, check this string instead of the current kill."
4766 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4767 (start-level (and kill
4768 (string-match (concat "\\`" outline-regexp) kill)
4769 (- (match-end 0) (match-beginning 0))))
4770 (re (concat "^" outline-regexp))
4771 (start 1))
4772 (if (not start-level)
4773 nil ;; does not even start with a heading
4774 (catch 'exit
4775 (while (setq start (string-match re kill (1+ start)))
4776 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4777 (throw 'exit nil)))
4778 t))))
4780 (defun org-narrow-to-subtree ()
4781 "Narrow buffer to the current subtree."
4782 (interactive)
4783 (save-excursion
4784 (narrow-to-region
4785 (progn (org-back-to-heading) (point))
4786 (progn (org-end-of-subtree t) (point)))))
4789 ;;; Outline Sorting
4791 (defun org-sort (with-case)
4792 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
4793 (interactive "P")
4794 (if (org-at-table-p)
4795 (org-call-with-arg 'org-table-sort-lines with-case)
4796 (org-call-with-arg 'org-sort-entries with-case)))
4798 (defun org-sort-entries (&optional with-case sorting-type)
4799 "Sort entries on a certain level of an outline tree.
4800 If there is an active region, the entries in the region are sorted.
4801 If not, the children of the entry at point are sorted.
4803 Sorting can be alphabetically, numerically, and by date/time as given by
4804 the first time stamp in the entry. The command prompts for the sorting
4805 type unless it has been given to the function through the SORTING-TYPE
4806 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
4808 Comparing entries ignores case by default. However, with an optional argument
4809 WITH-CASE, the sorting considers case as well. With two prefix arguments
4810 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
4811 (interactive "P")
4812 (let ((unique (equal with-case '(16)))
4813 start beg end entries stars re re2 p nentries (nremoved 0) last txt)
4815 ;; Find beginning and end of region to sort
4816 (if (org-region-active-p)
4817 (progn
4818 ;; we will sort the region
4819 (setq end (region-end))
4820 (goto-char (1- (setq start (region-beginning)))))
4821 ;; we will sort the children of the current headline
4822 (setq start (point) end (org-end-of-subtree))
4823 (goto-char start)
4824 (show-subtree))
4825 (outline-next-heading) ; this is the first heading to be included
4826 (setq beg (point))
4827 (if (>= (point) end) (error "Nothing to sort"))
4828 (looking-at "\\(\\*+\\)")
4829 (setq stars (match-string 1)
4830 re (concat "^" (regexp-quote stars) " +")
4831 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4832 txt (buffer-substring beg end))
4833 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4834 (if (string-match re2 txt)
4835 (error "Region to sort contains a level above the first entry"))
4836 ;; Make a list that can be sorted.
4837 ;; The car is the string for comparison, the cdr is the subtree
4838 (message "Sorting entries...")
4839 (setq entries
4840 (mapcar
4841 (lambda (x)
4842 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
4843 (cons (match-string 0 x) x))
4844 (org-split-string txt re)))
4846 ;; Sort the list
4847 (setq entries (org-do-sort
4848 entries
4849 (if (org-region-active-p) "region" "children")
4850 with-case sorting-type))
4852 ;; Delete the old stuff
4853 (goto-char beg)
4854 (kill-region beg end)
4855 (setq nentries (length entries))
4856 ;; Insert the sorted entries, and remove duplicates if this is required
4857 (while (setq p (pop entries))
4858 (if (and unique (equal last (setq last (org-trim (cdr p)))))
4859 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
4860 (insert stars " " (cdr p))))
4861 (goto-char start)
4862 (message "Sorting entries...done (%d entries%s)"
4863 nentries
4864 (if unique (format ", %d duplicates removed" nremoved) ""))))
4866 (defun org-do-sort (table what &optional with-case sorting-type)
4867 "Sort TABLE of WHAT according to SORTING-TYPE.
4868 The user will be prompted for the SORTING-TYPE if the call to this
4869 function does not specify it. WHAT is only for the prompt, to indicate
4870 what is being sorted. The sorting key will be extracted from
4871 the car of the elements of the table.
4872 If WITH-CASE is non-nil, the sorting will be case-sensitive."
4873 (unless sorting-type
4874 (message
4875 "Sort %s:[a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
4876 what)
4877 (setq sorting-type (read-char-exclusive)))
4878 (let ((dcst (downcase sorting-type))
4879 extractfun comparefun)
4880 ;; Define the appropriate functions
4881 (cond
4882 ((= dcst ?n)
4883 (setq extractfun 'string-to-number
4884 comparefun (if (= dcst sorting-type) '< '>)))
4885 ((= dcst ?a)
4886 (setq extractfun (if with-case 'identity 'downcase)
4887 comparefun (if (= dcst sorting-type)
4888 'string<
4889 (lambda (a b) (and (not (string< a b))
4890 (not (string= a b)))))))
4891 ((= dcst ?t)
4892 (setq extractfun
4893 (lambda (x)
4894 (if (string-match org-ts-regexp x)
4895 (time-to-seconds
4896 (org-time-string-to-time (match-string 0 x)))
4897 0))
4898 comparefun (if (= dcst sorting-type) '< '>)))
4899 (t (error "Invalid sorting type `%c'" sorting-type)))
4901 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
4902 table)
4903 (lambda (a b) (funcall comparefun (car a) (car b))))))
4905 ;;;; Plain list items, including checkboxes
4907 ;;; Plain list items
4909 (defun org-at-item-p ()
4910 "Is point in a line starting a hand-formatted item?"
4911 (let ((llt org-plain-list-ordered-item-terminator))
4912 (save-excursion
4913 (goto-char (point-at-bol))
4914 (looking-at
4915 (cond
4916 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4917 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4918 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4919 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4922 (defun org-in-item-p ()
4923 "It the cursor inside a plain list item.
4924 Does not have to be the first line."
4925 (save-excursion
4926 (condition-case nil
4927 (progn
4928 (org-beginning-of-item)
4929 (org-at-item-p)
4931 (error nil))))
4933 (defun org-insert-item (&optional checkbox)
4934 "Insert a new item at the current level.
4935 Return t when things worked, nil when we are not in an item."
4936 (when (save-excursion
4937 (condition-case nil
4938 (progn
4939 (org-beginning-of-item)
4940 (org-at-item-p)
4941 (if (org-invisible-p) (error "Invisible item"))
4943 (error nil)))
4944 (let* ((bul (match-string 0))
4945 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
4946 (match-end 0)))
4947 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
4948 pos)
4949 (cond
4950 ((and (org-at-item-p) (<= (point) eow))
4951 ;; before the bullet
4952 (beginning-of-line 1)
4953 (open-line (if blank 2 1)))
4954 ((<= (point) eow)
4955 (beginning-of-line 1))
4956 (t (newline (if blank 2 1))))
4957 (insert bul (if checkbox "[ ]" ""))
4958 (just-one-space)
4959 (setq pos (point))
4960 (end-of-line 1)
4961 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
4962 (org-maybe-renumber-ordered-list)
4963 (and checkbox (org-update-checkbox-count-maybe))
4966 ;;; Checkboxes
4968 (defun org-at-item-checkbox-p ()
4969 "Is point at a line starting a plain-list item with a checklet?"
4970 (and (org-at-item-p)
4971 (save-excursion
4972 (goto-char (match-end 0))
4973 (skip-chars-forward " \t")
4974 (looking-at "\\[[ X]\\]"))))
4976 (defun org-toggle-checkbox (&optional arg)
4977 "Toggle the checkbox in the current line."
4978 (interactive "P")
4979 (catch 'exit
4980 (let (beg end status (firstnew 'unknown))
4981 (cond
4982 ((org-region-active-p)
4983 (setq beg (region-beginning) end (region-end)))
4984 ((org-on-heading-p)
4985 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4986 ((org-at-item-checkbox-p)
4987 (save-excursion
4988 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4989 (throw 'exit t))
4990 (t (error "Not at a checkbox or heading, and no active region")))
4991 (save-excursion
4992 (goto-char beg)
4993 (while (< (point) end)
4994 (when (org-at-item-checkbox-p)
4995 (setq status (equal (match-string 0) "[X]"))
4996 (when (eq firstnew 'unknown)
4997 (setq firstnew (not status)))
4998 (replace-match
4999 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5000 (beginning-of-line 2)))))
5001 (org-update-checkbox-count-maybe))
5003 (defun org-update-checkbox-count-maybe ()
5004 "Update checkbox statistics unless turned off by user."
5005 (when org-provide-checkbox-statistics
5006 (org-update-checkbox-count)))
5008 (defun org-update-checkbox-count (&optional all)
5009 "Update the checkbox statistics in the current section.
5010 This will find all statistic cookies like [57%] and [6/12] and update them
5011 with the current numbers. With optional prefix argument ALL, do this for
5012 the whole buffer."
5013 (interactive "P")
5014 (save-excursion
5015 (let* ((buffer-invisibility-spec nil) ; Emacs 21 compatibility
5016 (beg (progn (outline-back-to-heading) (point)))
5017 (end (move-marker (make-marker)
5018 (progn (outline-next-heading) (point))))
5019 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5020 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
5021 b1 e1 f1 c-on c-off lim (cstat 0))
5022 (when all
5023 (goto-char (point-min))
5024 (outline-next-heading)
5025 (setq beg (point) end (point-max)))
5026 (goto-char beg)
5027 (while (re-search-forward re end t)
5028 (setq cstat (1+ cstat)
5029 b1 (match-beginning 0)
5030 e1 (match-end 0)
5031 f1 (match-beginning 1)
5032 lim (cond
5033 ((org-on-heading-p) (outline-next-heading) (point))
5034 ((org-at-item-p) (org-end-of-item) (point))
5035 (t nil))
5036 c-on 0 c-off 0)
5037 (goto-char e1)
5038 (when lim
5039 (while (re-search-forward re-box lim t)
5040 (if (equal (match-string 2) "[ ]")
5041 (setq c-off (1+ c-off))
5042 (setq c-on (1+ c-on))))
5043 (delete-region b1 e1)
5044 (goto-char b1)
5045 (insert (if f1
5046 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5047 (format "[%d/%d]" c-on (+ c-on c-off))))))
5048 (when (interactive-p)
5049 (message "Checkbox satistics updated %s (%d places)"
5050 (if all "in entire file" "in current outline entry") cstat)))))
5052 (defun org-get-checkbox-statistics-face ()
5053 "Select the face for checkbox statistics.
5054 The face will be `org-done' when all relevant boxes are checked. Otherwise
5055 it will be `org-todo'."
5056 (if (match-end 1)
5057 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5058 (if (and (> (match-end 2) (match-beginning 2))
5059 (equal (match-string 2) (match-string 3)))
5060 'org-done
5061 'org-todo)))
5063 (defun org-get-indentation (&optional line)
5064 "Get the indentation of the current line, interpreting tabs.
5065 When LINE is given, assume it represents a line and compute its indentation."
5066 (if line
5067 (if (string-match "^ *" (org-remove-tabs line))
5068 (match-end 0))
5069 (save-excursion
5070 (beginning-of-line 1)
5071 (skip-chars-forward " \t")
5072 (current-column))))
5074 (defun org-remove-tabs (s &optional width)
5075 "Replace tabulators in S with spaces.
5076 Assumes that s is a single line, starting in column 0."
5077 (setq width (or width tab-width))
5078 (while (string-match "\t" s)
5079 (setq s (replace-match
5080 (make-string
5081 (- (* width (/ (+ (match-beginning 0) width) width))
5082 (match-beginning 0)) ?\ )
5083 t t s)))
5086 ;; FIXME: document properly.
5087 (defun org-fix-indentation (line ind)
5088 "If the current indenation is smaller than ind1, leave it alone.
5089 If it is larger than ind, reduce it by ind."
5090 (let* ((l (org-remove-tabs line))
5091 (i (org-get-indentation l))
5092 (i1 (car ind)) (i2 (cdr ind)))
5093 (if (>= i i2) (setq l (substring line i2)))
5094 (if (> i1 0)
5095 (concat (make-string i1 ?\ ) l)
5096 l)))
5098 (defun org-beginning-of-item ()
5099 "Go to the beginning of the current hand-formatted item.
5100 If the cursor is not in an item, throw an error."
5101 (interactive)
5102 (let ((pos (point))
5103 (limit (save-excursion (org-back-to-heading)
5104 (beginning-of-line 2) (point)))
5105 ind ind1)
5106 (if (org-at-item-p)
5107 (beginning-of-line 1)
5108 (beginning-of-line 1)
5109 (skip-chars-forward " \t")
5110 (setq ind (current-column))
5111 (if (catch 'exit
5112 (while t
5113 (beginning-of-line 0)
5114 (if (< (point) limit) (throw 'exit nil))
5115 (unless (looking-at "[ \t]*$")
5116 (skip-chars-forward " \t")
5117 (setq ind1 (current-column))
5118 (if (< ind1 ind)
5119 (throw 'exit (org-at-item-p))))))
5121 (goto-char pos)
5122 (error "Not in an item")))))
5124 (defun org-end-of-item ()
5125 "Go to the end of the current hand-formatted item.
5126 If the cursor is not in an item, throw an error."
5127 (interactive)
5128 (let ((pos (point))
5129 (limit (save-excursion (outline-next-heading) (point)))
5130 (ind (save-excursion
5131 (org-beginning-of-item)
5132 (skip-chars-forward " \t")
5133 (current-column)))
5134 ind1)
5135 (if (catch 'exit
5136 (while t
5137 (beginning-of-line 2)
5138 (if (>= (point) limit) (throw 'exit t))
5139 (unless (looking-at "[ \t]*$")
5140 (skip-chars-forward " \t")
5141 (setq ind1 (current-column))
5142 (if (<= ind1 ind) (throw 'exit t)))))
5143 (beginning-of-line 1)
5144 (goto-char pos)
5145 (error "Not in an item"))))
5147 (defun org-next-item ()
5148 "Move to the beginning of the next item in the current plain list.
5149 Error if not at a plain list, or if this is the last item in the list."
5150 (interactive)
5151 (let (ind ind1 (pos (point)))
5152 (org-beginning-of-item)
5153 (setq ind (org-get-indentation))
5154 (org-end-of-item)
5155 (setq ind1 (org-get-indentation))
5156 (unless (and (org-at-item-p) (= ind ind1))
5157 (goto-char pos)
5158 (error "On last item"))))
5160 (defun org-previous-item ()
5161 "Move to the beginning of the previous item in the current plain list.
5162 Error if not at a plain list, or if this is the last item in the list."
5163 (interactive)
5164 (let (beg ind (pos (point)))
5165 (org-beginning-of-item)
5166 (setq beg (point))
5167 (setq ind (org-get-indentation))
5168 (goto-char beg)
5169 (catch 'exit
5170 (while t
5171 (beginning-of-line 0)
5172 (if (looking-at "[ \t]*$")
5174 (if (<= (org-get-indentation) ind)
5175 (throw 'exit t)))))
5176 (condition-case nil
5177 (org-beginning-of-item)
5178 (error (goto-char pos)
5179 (error "On first item")))))
5181 (defun org-move-item-down ()
5182 "Move the plain list item at point down, i.e. swap with following item.
5183 Subitems (items with larger indentation) are considered part of the item,
5184 so this really moves item trees."
5185 (interactive)
5186 (let (beg end ind ind1 (pos (point)) txt)
5187 (org-beginning-of-item)
5188 (setq beg (point))
5189 (setq ind (org-get-indentation))
5190 (org-end-of-item)
5191 (setq end (point))
5192 (setq ind1 (org-get-indentation))
5193 (if (and (org-at-item-p) (= ind ind1))
5194 (progn
5195 (org-end-of-item)
5196 (setq txt (buffer-substring beg end))
5197 (save-excursion
5198 (delete-region beg end))
5199 (setq pos (point))
5200 (insert txt)
5201 (goto-char pos)
5202 (org-maybe-renumber-ordered-list))
5203 (goto-char pos)
5204 (error "Cannot move this item further down"))))
5206 (defun org-move-item-up (arg)
5207 "Move the plain list item at point up, i.e. swap with previous item.
5208 Subitems (items with larger indentation) are considered part of the item,
5209 so this really moves item trees."
5210 (interactive "p")
5211 (let (beg end ind ind1 (pos (point)) txt)
5212 (org-beginning-of-item)
5213 (setq beg (point))
5214 (setq ind (org-get-indentation))
5215 (org-end-of-item)
5216 (setq end (point))
5217 (goto-char beg)
5218 (catch 'exit
5219 (while t
5220 (beginning-of-line 0)
5221 (if (looking-at "[ \t]*$")
5223 (if (<= (setq ind1 (org-get-indentation)) ind)
5224 (throw 'exit t)))))
5225 (condition-case nil
5226 (org-beginning-of-item)
5227 (error (goto-char beg)
5228 (error "Cannot move this item further up")))
5229 (setq ind1 (org-get-indentation))
5230 (if (and (org-at-item-p) (= ind ind1))
5231 (progn
5232 (setq txt (buffer-substring beg end))
5233 (save-excursion
5234 (delete-region beg end))
5235 (setq pos (point))
5236 (insert txt)
5237 (goto-char pos)
5238 (org-maybe-renumber-ordered-list))
5239 (goto-char pos)
5240 (error "Cannot move this item further up"))))
5242 (defun org-maybe-renumber-ordered-list ()
5243 "Renumber the ordered list at point if setup allows it.
5244 This tests the user option `org-auto-renumber-ordered-lists' before
5245 doing the renumbering."
5246 (and org-auto-renumber-ordered-lists
5247 (org-at-item-p)
5248 (match-beginning 3)
5249 (org-renumber-ordered-list 1)))
5251 (defun org-get-string-indentation (s)
5252 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5253 (let ((n -1) (i 0) (w tab-width) c)
5254 (catch 'exit
5255 (while (< (setq n (1+ n)) (length s))
5256 (setq c (aref s n))
5257 (cond ((= c ?\ ) (setq i (1+ i)))
5258 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5259 (t (throw 'exit t)))))
5262 (defun org-renumber-ordered-list (arg)
5263 "Renumber an ordered plain list.
5264 Cursor needs to be in the first line of an item, the line that starts
5265 with something like \"1.\" or \"2)\"."
5266 (interactive "p")
5267 (unless (and (org-at-item-p)
5268 (match-beginning 3))
5269 (error "This is not an ordered list"))
5270 (let ((line (org-current-line))
5271 (col (current-column))
5272 (ind (org-get-string-indentation
5273 (buffer-substring (point-at-bol) (match-beginning 3))))
5274 ;; (term (substring (match-string 3) -1))
5275 ind1 (n (1- arg)))
5276 ;; find where this list begins
5277 (catch 'exit
5278 (while t
5279 (catch 'next
5280 (beginning-of-line 0)
5281 (if (looking-at "[ \t]*$") (throw 'next t))
5282 (skip-chars-forward " \t") (setq ind1 (current-column))
5283 (if (or (< ind1 ind)
5284 (and (= ind1 ind)
5285 (not (org-at-item-p))))
5286 (throw 'exit t)))))
5287 ;; Walk forward and replace these numbers
5288 (catch 'exit
5289 (while t
5290 (catch 'next
5291 (beginning-of-line 2)
5292 (if (eobp) (throw 'exit nil))
5293 (if (looking-at "[ \t]*$") (throw 'next nil))
5294 (skip-chars-forward " \t") (setq ind1 (current-column))
5295 (if (> ind1 ind) (throw 'next t))
5296 (if (< ind1 ind) (throw 'exit t))
5297 (if (not (org-at-item-p)) (throw 'exit nil))
5298 (if (not (match-beginning 3))
5299 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
5300 (delete-region (match-beginning 3) (1- (match-end 3)))
5301 (goto-char (match-beginning 3))
5302 (insert (format "%d" (setq n (1+ n)))))))
5303 (goto-line line)
5304 (move-to-column col)))
5306 (defvar org-last-indent-begin-marker (make-marker))
5307 (defvar org-last-indent-end-marker (make-marker))
5309 (defun org-outdent-item (arg)
5310 "Outdent a local list item."
5311 (interactive "p")
5312 (org-indent-item (- arg)))
5314 (defun org-indent-item (arg)
5315 "Indent a local list item."
5316 (interactive "p")
5317 (unless (org-at-item-p)
5318 (error "Not on an item"))
5319 (save-excursion
5320 (let (beg end ind ind1)
5321 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5322 (setq beg org-last-indent-begin-marker
5323 end org-last-indent-end-marker)
5324 (org-beginning-of-item)
5325 (setq beg (move-marker org-last-indent-begin-marker (point)))
5326 (org-end-of-item)
5327 (setq end (move-marker org-last-indent-end-marker (point))))
5328 (goto-char beg)
5329 (skip-chars-forward " \t") (setq ind (current-column))
5330 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
5331 (while (< (point) end)
5332 (beginning-of-line 1)
5333 (skip-chars-forward " \t") (setq ind1 (current-column))
5334 (delete-region (point-at-bol) (point))
5335 (indent-to-column (+ ind1 arg))
5336 (beginning-of-line 2)))))
5338 ;;;; Archiving
5340 (defun org-archive-subtree (&optional find-done)
5341 "Move the current subtree to the archive.
5342 The archive can be a certain top-level heading in the current file, or in
5343 a different file. The tree will be moved to that location, the subtree
5344 heading be marked DONE, and the current time will be added.
5346 When called with prefix argument FIND-DONE, find whole trees without any
5347 open TODO items and archive them (after getting confirmation from the user).
5348 If the cursor is not at a headline when this comand is called, try all level
5349 1 trees. If the cursor is on a headline, only try the direct children of
5350 this heading. "
5351 (interactive "P")
5352 (if find-done
5353 (org-archive-all-done)
5354 ;; Save all relevant TODO keyword-relatex variables
5356 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
5357 (tr-org-todo-keywords org-todo-keywords)
5358 (tr-org-todo-interpretation org-todo-interpretation)
5359 (tr-org-done-string org-done-string)
5360 (tr-org-todo-regexp org-todo-regexp)
5361 (tr-org-todo-line-regexp org-todo-line-regexp)
5362 (this-buffer (current-buffer))
5363 file heading buffer level newfile-p)
5364 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
5365 (progn
5366 (setq file (format (match-string 1 org-archive-location)
5367 (file-name-nondirectory buffer-file-name))
5368 heading (match-string 2 org-archive-location)))
5369 (error "Invalid `org-archive-location'"))
5370 (if (> (length file) 0)
5371 (setq newfile-p (not (file-exists-p file))
5372 buffer (find-file-noselect file))
5373 (setq buffer (current-buffer)))
5374 (unless buffer
5375 (error "Cannot access file \"%s\"" file))
5376 (if (and (> (length heading) 0)
5377 (string-match "^\\*+" heading))
5378 (setq level (match-end 0))
5379 (setq heading nil level 0))
5380 (save-excursion
5381 ;; We first only copy, in case something goes wrong
5382 ;; we need to protect this-command, to avoid kill-region sets it,
5383 ;; which would lead to duplication of subtrees
5384 (let (this-command) (org-copy-subtree))
5385 (set-buffer buffer)
5386 ;; Enforce org-mode for the archive buffer
5387 (if (not (org-mode-p))
5388 ;; Force the mode for future visits.
5389 (let ((org-insert-mode-line-in-empty-file t))
5390 (call-interactively 'org-mode)))
5391 (when newfile-p
5392 (goto-char (point-max))
5393 (insert (format "\nArchived entries from file %s\n\n"
5394 (buffer-file-name this-buffer))))
5395 ;; Force the TODO keywords of the original buffer
5396 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
5397 (org-todo-keywords tr-org-todo-keywords)
5398 (org-todo-interpretation tr-org-todo-interpretation)
5399 (org-done-string tr-org-done-string)
5400 (org-todo-regexp tr-org-todo-regexp)
5401 (org-todo-line-regexp tr-org-todo-line-regexp))
5402 (goto-char (point-min))
5403 (if heading
5404 (progn
5405 (if (re-search-forward
5406 (concat "\\(^\\|\r\\)"
5407 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
5408 nil t)
5409 (goto-char (match-end 0))
5410 ;; Heading not found, just insert it at the end
5411 (goto-char (point-max))
5412 (or (bolp) (insert "\n"))
5413 (insert "\n" heading "\n")
5414 (end-of-line 0))
5415 ;; Make the subtree visible
5416 (show-subtree)
5417 (org-end-of-subtree t)
5418 (skip-chars-backward " \t\r\n")
5419 (and (looking-at "[ \t\r\n]*")
5420 (replace-match "\n\n")))
5421 ;; No specific heading, just go to end of file.
5422 (goto-char (point-max)) (insert "\n"))
5423 ;; Paste
5424 (org-paste-subtree (1+ level))
5425 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
5426 (if org-archive-mark-done
5427 (let (org-log-done)
5428 (org-todo (length org-todo-keywords))))
5429 ;; Move cursor to right after the TODO keyword
5430 (when org-archive-stamp-time
5431 (beginning-of-line 1)
5432 (looking-at org-todo-line-regexp)
5433 (goto-char (or (match-end 2) (match-beginning 3)))
5434 (org-insert-time-stamp (org-current-time) t t "(" ")"))
5435 ;; Save the buffer, if it is not the same buffer.
5436 (if (not (eq this-buffer buffer)) (save-buffer))))
5437 ;; Here we are back in the original buffer. Everything seems to have
5438 ;; worked. So now cut the tree and finish up.
5439 (let (this-command) (org-cut-subtree))
5440 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
5441 (message "Subtree archived %s"
5442 (if (eq this-buffer buffer)
5443 (concat "under heading: " heading)
5444 (concat "in file: " (abbreviate-file-name file)))))))
5446 (defun org-archive-all-done (&optional tag)
5447 "Archive sublevels of the current tree without open TODO items.
5448 If the cursor is not on a headline, try all level 1 trees. If
5449 it is on a headline, try all direct children.
5450 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
5451 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
5452 (rea (concat ".*:" org-archive-tag ":"))
5453 (begm (make-marker))
5454 (endm (make-marker))
5455 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
5456 "Move subtree to archive (no open TODO items)? "))
5457 beg end (cntarch 0))
5458 (if (org-on-heading-p)
5459 (progn
5460 (setq re1 (concat "^" (regexp-quote
5461 (make-string
5462 (1+ (- (match-end 0) (match-beginning 0)))
5463 ?*))
5464 " "))
5465 (move-marker begm (point))
5466 (move-marker endm (org-end-of-subtree t)))
5467 (setq re1 "^* ")
5468 (move-marker begm (point-min))
5469 (move-marker endm (point-max)))
5470 (save-excursion
5471 (goto-char begm)
5472 (while (re-search-forward re1 endm t)
5473 (setq beg (match-beginning 0)
5474 end (save-excursion (org-end-of-subtree t) (point)))
5475 (goto-char beg)
5476 (if (re-search-forward re end t)
5477 (goto-char end)
5478 (goto-char beg)
5479 (if (and (or (not tag) (not (looking-at rea)))
5480 (y-or-n-p question))
5481 (progn
5482 (if tag
5483 (org-toggle-tag org-archive-tag 'on)
5484 (org-archive-subtree))
5485 (setq cntarch (1+ cntarch)))
5486 (goto-char end)))))
5487 (message "%d trees archived" cntarch)))
5489 (defun org-cycle-hide-archived-subtrees (state)
5490 "Re-hide all archived subtrees after a visibility state change."
5491 (when (and (not org-cycle-open-archived-trees)
5492 (not (memq state '(overview folded))))
5493 (save-excursion
5494 (let* ((globalp (memq state '(contents all)))
5495 (beg (if globalp (point-min) (point)))
5496 (end (if globalp (point-max) (org-end-of-subtree t))))
5497 (org-hide-archived-subtrees beg end)
5498 (goto-char beg)
5499 (if (looking-at (concat ".*:" org-archive-tag ":"))
5500 (message (substitute-command-keys
5501 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5503 (defun org-force-cycle-archived ()
5504 "Cycle subtree even if it is archived."
5505 (interactive)
5506 (setq this-command 'org-cycle)
5507 (let ((org-cycle-open-archived-trees t))
5508 (call-interactively 'org-cycle)))
5510 (defun org-hide-archived-subtrees (beg end)
5511 "Re-hide all archived subtrees after a visibility state change."
5512 (save-excursion
5513 (let* ((re (concat ":" org-archive-tag ":")))
5514 (goto-char beg)
5515 (while (re-search-forward re end t)
5516 (and (org-on-heading-p) (hide-subtree))
5517 (org-end-of-subtree t)))))
5519 (defun org-toggle-tag (tag &optional onoff)
5520 "Toggle the tag TAG for the current line.
5521 If ONOFF is `on' or `off', don't toggle but set to this state."
5522 (unless (org-on-heading-p) (error "Not on headling"))
5523 (let (res current)
5524 (save-excursion
5525 (beginning-of-line)
5526 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5527 (point-at-eol) t)
5528 (progn
5529 (setq current (match-string 1))
5530 (replace-match ""))
5531 (setq current ""))
5532 (setq current (nreverse (org-split-string current ":")))
5533 (cond
5534 ((eq onoff 'on)
5535 (setq res t)
5536 (or (member tag current) (push tag current)))
5537 ((eq onoff 'off)
5538 (or (not (member tag current)) (setq current (delete tag current))))
5539 (t (if (member tag current)
5540 (setq current (delete tag current))
5541 (setq res t)
5542 (push tag current))))
5543 (end-of-line 1)
5544 (when current
5545 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5546 (org-set-tags nil t))
5547 res))
5549 (defun org-toggle-archive-tag (&optional arg)
5550 "Toggle the archive tag for the current headline.
5551 With prefix ARG, check all children of current headline and offer tagging
5552 the children that do not contain any open TODO items."
5553 (interactive "P")
5554 (if arg
5555 (org-archive-all-done 'tag)
5556 (let (set)
5557 (save-excursion
5558 (org-back-to-heading t)
5559 (setq set (org-toggle-tag org-archive-tag))
5560 (when set (hide-subtree)))
5561 (and set (beginning-of-line 1))
5562 (message "Subtree %s" (if set "archived" "unarchived")))))
5565 ;;;; Tables
5567 ;;; The table editor
5569 ;; Watch out: Here we are talking about two different kind of tables.
5570 ;; Most of the code is for the tables created with the Org-mode table editor.
5571 ;; Sometimes, we talk about tables created and edited with the table.el
5572 ;; Emacs package. We call the former org-type tables, and the latter
5573 ;; table.el-type tables.
5575 (defun org-before-change-function (beg end)
5576 "Every change indicates that a table might need an update."
5577 (setq org-table-may-need-update t))
5579 (defconst org-table-line-regexp "^[ \t]*|"
5580 "Detects an org-type table line.")
5581 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5582 "Detects an org-type table line.")
5583 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5584 "Detects a table line marked for automatic recalculation.")
5585 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5586 "Detects a table line marked for automatic recalculation.")
5587 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5588 "Detects a table line marked for automatic recalculation.")
5589 (defconst org-table-hline-regexp "^[ \t]*|-"
5590 "Detects an org-type table hline.")
5591 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5592 "Detects a table-type table hline.")
5593 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5594 "Detects an org-type or table-type table.")
5595 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5596 "Searching from within a table (any type) this finds the first line
5597 outside the table.")
5598 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5599 "Searching from within a table (any type) this finds the first line
5600 outside the table.")
5602 (defun org-table-create-with-table.el ()
5603 "Use the table.el package to insert a new table.
5604 If there is already a table at point, convert between Org-mode tables
5605 and table.el tables."
5606 (interactive)
5607 (require 'table)
5608 (cond
5609 ((org-at-table.el-p)
5610 (if (y-or-n-p "Convert table to Org-mode table? ")
5611 (org-table-convert)))
5612 ((org-at-table-p)
5613 (if (y-or-n-p "Convert table to table.el table? ")
5614 (org-table-convert)))
5615 (t (call-interactively 'table-insert))))
5617 (defun org-table-create-or-convert-from-region (arg)
5618 "Convert region to table, or create an empty table.
5619 If there is an active region, convert it to a table. If there is no such
5620 region, create an empty table."
5621 (interactive "P")
5622 (if (org-region-active-p)
5623 (org-table-convert-region (region-beginning) (region-end) arg)
5624 (org-table-create arg)))
5626 (defun org-table-create (&optional size)
5627 "Query for a size and insert a table skeleton.
5628 SIZE is a string Columns x Rows like for example \"3x2\"."
5629 (interactive "P")
5630 (unless size
5631 (setq size (read-string
5632 (concat "Table size Columns x Rows [e.g. "
5633 org-table-default-size "]: ")
5634 "" nil org-table-default-size)))
5636 (let* ((pos (point))
5637 (indent (make-string (current-column) ?\ ))
5638 (split (org-split-string size " *x *"))
5639 (rows (string-to-number (nth 1 split)))
5640 (columns (string-to-number (car split)))
5641 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5642 "\n")))
5643 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5644 (point-at-bol) (point)))
5645 (beginning-of-line 1)
5646 (newline))
5647 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5648 (dotimes (i rows) (insert line))
5649 (goto-char pos)
5650 (if (> rows 1)
5651 ;; Insert a hline after the first row.
5652 (progn
5653 (end-of-line 1)
5654 (insert "\n|-")
5655 (goto-char pos)))
5656 (org-table-align)))
5658 (defun org-table-convert-region (beg0 end0 &optional nspace)
5659 "Convert region to a table.
5660 The region goes from BEG0 to END0, but these borders will be moved
5661 slightly, to make sure a beginning of line in the first line is included.
5662 When NSPACE is non-nil, it indicates the minimum number of spaces that
5663 separate columns (default: just one space)."
5664 (interactive "rP")
5665 (let* ((beg (min beg0 end0))
5666 (end (max beg0 end0))
5667 (tabsep t)
5669 (goto-char beg)
5670 (beginning-of-line 1)
5671 (setq beg (move-marker (make-marker) (point)))
5672 (goto-char end)
5673 (if (bolp) (backward-char 1) (end-of-line 1))
5674 (setq end (move-marker (make-marker) (point)))
5675 ;; Lets see if this is tab-separated material. If every nonempty line
5676 ;; contains a tab, we will assume that it is tab-separated material
5677 (if nspace
5678 (setq tabsep nil)
5679 (goto-char beg)
5680 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5681 (if nspace (setq tabsep nil))
5682 (if tabsep
5683 (setq re "^\\|\t")
5684 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5685 (max 1 (prefix-numeric-value nspace)))))
5686 (goto-char beg)
5687 (while (re-search-forward re end t)
5688 (replace-match "| " t t))
5689 (goto-char beg)
5690 (insert " ")
5691 (org-table-align)))
5693 (defun org-table-import (file arg)
5694 "Import FILE as a table.
5695 The file is assumed to be tab-separated. Such files can be produced by most
5696 spreadsheet and database applications. If no tabs (at least one per line)
5697 are found, lines will be split on whitespace into fields."
5698 (interactive "f\nP")
5699 (or (bolp) (newline))
5700 (let ((beg (point))
5701 (pm (point-max)))
5702 (insert-file-contents file)
5703 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5705 (defun org-table-export ()
5706 "Export table as a tab-separated file.
5707 Such a file can be imported into a spreadsheet program like Excel."
5708 (interactive)
5709 (let* ((beg (org-table-begin))
5710 (end (org-table-end))
5711 (table (buffer-substring beg end))
5712 (file (read-file-name "Export table to: "))
5713 buf)
5714 (unless (or (not (file-exists-p file))
5715 (y-or-n-p (format "Overwrite file %s? " file)))
5716 (error "Abort"))
5717 (with-current-buffer (find-file-noselect file)
5718 (setq buf (current-buffer))
5719 (erase-buffer)
5720 (fundamental-mode)
5721 (insert table)
5722 (goto-char (point-min))
5723 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5724 (replace-match "" t t)
5725 (end-of-line 1))
5726 (goto-char (point-min))
5727 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5728 (replace-match "" t t)
5729 (goto-char (min (1+ (point)) (point-max))))
5730 (goto-char (point-min))
5731 (while (re-search-forward "^-[-+]*$" nil t)
5732 (replace-match "")
5733 (if (looking-at "\n")
5734 (delete-char 1)))
5735 (goto-char (point-min))
5736 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5737 (replace-match "\t" t t))
5738 (save-buffer))
5739 (kill-buffer buf)))
5741 (defvar org-table-aligned-begin-marker (make-marker)
5742 "Marker at the beginning of the table last aligned.
5743 Used to check if cursor still is in that table, to minimize realignment.")
5744 (defvar org-table-aligned-end-marker (make-marker)
5745 "Marker at the end of the table last aligned.
5746 Used to check if cursor still is in that table, to minimize realignment.")
5747 (defvar org-table-last-alignment nil
5748 "List of flags for flushright alignment, from the last re-alignment.
5749 This is being used to correctly align a single field after TAB or RET.")
5750 (defvar org-table-last-column-widths nil
5751 "List of max width of fields in each column.
5752 This is being used to correctly align a single field after TAB or RET.")
5754 (defvar org-last-recalc-line nil)
5755 (defconst org-narrow-column-arrow "=>"
5756 "Used as display property in narrowed table columns.")
5758 (defun org-table-align ()
5759 "Align the table at point by aligning all vertical bars."
5760 (interactive)
5761 (let* (
5762 ;; Limits of table
5763 (beg (org-table-begin))
5764 (end (org-table-end))
5765 ;; Current cursor position
5766 (linepos (org-current-line))
5767 (colpos (org-table-current-column))
5768 (winstart (window-start))
5769 (winstartline (org-current-line (min winstart (1- (point-max)))))
5770 lines (new "") lengths l typenums ty fields maxfields i
5771 column
5772 (indent "") cnt frac
5773 rfmt hfmt
5774 (spaces '(1 . 1))
5775 (sp1 (car spaces))
5776 (sp2 (cdr spaces))
5777 (rfmt1 (concat
5778 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
5779 (hfmt1 (concat
5780 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
5781 emptystrings links dates narrow fmax f1 len c e)
5782 (untabify beg end)
5783 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
5784 ;; Check if we have links or dates
5785 (goto-char beg)
5786 (setq links (re-search-forward org-bracket-link-regexp end t))
5787 (goto-char beg)
5788 (setq dates (and org-display-custom-times
5789 (re-search-forward org-ts-regexp-both end t)))
5790 ;; Make sure the link properties are right
5791 (when links (goto-char beg) (while (org-activate-bracket-links end)))
5792 ;; Make sure the date properties are right
5793 (when dates (goto-char beg) (while (org-activate-dates end)))
5795 ;; Check if we are narrowing any columns
5796 (goto-char beg)
5797 (setq narrow (and org-format-transports-properties-p
5798 (re-search-forward "<[0-9]+>" end t)))
5799 ;; Get the rows
5800 (setq lines (org-split-string
5801 (buffer-substring beg end) "\n"))
5802 ;; Store the indentation of the first line
5803 (if (string-match "^ *" (car lines))
5804 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
5805 ;; Mark the hlines by setting the corresponding element to nil
5806 ;; At the same time, we remove trailing space.
5807 (setq lines (mapcar (lambda (l)
5808 (if (string-match "^ *|-" l)
5810 (if (string-match "[ \t]+$" l)
5811 (substring l 0 (match-beginning 0))
5812 l)))
5813 lines))
5814 ;; Get the data fields by splitting the lines.
5815 (setq fields (mapcar
5816 (lambda (l)
5817 (org-split-string l " *| *"))
5818 (delq nil (copy-sequence lines))))
5819 ;; How many fields in the longest line?
5820 (condition-case nil
5821 (setq maxfields (apply 'max (mapcar 'length fields)))
5822 (error
5823 (kill-region beg end)
5824 (org-table-create org-table-default-size)
5825 (error "Empty table - created default table")))
5826 ;; A list of empty strings to fill any short rows on output
5827 (setq emptystrings (make-list maxfields ""))
5828 ;; Check for special formatting.
5829 (setq i -1)
5830 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
5831 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
5832 ;; Check if there is an explicit width specified
5833 (when (and org-table-limit-column-width narrow)
5834 (setq c column fmax nil)
5835 (while c
5836 (setq e (pop c))
5837 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
5838 (setq fmax (string-to-number (match-string 1 e)) c nil)))
5839 ;; Find fields that are wider than fmax, and shorten them
5840 (when fmax
5841 (loop for xx in column do
5842 (when (and (stringp xx)
5843 (> (org-string-width xx) fmax))
5844 (org-add-props xx nil
5845 'help-echo
5846 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
5847 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
5848 (unless (> f1 1)
5849 (error "Cannot narrow field starting with wide link \"%s\""
5850 (match-string 0 xx)))
5851 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
5852 (add-text-properties (- f1 2) f1
5853 (list 'display org-narrow-column-arrow)
5854 xx)))))
5855 ;; Get the maximum width for each column
5856 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
5857 ;; Get the fraction of numbers, to decide about alignment of the column
5858 (setq cnt 0 frac 0.0)
5859 (loop for x in column do
5860 (if (equal x "")
5862 (setq frac ( / (+ (* frac cnt)
5863 (if (string-match org-table-number-regexp x) 1 0))
5864 (setq cnt (1+ cnt))))))
5865 (push (>= frac org-table-number-fraction) typenums))
5866 (setq lengths (nreverse lengths) typenums (nreverse typenums))
5868 ;; Store the alignment of this table, for later editing of single fields
5869 (setq org-table-last-alignment typenums
5870 org-table-last-column-widths lengths)
5872 ;; With invisible characters, `format' does not get the field width right
5873 ;; So we need to make these fields wide by hand.
5874 (when links
5875 (loop for i from 0 upto (1- maxfields) do
5876 (setq len (nth i lengths))
5877 (loop for j from 0 upto (1- (length fields)) do
5878 (setq c (nthcdr i (car (nthcdr j fields))))
5879 (if (and (stringp (car c))
5880 (string-match org-bracket-link-regexp (car c))
5881 (< (org-string-width (car c)) len))
5882 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
5884 ;; Compute the formats needed for output of the table
5885 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
5886 (while (setq l (pop lengths))
5887 (setq ty (if (pop typenums) "" "-")) ; number types flushright
5888 (setq rfmt (concat rfmt (format rfmt1 ty l))
5889 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
5890 (setq rfmt (concat rfmt "\n")
5891 hfmt (concat (substring hfmt 0 -1) "|\n"))
5893 (setq new (mapconcat
5894 (lambda (l)
5895 (if l (apply 'format rfmt
5896 (append (pop fields) emptystrings))
5897 hfmt))
5898 lines ""))
5899 ;; Replace the old one
5900 (delete-region beg end)
5901 (move-marker end nil)
5902 (move-marker org-table-aligned-begin-marker (point))
5903 (insert new)
5904 (move-marker org-table-aligned-end-marker (point))
5905 (when (and orgtbl-mode (not (org-mode-p)))
5906 (goto-char org-table-aligned-begin-marker)
5907 (while (org-hide-wide-columns org-table-aligned-end-marker)))
5908 ;; Try to move to the old location
5909 (goto-line winstartline)
5910 (setq winstart (point-at-bol))
5911 (goto-line linepos)
5912 (set-window-start (selected-window) winstart 'noforce)
5913 (org-table-goto-column colpos)
5914 (setq org-table-may-need-update nil)
5917 (defun org-string-width (s)
5918 "Compute width of string, ignoring invisible characters.
5919 This ignores character with invisibility property `org-link', and also
5920 characters with property `org-cwidth', because these will become invisible
5921 upon the next fontification round."
5922 (let (b l)
5923 (when (or (eq t buffer-invisibility-spec)
5924 (assq 'org-link buffer-invisibility-spec))
5925 (while (setq b (text-property-any 0 (length s)
5926 'invisible 'org-link s))
5927 (setq s (concat (substring s 0 b)
5928 (substring s (or (next-single-property-change
5929 b 'invisible s) (length s)))))))
5930 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
5931 (setq s (concat (substring s 0 b)
5932 (substring s (or (next-single-property-change
5933 b 'org-cwidth s) (length s))))))
5934 (setq l (string-width s) b -1)
5935 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
5936 (setq l (- l (get-text-property b 'org-dwidth-n s))))
5939 (defun org-table-begin (&optional table-type)
5940 "Find the beginning of the table and return its position.
5941 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
5942 (save-excursion
5943 (if (not (re-search-backward
5944 (if table-type org-table-any-border-regexp
5945 org-table-border-regexp)
5946 nil t))
5947 (progn (goto-char (point-min)) (point))
5948 (goto-char (match-beginning 0))
5949 (beginning-of-line 2)
5950 (point))))
5952 (defun org-table-end (&optional table-type)
5953 "Find the end of the table and return its position.
5954 With argument TABLE-TYPE, go to the end of a table.el-type table."
5955 (save-excursion
5956 (if (not (re-search-forward
5957 (if table-type org-table-any-border-regexp
5958 org-table-border-regexp)
5959 nil t))
5960 (goto-char (point-max))
5961 (goto-char (match-beginning 0)))
5962 (point-marker)))
5964 (defun org-table-justify-field-maybe (&optional new)
5965 "Justify the current field, text to left, number to right.
5966 Optional argument NEW may specify text to replace the current field content."
5967 (cond
5968 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
5969 ((org-at-table-hline-p))
5970 ((and (not new)
5971 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
5972 (current-buffer)))
5973 (< (point) org-table-aligned-begin-marker)
5974 (>= (point) org-table-aligned-end-marker)))
5975 ;; This is not the same table, force a full re-align
5976 (setq org-table-may-need-update t))
5977 (t ;; realign the current field, based on previous full realign
5978 (let* ((pos (point)) s
5979 (col (org-table-current-column))
5980 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
5981 l f n o e)
5982 (when (> col 0)
5983 (skip-chars-backward "^|\n")
5984 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
5985 (progn
5986 (setq s (match-string 1)
5987 o (match-string 0)
5988 l (max 1 (- (match-end 0) (match-beginning 0) 3))
5989 e (not (= (match-beginning 2) (match-end 2))))
5990 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
5991 l (if e "|" (setq org-table-may-need-update t) ""))
5992 n (format f s))
5993 (if new
5994 (if (<= (length new) l) ;; FIXME: length -> str-width?
5995 (setq n (format f new))
5996 (setq n (concat new "|") org-table-may-need-update t)))
5997 (or (equal n o)
5998 (let (org-table-may-need-update)
5999 (replace-match n))))
6000 (setq org-table-may-need-update t))
6001 (goto-char pos))))))
6003 (defun org-table-next-field ()
6004 "Go to the next field in the current table, creating new lines as needed.
6005 Before doing so, re-align the table if necessary."
6006 (interactive)
6007 (org-table-maybe-eval-formula)
6008 (org-table-maybe-recalculate-line)
6009 (if (and org-table-automatic-realign
6010 org-table-may-need-update)
6011 (org-table-align))
6012 (let ((end (org-table-end)))
6013 (if (org-at-table-hline-p)
6014 (end-of-line 1))
6015 (condition-case nil
6016 (progn
6017 (re-search-forward "|" end)
6018 (if (looking-at "[ \t]*$")
6019 (re-search-forward "|" end))
6020 (if (and (looking-at "-")
6021 org-table-tab-jumps-over-hlines
6022 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
6023 (goto-char (match-beginning 1)))
6024 (if (looking-at "-")
6025 (progn
6026 (beginning-of-line 0)
6027 (org-table-insert-row 'below))
6028 (if (looking-at " ") (forward-char 1))))
6029 (error
6030 (org-table-insert-row 'below)))))
6032 (defun org-table-previous-field ()
6033 "Go to the previous field in the table.
6034 Before doing so, re-align the table if necessary."
6035 (interactive)
6036 (org-table-justify-field-maybe)
6037 (org-table-maybe-recalculate-line)
6038 (if (and org-table-automatic-realign
6039 org-table-may-need-update)
6040 (org-table-align))
6041 (if (org-at-table-hline-p)
6042 (end-of-line 1))
6043 (re-search-backward "|" (org-table-begin))
6044 (re-search-backward "|" (org-table-begin))
6045 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6046 (re-search-backward "|" (org-table-begin)))
6047 (if (looking-at "| ?")
6048 (goto-char (match-end 0))))
6050 (defun org-table-next-row ()
6051 "Go to the next row (same column) in the current table.
6052 Before doing so, re-align the table if necessary."
6053 (interactive)
6054 (org-table-maybe-eval-formula)
6055 (org-table-maybe-recalculate-line)
6056 (if (or (looking-at "[ \t]*$")
6057 (save-excursion (skip-chars-backward " \t") (bolp)))
6058 (newline)
6059 (if (and org-table-automatic-realign
6060 org-table-may-need-update)
6061 (org-table-align))
6062 (let ((col (org-table-current-column)))
6063 (beginning-of-line 2)
6064 (if (or (not (org-at-table-p))
6065 (org-at-table-hline-p))
6066 (progn
6067 (beginning-of-line 0)
6068 (org-table-insert-row 'below)))
6069 (org-table-goto-column col)
6070 (skip-chars-backward "^|\n\r")
6071 (if (looking-at " ") (forward-char 1)))))
6073 (defun org-table-copy-down (n)
6074 "Copy a field down in the current column.
6075 If the field at the cursor is empty, copy into it the content of the nearest
6076 non-empty field above. With argument N, use the Nth non-empty field.
6077 If the current field is not empty, it is copied down to the next row, and
6078 the cursor is moved with it. Therefore, repeating this command causes the
6079 column to be filled row-by-row.
6080 If the variable `org-table-copy-increment' is non-nil and the field is an
6081 integer, it will be incremented while copying."
6082 (interactive "p")
6083 (let* ((colpos (org-table-current-column))
6084 (field (org-table-get-field))
6085 (non-empty (string-match "[^ \t]" field))
6086 (beg (org-table-begin))
6087 txt)
6088 (org-table-check-inside-data-field)
6089 (if non-empty
6090 (progn
6091 (setq txt (org-trim field))
6092 (org-table-next-row)
6093 (org-table-blank-field))
6094 (save-excursion
6095 (setq txt
6096 (catch 'exit
6097 (while (progn (beginning-of-line 1)
6098 (re-search-backward org-table-dataline-regexp
6099 beg t))
6100 (org-table-goto-column colpos t)
6101 (if (and (looking-at
6102 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6103 (= (setq n (1- n)) 0))
6104 (throw 'exit (match-string 1))))))))
6105 (if txt
6106 (progn
6107 (if (and org-table-copy-increment
6108 (string-match "^[0-9]+$" txt))
6109 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6110 (insert txt)
6111 (org-table-maybe-recalculate-line)
6112 (org-table-align))
6113 (error "No non-empty field found"))))
6115 (defun org-table-check-inside-data-field ()
6116 "Is point inside a table data field?
6117 I.e. not on a hline or before the first or after the last column?
6118 This actually throws an error, so it aborts the current command."
6119 (if (or (not (org-at-table-p))
6120 (= (org-table-current-column) 0)
6121 (org-at-table-hline-p)
6122 (looking-at "[ \t]*$"))
6123 (error "Not in table data field")))
6125 (defvar org-table-clip nil
6126 "Clipboard for table regions.")
6128 (defun org-table-blank-field ()
6129 "Blank the current table field or active region."
6130 (interactive)
6131 (org-table-check-inside-data-field)
6132 (if (and (interactive-p) (org-region-active-p))
6133 (let (org-table-clip)
6134 (org-table-cut-region (region-beginning) (region-end)))
6135 (skip-chars-backward "^|")
6136 (backward-char 1)
6137 (if (looking-at "|[^|\n]+")
6138 (let* ((pos (match-beginning 0))
6139 (match (match-string 0))
6140 (len (org-string-width match)))
6141 (replace-match (concat "|" (make-string (1- len) ?\ )))
6142 (goto-char (+ 2 pos))
6143 (substring match 1)))))
6145 (defun org-table-get-field (&optional n replace)
6146 "Return the value of the field in column N of current row.
6147 N defaults to current field.
6148 If REPLACE is a string, replace field with this value. The return value
6149 is always the old value."
6150 (and n (org-table-goto-column n))
6151 (skip-chars-backward "^|\n")
6152 (backward-char 1)
6153 (if (looking-at "|[^|\r\n]*")
6154 (let* ((pos (match-beginning 0))
6155 (val (buffer-substring (1+ pos) (match-end 0))))
6156 (if replace
6157 (replace-match (concat "|" replace)))
6158 (goto-char (min (point-at-eol) (+ 2 pos)))
6159 val)
6160 (forward-char 1) ""))
6162 (defun org-table-current-column ()
6163 "Find out which column we are in.
6164 When called interactively, column is also displayed in echo area."
6165 (interactive)
6166 (if (interactive-p) (org-table-check-inside-data-field))
6167 (save-excursion
6168 (let ((cnt 0) (pos (point)))
6169 (beginning-of-line 1)
6170 (while (search-forward "|" pos t)
6171 (setq cnt (1+ cnt)))
6172 (if (interactive-p) (message "This is table column %d" cnt))
6173 cnt)))
6175 (defun org-table-goto-column (n &optional on-delim force)
6176 "Move the cursor to the Nth column in the current table line.
6177 With optional argument ON-DELIM, stop with point before the left delimiter
6178 of the field.
6179 If there are less than N fields, just go to after the last delimiter.
6180 However, when FORCE is non-nil, create new columns if necessary."
6181 (interactive "p")
6182 (let ((pos (point-at-eol)))
6183 (beginning-of-line 1)
6184 (when (> n 0)
6185 (while (and (> (setq n (1- n)) -1)
6186 (or (search-forward "|" pos t)
6187 (and force
6188 (progn (end-of-line 1)
6189 (skip-chars-backward "^|")
6190 (insert " | "))))))
6191 ; (backward-char 2) t)))))
6192 (when (and force (not (looking-at ".*|")))
6193 (save-excursion (end-of-line 1) (insert " | ")))
6194 (if on-delim
6195 (backward-char 1)
6196 (if (looking-at " ") (forward-char 1))))))
6198 (defun org-at-table-p (&optional table-type)
6199 "Return t if the cursor is inside an org-type table.
6200 If TABLE-TYPE is non-nil, also check for table.el-type tables."
6201 (if org-enable-table-editor
6202 (save-excursion
6203 (beginning-of-line 1)
6204 (looking-at (if table-type org-table-any-line-regexp
6205 org-table-line-regexp)))
6206 nil))
6208 (defun org-at-table.el-p ()
6209 "Return t if and only if we are at a table.el table."
6210 (and (org-at-table-p 'any)
6211 (save-excursion
6212 (goto-char (org-table-begin 'any))
6213 (looking-at org-table1-hline-regexp))))
6215 (defun org-table-recognize-table.el ()
6216 "If there is a table.el table nearby, recognize it and move into it."
6217 (if org-table-tab-recognizes-table.el
6218 (if (org-at-table.el-p)
6219 (progn
6220 (beginning-of-line 1)
6221 (if (looking-at org-table-dataline-regexp)
6223 (if (looking-at org-table1-hline-regexp)
6224 (progn
6225 (beginning-of-line 2)
6226 (if (looking-at org-table-any-border-regexp)
6227 (beginning-of-line -1)))))
6228 (if (re-search-forward "|" (org-table-end t) t)
6229 (progn
6230 (require 'table)
6231 (if (table--at-cell-p (point))
6233 (message "recognizing table.el table...")
6234 (table-recognize-table)
6235 (message "recognizing table.el table...done")))
6236 (error "This should not happen..."))
6238 nil)
6239 nil))
6241 (defun org-at-table-hline-p ()
6242 "Return t if the cursor is inside a hline in a table."
6243 (if org-enable-table-editor
6244 (save-excursion
6245 (beginning-of-line 1)
6246 (looking-at org-table-hline-regexp))
6247 nil))
6249 (defun org-table-insert-column ()
6250 "Insert a new column into the table."
6251 (interactive)
6252 (if (not (org-at-table-p))
6253 (error "Not at a table"))
6254 (org-table-find-dataline)
6255 (let* ((col (max 1 (org-table-current-column)))
6256 (beg (org-table-begin))
6257 (end (org-table-end))
6258 ;; Current cursor position
6259 (linepos (org-current-line))
6260 (colpos col))
6261 (goto-char beg)
6262 (while (< (point) end)
6263 (if (org-at-table-hline-p)
6265 (org-table-goto-column col t)
6266 (insert "| "))
6267 (beginning-of-line 2))
6268 (move-marker end nil)
6269 (goto-line linepos)
6270 (org-table-goto-column colpos)
6271 (org-table-align)
6272 (org-table-modify-formulas 'insert col)))
6274 (defun org-table-find-dataline ()
6275 "Find a dataline in the current table, which is needed for column commands."
6276 (if (and (org-at-table-p)
6277 (not (org-at-table-hline-p)))
6279 (let ((col (current-column))
6280 (end (org-table-end)))
6281 (move-to-column col)
6282 (while (and (< (point) end)
6283 (or (not (= (current-column) col))
6284 (org-at-table-hline-p)))
6285 (beginning-of-line 2)
6286 (move-to-column col))
6287 (if (and (org-at-table-p)
6288 (not (org-at-table-hline-p)))
6290 (error
6291 "Please position cursor in a data line for column operations")))))
6293 (defun org-table-delete-column ()
6294 "Delete a column from the table."
6295 (interactive)
6296 (if (not (org-at-table-p))
6297 (error "Not at a table"))
6298 (org-table-find-dataline)
6299 (org-table-check-inside-data-field)
6300 (let* ((col (org-table-current-column))
6301 (beg (org-table-begin))
6302 (end (org-table-end))
6303 ;; Current cursor position
6304 (linepos (org-current-line))
6305 (colpos col))
6306 (goto-char beg)
6307 (while (< (point) end)
6308 (if (org-at-table-hline-p)
6310 (org-table-goto-column col t)
6311 (and (looking-at "|[^|\n]+|")
6312 (replace-match "|")))
6313 (beginning-of-line 2))
6314 (move-marker end nil)
6315 (goto-line linepos)
6316 (org-table-goto-column colpos)
6317 (org-table-align)
6318 (org-table-modify-formulas 'remove col)))
6320 (defun org-table-move-column-right ()
6321 "Move column to the right."
6322 (interactive)
6323 (org-table-move-column nil))
6324 (defun org-table-move-column-left ()
6325 "Move column to the left."
6326 (interactive)
6327 (org-table-move-column 'left))
6329 (defun org-table-move-column (&optional left)
6330 "Move the current column to the right. With arg LEFT, move to the left."
6331 (interactive "P")
6332 (if (not (org-at-table-p))
6333 (error "Not at a table"))
6334 (org-table-find-dataline)
6335 (org-table-check-inside-data-field)
6336 (let* ((col (org-table-current-column))
6337 (col1 (if left (1- col) col))
6338 (beg (org-table-begin))
6339 (end (org-table-end))
6340 ;; Current cursor position
6341 (linepos (org-current-line))
6342 (colpos (if left (1- col) (1+ col))))
6343 (if (and left (= col 1))
6344 (error "Cannot move column further left"))
6345 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6346 (error "Cannot move column further right"))
6347 (goto-char beg)
6348 (while (< (point) end)
6349 (if (org-at-table-hline-p)
6351 (org-table-goto-column col1 t)
6352 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6353 (replace-match "|\\2|\\1|")))
6354 (beginning-of-line 2))
6355 (move-marker end nil)
6356 (goto-line linepos)
6357 (org-table-goto-column colpos)
6358 (org-table-align)
6359 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6361 (defun org-table-move-row-down ()
6362 "Move table row down."
6363 (interactive)
6364 (org-table-move-row nil))
6365 (defun org-table-move-row-up ()
6366 "Move table row up."
6367 (interactive)
6368 (org-table-move-row 'up))
6370 (defun org-table-move-row (&optional up)
6371 "Move the current table line down. With arg UP, move it up."
6372 (interactive "P")
6373 (let ((col (current-column))
6374 (pos (point))
6375 (tonew (if up 0 2))
6376 txt)
6377 (beginning-of-line tonew)
6378 (if (not (org-at-table-p))
6379 (progn
6380 (goto-char pos)
6381 (error "Cannot move row further")))
6382 (goto-char pos)
6383 (beginning-of-line 1)
6384 (setq pos (point))
6385 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6386 (delete-region (point) (1+ (point-at-eol)))
6387 (beginning-of-line tonew)
6388 (insert txt)
6389 (beginning-of-line 0)
6390 (move-to-column col)))
6392 (defun org-table-insert-row (&optional arg)
6393 "Insert a new row above the current line into the table.
6394 With prefix ARG, insert below the current line."
6395 (interactive "P")
6396 (if (not (org-at-table-p))
6397 (error "Not at a table"))
6398 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
6399 (new (org-table-clean-line line)))
6400 ;; Fix the first field if necessary
6401 (if (string-match "^[ \t]*| *[#$] *|" line)
6402 (setq new (replace-match (match-string 0 line) t t new)))
6403 (beginning-of-line (if arg 2 1))
6404 (let (org-table-may-need-update) (insert-before-markers new "\n"))
6405 (beginning-of-line 0)
6406 (re-search-forward "| ?" (point-at-eol) t)
6407 (and org-table-may-need-update (org-table-align))))
6409 (defun org-table-insert-hline (&optional arg)
6410 "Insert a horizontal-line below the current line into the table.
6411 With prefix ARG, insert above the current line."
6412 (interactive "P")
6413 (if (not (org-at-table-p))
6414 (error "Not at a table"))
6415 (let ((line (org-table-clean-line
6416 (buffer-substring (point-at-bol) (point-at-eol))))
6417 (col (current-column)))
6418 (while (string-match "|\\( +\\)|" line)
6419 (setq line (replace-match
6420 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
6421 ?-) "|") t t line)))
6422 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
6423 (beginning-of-line (if arg 1 2))
6424 (insert line "\n")
6425 (beginning-of-line (if arg 1 -1))
6426 (move-to-column col)))
6428 (defun org-table-clean-line (s)
6429 "Convert a table line S into a string with only \"|\" and space.
6430 In particular, this does handle wide and invisible characters."
6431 (if (string-match "^[ \t]*|-" s)
6432 ;; It's a hline, just map the characters
6433 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
6434 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
6435 (setq s (replace-match
6436 (concat "|" (make-string (org-string-width (match-string 1 s))
6437 ?\ ) "|")
6438 t t s)))
6441 (defun org-table-kill-row ()
6442 "Delete the current row or horizontal line from the table."
6443 (interactive)
6444 (if (not (org-at-table-p))
6445 (error "Not at a table"))
6446 (let ((col (current-column)))
6447 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6448 (if (not (org-at-table-p)) (beginning-of-line 0))
6449 (move-to-column col)))
6451 (defun org-table-sort-lines (with-case &optional sorting-type)
6452 "Sort table lines according to the column at point.
6454 The position of point indicates the column to be used for
6455 sorting, and the range of lines is the range between the nearest
6456 horizontal separator lines, or the entire table of no such lines
6457 exist. If point is before the first column, you will be prompted
6458 for the sorting column. If there is an active region, the mark
6459 specifies the first line and the sorting column, while point
6460 should be in the last line to be included into the sorting.
6462 The command then prompts for the sorting type which can be
6463 alphabetically, numerically, or by time (as given in a time stamp
6464 in the field). Sorting in reverse order is also possible.
6466 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
6468 If SORTING-TYPE is specified when this function is called from a Lisp
6469 program, no prompting will take place. SORTING-TYPE must be a character,
6470 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
6471 should be done in reverse order."
6472 (interactive "P")
6473 (let* ((thisline (org-current-line))
6474 (thiscol (org-table-current-column))
6475 beg end bcol ecol tend tbeg column lns pos)
6476 (when (equal thiscol 0)
6477 (if (interactive-p)
6478 (setq thiscol
6479 (string-to-number
6480 (read-string "Use column N for sorting: ")))
6481 (setq thiscol 1))
6482 (org-table-goto-column thiscol))
6483 (org-table-check-inside-data-field)
6484 (if (org-region-active-p)
6485 (progn
6486 (setq beg (region-beginning) end (region-end))
6487 (goto-char beg)
6488 (setq column (org-table-current-column)
6489 beg (point-at-bol))
6490 (goto-char end)
6491 (setq end (point-at-bol 2)))
6492 (setq column (org-table-current-column)
6493 pos (point)
6494 tbeg (org-table-begin)
6495 tend (org-table-end))
6496 (if (re-search-backward org-table-hline-regexp tbeg t)
6497 (setq beg (point-at-bol 2))
6498 (goto-char tbeg)
6499 (setq beg (point-at-bol 1)))
6500 (goto-char pos)
6501 (if (re-search-forward org-table-hline-regexp tend t)
6502 (setq beg (point-at-bol 0))
6503 (goto-char tend)
6504 (setq end (point-at-bol))))
6505 (setq beg (move-marker (make-marker) beg)
6506 end (move-marker (make-marker) end))
6507 (untabify beg end)
6508 (goto-char beg)
6509 (org-table-goto-column column)
6510 (skip-chars-backward "^|")
6511 (setq bcol (current-column))
6512 (org-table-goto-column (1+ column))
6513 (skip-chars-backward "^|")
6514 (setq ecol (1- (current-column)))
6515 (org-table-goto-column column)
6516 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
6517 (org-split-string (buffer-substring beg end) "\n")))
6518 (setq lns (org-do-sort lns "Table" with-case sorting-type))
6519 (delete-region beg end)
6520 (move-marker beg nil)
6521 (move-marker end nil)
6522 (insert (mapconcat 'cdr lns "\n") "\n")
6523 (goto-line thisline)
6524 (org-table-goto-column thiscol)
6525 (message "%d lines sorted, based on column %d" (length lns) column)))
6527 (defun org-table-cut-region (beg end)
6528 "Copy region in table to the clipboard and blank all relevant fields."
6529 (interactive "r")
6530 (org-table-copy-region beg end 'cut))
6532 (defun org-table-copy-region (beg end &optional cut)
6533 "Copy rectangular region in table to clipboard.
6534 A special clipboard is used which can only be accessed
6535 with `org-table-paste-rectangle'."
6536 (interactive "rP")
6537 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6538 region cols
6539 (rpl (if cut " " nil)))
6540 (goto-char beg)
6541 (org-table-check-inside-data-field)
6542 (setq l01 (count-lines (point-min) (point))
6543 c01 (org-table-current-column))
6544 (goto-char end)
6545 (org-table-check-inside-data-field)
6546 (setq l02 (count-lines (point-min) (point))
6547 c02 (org-table-current-column))
6548 (setq l1 (min l01 l02) l2 (max l01 l02)
6549 c1 (min c01 c02) c2 (max c01 c02))
6550 (catch 'exit
6551 (while t
6552 (catch 'nextline
6553 (if (> l1 l2) (throw 'exit t))
6554 (goto-line l1)
6555 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6556 (setq cols nil ic1 c1 ic2 c2)
6557 (while (< ic1 (1+ ic2))
6558 (push (org-table-get-field ic1 rpl) cols)
6559 (setq ic1 (1+ ic1)))
6560 (push (nreverse cols) region)
6561 (setq l1 (1+ l1)))))
6562 (setq org-table-clip (nreverse region))
6563 (if cut (org-table-align))
6564 org-table-clip))
6566 (defun org-table-paste-rectangle ()
6567 "Paste a rectangular region into a table.
6568 The upper right corner ends up in the current field. All involved fields
6569 will be overwritten. If the rectangle does not fit into the present table,
6570 the table is enlarged as needed. The process ignores horizontal separator
6571 lines."
6572 (interactive)
6573 (unless (and org-table-clip (listp org-table-clip))
6574 (error "First cut/copy a region to paste!"))
6575 (org-table-check-inside-data-field)
6576 (let* ((clip org-table-clip)
6577 (line (count-lines (point-min) (point)))
6578 (col (org-table-current-column))
6579 (org-enable-table-editor t)
6580 (org-table-automatic-realign nil)
6581 c cols field)
6582 (while (setq cols (pop clip))
6583 (while (org-at-table-hline-p) (beginning-of-line 2))
6584 (if (not (org-at-table-p))
6585 (progn (end-of-line 0) (org-table-next-field)))
6586 (setq c col)
6587 (while (setq field (pop cols))
6588 (org-table-goto-column c nil 'force)
6589 (org-table-get-field nil field)
6590 (setq c (1+ c)))
6591 (beginning-of-line 2))
6592 (goto-line line)
6593 (org-table-goto-column col)
6594 (org-table-align)))
6596 (defun org-table-convert ()
6597 "Convert from `org-mode' table to table.el and back.
6598 Obviously, this only works within limits. When an Org-mode table is
6599 converted to table.el, all horizontal separator lines get lost, because
6600 table.el uses these as cell boundaries and has no notion of horizontal lines.
6601 A table.el table can be converted to an Org-mode table only if it does not
6602 do row or column spanning. Multiline cells will become multiple cells.
6603 Beware, Org-mode does not test if the table can be successfully converted - it
6604 blindly applies a recipe that works for simple tables."
6605 (interactive)
6606 (require 'table)
6607 (if (org-at-table.el-p)
6608 ;; convert to Org-mode table
6609 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6610 (end (move-marker (make-marker) (org-table-end t))))
6611 (table-unrecognize-region beg end)
6612 (goto-char beg)
6613 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6614 (replace-match ""))
6615 (goto-char beg))
6616 (if (org-at-table-p)
6617 ;; convert to table.el table
6618 (let ((beg (move-marker (make-marker) (org-table-begin)))
6619 (end (move-marker (make-marker) (org-table-end))))
6620 ;; first, get rid of all horizontal lines
6621 (goto-char beg)
6622 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6623 (replace-match ""))
6624 ;; insert a hline before first
6625 (goto-char beg)
6626 (org-table-insert-hline 'above)
6627 (beginning-of-line -1)
6628 ;; insert a hline after each line
6629 (while (progn (beginning-of-line 3) (< (point) end))
6630 (org-table-insert-hline))
6631 (goto-char beg)
6632 (setq end (move-marker end (org-table-end)))
6633 ;; replace "+" at beginning and ending of hlines
6634 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6635 (replace-match "\\1+-"))
6636 (goto-char beg)
6637 (while (re-search-forward "-|[ \t]*$" end t)
6638 (replace-match "-+"))
6639 (goto-char beg)))))
6641 (defun org-table-wrap-region (arg)
6642 "Wrap several fields in a column like a paragraph.
6643 This is useful if you'd like to spread the contents of a field over several
6644 lines, in order to keep the table compact.
6646 If there is an active region, and both point and mark are in the same column,
6647 the text in the column is wrapped to minimum width for the given number of
6648 lines. Generally, this makes the table more compact. A prefix ARG may be
6649 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6650 formats the selected text to two lines. If the region was longer than two
6651 lines, the remaining lines remain empty. A negative prefix argument reduces
6652 the current number of lines by that amount. The wrapped text is pasted back
6653 into the table. If you formatted it to more lines than it was before, fields
6654 further down in the table get overwritten - so you might need to make space in
6655 the table first.
6657 If there is no region, the current field is split at the cursor position and
6658 the text fragment to the right of the cursor is prepended to the field one
6659 line down.
6661 If there is no region, but you specify a prefix ARG, the current field gets
6662 blank, and the content is appended to the field above."
6663 (interactive "P")
6664 (org-table-check-inside-data-field)
6665 (if (org-region-active-p)
6666 ;; There is a region: fill as a paragraph
6667 (let ((beg (region-beginning))
6668 nlines)
6669 (org-table-cut-region (region-beginning) (region-end))
6670 (if (> (length (car org-table-clip)) 1)
6671 (error "Region must be limited to single column"))
6672 (setq nlines (if arg
6673 (if (< arg 1)
6674 (+ (length org-table-clip) arg)
6675 arg)
6676 (length org-table-clip)))
6677 (setq org-table-clip
6678 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6679 nil nlines)))
6680 (goto-char beg)
6681 (org-table-paste-rectangle))
6682 ;; No region, split the current field at point
6683 (if arg
6684 ;; combine with field above
6685 (let ((s (org-table-blank-field))
6686 (col (org-table-current-column)))
6687 (beginning-of-line 0)
6688 (while (org-at-table-hline-p) (beginning-of-line 0))
6689 (org-table-goto-column col)
6690 (skip-chars-forward "^|")
6691 (skip-chars-backward " ")
6692 (insert " " (org-trim s))
6693 (org-table-align))
6694 ;; split field
6695 (when (looking-at "\\([^|]+\\)+|")
6696 (let ((s (match-string 1)))
6697 (replace-match " |")
6698 (goto-char (match-beginning 0))
6699 (org-table-next-row)
6700 (insert (org-trim s) " ")
6701 (org-table-align))))))
6703 (defvar org-field-marker nil)
6705 (defun org-table-edit-field (arg)
6706 "Edit table field in a different window.
6707 This is mainly useful for fields that contain hidden parts.
6708 When called with a \\[universal-argument] prefix, just make the full field visible so that
6709 it can be edited in place."
6710 (interactive "P")
6711 (if arg
6712 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
6713 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
6714 (remove-text-properties b e '(org-cwidth t invisible t
6715 display t intangible t))
6716 (if (and (boundp 'font-lock-mode) font-lock-mode)
6717 (font-lock-fontify-block)))
6718 (let ((pos (move-marker (make-marker) (point)))
6719 (field (org-table-get-field))
6720 (cw (current-window-configuration))
6722 (switch-to-buffer-other-window "*Org tmp*")
6723 (erase-buffer)
6724 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
6725 (org-mode)
6726 (goto-char (setq p (point-max)))
6727 (insert (org-trim field))
6728 (remove-text-properties p (point-max)
6729 '(invisible t org-cwidth t display t
6730 intangible t))
6731 (goto-char p)
6732 (org-set-local 'org-finish-function
6733 'org-table-finish-edit-field)
6734 (org-set-local 'org-window-configuration cw)
6735 (org-set-local 'org-field-marker pos)
6736 (message "Edit and finish with C-c C-c"))))
6738 (defun org-table-finish-edit-field ()
6739 "Finish editing a table data field.
6740 Remove all newline characters, insert the result into the table, realign
6741 the table and kill the editing buffer."
6742 (let ((pos org-field-marker)
6743 (cw org-window-configuration)
6744 (cb (current-buffer))
6745 text)
6746 (goto-char (point-min))
6747 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
6748 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
6749 (replace-match " "))
6750 (setq text (org-trim (buffer-string)))
6751 (set-window-configuration cw)
6752 (kill-buffer cb)
6753 (select-window (get-buffer-window (marker-buffer pos)))
6754 (goto-char pos)
6755 (move-marker pos nil)
6756 (org-table-check-inside-data-field)
6757 (org-table-get-field nil text)
6758 (org-table-align)
6759 (message "New field value inserted")))
6761 (defun org-trim (s)
6762 "Remove whitespace at beginning and end of string."
6763 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6764 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6767 (defun org-wrap (string &optional width lines)
6768 "Wrap string to either a number of lines, or a width in characters.
6769 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6770 that costs. If there is a word longer than WIDTH, the text is actually
6771 wrapped to the length of that word.
6772 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6773 many lines, whatever width that takes.
6774 The return value is a list of lines, without newlines at the end."
6775 (let* ((words (org-split-string string "[ \t\n]+"))
6776 (maxword (apply 'max (mapcar 'org-string-width words)))
6777 w ll)
6778 (cond (width
6779 (org-do-wrap words (max maxword width)))
6780 (lines
6781 (setq w maxword)
6782 (setq ll (org-do-wrap words maxword))
6783 (if (<= (length ll) lines)
6785 (setq ll words)
6786 (while (> (length ll) lines)
6787 (setq w (1+ w))
6788 (setq ll (org-do-wrap words w)))
6789 ll))
6790 (t (error "Cannot wrap this")))))
6793 (defun org-do-wrap (words width)
6794 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6795 (let (lines line)
6796 (while words
6797 (setq line (pop words))
6798 (while (and words (< (+ (length line) (length (car words))) width))
6799 (setq line (concat line " " (pop words))))
6800 (setq lines (push line lines)))
6801 (nreverse lines)))
6803 (defun org-split-string (string &optional separators)
6804 "Splits STRING into substrings at SEPARATORS.
6805 No empty strings are returned if there are matches at the beginning
6806 and end of string."
6807 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6808 (start 0)
6809 notfirst
6810 (list nil))
6811 (while (and (string-match rexp string
6812 (if (and notfirst
6813 (= start (match-beginning 0))
6814 (< start (length string)))
6815 (1+ start) start))
6816 (< (match-beginning 0) (length string)))
6817 (setq notfirst t)
6818 (or (eq (match-beginning 0) 0)
6819 (and (eq (match-beginning 0) (match-end 0))
6820 (eq (match-beginning 0) start))
6821 (setq list
6822 (cons (substring string start (match-beginning 0))
6823 list)))
6824 (setq start (match-end 0)))
6825 (or (eq start (length string))
6826 (setq list
6827 (cons (substring string start)
6828 list)))
6829 (nreverse list)))
6831 (defun org-table-map-tables (function)
6832 "Apply FUNCTION to the start of all tables in the buffer."
6833 (save-excursion
6834 (save-restriction
6835 (widen)
6836 (goto-char (point-min))
6837 (while (re-search-forward org-table-any-line-regexp nil t)
6838 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6839 (beginning-of-line 1)
6840 (if (looking-at org-table-line-regexp)
6841 (save-excursion (funcall function)))
6842 (re-search-forward org-table-any-border-regexp nil 1))))
6843 (message "Mapping tables: done"))
6845 (defvar org-timecnt) ; dynamically scoped parameter
6847 (defun org-table-sum (&optional beg end nlast)
6848 "Sum numbers in region of current table column.
6849 The result will be displayed in the echo area, and will be available
6850 as kill to be inserted with \\[yank].
6852 If there is an active region, it is interpreted as a rectangle and all
6853 numbers in that rectangle will be summed. If there is no active
6854 region and point is located in a table column, sum all numbers in that
6855 column.
6857 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6858 numbers are assumed to be times as well (in decimal hours) and the
6859 numbers are added as such.
6861 If NLAST is a number, only the NLAST fields will actually be summed."
6862 (interactive)
6863 (save-excursion
6864 (let (col (org-timecnt 0) diff h m s org-table-clip)
6865 (cond
6866 ((and beg end)) ; beg and end given explicitly
6867 ((org-region-active-p)
6868 (setq beg (region-beginning) end (region-end)))
6870 (setq col (org-table-current-column))
6871 (goto-char (org-table-begin))
6872 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
6873 (error "No table data"))
6874 (org-table-goto-column col)
6875 ;not needed? (skip-chars-backward "^|")
6876 (setq beg (point))
6877 (goto-char (org-table-end))
6878 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
6879 (error "No table data"))
6880 (org-table-goto-column col)
6881 ;not needed? (skip-chars-forward "^|")
6882 (setq end (point))))
6883 (let* ((items (apply 'append (org-table-copy-region beg end)))
6884 (items1 (cond ((not nlast) items)
6885 ((>= nlast (length items)) items)
6886 (t (setq items (reverse items))
6887 (setcdr (nthcdr (1- nlast) items) nil)
6888 (nreverse items))))
6889 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
6890 items1)))
6891 (res (apply '+ numbers))
6892 (sres (if (= org-timecnt 0)
6893 (format "%g" res)
6894 (setq diff (* 3600 res)
6895 h (floor (/ diff 3600)) diff (mod diff 3600)
6896 m (floor (/ diff 60)) diff (mod diff 60)
6897 s diff)
6898 (format "%d:%02d:%02d" h m s))))
6899 (kill-new sres)
6900 (if (interactive-p)
6901 (message "%s"
6902 (substitute-command-keys
6903 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
6904 (length numbers) sres))))
6905 sres))))
6907 (defun org-table-get-number-for-summing (s)
6908 (let (n)
6909 (if (string-match "^ *|? *" s)
6910 (setq s (replace-match "" nil nil s)))
6911 (if (string-match " *|? *$" s)
6912 (setq s (replace-match "" nil nil s)))
6913 (setq n (string-to-number s))
6914 (cond
6915 ((and (string-match "0" s)
6916 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
6917 ((string-match "\\`[ \t]+\\'" s) nil)
6918 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
6919 (let ((h (string-to-number (or (match-string 1 s) "0")))
6920 (m (string-to-number (or (match-string 2 s) "0")))
6921 (s (string-to-number (or (match-string 4 s) "0"))))
6922 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
6923 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
6924 ((equal n 0) nil)
6925 (t n))))
6927 (defun org-table-get-vertical-vector (desc &optional tbeg col)
6928 "Get a calc vector from a column, accorting to descriptor DESC.
6929 Optional arguments TBEG and COL can give the beginning of the table and
6930 the current column, to avoid unnecessary parsing."
6931 (save-excursion
6932 (or tbeg (setq tbeg (org-table-begin)))
6933 (or col (setq col (org-table-current-column)))
6934 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
6935 (cond
6936 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
6937 (setq n1 (- (match-end 1) (match-beginning 1)))
6938 (if (match-beginning 3)
6939 (setq n2 (- (match-end 2) (match-beginning 3))))
6940 (setq n (if n2 (max n1 n2) n1))
6941 (setq n1 (if n2 (min n1 n2)))
6942 (setq nn n)
6943 (while (and (> nn 0)
6944 (re-search-backward org-table-hline-regexp tbeg t))
6945 (push (org-current-line) hline-list)
6946 (setq nn (1- nn)))
6947 (setq hline-list (nreverse hline-list))
6948 (goto-line (nth (1- n) hline-list))
6949 (when (re-search-forward org-table-dataline-regexp)
6950 (org-table-goto-column col)
6951 (setq beg (point)))
6952 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
6953 (when (re-search-backward org-table-dataline-regexp)
6954 (org-table-goto-column col)
6955 (setq end (point)))
6956 (setq l (apply 'append (org-table-copy-region beg end)))
6957 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
6958 (if (equal x "") "0" x))
6959 l ",") "]"))
6960 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
6961 (setq n1 (string-to-number (match-string 1 desc))
6962 n2 (string-to-number (match-string 2 desc)))
6963 (beginning-of-line 1)
6964 (save-excursion
6965 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
6966 (org-table-goto-column col)
6967 (setq beg (point))))
6968 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
6969 (org-table-goto-column col)
6970 (setq end (point)))
6971 (setq l (apply 'append (org-table-copy-region beg end)))
6972 (concat "[" (mapconcat
6973 (lambda (x) (setq x (org-trim x))
6974 (if (equal x "") "0" x))
6975 l ",") "]"))
6976 ((string-match "\\([0-9]+\\)" desc)
6977 (beginning-of-line 1)
6978 (when (re-search-backward org-table-dataline-regexp tbeg t
6979 (string-to-number (match-string 0 desc)))
6980 (org-table-goto-column col)
6981 (org-trim (org-table-get-field))))))))
6983 (defvar org-table-formula-history nil)
6985 (defvar org-table-column-names nil
6986 "Alist with column names, derived from the `!' line.")
6987 (defvar org-table-column-name-regexp nil
6988 "Regular expression matching the current column names.")
6989 (defvar org-table-local-parameters nil
6990 "Alist with parameter names, derived from the `$' line.")
6991 (defvar org-table-named-field-locations nil
6992 "Alist with locations of named fields.")
6994 (defun org-table-get-formula (&optional equation named)
6995 "Read a formula from the minibuffer, offer stored formula as default."
6996 (let* ((name (car (rassoc (list (org-current-line)
6997 (org-table-current-column))
6998 org-table-named-field-locations)))
6999 (scol (if named
7000 (if name name
7001 (error "Not in a named field"))
7002 (int-to-string (org-table-current-column))))
7003 (dummy (and name (not named)
7004 (not (y-or-n-p "Replace named-field formula with column equation? " ))
7005 (error "Abort")))
7006 (org-table-may-need-update nil)
7007 (stored-list (org-table-get-stored-formulas))
7008 (stored (cdr (assoc scol stored-list)))
7009 (eq (cond
7010 ((and stored equation (string-match "^ *=? *$" equation))
7011 stored)
7012 ((stringp equation)
7013 equation)
7014 (t (read-string
7015 (format "%s formula $%s=" (if named "Field" "Column") scol)
7016 (or stored "") 'org-table-formula-history
7017 ;stored
7018 ))))
7019 mustsave)
7020 (when (not (string-match "\\S-" eq))
7021 ;; remove formula
7022 (setq stored-list (delq (assoc scol stored-list) stored-list))
7023 (org-table-store-formulas stored-list)
7024 (error "Formula removed"))
7025 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7026 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7027 (if (and name (not named))
7028 ;; We set the column equation, delete the named one.
7029 (setq stored-list (delq (assoc name stored-list) stored-list)
7030 mustsave t))
7031 (if stored
7032 (setcdr (assoc scol stored-list) eq)
7033 (setq stored-list (cons (cons scol eq) stored-list)))
7034 (if (or mustsave (not (equal stored eq)))
7035 (org-table-store-formulas stored-list))
7036 eq))
7038 (defun org-table-store-formulas (alist)
7039 "Store the list of formulas below the current table."
7040 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
7041 (save-excursion
7042 (goto-char (org-table-end))
7043 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
7044 (delete-region (point) (match-end 0)))
7045 (insert "#+TBLFM: "
7046 (mapconcat (lambda (x)
7047 (concat "$" (car x) "=" (cdr x)))
7048 alist "::")
7049 "\n")))
7051 (defun org-table-get-stored-formulas ()
7052 "Return an alist with the stored formulas directly after current table."
7053 (interactive)
7054 (let (scol eq eq-alist strings string seen)
7055 (save-excursion
7056 (goto-char (org-table-end))
7057 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7058 (setq strings (org-split-string (match-string 2) " *:: *"))
7059 (while (setq string (pop strings))
7060 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7061 (setq scol (match-string 1 string)
7062 eq (match-string 2 string)
7063 eq-alist (cons (cons scol eq) eq-alist))
7064 (if (member scol seen)
7065 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7066 (push scol seen))))))
7067 (nreverse eq-alist)))
7069 (defun org-table-modify-formulas (action &rest columns)
7070 "Modify the formulas stored below the current table.
7071 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7072 expected, for the other actions only a single column number is needed."
7073 (let ((list (org-table-get-stored-formulas))
7074 (nmax (length (org-split-string
7075 (buffer-substring (point-at-bol) (point-at-eol))
7076 "|")))
7077 col col1 col2 scol si sc1 sc2)
7078 (cond
7079 ((null list)) ; No action needed if there are no stored formulas
7080 ((eq action 'remove)
7081 (setq col (car columns)
7082 scol (int-to-string col))
7083 (org-table-replace-in-formulas list scol "INVALID")
7084 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
7085 (loop for i from (1+ col) upto nmax by 1 do
7086 (setq si (int-to-string i))
7087 (org-table-replace-in-formulas list si (int-to-string (1- i)))
7088 (if (assoc si list) (setcar (assoc si list)
7089 (int-to-string (1- i))))))
7090 ((eq action 'insert)
7091 (setq col (car columns))
7092 (loop for i from nmax downto col by 1 do
7093 (setq si (int-to-string i))
7094 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
7095 (if (assoc si list) (setcar (assoc si list)
7096 (int-to-string (1+ i))))))
7097 ((eq action 'swap)
7098 (setq col1 (car columns) col2 (nth 1 columns)
7099 sc1 (int-to-string col1) sc2 (int-to-string col2))
7100 ;; Hopefully, ZqZtZ will never be a name in a table
7101 (org-table-replace-in-formulas list sc1 "ZqZtZ")
7102 (org-table-replace-in-formulas list sc2 sc1)
7103 (org-table-replace-in-formulas list "ZqZtZ" sc2)
7104 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
7105 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
7106 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
7107 (t (error "Invalid action in `org-table-modify-formulas'")))
7108 (if list (org-table-store-formulas list))))
7110 (defun org-table-replace-in-formulas (list s1 s2)
7111 (let (elt re s)
7112 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7113 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7114 re (concat (regexp-quote s1) "\\>"))
7115 (while (setq elt (pop list))
7116 (setq s (cdr elt))
7117 (while (string-match re s)
7118 (setq s (replace-match s2 t t s)))
7119 (setcdr elt s))))
7121 (defun org-table-get-specials ()
7122 "Get the column names and local parameters for this table."
7123 (save-excursion
7124 (let ((beg (org-table-begin)) (end (org-table-end))
7125 names name fields fields1 field cnt c v line col)
7126 (setq org-table-column-names nil
7127 org-table-local-parameters nil
7128 org-table-named-field-locations nil)
7129 (goto-char beg)
7130 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7131 (setq names (org-split-string (match-string 1) " *| *")
7132 cnt 1)
7133 (while (setq name (pop names))
7134 (setq cnt (1+ cnt))
7135 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7136 (push (cons name (int-to-string cnt)) org-table-column-names))))
7137 (setq org-table-column-names (nreverse org-table-column-names))
7138 (setq org-table-column-name-regexp
7139 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7140 (goto-char beg)
7141 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7142 (setq fields (org-split-string (match-string 1) " *| *"))
7143 (while (setq field (pop fields))
7144 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7145 (push (cons (match-string 1 field) (match-string 2 field))
7146 org-table-local-parameters))))
7147 (goto-char beg)
7148 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7149 (setq c (match-string 1)
7150 fields (org-split-string (match-string 2) " *| *"))
7151 (save-excursion
7152 (beginning-of-line (if (equal c "_") 2 0))
7153 (setq line (org-current-line) col 1)
7154 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7155 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7156 (while (and fields1 (setq field (pop fields)))
7157 (setq v (pop fields1) col (1+ col))
7158 (when (and (stringp field) (stringp v)
7159 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7160 (push (cons field v) org-table-local-parameters)
7161 (push (list field line col) org-table-named-field-locations)))))))
7163 (defun org-this-word ()
7164 ;; Get the current word
7165 (save-excursion
7166 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7167 (end (progn (skip-chars-forward "^ \t\n") (point))))
7168 (buffer-substring-no-properties beg end))))
7170 (defun org-table-maybe-eval-formula ()
7171 "Check if the current field starts with \"=\" or \":=\".
7172 If yes, store the formula and apply it."
7173 ;; We already know we are in a table. Get field will only return a formula
7174 ;; when appropriate. It might return a separator line, but no problem.
7175 (when org-table-formula-evaluate-inline
7176 (let* ((field (org-trim (or (org-table-get-field) "")))
7177 named eq)
7178 (when (string-match "^:?=\\(.*\\)" field)
7179 (setq named (equal (string-to-char field) ?:)
7180 eq (match-string 1 field))
7181 (if (fboundp 'calc-eval)
7182 (org-table-eval-formula (if named '(4) nil) eq))))))
7184 (defvar org-recalc-commands nil
7185 "List of commands triggering the recalculation of a line.
7186 Will be filled automatically during use.")
7188 (defvar org-recalc-marks
7189 '((" " . "Unmarked: no special line, no automatic recalculation")
7190 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7191 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7192 ("!" . "Column name definition line. Reference in formula as $name.")
7193 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7194 ("_" . "Names for values in row below this one.")
7195 ("^" . "Names for values in row above this one.")))
7197 (defun org-table-rotate-recalc-marks (&optional newchar)
7198 "Rotate the recalculation mark in the first column.
7199 If in any row, the first field is not consistent with a mark,
7200 insert a new column for the markers.
7201 When there is an active region, change all the lines in the region,
7202 after prompting for the marking character.
7203 After each change, a message will be displayed indicating the meaning
7204 of the new mark."
7205 (interactive)
7206 (unless (org-at-table-p) (error "Not at a table"))
7207 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7208 (beg (org-table-begin))
7209 (end (org-table-end))
7210 (l (org-current-line))
7211 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7212 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7213 (have-col
7214 (save-excursion
7215 (goto-char beg)
7216 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7217 (col (org-table-current-column))
7218 (forcenew (car (assoc newchar org-recalc-marks)))
7219 epos new)
7220 (when l1
7221 (message "Change region to what mark? Type # * ! $ or SPC: ")
7222 (setq newchar (char-to-string (read-char-exclusive))
7223 forcenew (car (assoc newchar org-recalc-marks))))
7224 (if (and newchar (not forcenew))
7225 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7226 newchar))
7227 (if l1 (goto-line l1))
7228 (save-excursion
7229 (beginning-of-line 1)
7230 (unless (looking-at org-table-dataline-regexp)
7231 (error "Not at a table data line")))
7232 (unless have-col
7233 (org-table-goto-column 1)
7234 (org-table-insert-column)
7235 (org-table-goto-column (1+ col)))
7236 (setq epos (point-at-eol))
7237 (save-excursion
7238 (beginning-of-line 1)
7239 (org-table-get-field
7240 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7241 (concat " "
7242 (setq new (or forcenew
7243 (cadr (member (match-string 1) marks))))
7244 " ")
7245 " # ")))
7246 (if (and l1 l2)
7247 (progn
7248 (goto-line l1)
7249 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7250 (and (looking-at org-table-dataline-regexp)
7251 (org-table-get-field 1 (concat " " new " "))))
7252 (goto-line l1)))
7253 (if (not (= epos (point-at-eol))) (org-table-align))
7254 (goto-line l)
7255 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7257 (defun org-table-maybe-recalculate-line ()
7258 "Recompute the current line if marked for it, and if we haven't just done it."
7259 (interactive)
7260 (and org-table-allow-automatic-line-recalculation
7261 (not (and (memq last-command org-recalc-commands)
7262 (equal org-last-recalc-line (org-current-line))))
7263 (save-excursion (beginning-of-line 1)
7264 (looking-at org-table-auto-recalculate-regexp))
7265 (fboundp 'calc-eval)
7266 (org-table-recalculate) t))
7268 (defvar org-table-formula-debug nil
7269 "Non-nil means, debug table formulas.
7270 When nil, simply write \"#ERROR\" in corrupted fields.")
7272 (defvar modes)
7273 (defsubst org-set-calc-mode (var &optional value)
7274 (if (stringp var)
7275 (setq var (assoc var '(("D" calc-angle-mode deg)
7276 ("R" calc-angle-mode rad)
7277 ("F" calc-prefer-frac t)
7278 ("S" calc-symbolic-mode t)))
7279 value (nth 2 var) var (nth 1 var)))
7280 (if (memq var modes)
7281 (setcar (cdr (memq var modes)) value)
7282 (cons var (cons value modes)))
7283 modes)
7285 (defun org-table-eval-formula (&optional arg equation
7286 suppress-align suppress-const
7287 suppress-store)
7288 "Replace the table field value at the cursor by the result of a calculation.
7290 This function makes use of Dave Gillespie's Calc package, in my view the
7291 most exciting program ever written for GNU Emacs. So you need to have Calc
7292 installed in order to use this function.
7294 In a table, this command replaces the value in the current field with the
7295 result of a formula. It also installs the formula as the \"current\" column
7296 formula, by storing it in a special line below the table. When called
7297 with a `C-u' prefix, the current field must ba a named field, and the
7298 formula is installed as valid in only this specific field.
7300 When called, the command first prompts for a formula, which is read in
7301 the minibuffer. Previously entered formulas are available through the
7302 history list, and the last used formula is offered as a default.
7303 These stored formulas are adapted correctly when moving, inserting, or
7304 deleting columns with the corresponding commands.
7306 The formula can be any algebraic expression understood by the Calc package.
7307 For details, see the Org-mode manual.
7309 This function can also be called from Lisp programs and offers
7310 additional arguments: EQUATION can be the formula to apply. If this
7311 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7312 used to speed-up recursive calls by by-passing unnecessary aligns.
7313 SUPPRESS-CONST suppresses the interpretation of constants in the
7314 formula, assuming that this has been done already outside the function.
7315 SUPPRESS-STORE means the formula should not be stored, either because
7316 it is already stored, or because it is a modified equation that should
7317 not overwrite the stored one."
7318 (interactive "P")
7319 (require 'calc)
7320 (org-table-check-inside-data-field)
7321 (org-table-get-specials)
7322 (let* (fields
7323 (ndown (if (integerp arg) arg 1))
7324 (org-table-automatic-realign nil)
7325 (case-fold-search nil)
7326 (down (> ndown 1))
7327 (formula (if (and equation suppress-store)
7328 equation
7329 (org-table-get-formula equation (equal arg '(4)))))
7330 (n0 (org-table-current-column))
7331 (modes (copy-sequence org-calc-default-modes))
7332 n form fmt x ev orig c lispp)
7333 ;; Parse the format string. Since we have a lot of modes, this is
7334 ;; a lot of work. However, I think calc still uses most of the time.
7335 (if (string-match ";" formula)
7336 (let ((tmp (org-split-string formula ";")))
7337 (setq formula (car tmp)
7338 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7339 (nth 1 tmp)))
7340 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
7341 (setq c (string-to-char (match-string 1 fmt))
7342 n (string-to-number (match-string 2 fmt)))
7343 (if (= c ?p)
7344 (setq modes (org-set-calc-mode 'calc-internal-prec n))
7345 (setq modes (org-set-calc-mode
7346 'calc-float-format
7347 (list (cdr (assoc c '((?n . float) (?f . fix)
7348 (?s . sci) (?e . eng))))
7349 n))))
7350 (setq fmt (replace-match "" t t fmt)))
7351 (while (string-match "[DRFS]" fmt)
7352 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7353 (setq fmt (replace-match "" t t fmt)))
7354 (unless (string-match "\\S-" fmt)
7355 (setq fmt nil))))
7356 (if (and (not suppress-const) org-table-formula-use-constants)
7357 (setq formula (org-table-formula-substitute-names formula)))
7358 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7359 (while (> ndown 0)
7360 (setq fields (org-split-string
7361 (buffer-substring
7362 (point-at-bol) (point-at-eol)) " *| *"))
7363 (if org-table-formula-numbers-only
7364 (setq fields (mapcar
7365 (lambda (x) (number-to-string (string-to-number x)))
7366 fields)))
7367 (setq ndown (1- ndown))
7368 (setq form (copy-sequence formula)
7369 lispp (equal (substring form 0 2) "'("))
7370 ;; Insert the references to fields in same row
7371 (while (string-match "\\$\\([0-9]+\\)?" form)
7372 (setq n (if (match-beginning 1)
7373 (string-to-number (match-string 1 form))
7375 x (nth (1- n) fields))
7376 (unless x (error "Invalid field specifier \"%s\""
7377 (match-string 0 form)))
7378 (if (equal x "") (setq x "0"))
7379 (setq form (replace-match
7380 (if lispp x (concat "(" x ")"))
7381 t t form)))
7382 ;; Insert ranges in current column
7383 (while (string-match "\\&[-I0-9]+" form)
7384 (setq form (replace-match
7385 (save-match-data
7386 (org-table-get-vertical-vector (match-string 0 form)
7387 nil n0))
7388 t t form)))
7389 (if lispp
7390 (setq ev (eval (eval (read form)))
7391 ev (if (numberp ev) (number-to-string ev) ev))
7392 (setq ev (calc-eval (cons form modes)
7393 (if org-table-formula-numbers-only 'num))))
7395 (when org-table-formula-debug
7396 (with-output-to-temp-buffer "*Help*"
7397 (princ (format "Substitution history of formula
7398 Orig: %s
7399 $xyz-> %s
7400 $1-> %s\n" orig formula form))
7401 (if (listp ev)
7402 (princ (format " %s^\nError: %s"
7403 (make-string (car ev) ?\-) (nth 1 ev)))
7404 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7405 ev (or fmt "NONE")
7406 (if fmt (format fmt (string-to-number ev)) ev)))))
7407 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7408 (unless (and (interactive-p) (not ndown))
7409 (unless (let (inhibit-redisplay)
7410 (y-or-n-p "Debugging Formula. Continue to next? "))
7411 (org-table-align)
7412 (error "Abort"))
7413 (delete-window (get-buffer-window "*Help*"))
7414 (message "")))
7415 (if (listp ev) (setq fmt nil ev "#ERROR"))
7416 (org-table-justify-field-maybe
7417 (if fmt (format fmt (string-to-number ev)) ev))
7418 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7419 (call-interactively 'org-return)
7420 (setq ndown 0)))
7421 (and down (org-table-maybe-recalculate-line))
7422 (or suppress-align (and org-table-may-need-update
7423 (org-table-align)))))
7425 (defun org-table-recalculate (&optional all noalign)
7426 "Recalculate the current table line by applying all stored formulas.
7427 With prefix arg ALL, do this for all lines in the table."
7428 (interactive "P")
7429 (or (memq this-command org-recalc-commands)
7430 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7431 (unless (org-at-table-p) (error "Not at a table"))
7432 (org-table-get-specials)
7433 (let* ((eqlist (sort (org-table-get-stored-formulas)
7434 (lambda (a b) (string< (car a) (car b)))))
7435 (inhibit-redisplay t)
7436 (line-re org-table-dataline-regexp)
7437 (thisline (org-current-line))
7438 (thiscol (org-table-current-column))
7439 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7440 ;; Insert constants in all formulas
7441 (setq eqlist
7442 (mapcar (lambda (x)
7443 (setcdr x (org-table-formula-substitute-names (cdr x)))
7445 eqlist))
7446 ;; Split the equation list
7447 (while (setq eq (pop eqlist))
7448 (if (<= (string-to-char (car eq)) ?9)
7449 (push eq eqlnum)
7450 (push eq eqlname)))
7451 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7452 (if all
7453 (progn
7454 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7455 (goto-char (setq beg (org-table-begin)))
7456 (if (re-search-forward org-table-calculate-mark-regexp end t)
7457 ;; This is a table with marked lines, only compute selected lines
7458 (setq line-re org-table-recalculate-regexp)
7459 ;; Move forward to the first non-header line
7460 (if (and (re-search-forward org-table-dataline-regexp end t)
7461 (re-search-forward org-table-hline-regexp end t)
7462 (re-search-forward org-table-dataline-regexp end t))
7463 (setq beg (match-beginning 0))
7464 nil))) ;; just leave beg where it is
7465 (setq beg (point-at-bol)
7466 end (move-marker (make-marker) (1+ (point-at-eol)))))
7467 (goto-char beg)
7468 (and all (message "Re-applying formulas to full table..."))
7469 (while (re-search-forward line-re end t)
7470 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7471 ;; Unprotected line, recalculate
7472 (and all (message "Re-applying formulas to full table...(line %d)"
7473 (setq cnt (1+ cnt))))
7474 (setq org-last-recalc-line (org-current-line))
7475 (setq eql eqlnum)
7476 (while (setq entry (pop eql))
7477 (goto-line org-last-recalc-line)
7478 (org-table-goto-column (string-to-number (car entry)) nil 'force)
7479 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7480 (goto-line thisline)
7481 (org-table-goto-column thiscol)
7482 (or noalign (and org-table-may-need-update (org-table-align))
7483 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7484 ;; Now do the names fields
7485 (while (setq eq (pop eqlname))
7486 (setq name (car eq)
7487 a (assoc name org-table-named-field-locations))
7488 (when a
7489 (message "Re-applying formula to named field: %s" name)
7490 (goto-line (nth 1 a))
7491 (org-table-goto-column (nth 2 a))
7492 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
7493 ;; back to initial position
7494 (goto-line thisline)
7495 (org-table-goto-column thiscol)
7496 (or noalign (and org-table-may-need-update (org-table-align))
7497 (and all (message "Re-applying formulas...done")))))
7499 (defun org-table-formula-substitute-names (f)
7500 "Replace $const with values in string F."
7501 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7502 ;; First, check for column names
7503 (while (setq start (string-match org-table-column-name-regexp f start))
7504 (setq start (1+ start))
7505 (setq a (assoc (match-string 1 f) org-table-column-names))
7506 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7507 ;; Expand ranges to vectors
7508 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7509 (setq n1 (string-to-number (match-string 1 f))
7510 n2 (string-to-number (match-string 2 f))
7511 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7512 s (concat "[($" (number-to-string (1- nn1)) ")"))
7513 (loop for i from nn1 upto nn2 do
7514 (setq s (concat s ",($" (int-to-string i) ")")))
7515 (setq s (concat s "]"))
7516 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7517 (setq f (replace-match s t t f)))
7518 ;; Parameters and constants
7519 (setq start 0)
7520 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7521 (setq start (1+ start))
7522 (if (setq a (save-match-data
7523 (org-table-get-constant (match-string 1 f))))
7524 (setq f (replace-match (concat "(" a ")") t t f))))
7525 (if org-table-formula-debug
7526 (put-text-property 0 (length f) :orig-formula f1 f))
7529 (defun org-table-get-constant (const)
7530 "Find the value for a parameter or constant in a formula.
7531 Parameters get priority."
7532 (or (cdr (assoc const org-table-local-parameters))
7533 (cdr (assoc const org-table-formula-constants))
7534 (and (fboundp 'constants-get) (constants-get const))
7535 "#UNDEFINED_NAME"))
7537 (defvar org-edit-formulas-map (make-sparse-keymap))
7538 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
7539 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
7540 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
7542 (defvar org-pos)
7544 (defun org-table-edit-formulas ()
7545 "Edit the formulas of the current table in a separate buffer."
7546 (interactive)
7547 (unless (org-at-table-p)
7548 (error "Not at a table"))
7549 (org-table-get-specials)
7550 (let ((eql (org-table-get-stored-formulas))
7551 (pos (move-marker (make-marker) (point)))
7552 (wc (current-window-configuration))
7553 entry loc s)
7554 (switch-to-buffer-other-window "*Edit Formulas*")
7555 (erase-buffer)
7556 (fundamental-mode)
7557 (org-set-local 'org-pos pos)
7558 (org-set-local 'org-window-configuration wc)
7559 (use-local-map org-edit-formulas-map)
7560 (setq s "# Edit formulas and finish with `C-c C-c'.
7561 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
7562 # Use `C-c ?' to get information about $name at point.
7563 # To cancel editing, press `C-c C-q'.\n")
7564 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7565 (insert s)
7566 (while (setq entry (pop eql))
7567 (when (setq loc (assoc (car entry) org-table-named-field-locations))
7568 (setq s (format "# Named formula, referring to column %d in line %d\n"
7569 (nth 2 loc) (nth 1 loc)))
7570 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7571 (insert s))
7572 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
7573 (remove-text-properties 0 (length s) '(face nil) s)
7574 (insert s))
7575 (goto-char (point-min))
7576 (message "Edit formulas and finish with `C-c C-c'.")))
7578 (defun org-show-variable ()
7579 "Show the location/value of the $ expression at point."
7580 (interactive)
7581 (let (var (pos org-pos) (win (selected-window)) e)
7582 (save-excursion
7583 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
7584 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
7585 (setq var (match-string 1))
7586 (error "No variable at point")))
7587 (cond
7588 ((setq e (assoc var org-table-named-field-locations))
7589 (switch-to-buffer-other-window (marker-buffer pos))
7590 (goto-line (nth 1 e))
7591 (org-table-goto-column (nth 2 e))
7592 (select-window win)
7593 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
7594 ((setq e (assoc var org-table-column-names))
7595 (switch-to-buffer-other-window (marker-buffer pos))
7596 (goto-char pos)
7597 (goto-char (org-table-begin))
7598 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
7599 (org-table-end) t)
7600 (progn
7601 (goto-char (match-beginning 1))
7602 (message "Named column (column %s)" (cdr e)))
7603 (error "Column name not found"))
7604 (select-window win))
7605 ((string-match "^[0-9]$" var)
7606 ;; column number
7607 (switch-to-buffer-other-window (marker-buffer pos))
7608 (goto-char pos)
7609 (goto-char (org-table-begin))
7610 (recenter 1)
7611 (if (re-search-forward org-table-dataline-regexp
7612 (org-table-end) t)
7613 (progn
7614 (goto-char (match-beginning 0))
7615 (org-table-goto-column (string-to-number var))
7616 (message "Column %s" var))
7617 (error "Column name not found"))
7618 (select-window win))
7619 ((setq e (assoc var org-table-local-parameters))
7620 (switch-to-buffer-other-window (marker-buffer pos))
7621 (goto-char pos)
7622 (goto-char (org-table-begin))
7623 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
7624 (progn
7625 (goto-char (match-beginning 1))
7626 (message "Local parameter."))
7627 (error "Parameter not found"))
7628 (select-window win))
7630 (cond
7631 ((setq e (assoc var org-table-formula-constants))
7632 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
7633 ((setq e (and (fboundp 'constants-get) (constants-get var)))
7634 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
7635 (t (error "Undefined name $%s" var)))))))
7637 (defun org-finish-edit-formulas (&optional arg)
7638 "Parse the buffer for formula definitions and install them.
7639 With prefix ARG, apply the new formulas to the table."
7640 (interactive "P")
7641 (let ((pos org-pos) eql)
7642 (goto-char (point-min))
7643 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
7644 (push (cons (match-string 1) (match-string 2)) eql))
7645 (set-window-configuration org-window-configuration)
7646 (select-window (get-buffer-window (marker-buffer pos)))
7647 (goto-char pos)
7648 (unless (org-at-table-p)
7649 (error "Lost table position - cannot install formulae"))
7650 (org-table-store-formulas eql)
7651 (move-marker pos nil)
7652 (kill-buffer "*Edit Formulas*")
7653 (if arg
7654 (org-table-recalculate 'all)
7655 (message "New formulas installed - press C-u C-c C-c to apply."))))
7657 (defun org-abort-edit-formulas ()
7658 "Abort editing formulas, without installing the changes."
7659 (interactive)
7660 (let ((pos org-pos))
7661 (set-window-configuration org-window-configuration)
7662 (select-window (get-buffer-window (marker-buffer pos)))
7663 (goto-char pos)
7664 (message "Formula editing aborted without installing changes")))
7666 ;;; The orgtbl minor mode
7668 ;; Define a minor mode which can be used in other modes in order to
7669 ;; integrate the org-mode table editor.
7671 ;; This is really a hack, because the org-mode table editor uses several
7672 ;; keys which normally belong to the major mode, for example the TAB and
7673 ;; RET keys. Here is how it works: The minor mode defines all the keys
7674 ;; necessary to operate the table editor, but wraps the commands into a
7675 ;; function which tests if the cursor is currently inside a table. If that
7676 ;; is the case, the table editor command is executed. However, when any of
7677 ;; those keys is used outside a table, the function uses `key-binding' to
7678 ;; look up if the key has an associated command in another currently active
7679 ;; keymap (minor modes, major mode, global), and executes that command.
7680 ;; There might be problems if any of the keys used by the table editor is
7681 ;; otherwise used as a prefix key.
7683 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7684 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7685 ;; addresses this by checking explicitly for both bindings.
7687 ;; The optimized version (see variable `orgtbl-optimized') takes over
7688 ;; all keys which are bound to `self-insert-command' in the *global map*.
7689 ;; Some modes bind other commands to simple characters, for example
7690 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7691 ;; active, this binding is ignored inside tables and replaced with a
7692 ;; modified self-insert.
7694 (defvar orgtbl-mode nil
7695 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7696 table editor in arbitrary modes.")
7697 (make-variable-buffer-local 'orgtbl-mode)
7699 (defvar orgtbl-mode-map (make-keymap)
7700 "Keymap for `orgtbl-mode'.")
7702 ;;;###autoload
7703 (defun turn-on-orgtbl ()
7704 "Unconditionally turn on `orgtbl-mode'."
7705 (orgtbl-mode 1))
7707 (defvar org-old-auto-fill-inhibit-regexp nil
7708 "Local variable used by `orgtbl-mode'")
7710 ;;;###autoload
7711 (defun orgtbl-mode (&optional arg)
7712 "The `org-mode' table editor as a minor mode for use in other modes."
7713 (interactive)
7714 (if (org-mode-p)
7715 ;; Exit without error, in case some hook functions calls this
7716 ;; by accident in org-mode.
7717 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7718 (setq orgtbl-mode
7719 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7720 (if orgtbl-mode
7721 (progn
7722 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7723 ;; Make sure we are first in minor-mode-map-alist
7724 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7725 (and c (setq minor-mode-map-alist
7726 (cons c (delq c minor-mode-map-alist)))))
7727 (org-set-local (quote org-table-may-need-update) t)
7728 (org-add-hook 'before-change-functions 'org-before-change-function
7729 nil 'local)
7730 (org-set-local 'org-old-auto-fill-inhibit-regexp
7731 auto-fill-inhibit-regexp)
7732 (org-set-local 'auto-fill-inhibit-regexp
7733 (if auto-fill-inhibit-regexp
7734 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7735 "[ \t]*|"))
7736 (org-add-to-invisibility-spec '(org-cwidth))
7737 (easy-menu-add orgtbl-mode-menu)
7738 (run-hooks 'orgtbl-mode-hook))
7739 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7740 (org-cleanup-narrow-column-properties)
7741 (org-remove-from-invisibility-spec '(org-cwidth))
7742 (remove-hook 'before-change-functions 'org-before-change-function t)
7743 (easy-menu-remove orgtbl-mode-menu)
7744 (force-mode-line-update 'all))))
7746 (defun org-cleanup-narrow-column-properties ()
7747 "Remove all properties related to narrow-column invisibility."
7748 (let ((s 1))
7749 (while (setq s (text-property-any s (point-max)
7750 'display org-narrow-column-arrow))
7751 (remove-text-properties s (1+ s) '(display t)))
7752 (setq s 1)
7753 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
7754 (remove-text-properties s (1+ s) '(org-cwidth t)))
7755 (setq s 1)
7756 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
7757 (remove-text-properties s (1+ s) '(invisible t)))))
7759 ;; Install it as a minor mode.
7760 (put 'orgtbl-mode :included t)
7761 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7762 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7764 (defun orgtbl-make-binding (fun n &rest keys)
7765 "Create a function for binding in the table minor mode.
7766 FUN is the command to call inside a table. N is used to create a unique
7767 command name. KEYS are keys that should be checked in for a command
7768 to execute outside of tables."
7769 (eval
7770 (list 'defun
7771 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7772 '(arg)
7773 (concat "In tables, run `" (symbol-name fun) "'.\n"
7774 "Outside of tables, run the binding of `"
7775 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7776 "'.")
7777 '(interactive "p")
7778 (list 'if
7779 '(org-at-table-p)
7780 (list 'call-interactively (list 'quote fun))
7781 (list 'let '(orgtbl-mode)
7782 (list 'call-interactively
7783 (append '(or)
7784 (mapcar (lambda (k)
7785 (list 'key-binding k))
7786 keys)
7787 '('orgtbl-error))))))))
7789 (defun orgtbl-error ()
7790 "Error when there is no default binding for a table key."
7791 (interactive)
7792 (error "This key is has no function outside tables"))
7794 (defun orgtbl-setup ()
7795 "Setup orgtbl keymaps."
7796 (let ((nfunc 0)
7797 (bindings
7798 (list
7799 '([(meta shift left)] org-table-delete-column)
7800 '([(meta left)] org-table-move-column-left)
7801 '([(meta right)] org-table-move-column-right)
7802 '([(meta shift right)] org-table-insert-column)
7803 '([(meta shift up)] org-table-kill-row)
7804 '([(meta shift down)] org-table-insert-row)
7805 '([(meta up)] org-table-move-row-up)
7806 '([(meta down)] org-table-move-row-down)
7807 '("\C-c\C-w" org-table-cut-region)
7808 '("\C-c\M-w" org-table-copy-region)
7809 '("\C-c\C-y" org-table-paste-rectangle)
7810 '("\C-c-" org-table-insert-hline)
7811 ; '([(shift tab)] org-table-previous-field)
7812 '("\C-m" org-table-next-row)
7813 (list (org-key 'S-return) 'org-table-copy-down)
7814 '([(meta return)] org-table-wrap-region)
7815 '("\C-c\C-q" org-table-wrap-region)
7816 '("\C-c?" org-table-current-column)
7817 '("\C-c " org-table-blank-field)
7818 '("\C-c+" org-table-sum)
7819 '("\C-c=" org-table-eval-formula)
7820 '("\C-c'" org-table-edit-formulas)
7821 '("\C-c`" org-table-edit-field)
7822 '("\C-c*" org-table-recalculate)
7823 '("\C-c|" org-table-create-or-convert-from-region)
7824 '("\C-c^" org-table-sort-lines)
7825 '([(control ?#)] org-table-rotate-recalc-marks)))
7826 elt key fun cmd)
7827 (while (setq elt (pop bindings))
7828 (setq nfunc (1+ nfunc))
7829 (setq key (car elt)
7830 fun (nth 1 elt)
7831 cmd (orgtbl-make-binding fun nfunc key))
7832 (define-key orgtbl-mode-map key cmd))
7833 ;; Special treatment needed for TAB and RET
7834 (define-key orgtbl-mode-map [(return)]
7835 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
7836 (define-key orgtbl-mode-map "\C-m"
7837 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
7838 (define-key orgtbl-mode-map [(tab)]
7839 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
7840 (define-key orgtbl-mode-map "\C-i"
7841 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
7842 (define-key orgtbl-mode-map "\C-i"
7843 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
7844 (define-key orgtbl-mode-map "\C-c\C-c"
7845 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
7846 (when orgtbl-optimized
7847 ;; If the user wants maximum table support, we need to hijack
7848 ;; some standard editing functions
7849 (org-remap orgtbl-mode-map
7850 'self-insert-command 'orgtbl-self-insert-command
7851 'delete-char 'org-delete-char
7852 'delete-backward-char 'org-delete-backward-char)
7853 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
7854 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
7855 '("OrgTbl"
7856 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
7857 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
7858 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
7859 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
7860 "--"
7861 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
7862 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
7863 ["Copy Field from Above"
7864 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
7865 "--"
7866 ("Column"
7867 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
7868 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
7869 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
7870 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
7871 "--"
7872 ["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])
7873 ("Row"
7874 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
7875 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
7876 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
7877 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
7878 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
7879 "--"
7880 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
7881 ("Rectangle"
7882 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
7883 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
7884 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
7885 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
7886 "--"
7887 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
7888 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
7889 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
7890 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
7891 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
7892 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
7893 ["Sum Column/Rectangle" org-table-sum
7894 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
7895 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
7896 ["Debug Formulas"
7897 (setq org-table-formula-debug (not org-table-formula-debug))
7898 :style toggle :selected org-table-formula-debug]
7902 (defun orgtbl-tab (arg)
7903 "Justification and field motion for `orgtbl-mode'."
7904 (interactive "P")
7905 (if arg (org-table-edit-field t)
7906 (org-table-justify-field-maybe)
7907 (org-table-next-field)))
7909 (defun orgtbl-ret ()
7910 "Justification and field motion for `orgtbl-mode'."
7911 (interactive)
7912 (org-table-justify-field-maybe)
7913 (org-table-next-row))
7915 (defun orgtbl-self-insert-command (N)
7916 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
7917 If the cursor is in a table looking at whitespace, the whitespace is
7918 overwritten, and the table is not marked as requiring realignment."
7919 (interactive "p")
7920 (if (and (org-at-table-p)
7922 (and org-table-auto-blank-field
7923 (member last-command
7924 '(orgtbl-hijacker-command-100
7925 orgtbl-hijacker-command-101
7926 orgtbl-hijacker-command-102
7927 orgtbl-hijacker-command-103
7928 orgtbl-hijacker-command-104
7929 orgtbl-hijacker-command-105))
7930 (org-table-blank-field))
7932 (eq N 1)
7933 (looking-at "[^|\n]* +|"))
7934 (let (org-table-may-need-update)
7935 (goto-char (1- (match-end 0)))
7936 (delete-backward-char 1)
7937 (goto-char (match-beginning 0))
7938 (self-insert-command N))
7939 (setq org-table-may-need-update t)
7940 (let (orgtbl-mode)
7941 (call-interactively (key-binding (vector last-input-event))))))
7943 (defun org-force-self-insert (N)
7944 "Needed to enforce self-insert under remapping."
7945 (interactive "p")
7946 (self-insert-command N))
7948 ;;;; Link Stuff
7950 ;;; Link abbreviations
7952 (defun org-link-expand-abbrev (link)
7953 "Apply replacements as defined in `org-link-abbrev-alist."
7954 (if (string-match "^\\([a-zA-Z]+\\)\\(::\\(.*\\)\\)?$" link)
7955 (let* ((key (match-string 1 link))
7956 (as (or (assoc key org-link-abbrev-alist-local)
7957 (assoc key org-link-abbrev-alist)))
7958 (tag (and (match-end 2) (match-string 3 link)))
7959 rpl)
7960 (if (not as)
7961 link
7962 (setq rpl (cdr as))
7963 (cond
7964 ((symbolp rpl) (funcall rpl tag))
7965 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7966 (t (concat rpl tag)))))
7967 link))
7969 ;;; Storing and inserting links
7971 (defvar org-insert-link-history nil
7972 "Minibuffer history for links inserted with `org-insert-link'.")
7974 (defvar org-stored-links nil
7975 "Contains the links stored with `org-store-link'.")
7977 ;;;###autoload
7978 (defun org-store-link (arg)
7979 "\\<org-mode-map>Store an org-link to the current location.
7980 This link can later be inserted into an org-buffer with
7981 \\[org-insert-link].
7982 For some link types, a prefix arg is interpreted:
7983 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7984 For file links, arg negates `org-context-in-file-links'."
7985 (interactive "P")
7986 (let (link cpltxt desc description search txt (pos (point)))
7987 (cond
7989 ((eq major-mode 'bbdb-mode)
7990 (setq cpltxt (concat
7991 "bbdb:"
7992 (or (bbdb-record-name (bbdb-current-record))
7993 (bbdb-record-company (bbdb-current-record))))
7994 link (org-make-link cpltxt)))
7996 ((eq major-mode 'Info-mode)
7997 (setq link (org-make-link "info:"
7998 (file-name-nondirectory Info-current-file)
7999 ":" Info-current-node))
8000 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
8001 ":" Info-current-node)))
8003 ((eq major-mode 'calendar-mode)
8004 (let ((cd (calendar-cursor-to-date)))
8005 (setq link
8006 (format-time-string
8007 (car org-time-stamp-formats)
8008 (apply 'encode-time
8009 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8010 nil nil nil))))))
8012 ((or (eq major-mode 'vm-summary-mode)
8013 (eq major-mode 'vm-presentation-mode))
8014 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
8015 (vm-follow-summary-cursor)
8016 (save-excursion
8017 (vm-select-folder-buffer)
8018 (let* ((message (car vm-message-pointer))
8019 (folder buffer-file-name)
8020 (subject (vm-su-subject message))
8021 (author (vm-su-full-name message))
8022 (message-id (vm-su-message-id message)))
8023 (setq message-id (org-remove-angle-brackets message-id))
8024 (setq folder (abbreviate-file-name folder))
8025 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
8026 folder)
8027 (setq folder (replace-match "" t t folder)))
8028 (setq cpltxt (concat author " on: " subject))
8029 (setq link (org-make-link "vm:" folder "#" message-id)))))
8031 ((eq major-mode 'wl-summary-mode)
8032 (let* ((msgnum (wl-summary-message-number))
8033 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
8034 msgnum 'message-id))
8035 (wl-message-entity
8036 (if (fboundp 'elmo-message-entity)
8037 (elmo-message-entity
8038 wl-summary-buffer-elmo-folder msgnum)
8039 (elmo-msgdb-overview-get-entity
8040 msgnum (wl-summary-buffer-msgdb))))
8041 (author (wl-summary-line-from)) ; FIXME: correct?
8042 (subject "???")) ; FIXME:
8043 (setq message-id (org-remove-angle-brackets message-id))
8044 (setq cpltxt (concat author " on: " subject))
8045 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
8046 "#" message-id))))
8048 ((or (equal major-mode 'mh-folder-mode)
8049 (equal major-mode 'mh-show-mode))
8050 (let ((from-header (org-mhe-get-header "From:"))
8051 (to-header (org-mhe-get-header "To:"))
8052 (subject (org-mhe-get-header "Subject:")))
8053 (setq cpltxt (concat from-header " on: " subject))
8054 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
8055 (org-remove-angle-brackets
8056 (org-mhe-get-header "Message-Id:"))))))
8058 ((eq major-mode 'rmail-mode)
8059 (save-excursion
8060 (save-restriction
8061 (rmail-narrow-to-non-pruned-header)
8062 (let ((folder buffer-file-name)
8063 (message-id (mail-fetch-field "message-id"))
8064 (author (mail-fetch-field "from"))
8065 (subject (mail-fetch-field "subject")))
8066 (setq message-id (org-remove-angle-brackets message-id))
8067 (setq cpltxt (concat author " on: " subject))
8068 (setq link (org-make-link "rmail:" folder "#" message-id))))))
8070 ((eq major-mode 'gnus-group-mode)
8071 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
8072 (gnus-group-group-name)) ; version
8073 ((fboundp 'gnus-group-name)
8074 (gnus-group-name))
8075 (t "???"))))
8076 (setq cpltxt (concat
8077 (if (org-xor arg org-usenet-links-prefer-google)
8078 "http://groups.google.com/groups?group="
8079 "gnus:")
8080 group)
8081 link (org-make-link cpltxt))))
8083 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
8084 (require 'gnus-sum) ; FIXME: I don't think this is needed, actually
8085 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
8086 (gnus-summary-beginning-of-article)
8087 (let* ((group (car gnus-article-current))
8088 (article (cdr gnus-article-current))
8089 (header (gnus-summary-article-header article))
8090 (author (mail-header-from header))
8091 (message-id (mail-header-id header))
8092 (date (mail-header-date header))
8093 (subject (gnus-summary-subject-string)))
8094 (setq cpltxt (concat author " on: " subject))
8095 (if (org-xor arg org-usenet-links-prefer-google)
8096 (setq link
8097 (concat
8098 cpltxt "\n "
8099 (format "http://groups.google.com/groups?as_umsgid=%s"
8100 (org-fixup-message-id-for-http message-id))))
8101 (setq link (org-make-link "gnus:" group
8102 "#" (number-to-string article))))))
8104 ((eq major-mode 'w3-mode)
8105 (setq cpltxt (url-view-url t)
8106 link (org-make-link cpltxt)))
8107 ((eq major-mode 'w3m-mode)
8108 (setq cpltxt (or w3m-current-title w3m-current-url)
8109 link (org-make-link w3m-current-url)))
8111 ((setq search (run-hook-with-args-until-success
8112 'org-create-file-search-functions))
8113 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8114 "::" search))
8115 (setq cpltxt (or description link)))
8117 ((eq major-mode 'image-mode)
8118 (setq cpltxt (concat "file:"
8119 (abbreviate-file-name buffer-file-name))
8120 link (org-make-link cpltxt)))
8122 ((eq major-mode 'dired-mode)
8123 ;; link to the file in the current line
8124 (setq cpltxt (concat "file:"
8125 (abbreviate-file-name
8126 (expand-file-name
8127 (dired-get-filename nil t))))
8128 link (org-make-link cpltxt)))
8130 ((and buffer-file-name (org-mode-p))
8131 ;; Just link to current headline
8132 (setq cpltxt (concat "file:"
8133 (abbreviate-file-name buffer-file-name)))
8134 ;; Add a context search string
8135 (when (org-xor org-context-in-file-links arg)
8136 ;; Check if we are on a target
8137 (if (save-excursion
8138 (skip-chars-forward "^>\n\r")
8139 (and (re-search-backward "<<" nil t)
8140 (looking-at "<<\\(.*?\\)>>")
8141 (<= (match-beginning 0) pos)
8142 (>= (match-end 0) pos)))
8143 (setq cpltxt (concat cpltxt "::" (match-string 1)))
8144 (setq txt (cond
8145 ((org-on-heading-p) nil)
8146 ((org-region-active-p)
8147 (buffer-substring (region-beginning) (region-end)))
8148 (t (buffer-substring (point-at-bol) (point-at-eol)))))
8149 (when (or (null txt) (string-match "\\S-" txt))
8150 (setq cpltxt
8151 (concat cpltxt "::"
8152 (if org-file-link-context-use-camel-case
8153 (org-make-org-heading-camel txt)
8154 (org-make-org-heading-search-string txt)))
8155 desc "NONE"))))
8156 (if (string-match "::\\'" cpltxt)
8157 (setq cpltxt (substring cpltxt 0 -2)))
8158 (setq link (org-make-link cpltxt)))
8160 (buffer-file-name
8161 ;; Just link to this file here.
8162 (setq cpltxt (concat "file:"
8163 (abbreviate-file-name buffer-file-name)))
8164 ;; Add a context string
8165 (when (org-xor org-context-in-file-links arg)
8166 (setq txt (if (org-region-active-p)
8167 (buffer-substring (region-beginning) (region-end))
8168 (buffer-substring (point-at-bol) (point-at-eol))))
8169 ;; Only use search option if there is some text.
8170 (when (string-match "\\S-" txt)
8171 (setq cpltxt
8172 (concat cpltxt "::"
8173 (if org-file-link-context-use-camel-case
8174 (org-make-org-heading-camel txt)
8175 (org-make-org-heading-search-string txt)))
8176 desc "NONE")))
8177 (setq link (org-make-link cpltxt)))
8179 ((interactive-p)
8180 (error "Cannot link to a buffer which is not visiting a file"))
8182 (t (setq link nil)))
8184 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8185 (setq link (or link cpltxt)
8186 desc (or desc cpltxt))
8187 (if (equal desc "NONE") (setq desc nil))
8189 (if (and (interactive-p) link)
8190 (progn
8191 (setq org-stored-links
8192 (cons (list cpltxt link desc) org-stored-links))
8193 (message "Stored: %s" (or cpltxt link)))
8194 (org-make-link-string link desc))))
8196 (defun org-make-org-heading-search-string (&optional string heading)
8197 "Make search string for STRING or current headline."
8198 (interactive)
8199 (let ((s (or string (org-get-heading))))
8200 (unless (and string (not heading))
8201 ;; We are using a headline, clean up garbage in there.
8202 (if (string-match org-todo-regexp s)
8203 (setq s (replace-match "" t t s)))
8204 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8205 (setq s (replace-match "" t t s)))
8206 (setq s (org-trim s))
8207 (if (string-match (concat "^\\(" org-quote-string "\\|"
8208 org-comment-string "\\)") s)
8209 (setq s (replace-match "" t t s)))
8210 (while (string-match org-ts-regexp s)
8211 (setq s (replace-match "" t t s))))
8212 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8213 (setq s (replace-match " " t t s)))
8214 (or string (setq s (concat "*" s))) ; Add * for headlines
8215 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8217 (defun org-make-org-heading-camel (&optional string heading)
8218 "Make a CamelCase string for STRING or the current headline."
8219 (interactive)
8220 (let ((s (or string (org-get-heading))))
8221 (unless (and string (not heading))
8222 ;; We are using a headline, clean up garbage in there.
8223 (if (string-match org-todo-regexp s)
8224 (setq s (replace-match "" t t s)))
8225 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8226 (setq s (replace-match "" t t s)))
8227 (setq s (org-trim s))
8228 (if (string-match (concat "^\\(" org-quote-string "\\|"
8229 org-comment-string "\\)") s)
8230 (setq s (replace-match "" t t s)))
8231 (while (string-match org-ts-regexp s)
8232 (setq s (replace-match "" t t s))))
8233 (while (string-match "[^a-zA-Z_ \t]+" s)
8234 (setq s (replace-match " " t t s)))
8235 (or string (setq s (concat "*" s))) ; Add * for headlines
8236 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
8238 (defun org-make-link (&rest strings)
8239 "Concatenate STRINGS, format resulting string with `org-link-format'."
8240 (format org-link-format (apply 'concat strings)))
8242 (defun org-make-link-string (link &optional description)
8243 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8244 (if (eq org-link-style 'plain)
8245 (if (equal description link)
8246 link
8247 (concat description "\n" link))
8248 (when (stringp description)
8249 ;; Remove brackets from the description, they are fatal.
8250 (while (string-match "\\[\\|\\]" description)
8251 (setq description (replace-match "" t t description))))
8252 (when (equal (org-link-escape link) description)
8253 ;; No description needed, it is identical
8254 (setq description nil))
8255 (when (and (not description)
8256 (not (equal link (org-link-escape link))))
8257 (setq description link))
8258 (concat "[[" (org-link-escape link) "]"
8259 (if description (concat "[" description "]") "")
8260 "]")))
8262 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8263 "Association list of escapes for some characters problematic in links.")
8265 (defun org-link-escape (text)
8266 "Escape charaters in TEXT that are problematic for links."
8267 (when text
8268 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8269 org-link-escape-chars "\\|")))
8270 (while (string-match re text)
8271 (setq text
8272 (replace-match
8273 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8274 t t text)))
8275 text)))
8277 (defun org-link-unescape (text)
8278 "Reverse the action of `org-link-escape'."
8279 (when text
8280 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8281 org-link-escape-chars "\\|")))
8282 (while (string-match re text)
8283 (setq text
8284 (replace-match
8285 (car (rassoc (match-string 0 text) org-link-escape-chars))
8286 t t text)))
8287 text)))
8289 (defun org-xor (a b)
8290 "Exclusive or."
8291 (if a (not b) b))
8293 (defun org-get-header (header)
8294 "Find a header field in the current buffer."
8295 (save-excursion
8296 (goto-char (point-min))
8297 (let ((case-fold-search t) s)
8298 (cond
8299 ((eq header 'from)
8300 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8301 (setq s (match-string 1)))
8302 (while (string-match "\"" s)
8303 (setq s (replace-match "" t t s)))
8304 (if (string-match "[<(].*" s)
8305 (setq s (replace-match "" t t s))))
8306 ((eq header 'message-id)
8307 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8308 (setq s (match-string 1))))
8309 ((eq header 'subject)
8310 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8311 (setq s (match-string 1)))))
8312 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8313 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8314 s)))
8317 (defun org-fixup-message-id-for-http (s)
8318 "Replace special characters in a message id, so it can be used in an http query."
8319 (while (string-match "<" s)
8320 (setq s (replace-match "%3C" t t s)))
8321 (while (string-match ">" s)
8322 (setq s (replace-match "%3E" t t s)))
8323 (while (string-match "@" s)
8324 (setq s (replace-match "%40" t t s)))
8327 (defun org-insert-link (&optional complete-file)
8328 "Insert a link. At the prompt, enter the link.
8330 Completion can be used to select a link previously stored with
8331 `org-store-link'. When the empty string is entered (i.e. if you just
8332 press RET at the prompt), the link defaults to the most recently
8333 stored link. As SPC triggers completion in the minibuffer, you need to
8334 use M-SPC or C-q SPC to force the insertion of a space character.
8336 You will also be prompted for a description, and if one is given, it will
8337 be displayed in the buffer instead of the link.
8339 If there is already a link at point, this command will allow you to edit link
8340 and description parts.
8342 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8343 selected using completion. The path to the file will be relative to
8344 the current directory if the file is in the current directory or a
8345 subdirectory. Otherwise, the link will be the absolute path as
8346 completed in the minibuffer (i.e. normally ~/path/to/file).
8348 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8349 is in the current directory or below.
8350 With three \\[universal-argument] prefixes, negate the meaning of
8351 `org-keep-stored-link-after-insertion'."
8352 (interactive "P")
8353 (let (link desc entry remove file (pos (point)))
8354 (cond
8355 ((save-excursion
8356 (skip-chars-forward "^]\n\r")
8357 (and (re-search-backward "\\[\\[" nil t)
8358 (looking-at org-bracket-link-regexp)
8359 (<= (match-beginning 0) pos)
8360 (>= (match-end 0) pos)))
8361 ;; We do have a link at point, and we are going to edit it.
8362 (setq remove (list (match-beginning 0) (match-end 0)))
8363 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8364 (setq link (read-string "Link: "
8365 (org-link-unescape
8366 (org-match-string-no-properties 1)))))
8367 ((equal complete-file '(4))
8368 ;; Completing read for file names.
8369 (setq file (read-file-name "File: "))
8370 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8371 (pwd1 (file-name-as-directory (abbreviate-file-name
8372 (expand-file-name ".")))))
8373 (cond
8374 ((equal complete-file '(16))
8375 (setq link (org-make-link
8376 "file:"
8377 (abbreviate-file-name (expand-file-name file)))))
8378 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8379 (setq link (org-make-link "file:" (match-string 1 file))))
8380 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8381 (expand-file-name file))
8382 (setq link (org-make-link
8383 "file:" (match-string 1 (expand-file-name file)))))
8384 (t (setq link (org-make-link "file:" file))))))
8386 ;; Read link, with completion for stored links.
8387 (setq link (org-completing-read
8388 "Link: " org-stored-links nil nil nil
8389 org-insert-link-history
8390 (or (car (car org-stored-links)))))
8391 (setq entry (assoc link org-stored-links))
8392 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8393 (not org-keep-stored-link-after-insertion))
8394 (setq org-stored-links (delq (assoc link org-stored-links)
8395 org-stored-links)))
8396 (setq link (if entry (nth 1 entry) link)
8397 desc (or desc (nth 2 entry)))))
8399 (if (string-match org-plain-link-re link)
8400 ;; URL-like link, normalize the use of angular brackets.
8401 (setq link (org-make-link (org-remove-angle-brackets link))))
8403 ;; Check if we are linking to the current file with a search option
8404 ;; If yes, simplify the link by using only the search option.
8405 (when (and buffer-file-name
8406 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
8407 (let* ((path (match-string 1 link))
8408 (case-fold-search nil)
8409 (search (match-string 2 link)))
8410 (save-match-data
8411 (if (equal (file-truename buffer-file-name) (file-truename path))
8412 ;; We are linking to this same file, with a search option
8413 (setq link search)))))
8415 ;; Check if we can/should use a relative path. If yes, simplify the link
8416 (when (string-match "\\<file:\\(.*\\)" link)
8417 (let* ((path (match-string 1 link))
8418 (case-fold-search nil))
8419 (cond
8420 ((eq org-link-file-path-type 'absolute)
8421 (setq path (abbreviate-file-name (expand-file-name path))))
8422 ((eq org-link-file-path-type 'noabbrev)
8423 (setq path (expand-file-name path)))
8424 ((eq org-link-file-path-type 'relative)
8425 (setq path (file-relative-name path)))
8427 (save-match-data
8428 (if (string-match (concat "^" (regexp-quote
8429 (file-name-as-directory
8430 (expand-file-name "."))))
8431 (expand-file-name path))
8432 ;; We are linking a file with relative path name.
8433 (setq path (substring (expand-file-name path)
8434 (match-end 0)))))))
8435 (setq link (concat "file:" path))))
8437 (setq desc (read-string "Description: " desc))
8438 (unless (string-match "\\S-" desc) (setq desc nil))
8439 (if remove (apply 'delete-region remove))
8440 (insert (org-make-link-string link desc))))
8442 (defun org-completing-read (&rest args)
8443 (let ((minibuffer-local-completion-map
8444 (copy-keymap minibuffer-local-completion-map)))
8445 (define-key minibuffer-local-completion-map " " 'self-insert-command)
8446 (apply 'completing-read args)))
8448 ;;; Opening/following a link
8450 (defun org-find-file-at-mouse (ev)
8451 "Open file link or URL at mouse."
8452 (interactive "e")
8453 (mouse-set-point ev)
8454 (org-open-at-point 'in-emacs))
8456 (defun org-open-at-mouse (ev)
8457 "Open file link or URL at mouse."
8458 (interactive "e")
8459 (mouse-set-point ev)
8460 (org-open-at-point))
8462 (defvar org-window-config-before-follow-link nil
8463 "The window configuration before following a link.
8464 This is saved in case the need arises to restore it.")
8466 ;; FIXME: IN-EMACS is used for many purposes, maybe rename this argument???
8467 (defun org-open-at-point (&optional in-emacs)
8468 "Open link at or after point.
8469 If there is no link at point, this function will search forward up to
8470 the end of the current subtree.
8471 Normally, files will be opened by an appropriate application. If the
8472 optional argument IN-EMACS is non-nil, Emacs will visit the file."
8473 (interactive "P")
8474 (setq org-window-config-before-follow-link (current-window-configuration))
8475 (org-remove-occur-highlights nil nil t)
8476 (if (org-at-timestamp-p t)
8477 (org-follow-timestamp-link)
8478 (let (type path link line search (pos (point)))
8479 (catch 'match
8480 (save-excursion
8481 (skip-chars-forward "^]\n\r")
8482 (when (and (re-search-backward "\\[\\[" nil t)
8483 (looking-at org-bracket-link-regexp)
8484 (<= (match-beginning 0) pos)
8485 (>= (match-end 0) pos))
8486 (setq link (org-link-unescape (org-match-string-no-properties 1)))
8487 (while (string-match " *\n *" link)
8488 (setq link (replace-match " " t t link)))
8489 (setq link (org-link-expand-abbrev link))
8490 (if (string-match org-link-re-with-space2 link)
8491 (setq type (match-string 1 link)
8492 path (match-string 2 link))
8493 (setq type "thisfile"
8494 path link))
8495 (throw 'match t)))
8497 (when (get-text-property (point) 'org-linked-text)
8498 (setq type "thisfile"
8499 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8500 (1+ (point)) (point))
8501 path (buffer-substring
8502 (previous-single-property-change pos 'org-linked-text)
8503 (next-single-property-change pos 'org-linked-text)))
8504 (throw 'match t))
8506 (save-excursion
8507 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
8508 (if (equal (char-before) ?<) (backward-char 1))
8509 (when (or (looking-at org-angle-link-re)
8510 (looking-at org-plain-link-re)
8511 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
8512 (re-search-forward org-plain-link-re (point-at-eol) t))
8513 (<= (match-beginning 0) pos)
8514 (>= (match-end 0) pos)))
8515 (setq type (match-string 1)
8516 path (match-string 2))
8517 (throw 'match t)))
8518 (save-excursion
8519 (skip-chars-backward "^ \t\n\r")
8520 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
8521 (setq type "tags"
8522 path (match-string 1))
8523 (while (string-match ":" path)
8524 (setq path (replace-match "+" t t path)))
8525 (throw 'match t)))
8526 (save-excursion
8527 (skip-chars-backward "a-zA-Z_")
8528 (when (and (memq 'camel org-activate-links)
8529 (looking-at org-camel-regexp))
8530 (setq type "camel" path (match-string 0))
8531 (if (equal (char-before) ?*)
8532 (setq path (concat "*" path))))
8533 (throw 'match t)))
8534 (unless path
8535 (error "No link found"))
8536 ;; Remove any trailing spaces in path
8537 (if (string-match " +\\'" path)
8538 (setq path (replace-match "" t t path)))
8540 (cond
8542 ((equal type "mailto")
8543 (let ((cmd (car org-link-mailto-program))
8544 (args (cdr org-link-mailto-program)) args1
8545 (address path) (subject "") a)
8546 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8547 (setq address (match-string 1 path)
8548 subject (org-link-escape (match-string 2 path))))
8549 (while args
8550 (cond
8551 ((not (stringp (car args))) (push (pop args) args1))
8552 (t (setq a (pop args))
8553 (if (string-match "%a" a)
8554 (setq a (replace-match address t t a)))
8555 (if (string-match "%s" a)
8556 (setq a (replace-match subject t t a)))
8557 (push a args1))))
8558 (apply cmd (nreverse args1))))
8560 ((member type '("http" "https" "ftp" "news"))
8561 (browse-url (concat type ":" path)))
8563 ((string= type "tags")
8564 (org-tags-view in-emacs path))
8565 ((or (string= type "camel")
8566 (string= type "thisfile"))
8567 (if in-emacs
8568 (switch-to-buffer-other-window
8569 (org-get-buffer-for-internal-link (current-buffer)))
8570 (org-mark-ring-push))
8571 (org-link-search
8572 path
8573 (cond ((equal in-emacs '(4)) 'occur)
8574 ((equal in-emacs '(16)) 'org-occur)
8575 (t nil))))
8577 ((string= type "file")
8578 (if (string-match "::\\([0-9]+\\)\\'" path)
8579 (setq line (string-to-number (match-string 1 path))
8580 path (substring path 0 (match-beginning 0)))
8581 (if (string-match "::\\(.+\\)\\'" path)
8582 (setq search (match-string 1 path)
8583 path (substring path 0 (match-beginning 0)))))
8584 (org-open-file path in-emacs line search))
8586 ((string= type "news")
8587 (org-follow-gnus-link path))
8589 ((string= type "bbdb")
8590 (org-follow-bbdb-link path))
8592 ((string= type "info")
8593 (org-follow-info-link path))
8595 ((string= type "gnus")
8596 (let (group article)
8597 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8598 (error "Error in Gnus link"))
8599 (setq group (match-string 1 path)
8600 article (match-string 3 path))
8601 (org-follow-gnus-link group article)))
8603 ((string= type "vm")
8604 (let (folder article)
8605 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8606 (error "Error in VM link"))
8607 (setq folder (match-string 1 path)
8608 article (match-string 3 path))
8609 ;; in-emacs is the prefix arg, will be interpreted as read-only
8610 (org-follow-vm-link folder article in-emacs)))
8612 ((string= type "wl")
8613 (let (folder article)
8614 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8615 (error "Error in Wanderlust link"))
8616 (setq folder (match-string 1 path)
8617 article (match-string 3 path))
8618 (org-follow-wl-link folder article)))
8620 ((string= type "mhe")
8621 (let (folder article)
8622 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8623 (error "Error in MHE link"))
8624 (setq folder (match-string 1 path)
8625 article (match-string 3 path))
8626 (org-follow-mhe-link folder article)))
8628 ((string= type "rmail")
8629 (let (folder article)
8630 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8631 (error "Error in RMAIL link"))
8632 (setq folder (match-string 1 path)
8633 article (match-string 3 path))
8634 (org-follow-rmail-link folder article)))
8636 ((string= type "shell")
8637 (let ((cmd path))
8638 (while (string-match "@{" cmd) ; FIXME: not needed for [[]] links
8639 (setq cmd (replace-match "<" t t cmd)))
8640 (while (string-match "@}" cmd) ; FIXME: not needed for [[]] links
8641 (setq cmd (replace-match ">" t t cmd)))
8642 (if (or (not org-confirm-shell-link-function)
8643 (funcall org-confirm-shell-link-function
8644 (format "Execute \"%s\" in shell? "
8645 (org-add-props cmd nil
8646 'face 'org-warning))))
8647 (progn
8648 (message "Executing %s" cmd)
8649 (shell-command cmd))
8650 (error "Abort"))))
8652 ((string= type "elisp")
8653 (let ((cmd path))
8654 (if (or (not org-confirm-elisp-link-function)
8655 (funcall org-confirm-elisp-link-function
8656 (format "Execute \"%s\" as elisp? "
8657 (org-add-props cmd nil
8658 'face 'org-warning))))
8659 (message "%s => %s" cmd (eval (read cmd)))
8660 (error "Abort"))))
8663 (browse-url-at-point))))))
8665 ;;; File search
8667 (defvar org-create-file-search-functions nil
8668 "List of functions to construct the right search string for a file link.
8669 These functions are called in turn with point at the location to
8670 which the link should point.
8672 A function in the hook should first test if it would like to
8673 handle this file type, for example by checking the major-mode or
8674 the file extension. If it decides not to handle this file, it
8675 should just return nil to give other functions a chance. If it
8676 does handle the file, it must return the search string to be used
8677 when following the link. The search string will be part of the
8678 file link, given after a double colon, and `org-open-at-point'
8679 will automatically search for it. If special measures must be
8680 taken to make the search successful, another function should be
8681 added to the companion hook `org-execute-file-search-functions',
8682 which see.
8684 A function in this hook may also use `setq' to set the variable
8685 `description' to provide a suggestion for the descriptive text to
8686 be used for this link when it gets inserted into an Org-mode
8687 buffer with \\[org-insert-link].")
8689 (defvar org-execute-file-search-functions nil
8690 "List of functions to execute a file search triggered by a link.
8692 Functions added to this hook must accept a single argument, the
8693 search string that was part of the file link, the part after the
8694 double colon. The function must first check if it would like to
8695 handle this search, for example by checking the major-mode or the
8696 file extension. If it decides not to handle this search, it
8697 should just return nil to give other functions a chance. If it
8698 does handle the search, it must return a non-nil value to keep
8699 other functions from trying.
8701 Each function can access the current prefix argument through the
8702 variable `current-prefix-argument'. Note that a single prefix is
8703 used to force opening a link in Emacs, so it may be good to only
8704 use a numeric or double prefix to guide the search function.
8706 In case this is needed, a function in this hook can also restore
8707 the window configuration before `org-open-at-point' was called using:
8709 (set-window-configuration org-window-config-before-follow-link)")
8711 (defun org-link-search (s &optional type)
8712 "Search for a link search option.
8713 When S is a CamelCaseWord, search for a target, or for a sentence containing
8714 the words. If S is surrounded by forward slashes, it is interpreted as a
8715 regular expression. In org-mode files, this will create an `org-occur'
8716 sparse tree. In ordinary files, `occur' will be used to list matches.
8717 If the current buffer is in `dired-mode', grep will be used to search
8718 in all files."
8719 (let ((case-fold-search t)
8720 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8721 (pos (point))
8722 (pre "") (post "")
8723 words re0 re1 re2 re3 re4 re5 re2a reall camel)
8724 (cond
8725 ;; First check if there are any special
8726 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8727 ;; Now try the builtin stuff
8728 ((save-excursion
8729 (goto-char (point-min))
8730 (and
8731 (re-search-forward
8732 (concat "<<" (regexp-quote s0) ">>") nil t)
8733 (setq pos (match-beginning 0))))
8734 ;; There is an exact target for this
8735 (goto-char pos))
8736 ((string-match "^/\\(.*\\)/$" s)
8737 ;; A regular expression
8738 (cond
8739 ((org-mode-p)
8740 (org-occur (match-string 1 s)))
8741 ;;((eq major-mode 'dired-mode)
8742 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8743 (t (org-do-occur (match-string 1 s)))))
8744 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
8746 ;; A camel or a normal search string
8747 (when (equal (string-to-char s) ?*)
8748 ;; Anchor on headlines, post may include tags.
8749 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
8750 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
8751 s (substring s 1)))
8752 (remove-text-properties
8753 0 (length s)
8754 '(face nil mouse-face nil keymap nil fontified nil) s)
8755 ;; Make a series of regular expressions to find a match
8756 (setq words
8757 (if camel
8758 (org-camel-to-words s)
8759 (org-split-string s "[ \n\r\t]+"))
8760 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8761 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
8762 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8763 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8764 re1 (concat pre re2 post)
8765 re3 (concat pre re4 post)
8766 re5 (concat pre ".*" re4)
8767 re2 (concat pre re2)
8768 re2a (concat pre re2a)
8769 re4 (concat pre re4)
8770 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8771 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8772 re5 "\\)"
8774 (cond
8775 ((eq type 'org-occur) (org-occur reall))
8776 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8777 (t (goto-char (point-min))
8778 (if (or (org-search-not-link re0 nil t)
8779 (org-search-not-link re1 nil t)
8780 (org-search-not-link re2 nil t)
8781 (org-search-not-link re2a nil t)
8782 (org-search-not-link re3 nil t)
8783 (org-search-not-link re4 nil t)
8784 (org-search-not-link re5 nil t)
8786 (goto-char (match-beginning 1))
8787 (goto-char pos)
8788 (error "No match")))))
8790 ;; Normal string-search
8791 (goto-char (point-min))
8792 (if (search-forward s nil t)
8793 (goto-char (match-beginning 0))
8794 (error "No match"))))
8795 (and (org-mode-p) (org-show-context 'link-search))))
8797 (defun org-search-not-link (&rest args)
8798 "Execute `re-search-forward', but only accept matches that are not a link."
8799 (catch 'exit
8800 (let (p1)
8801 (while (apply 're-search-forward args)
8802 (setq p1 (point))
8803 (if (not (save-match-data
8804 (and (re-search-backward "\\[\\[" nil t)
8805 (looking-at org-bracket-link-regexp)
8806 (<= (match-beginning 0) p1)
8807 (>= (match-end 0) p1))))
8808 (progn (goto-char (match-end 0))
8809 (throw 'exit (point)))
8810 (goto-char (match-end 0)))))))
8812 (defun org-get-buffer-for-internal-link (buffer)
8813 "Return a buffer to be used for displaying the link target of internal links."
8814 (cond
8815 ((not org-display-internal-link-with-indirect-buffer)
8816 buffer)
8817 ((string-match "(Clone)$" (buffer-name buffer))
8818 (message "Buffer is already a clone, not making another one")
8819 ;; we also do not modify visibility in this case
8820 buffer)
8821 (t ; make a new indirect buffer for displaying the link
8822 (let* ((bn (buffer-name buffer))
8823 (ibn (concat bn "(Clone)"))
8824 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8825 (with-current-buffer ib (org-overview))
8826 ib))))
8828 (defun org-do-occur (regexp &optional cleanup)
8829 "Call the Emacs command `occur'.
8830 If CLEANUP is non-nil, remove the printout of the regular expression
8831 in the *Occur* buffer. This is useful if the regex is long and not useful
8832 to read."
8833 (occur regexp)
8834 (when cleanup
8835 (let ((cwin (selected-window)) win beg end)
8836 (when (setq win (get-buffer-window "*Occur*"))
8837 (select-window win))
8838 (goto-char (point-min))
8839 (when (re-search-forward "match[a-z]+" nil t)
8840 (setq beg (match-end 0))
8841 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8842 (setq end (1- (match-beginning 0)))))
8843 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
8844 (goto-char (point-min))
8845 (select-window cwin))))
8847 ;;; The mark ring for links jumps
8849 (defvar org-mark-ring nil
8850 "Mark ring for positions before jumps in Org-mode.")
8851 (defvar org-mark-ring-last-goto nil
8852 "Last position in the mark ring used to go back.")
8853 ;; Fill and close the ring
8854 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8855 (loop for i from 1 to org-mark-ring-length do
8856 (push (make-marker) org-mark-ring))
8857 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8858 org-mark-ring)
8860 (defun org-mark-ring-push (&optional pos buffer)
8861 "Put the current position or POS into the mark ring and rotate it."
8862 (interactive)
8863 (setq pos (or pos (point)))
8864 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8865 (move-marker (car org-mark-ring)
8866 (or pos (point))
8867 (or buffer (current-buffer)))
8868 (message
8869 (substitute-command-keys
8870 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8872 (defun org-mark-ring-goto (&optional n)
8873 "Jump to the previous position in the mark ring.
8874 With prefix arg N, jump back that many stored positions. When
8875 called several times in succession, walk through the entire ring.
8876 Org-mode commands jumping to a different position in the current file,
8877 or to another Org-mode file, automatically push the old position
8878 onto the ring."
8879 (interactive "p")
8880 (let (p m)
8881 (if (eq last-command this-command)
8882 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8883 (setq p org-mark-ring))
8884 (setq org-mark-ring-last-goto p)
8885 (setq m (car p))
8886 (switch-to-buffer (marker-buffer m))
8887 (goto-char m)
8888 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8890 (defun org-camel-to-words (s)
8891 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
8892 (let ((case-fold-search nil)
8893 words)
8894 (while (string-match "[a-z][A-Z]" s)
8895 (push (substring s 0 (1+ (match-beginning 0))) words)
8896 (setq s (substring s (1+ (match-beginning 0)))))
8897 (nreverse (cons s words))))
8899 (defun org-remove-angle-brackets (s)
8900 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8901 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8903 (defun org-add-angle-brackets (s)
8904 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8905 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8908 ;;; Following specific links
8910 (defun org-follow-timestamp-link ()
8911 (cond
8912 ((org-at-date-range-p t)
8913 (let ((org-agenda-start-on-weekday)
8914 (t1 (match-string 1))
8915 (t2 (match-string 2)))
8916 (setq t1 (time-to-days (org-time-string-to-time t1))
8917 t2 (time-to-days (org-time-string-to-time t2)))
8918 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8919 ((org-at-timestamp-p t)
8920 (org-agenda-list nil (time-to-days (org-time-string-to-time
8921 (substring (match-string 1) 0 10)))
8923 (t (error "This should not happen"))))
8926 (defun org-follow-bbdb-link (name)
8927 "Follow a BBDB link to NAME."
8928 (require 'bbdb)
8929 (let ((inhibit-redisplay t)
8930 (bbdb-electric-p nil))
8931 (catch 'exit
8932 ;; Exact match on name
8933 (bbdb-name (concat "\\`" name "\\'") nil)
8934 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8935 ;; Exact match on name
8936 (bbdb-company (concat "\\`" name "\\'") nil)
8937 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8938 ;; Partial match on name
8939 (bbdb-name name nil)
8940 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8941 ;; Partial match on company
8942 (bbdb-company name nil)
8943 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8944 ;; General match including network address and notes
8945 (bbdb name nil)
8946 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
8947 (delete-window (get-buffer-window "*BBDB*"))
8948 (error "No matching BBDB record")))))
8950 (defun org-follow-info-link (name)
8951 "Follow an info file & node link to NAME."
8952 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
8953 (string-match "\\(.*\\)" name))
8954 (progn
8955 (require 'info)
8956 (if (match-string 2 name) ; If there isn't a node, choose "Top"
8957 (Info-find-node (match-string 1 name) (match-string 2 name))
8958 (Info-find-node (match-string 1 name) "Top")))
8959 (message (concat "Could not open: " name))))
8961 (defun org-follow-gnus-link (&optional group article)
8962 "Follow a Gnus link to GROUP and ARTICLE."
8963 (require 'gnus)
8964 (funcall (cdr (assq 'gnus org-link-frame-setup)))
8965 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
8966 (if group (gnus-fetch-group group))
8967 (if article
8968 (or (gnus-summary-goto-article article nil 'force)
8969 (if (fboundp 'gnus-summary-insert-cached-articles)
8970 (progn
8971 (gnus-summary-insert-cached-articles)
8972 (gnus-summary-goto-article article nil 'force))
8973 (message "Message could not be found.")))))
8975 (defun org-follow-vm-link (&optional folder article readonly)
8976 "Follow a VM link to FOLDER and ARTICLE."
8977 (require 'vm)
8978 (setq article (org-add-angle-brackets article))
8979 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
8980 ;; ange-ftp or efs or tramp access
8981 (let ((user (or (match-string 1 folder) (user-login-name)))
8982 (host (match-string 2 folder))
8983 (file (match-string 3 folder)))
8984 (cond
8985 ((featurep 'tramp)
8986 ;; use tramp to access the file
8987 (if (featurep 'xemacs)
8988 (setq folder (format "[%s@%s]%s" user host file))
8989 (setq folder (format "/%s@%s:%s" user host file))))
8991 ;; use ange-ftp or efs
8992 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
8993 (setq folder (format "/%s@%s:%s" user host file))))))
8994 (when folder
8995 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
8996 (sit-for 0.1)
8997 (when article
8998 (vm-select-folder-buffer)
8999 (widen)
9000 (let ((case-fold-search t))
9001 (goto-char (point-min))
9002 (if (not (re-search-forward
9003 (concat "^" "message-id: *" (regexp-quote article))))
9004 (error "Could not find the specified message in this folder"))
9005 (vm-isearch-update)
9006 (vm-isearch-narrow)
9007 (vm-beginning-of-message)
9008 (vm-summarize)))))
9010 (defun org-follow-wl-link (folder article)
9011 "Follow a Wanderlust link to FOLDER and ARTICLE."
9012 (setq article (org-add-angle-brackets article))
9013 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
9014 (if article (wl-summary-jump-to-msg-by-message-id article))
9015 (wl-summary-redisplay))
9017 (defun org-follow-rmail-link (folder article)
9018 "Follow an RMAIL link to FOLDER and ARTICLE."
9019 (setq article (org-add-angle-brackets article))
9020 (let (message-number)
9021 (save-excursion
9022 (save-window-excursion
9023 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9024 (setq message-number
9025 (save-restriction
9026 (widen)
9027 (goto-char (point-max))
9028 (if (re-search-backward
9029 (concat "^Message-ID:\\s-+" (regexp-quote
9030 (or article "")))
9031 nil t)
9032 (rmail-what-message))))))
9033 (if message-number
9034 (progn
9035 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9036 (rmail-show-message message-number)
9037 message-number)
9038 (error "Message not found"))))
9040 ;;; mh-e integration based on planner-mode
9041 (defun org-mhe-get-message-real-folder ()
9042 "Return the name of the current message real folder, so if you use
9043 sequences, it will now work."
9044 (save-excursion
9045 (let* ((folder
9046 (if (equal major-mode 'mh-folder-mode)
9047 mh-current-folder
9048 ;; Refer to the show buffer
9049 mh-show-folder-buffer))
9050 (end-index
9051 (if (boundp 'mh-index-folder)
9052 (min (length mh-index-folder) (length folder))))
9054 ;; a simple test on mh-index-data does not work, because
9055 ;; mh-index-data is always nil in a show buffer.
9056 (if (and (boundp 'mh-index-folder)
9057 (string= mh-index-folder (substring folder 0 end-index)))
9058 (if (equal major-mode 'mh-show-mode)
9059 (save-window-excursion
9060 (when (buffer-live-p (get-buffer folder))
9061 (progn
9062 (pop-to-buffer folder)
9063 (org-mhe-get-message-folder-from-index)
9066 (org-mhe-get-message-folder-from-index)
9068 folder
9072 (defun org-mhe-get-message-folder-from-index ()
9073 "Returns the name of the message folder in a index folder buffer."
9074 (save-excursion
9075 (mh-index-previous-folder)
9076 (re-search-forward "^\\(+.*\\)$" nil t)
9077 (message (match-string 1))))
9079 (defun org-mhe-get-message-folder ()
9080 "Return the name of the current message folder. Be careful if you
9081 use sequences."
9082 (save-excursion
9083 (if (equal major-mode 'mh-folder-mode)
9084 mh-current-folder
9085 ;; Refer to the show buffer
9086 mh-show-folder-buffer)))
9088 (defun org-mhe-get-message-num ()
9089 "Return the number of the current message. Be careful if you
9090 use sequences."
9091 (save-excursion
9092 (if (equal major-mode 'mh-folder-mode)
9093 (mh-get-msg-num nil)
9094 ;; Refer to the show buffer
9095 (mh-show-buffer-message-number))))
9097 (defun org-mhe-get-header (header)
9098 "Return a header of the message in folder mode. This will create a
9099 show buffer for the corresponding message. If you have a more clever
9100 idea..."
9101 (let* ((folder (org-mhe-get-message-folder))
9102 (num (org-mhe-get-message-num))
9103 (buffer (get-buffer-create (concat "show-" folder)))
9104 (header-field))
9105 (with-current-buffer buffer
9106 (mh-display-msg num folder)
9107 (if (equal major-mode 'mh-folder-mode)
9108 (mh-header-display)
9109 (mh-show-header-display))
9110 (set-buffer buffer)
9111 (setq header-field (mh-get-header-field header))
9112 (if (equal major-mode 'mh-folder-mode)
9113 (mh-show)
9114 (mh-show-show))
9115 header-field)))
9117 (defun org-follow-mhe-link (folder article)
9118 "Follow an MHE link to FOLDER and ARTICLE.
9119 If ARTICLE is nil FOLDER is shown. If the configuration variable
9120 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9121 ARTICLE is searched in all folders. Indexed searches (swish++,
9122 namazu, and others supported by MH-E) will always search in all
9123 folders."
9124 (require 'mh-e)
9125 (require 'mh-search)
9126 (require 'mh-utils)
9127 (mh-find-path)
9128 (if (not article)
9129 (mh-visit-folder (mh-normalize-folder-name folder))
9130 (setq article (org-add-angle-brackets article))
9131 (mh-search-choose)
9132 (if (equal mh-searcher 'pick)
9133 (progn
9134 (mh-search folder (list "--message-id" article))
9135 (when (and org-mhe-search-all-folders
9136 (not (org-mhe-get-message-real-folder)))
9137 (kill-this-buffer)
9138 (mh-search "+" (list "--message-id" article))))
9139 (mh-search "+" article))
9140 (if (org-mhe-get-message-real-folder)
9141 (mh-show-msg 1)
9142 (kill-this-buffer)
9143 (error "Message not found"))))
9145 ;;; BibTeX links
9147 ;; Use the custom search meachnism to construct and use search strings for
9148 ;; file links to BibTeX database entries.
9150 (defun org-create-file-search-in-bibtex ()
9151 "Create the search string and description for a BibTeX database entry."
9152 (when (eq major-mode 'bibtex-mode)
9153 ;; yes, we want to construct this search string.
9154 ;; Make a good description for this entry, using names, year and the title
9155 ;; Put it into the `description' variable which is dynamically scoped.
9156 (let ((bibtex-autokey-names 1)
9157 (bibtex-autokey-names-stretch 1)
9158 (bibtex-autokey-name-case-convert-function 'identity)
9159 (bibtex-autokey-name-separator " & ")
9160 (bibtex-autokey-additional-names " et al.")
9161 (bibtex-autokey-year-length 4)
9162 (bibtex-autokey-name-year-separator " ")
9163 (bibtex-autokey-titlewords 3)
9164 (bibtex-autokey-titleword-separator " ")
9165 (bibtex-autokey-titleword-case-convert-function 'identity)
9166 (bibtex-autokey-titleword-length 'infty)
9167 (bibtex-autokey-year-title-separator ": "))
9168 (setq description (bibtex-generate-autokey)))
9169 ;; Now parse the entry, get the key and return it.
9170 (save-excursion
9171 (bibtex-beginning-of-entry)
9172 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9174 (defun org-execute-file-search-in-bibtex (s)
9175 "Find the link search string S as a key for a database entry."
9176 (when (eq major-mode 'bibtex-mode)
9177 ;; Yes, we want to do the search in this file.
9178 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9179 (goto-char (point-min))
9180 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9181 (regexp-quote s) "[ \t\n]*,") nil t)
9182 (goto-char (match-beginning 0)))
9183 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9184 ;; Use double prefix to indicate that any web link should be browsed
9185 (let ((b (current-buffer)) (p (point)))
9186 ;; Restore the window configuration because we just use the web link
9187 (set-window-configuration org-window-config-before-follow-link)
9188 (save-excursion (set-buffer b) (goto-char p)
9189 (bibtex-url)))
9190 (recenter 0)) ; Move entry start to beginning of window
9191 ;; return t to indicate that the search is done.
9194 ;; Finally add the functions to the right hooks.
9195 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9196 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9198 ;; end of Bibtex link setup
9201 ;; FIXME: This function can be removed, I think.
9202 (defun org-upgrade-old-links (&optional query-description)
9203 "Transfer old <...> style links to new [[...]] style links.
9204 With arg query-description, ask at each match for a description text to use
9205 for this link."
9206 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
9207 (save-excursion
9208 (goto-char (point-min))
9209 (let ((re (concat "\\([^[]\\)<\\("
9210 "\\(" (mapconcat 'identity org-link-types "\\|")
9211 "\\):"
9212 "[^" org-non-link-chars "]+\\)>"))
9213 l1 l2 (cnt 0))
9214 (while (re-search-forward re nil t)
9215 (setq cnt (1+ cnt)
9216 l1 (org-match-string-no-properties 2)
9217 l2 (save-match-data (org-link-escape l1)))
9218 (when query-description (setq l1 (read-string "Desc: " l1)))
9219 (if (equal l1 l2)
9220 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
9221 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
9222 (message "%d matches have beed treated" cnt))))
9224 ;;; Following file links
9226 (defun org-open-file (path &optional in-emacs line search)
9227 "Open the file at PATH.
9228 First, this expands any special file name abbreviations. Then the
9229 configuration variable `org-file-apps' is checked if it contains an
9230 entry for this file type, and if yes, the corresponding command is launched.
9231 If no application is found, Emacs simply visits the file.
9232 With optional argument IN-EMACS, Emacs will visit the file.
9233 Optional LINE specifies a line to go to, optional SEARCH a string to
9234 search for. If LINE or SEARCH is given, the file will always be
9235 opened in Emacs.
9236 If the file does not exist, an error is thrown."
9237 (setq in-emacs (or in-emacs line search))
9238 (let* ((file (if (equal path "")
9239 buffer-file-name
9240 (substitute-in-file-name (expand-file-name path))))
9241 (apps (append org-file-apps (org-default-apps)))
9242 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9243 (dirp (if remp nil (file-directory-p file)))
9244 (dfile (downcase file))
9245 (old-buffer (current-buffer))
9246 (old-pos (point))
9247 (old-mode major-mode)
9248 ext cmd)
9249 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9250 (setq ext (match-string 1 dfile))
9251 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9252 (setq ext (match-string 1 dfile))))
9253 (if in-emacs
9254 (setq cmd 'emacs)
9255 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9256 (and dirp (cdr (assoc 'directory apps)))
9257 (cdr (assoc ext apps))
9258 (cdr (assoc t apps)))))
9259 (when (eq cmd 'mailcap)
9260 (require 'mailcap)
9261 (mailcap-parse-mailcaps)
9262 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9263 (command (mailcap-mime-info mime-type)))
9264 (if (stringp command)
9265 (setq cmd command)
9266 (setq cmd 'emacs))))
9267 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
9268 (not (file-exists-p file))
9269 (not org-open-non-existing-files))
9270 (error "No such file: %s" file))
9271 (cond
9272 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9273 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9274 (if (string-match "['\"]%s['\"]" cmd)
9275 (setq cmd (replace-match "%s" t t cmd)))
9276 (setq cmd (format cmd (shell-quote-argument file)))
9277 (save-window-excursion
9278 (shell-command (concat cmd " &"))))
9279 ((or (stringp cmd)
9280 (eq cmd 'emacs))
9281 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9282 (if line (goto-line line)
9283 (if search (org-link-search search))))
9284 ((consp cmd)
9285 (eval cmd))
9286 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9287 (and (org-mode-p) (eq old-mode 'org-mode)
9288 (or (not (equal old-buffer (current-buffer)))
9289 (not (equal old-pos (point))))
9290 (org-mark-ring-push old-pos old-buffer))))
9292 (defun org-default-apps ()
9293 "Return the default applications for this operating system."
9294 (cond
9295 ((eq system-type 'darwin)
9296 org-file-apps-defaults-macosx)
9297 ((eq system-type 'windows-nt)
9298 org-file-apps-defaults-windowsnt)
9299 (t org-file-apps-defaults-gnu)))
9301 (defun org-expand-file-name (path)
9302 "Replace special path abbreviations and expand the file name."
9303 (expand-file-name path))
9305 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9306 (defun org-file-remote-p (file)
9307 "Test whether FILE specifies a location on a remote system.
9308 Return non-nil if the location is indeed remote.
9310 For example, the filename \"/user@host:/foo\" specifies a location
9311 on the system \"/user@host:\"."
9312 (cond ((fboundp 'file-remote-p)
9313 (file-remote-p file))
9314 ((fboundp 'tramp-handle-file-remote-p)
9315 (tramp-handle-file-remote-p file))
9316 ((and (boundp 'ange-ftp-name-format)
9317 (string-match (car ange-ftp-name-format) file))
9319 (t nil)))
9322 ;;;; Hooks for remember.el
9324 ;;;###autoload
9325 (defun org-remember-annotation ()
9326 "Return a link to the current location as an annotation for remember.el.
9327 If you are using Org-mode files as target for data storage with
9328 remember.el, then the annotations should include a link compatible with the
9329 conventions in Org-mode. This function returns such a link."
9330 (org-store-link nil))
9332 (defconst org-remember-help
9333 "Select a destination location for the note.
9334 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
9335 RET at beg-of-buf -> Append to file as level 2 headline
9336 RET on headline -> Store as sublevel entry to current headline
9337 <left>/<right> -> before/after current headline, same headings level")
9339 ;;;###autoload
9340 (defun org-remember-apply-template ()
9341 "Initialize *remember* buffer with template, invoke `org-mode'.
9342 This function should be placed into `remember-mode-hook' and in fact requires
9343 to be run from that hook to fucntion properly."
9344 (if org-remember-templates
9346 (let* ((entry (if (= (length org-remember-templates) 1)
9347 (cdar org-remember-templates)
9348 (message "Select template: %s"
9349 (mapconcat
9350 (lambda (x) (char-to-string (car x)))
9351 org-remember-templates " "))
9352 (cdr (assoc (read-char-exclusive) org-remember-templates))))
9353 (tpl (car entry))
9354 (file (if (consp (cdr entry)) (nth 1 entry)))
9355 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
9356 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
9357 (v-u (concat "[" (substring v-t 1 -1) "]"))
9358 (v-U (concat "[" (substring v-T 1 -1) "]"))
9359 (v-a annotation) ; defined in `remember-mode'
9360 (v-i initial) ; defined in `remember-mode'
9361 (v-n user-full-name)
9363 (unless tpl (setq tpl "") (message "No template") (ding))
9364 (insert tpl) (goto-char (point-min))
9365 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
9366 (when (and initial (equal (match-string 0) "%i"))
9367 (save-match-data
9368 (let* ((lead (buffer-substring
9369 (point-at-bol) (match-beginning 0))))
9370 (setq v-i (mapconcat 'identity
9371 (org-split-string initial "\n")
9372 (concat "\n" lead))))))
9373 (replace-match
9374 (or (eval (intern (concat "v-" (match-string 1)))) "")
9375 t t))
9376 (let ((org-startup-folded nil)
9377 (org-startup-with-deadline-check nil))
9378 (org-mode))
9379 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
9380 (org-set-local 'org-default-notes-file file))
9381 (goto-char (point-min))
9382 (if (re-search-forward "%\\?" nil t) (replace-match "")))
9383 (let ((org-startup-folded nil)
9384 (org-startup-with-deadline-check nil))
9385 (org-mode)))
9386 (org-set-local 'org-finish-function 'remember-buffer))
9388 ;;;###autoload
9389 (defun org-remember-handler ()
9390 "Store stuff from remember.el into an org file.
9391 First prompts for an org file. If the user just presses return, the value
9392 of `org-default-notes-file' is used.
9393 Then the command offers the headings tree of the selected file in order to
9394 file the text at a specific location.
9395 You can either immediately press RET to get the note appended to the
9396 file, or you can use vertical cursor motion and visibility cycling (TAB) to
9397 find a better place. Then press RET or <left> or <right> in insert the note.
9399 Key Cursor position Note gets inserted
9400 -----------------------------------------------------------------------------
9401 RET buffer-start as level 2 heading at end of file
9402 RET on headline as sublevel of the heading at cursor
9403 RET no heading at cursor position, level taken from context.
9404 Or use prefix arg to specify level manually.
9405 <left> on headline as same level, before current heading
9406 <right> on headline as same level, after current heading
9408 So the fastest way to store the note is to press RET RET to append it to
9409 the default file. This way your current train of thought is not
9410 interrupted, in accordance with the principles of remember.el. But with
9411 little extra effort, you can push it directly to the correct location.
9413 Before being stored away, the function ensures that the text has a
9414 headline, i.e. a first line that starts with a \"*\". If not, a headline
9415 is constructed from the current date and some additional data.
9417 If the variable `org-adapt-indentation' is non-nil, the entire text is
9418 also indented so that it starts in the same column as the headline
9419 \(i.e. after the stars).
9421 See also the variable `org-reverse-note-order'."
9422 (catch 'quit
9423 (let* ((txt (buffer-substring (point-min) (point-max)))
9424 (fastp current-prefix-arg)
9425 (file (if fastp org-default-notes-file (org-get-org-file)))
9426 (visiting (find-buffer-visiting file))
9427 (org-startup-with-deadline-check nil)
9428 (org-startup-folded nil)
9429 (org-startup-align-all-tables nil)
9430 spos level indent reversed)
9431 ;; Modify text so that it becomes a nice subtree which can be inserted
9432 ;; into an org tree.
9433 (let* ((lines (split-string txt "\n"))
9434 first)
9435 ;; remove empty lines at the beginning
9436 (while (and lines (string-match "^[ \t]*\n" (car lines)))
9437 (setq lines (cdr lines)))
9438 (setq first (car lines) lines (cdr lines))
9439 (if (string-match "^\\*+" first)
9440 ;; Is already a headline
9441 (setq indent nil)
9442 ;; We need to add a headline: Use time and first buffer line
9443 (setq lines (cons first lines)
9444 first (concat "* " (current-time-string)
9445 " (" (remember-buffer-desc) ")")
9446 indent " "))
9447 (if (and org-adapt-indentation indent)
9448 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
9449 (setq txt (concat first "\n"
9450 (mapconcat 'identity lines "\n"))))
9451 ;; Find the file
9452 (if (not visiting)
9453 (find-file-noselect file))
9454 (with-current-buffer (get-file-buffer file)
9455 (save-excursion (and (goto-char (point-min))
9456 (not (re-search-forward "^\\* " nil t))
9457 (insert "\n* Notes\n")))
9458 (setq reversed (org-notes-order-reversed-p))
9459 (save-excursion
9460 (save-restriction
9461 (widen)
9462 ;; Ask the User for a location
9463 (setq spos (if fastp 1 (org-get-location
9464 (current-buffer)
9465 org-remember-help)))
9466 (if (not spos) (throw 'quit nil)) ; return nil to show we did
9467 ; not handle this note
9468 (goto-char spos)
9469 (cond ((and (bobp) (not reversed))
9470 ;; Put it at the end, as level 2
9471 (save-restriction
9472 (widen)
9473 (goto-char (point-max))
9474 (if (not (bolp)) (newline))
9475 (org-paste-subtree 2 txt)))
9476 ((and (bobp) reversed)
9477 ;; Put it at the start, as level 1
9478 (save-restriction
9479 (widen)
9480 (goto-char (point-min))
9481 (re-search-forward "^\\*" nil t)
9482 (beginning-of-line 1)
9483 (org-paste-subtree 1 txt)))
9484 ((and (org-on-heading-p nil) (not current-prefix-arg))
9485 ;; Put it below this entry, at the beg/end of the subtree
9486 (org-back-to-heading)
9487 (setq level (funcall outline-level))
9488 (if reversed
9489 (outline-end-of-heading)
9490 (outline-end-of-subtree))
9491 (if (not (bolp)) (newline))
9492 (beginning-of-line 1)
9493 (org-paste-subtree (org-get-legal-level level 1) txt))
9495 ;; Put it right there, with automatic level determined by
9496 ;; org-paste-subtree or from prefix arg
9497 (org-paste-subtree current-prefix-arg txt)))
9498 (when remember-save-after-remembering
9499 (save-buffer)
9500 (if (not visiting) (kill-buffer (current-buffer)))))))))
9501 t) ;; return t to indicate that we took care of this note.
9503 (defun org-get-org-file ()
9504 "Read a filename, with default directory `org-directory'."
9505 (let ((default (or org-default-notes-file remember-data-file)))
9506 (read-file-name (format "File name [%s]: " default)
9507 (file-name-as-directory org-directory)
9508 default)))
9510 (defun org-notes-order-reversed-p ()
9511 "Check if the current file should receive notes in reversed order."
9512 (cond
9513 ((not org-reverse-note-order) nil)
9514 ((eq t org-reverse-note-order) t)
9515 ((not (listp org-reverse-note-order)) nil)
9516 (t (catch 'exit
9517 (let ((all org-reverse-note-order)
9518 entry)
9519 (while (setq entry (pop all))
9520 (if (string-match (car entry) buffer-file-name)
9521 (throw 'exit (cdr entry))))
9522 nil)))))
9524 ;;;; Dynamic blocks
9526 (defun org-find-dblock (name)
9527 "Find the first dynamic block with name NAME in the buffer.
9528 If not found, stay at current position and return nil."
9529 (let (pos)
9530 (save-excursion
9531 (goto-char (point-min))
9532 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9533 nil t)
9534 (match-beginning 0))))
9535 (if pos (goto-char pos))
9536 pos))
9538 (defconst org-dblock-start-re
9539 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9540 "Matches the startline of a dynamic block, with parameters.")
9542 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
9543 "Matches the end of a dyhamic block.")
9545 (defun org-create-dblock (plist)
9546 "Create a dynamic block section, with parameters taken from PLIST.
9547 PLIST must containe a :name entry which is used as name of the block."
9548 (unless (bolp) (newline))
9549 (let ((name (plist-get plist :name)))
9550 (insert "#+BEGIN: " name)
9551 (while plist
9552 (if (eq (car plist) :name)
9553 (setq plist (cddr plist))
9554 (insert " " (prin1-to-string (pop plist)))))
9555 (insert "\n\n#+END:\n")
9556 (beginning-of-line -2)))
9558 (defun org-prepare-dblock ()
9559 "Prepare dynamic block for refresh.
9560 This empties the block, puts the cursor at the insert position and returns
9561 the property list including an extra property :name with the block name."
9562 (unless (looking-at org-dblock-start-re)
9563 (error "Not at a dynamic block"))
9564 (let* ((begdel (1+ (match-end 0)))
9565 (name (match-string 1))
9566 (params (append (list :name name)
9567 (read (concat "(" (match-string 3) ")")))))
9568 (unless (re-search-forward org-dblock-end-re nil t)
9569 (error "Dynamic block not terminated"))
9570 (delete-region begdel (match-beginning 0))
9571 (goto-char begdel)
9572 (open-line 1)
9573 params))
9575 (defun org-map-dblocks (&optional command)
9576 "Apply COMMAND to all dynamic blocks in the current buffer.
9577 If COMMAND is not given, use `org-update-dblock'."
9578 (let ((cmd (or command 'org-update-dblock))
9579 pos)
9580 (save-excursion
9581 (goto-char (point-min))
9582 (while (re-search-forward org-dblock-start-re nil t)
9583 (goto-char (setq pos (match-beginning 0)))
9584 (condition-case nil
9585 (funcall cmd)
9586 (error (message "Error during update of dynamic block")))
9587 (goto-char pos)
9588 (unless (re-search-forward org-dblock-end-re nil t)
9589 (error "Dynamic block not terminated"))))))
9591 (defun org-dblock-update (&optional arg)
9592 "User command for updating dynamic blocks.
9593 Update the dynamic block at point. With prefix ARG, update all dynamic
9594 blocks in the buffer."
9595 (interactive "P")
9596 (if arg
9597 (org-update-all-dblocks)
9598 (or (looking-at org-dblock-start-re)
9599 (org-beginning-of-dblock))
9600 (org-update-dblock)))
9602 (defun org-update-dblock ()
9603 "Update the dynamic block at point
9604 This means to empty the block, parse for parameters and then call
9605 the correct writing function."
9606 (let* ((pos (point))
9607 (params (org-prepare-dblock))
9608 (name (plist-get params :name))
9609 (cmd (intern (concat "org-dblock-write:" name))))
9610 (funcall cmd params)
9611 (goto-char pos)))
9613 (defun org-beginning-of-dblock ()
9614 "Find the beginning of the dynamic block at point.
9615 Error if there is no scuh block at point."
9616 (let ((pos (point))
9617 beg)
9618 (end-of-line 1)
9619 (if (and (re-search-backward org-dblock-start-re nil t)
9620 (setq beg (match-beginning 0))
9621 (re-search-forward org-dblock-end-re nil t)
9622 (> (match-end 0) pos))
9623 (goto-char beg)
9624 (goto-char pos)
9625 (error "Not in a dynamic block"))))
9627 (defun org-update-all-dblocks ()
9628 "Update all dynamic blocks in the buffer.
9629 This function can be used in a hook."
9630 (when (org-mode-p)
9631 (org-map-dblocks 'org-update-dblock)))
9634 ;;;; Completion
9636 (defun org-complete (&optional arg)
9637 "Perform completion on word at point.
9638 At the beginning of a headline, this completes TODO keywords as given in
9639 `org-todo-keywords'.
9640 If the current word is preceded by a backslash, completes the TeX symbols
9641 that are supported for HTML support.
9642 If the current word is preceded by \"#+\", completes special words for
9643 setting file options.
9644 In the line after \"#+STARTUP:, complete valid keywords.\"
9645 At all other locations, this simply calls `ispell-complete-word'."
9646 (interactive "P")
9647 (catch 'exit
9648 (let* ((end (point))
9649 (beg1 (save-excursion
9650 (skip-chars-backward "a-zA-Z_@0-9")
9651 (point)))
9652 (beg (save-excursion
9653 (skip-chars-backward "a-zA-Z0-9_:$")
9654 (point)))
9655 (confirm (lambda (x) (stringp (car x))))
9656 (camel (equal (char-before beg) ?*))
9657 (tag (equal (char-before beg1) ?:))
9658 (texp (equal (char-before beg) ?\\))
9659 (link (equal (char-before beg) ?\[))
9660 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9661 beg)
9662 "#+"))
9663 (startup (string-match "^#\\+STARTUP:.*"
9664 (buffer-substring (point-at-bol) (point))))
9665 (completion-ignore-case opt)
9666 (type nil)
9667 (tbl nil)
9668 (table (cond
9669 (opt
9670 (setq type :opt)
9671 (mapcar (lambda (x)
9672 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9673 (cons (match-string 2 x) (match-string 1 x)))
9674 (org-split-string (org-get-current-options) "\n")))
9675 (startup
9676 (setq type :startup)
9677 org-startup-options)
9678 (link (append org-link-abbrev-alist-local
9679 org-link-abbrev-alist))
9680 (texp
9681 (setq type :tex)
9682 org-html-entities)
9683 ((string-match "\\`\\*+[ \t]*\\'"
9684 (buffer-substring (point-at-bol) beg))
9685 (setq type :todo)
9686 (mapcar 'list org-todo-keywords))
9687 (camel
9688 (setq type :camel)
9689 (save-excursion
9690 (goto-char (point-min))
9691 (while (re-search-forward org-todo-line-regexp nil t)
9692 (push (list
9693 (if org-file-link-context-use-camel-case
9694 (org-make-org-heading-camel (match-string 3) t)
9695 (org-make-org-heading-search-string
9696 (match-string 3) t)))
9697 tbl)))
9698 tbl)
9699 (tag (setq type :tag beg beg1)
9700 (or org-tag-alist (org-get-buffer-tags)))
9701 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
9702 (pattern (buffer-substring-no-properties beg end))
9703 (completion (try-completion pattern table confirm)))
9704 (cond ((eq completion t)
9705 (if (equal type :opt)
9706 (insert (substring (cdr (assoc (upcase pattern) table))
9707 (length pattern)))
9708 (if (equal type :tag) (insert ":"))))
9709 ((null completion)
9710 (message "Can't find completion for \"%s\"" pattern)
9711 (ding))
9712 ((not (string= pattern completion))
9713 (delete-region beg end)
9714 (if (string-match " +$" completion)
9715 (setq completion (replace-match "" t t completion)))
9716 (insert completion)
9717 (if (get-buffer-window "*Completions*")
9718 (delete-window (get-buffer-window "*Completions*")))
9719 (if (assoc completion table)
9720 (if (eq type :todo) (insert " ")
9721 (if (eq type :tag) (insert ":"))))
9722 (if (and (equal type :opt) (assoc completion table))
9723 (message "%s" (substitute-command-keys
9724 "Press \\[org-complete] again to insert example settings"))))
9726 (message "Making completion list...")
9727 (let ((list (sort (all-completions pattern table confirm)
9728 'string<)))
9729 (with-output-to-temp-buffer "*Completions*"
9730 (condition-case nil
9731 ;; Protection needed for XEmacs and emacs 21
9732 (display-completion-list list pattern)
9733 (error (display-completion-list list)))))
9734 (message "Making completion list...%s" "done"))))))
9736 ;;;; TODO, DEADLINE, Comments
9738 (defun org-toggle-comment ()
9739 "Change the COMMENT state of an entry."
9740 (interactive)
9741 (save-excursion
9742 (org-back-to-heading)
9743 (if (looking-at (concat outline-regexp
9744 "\\( +\\<" org-comment-string "\\>\\)"))
9745 (replace-match "" t t nil 1)
9746 (if (looking-at outline-regexp)
9747 (progn
9748 (goto-char (match-end 0))
9749 (insert " " org-comment-string))))))
9751 (defvar org-last-todo-state-is-todo nil
9752 "This is non-nil when the last TODO state change led to a TODO state.
9753 If the last change removed the TODO tag or switched to DONE, then
9754 this is nil.")
9756 (defun org-todo (&optional arg)
9757 "Change the TODO state of an item.
9758 The state of an item is given by a keyword at the start of the heading,
9759 like
9760 *** TODO Write paper
9761 *** DONE Call mom
9763 The different keywords are specified in the variable `org-todo-keywords'.
9764 By default the available states are \"TODO\" and \"DONE\".
9765 So for this example: when the item starts with TODO, it is changed to DONE.
9766 When it starts with DONE, the DONE is removed. And when neither TODO nor
9767 DONE are present, add TODO at the beginning of the heading.
9769 With prefix arg, use completion to determine the new state. With numeric
9770 prefix arg, switch to that state."
9771 (interactive "P")
9772 (save-excursion
9773 (org-back-to-heading)
9774 (if (looking-at outline-regexp) (goto-char (match-end 0)))
9775 (or (looking-at (concat " +" org-todo-regexp " *"))
9776 (looking-at " *"))
9777 (let* ((this (match-string 1))
9778 (completion-ignore-case t)
9779 (member (member this org-todo-keywords))
9780 (tail (cdr member))
9781 (state (cond
9782 ((equal arg '(4))
9783 ;; Read a state with completion
9784 (completing-read "State: " (mapcar (lambda(x) (list x))
9785 org-todo-keywords)
9786 nil t))
9787 ((eq arg 'right)
9788 (if this
9789 (if tail (car tail) nil)
9790 (car org-todo-keywords)))
9791 ((eq arg 'left)
9792 (if (equal member org-todo-keywords)
9794 (if this
9795 (nth (- (length org-todo-keywords) (length tail) 2)
9796 org-todo-keywords)
9797 org-done-string)))
9798 (arg
9799 ;; user requests a specific state
9800 (nth (1- (prefix-numeric-value arg))
9801 org-todo-keywords))
9802 ((null member) (car org-todo-keywords))
9803 ((null tail) nil) ;; -> first entry
9804 ((eq org-todo-interpretation 'sequence)
9805 (car tail))
9806 ((memq org-todo-interpretation '(type priority))
9807 (if (eq this-command last-command)
9808 (car tail)
9809 (if (> (length tail) 0) org-done-string nil)))
9810 (t nil)))
9811 (next (if state (concat " " state " ") " ")))
9812 (replace-match next t t)
9813 (setq org-last-todo-state-is-todo
9814 (not (equal state org-done-string)))
9815 (when org-log-done
9816 (if (equal state org-done-string)
9817 (org-add-planning-info 'closed (org-current-time) 'scheduled)
9818 (if (not this)
9819 (org-add-planning-info nil nil 'closed))))
9820 ;; Fixup tag positioning
9821 (and org-auto-align-tags (org-set-tags nil t))
9822 (run-hooks 'org-after-todo-state-change-hook)))
9823 ;; Fixup cursor location if close to the keyword
9824 (if (and (outline-on-heading-p)
9825 (not (bolp))
9826 (save-excursion (beginning-of-line 1)
9827 (looking-at org-todo-line-regexp))
9828 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9829 (progn
9830 (goto-char (or (match-end 2) (match-end 1)))
9831 (just-one-space))))
9833 (defun org-show-todo-tree (arg)
9834 "Make a compact tree which shows all headlines marked with TODO.
9835 The tree will show the lines where the regexp matches, and all higher
9836 headlines above the match.
9837 With \\[universal-argument] prefix, also show the DONE entries.
9838 With a numeric prefix N, construct a sparse tree for the Nth element
9839 of `org-todo-keywords'."
9840 (interactive "P")
9841 (let ((case-fold-search nil)
9842 (kwd-re
9843 (cond ((null arg) org-not-done-regexp)
9844 ((equal arg '(4)) org-todo-regexp)
9845 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
9846 (regexp-quote (nth (1- (prefix-numeric-value arg))
9847 org-todo-keywords)))
9848 (t (error "Invalid prefix argument: %s" arg)))))
9849 (message "%d TODO entries found"
9850 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
9852 (defun org-deadline ()
9853 "Insert the DEADLINE: string to make a deadline.
9854 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
9855 to modify it to the correct date."
9856 (interactive)
9857 (org-add-planning-info 'deadline nil 'closed))
9859 (defun org-schedule ()
9860 "Insert the SCHEDULED: string to schedule a TODO item.
9861 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
9862 to modify it to the correct date."
9863 (interactive)
9864 (org-add-planning-info 'scheduled nil 'closed))
9866 (defun org-add-planning-info (what &optional time &rest remove)
9867 "Insert new timestamp with keyword in the line directly after the headline.
9868 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9869 If non is given, the user is prompted for a date.
9870 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9871 be removed."
9872 (interactive)
9873 (when what (setq time (or time (org-read-date nil 'to-time))))
9874 (when (and org-insert-labeled-timestamps-at-point
9875 (member what '(scheduled deadline)))
9876 (insert
9877 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9878 (org-insert-time-stamp time)
9879 (setq what nil))
9880 (save-excursion
9881 (save-restriction
9882 (let (col list elt ts buffer-invisibility-spec)
9883 (org-back-to-heading t)
9884 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9885 (goto-char (match-end 1))
9886 (setq col (current-column))
9887 (goto-char (1+ (match-end 0)))
9888 (if (and (not (looking-at outline-regexp))
9889 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9890 "[^\r\n]*"))
9891 (not (equal (match-string 1) org-clock-string)))
9892 (narrow-to-region (match-beginning 0) (match-end 0))
9893 (insert "\n")
9894 (backward-char 1)
9895 (narrow-to-region (point) (point))
9896 (indent-to-column col))
9897 ;; Check if we have to remove something.
9898 (setq list (cons what remove))
9899 (while list
9900 (setq elt (pop list))
9901 (goto-char (point-min))
9902 (when (or (and (eq elt 'scheduled)
9903 (re-search-forward org-scheduled-time-regexp nil t))
9904 (and (eq elt 'deadline)
9905 (re-search-forward org-deadline-time-regexp nil t))
9906 (and (eq elt 'closed)
9907 (re-search-forward org-closed-time-regexp nil t)))
9908 (replace-match "")
9909 (if (looking-at "--+<[^>]+>") (replace-match ""))
9910 (if (looking-at " +") (replace-match ""))))
9911 (goto-char (point-max))
9912 (when what
9913 (insert
9914 (if (not (equal (char-before) ?\ )) " " "")
9915 (cond ((eq what 'scheduled) org-scheduled-string)
9916 ((eq what 'deadline) org-deadline-string)
9917 ((eq what 'closed) org-closed-string))
9918 " ")
9919 (org-insert-time-stamp time nil (eq what 'closed))
9920 (end-of-line 1)
9921 (and (eq what 'closed) (org-add-log-maybe 'done)))
9922 (goto-char (point-min))
9923 (widen)
9924 (if (looking-at "[ \t]+\r?\n")
9925 (replace-match ""))
9926 ts))))
9928 (defvar org-log-note-marker (make-marker))
9929 (defvar org-log-note-purpose nil)
9930 (defvar org-log-note-window-configuration nil)
9932 (defun org-add-log-maybe (&optional purpose)
9933 (when (and (listp org-log-done)
9934 (memq purpose org-log-done))
9935 (move-marker org-log-note-marker (point))
9936 (setq org-log-note-purpose purpose)
9937 (add-hook 'post-command-hook 'org-add-log-note 'append)))
9939 (defun org-add-log-note (&optional purpose)
9940 "Pop up a window for taking a note, and add this note later at point."
9941 (remove-hook 'post-command-hook 'org-add-log-note)
9942 (setq org-log-note-window-configuration (current-window-configuration))
9943 (delete-other-windows)
9944 (switch-to-buffer (marker-buffer org-log-note-marker))
9945 (goto-char org-log-note-marker)
9946 (switch-to-buffer-other-window "*Org Note*")
9947 (erase-buffer)
9948 (org-mode)
9949 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
9950 (cond
9951 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9952 ((eq org-log-note-purpose 'done) "closed todo item")
9953 (t (error "This should not happen")))))
9954 (org-set-local 'org-finish-function 'org-store-log-note))
9956 (defun org-store-log-note ()
9957 "Finish taking a log note, and insert it to where it belongs."
9958 (let ((txt (buffer-string))
9959 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9960 lines ind)
9961 (kill-buffer (current-buffer))
9962 (if (string-match "^#.*\n[ \t\\n]*" txt)
9963 (setq txt (replace-match "" t t txt)))
9964 (when (string-match "\\S-" txt)
9965 (if (string-match "\\s-+\\'" txt)
9966 (setq txt (replace-match "" t t txt)))
9967 (setq lines (org-split-string txt "\n"))
9968 (when (and note (string-match "\\S-" note))
9969 (setq note
9970 (org-replace-escapes
9971 note
9972 (list (cons "%u" user-login-name)
9973 (cons "%U" user-full-name)
9974 (cons "%t" (format-time-string
9975 (org-time-stamp-format 'long 'inactive)
9976 (current-time))))))
9977 (push note lines))
9978 (save-excursion
9979 (set-buffer (marker-buffer org-log-note-marker))
9980 (save-excursion
9981 (goto-char org-log-note-marker)
9982 (if (not (bolp)) (newline))
9983 (indent-relative t)
9984 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
9985 (insert " - " (pop lines))
9986 (while lines
9987 (insert "\n" ind (pop lines))))))
9988 (set-window-configuration org-log-note-window-configuration)))
9990 (defvar org-occur-highlights nil)
9991 (make-variable-buffer-local 'org-occur-highlights)
9993 (defun org-occur (regexp &optional keep-previous callback)
9994 "Make a compact tree which shows all matches of REGEXP.
9995 The tree will show the lines where the regexp matches, and all higher
9996 headlines above the match. It will also show the heading after the match,
9997 to make sure editing the matching entry is easy.
9998 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9999 call to `org-occur' will be kept, to allow stacking of calls to this
10000 command.
10001 If CALLBACK is non-nil, it is a function which is called to confirm
10002 that the match should indeed be shown."
10003 (interactive "sRegexp: \nP")
10004 (or keep-previous (org-remove-occur-highlights nil nil t))
10005 (let ((cnt 0))
10006 (save-excursion
10007 (goto-char (point-min))
10008 (if (or (not keep-previous) ; do not want to keep
10009 (not org-occur-highlights)) ; no previous matches
10010 ;; hide everything
10011 (org-overview))
10012 (while (re-search-forward regexp nil t)
10013 (when (or (not callback)
10014 (save-match-data (funcall callback)))
10015 (setq cnt (1+ cnt))
10016 (org-highlight-new-match (match-beginning 0) (match-end 0))
10017 (org-show-context 'occur-tree))))
10018 (when org-remove-highlights-with-change
10019 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10020 nil 'local))
10021 (unless org-sparse-tree-open-archived-trees
10022 (org-hide-archived-subtrees (point-min) (point-max)))
10023 (run-hooks 'org-occur-hook)
10024 (if (interactive-p)
10025 (message "%d match(es) for regexp %s" cnt regexp))
10026 cnt))
10028 (defun org-show-context (&optional key siblings)
10029 "Make sure point and context and visible.
10030 How much context is shown depends upon the variables
10031 `org-show-hierarchy-above' and `org-show-following-heading'.
10032 When SIBLINGS is non-nil, show all siblings on each hierarchy level."
10033 (let ((heading-p (org-on-heading-p t))
10034 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10035 (following-p (org-get-alist-option org-show-following-heading key)))
10036 (catch 'exit
10037 ;; Show heading or entry text
10038 (if heading-p
10039 (org-flag-heading nil) ; only show the heading
10040 (and (or (org-invisible-p) (org-invisible-p2))
10041 (org-show-hidden-entry))) ; show entire entry
10042 (when following-p
10043 ;; Show next sibling, or heading below text
10044 (save-excursion
10045 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10046 (org-flag-heading nil))))
10047 (when hierarchy-p
10048 ;; show all higher headings, possibly with siblings
10049 (save-excursion
10050 (while (and (condition-case nil
10051 (progn (org-up-heading-all 1) t)
10052 (error nil))
10053 (not (bobp)))
10054 (org-flag-heading nil)
10055 (when siblings
10056 (save-excursion
10057 (while (org-goto-sibling) (org-flag-heading nil)))
10058 (save-excursion
10059 (while (org-goto-sibling 'previous)
10060 (org-flag-heading nil))))))))))
10062 (defun org-reveal (&optional siblings)
10063 "Show current entry, hierarchy above it, and the following headline.
10064 This can be used to show a consistent set of context around locations
10065 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10066 not t for the search context.
10068 With optional argument SIBLINGS, on each level of the hierarchy all
10069 siblings are shown. This repairs the tree structure so what it would
10070 look like when opend with successive calls to `org-cycle'."
10071 (interactive "P")
10072 (let ((org-show-hierarchy-above t)
10073 (org-show-following-heading t))
10074 (org-show-context nil siblings)))
10077 (defun org-highlight-new-match (beg end)
10078 "Highlight from BEG to END and mark the highlight is an occur headline."
10079 (let ((ov (org-make-overlay beg end)))
10080 (org-overlay-put ov 'face 'secondary-selection)
10081 (push ov org-occur-highlights)))
10083 (defvar org-inhibit-highlight-removal nil)
10084 (defun org-remove-occur-highlights (&optional beg end noremove)
10085 "Remove the occur highlights from the buffer.
10086 BEG and END are ignored. If NOREMOVE is nil, remove this function
10087 from the `before-change-functions' in the current buffer."
10088 (interactive)
10089 (unless org-inhibit-highlight-removal
10090 (mapc 'org-delete-overlay org-occur-highlights)
10091 (setq org-occur-highlights nil)
10092 (unless noremove
10093 (remove-hook 'before-change-functions
10094 'org-remove-occur-highlights 'local))))
10096 ;;;; Priorities
10098 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
10099 "Regular expression matching the priority indicator.")
10101 (defvar org-remove-priority-next-time nil)
10103 (defun org-priority-up ()
10104 "Increase the priority of the current item."
10105 (interactive)
10106 (org-priority 'up))
10108 (defun org-priority-down ()
10109 "Decrease the priority of the current item."
10110 (interactive)
10111 (org-priority 'down))
10113 (defun org-priority (&optional action)
10114 "Change the priority of an item by ARG.
10115 ACTION can be set, up, or down."
10116 (interactive)
10117 (setq action (or action 'set))
10118 (let (current new news have remove)
10119 (save-excursion
10120 (org-back-to-heading)
10121 (if (looking-at org-priority-regexp)
10122 (setq current (string-to-char (match-string 2))
10123 have t)
10124 (setq current org-default-priority))
10125 (cond
10126 ((eq action 'set)
10127 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
10128 (setq new (read-char-exclusive))
10129 (cond ((equal new ?\ ) (setq remove t))
10130 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
10131 (error "Priority must be between `%c' and `%c'"
10132 ?A org-lowest-priority))))
10133 ((eq action 'up)
10134 (setq new (1- current)))
10135 ((eq action 'down)
10136 (setq new (1+ current)))
10137 (t (error "Invalid action")))
10138 (setq new (min (max ?A (upcase new)) org-lowest-priority))
10139 (setq news (format "%c" new))
10140 (if have
10141 (if remove
10142 (replace-match "" t t nil 1)
10143 (replace-match news t t nil 2))
10144 (if remove
10145 (error "No priority cookie found in line")
10146 (looking-at org-todo-line-regexp)
10147 (if (match-end 2)
10148 (progn
10149 (goto-char (match-end 2))
10150 (insert " [#" news "]"))
10151 (goto-char (match-beginning 3))
10152 (insert "[#" news "] ")))))
10153 (if remove
10154 (message "Priority removed")
10155 (message "Priority of current item set to %s" news))))
10158 (defun org-get-priority (s)
10159 "Find priority cookie and return priority."
10160 (save-match-data
10161 (if (not (string-match org-priority-regexp s))
10162 (* 1000 (- org-lowest-priority org-default-priority))
10163 (* 1000 (- org-lowest-priority
10164 (string-to-char (match-string 2 s)))))))
10166 ;;;; Tags
10168 (defun org-scan-tags (action matcher &optional todo-only)
10169 "Scan headline tags with inheritance and produce output ACTION.
10170 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
10171 evaluated, testing if a given set of tags qualifies a headline for
10172 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
10173 are included in the output."
10174 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
10175 (mapconcat 'regexp-quote
10176 (nreverse (cdr (reverse org-todo-keywords)))
10177 "\\|")
10178 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*$"))
10179 (props (list 'face nil
10180 'done-face 'org-done
10181 'undone-face nil
10182 'mouse-face 'highlight
10183 'org-not-done-regexp org-not-done-regexp
10184 'keymap org-agenda-keymap
10185 'help-echo
10186 (format "mouse-2 or RET jump to org file %s"
10187 (abbreviate-file-name buffer-file-name))))
10188 (case-fold-search nil)
10189 lspos
10190 tags tags-list tags-alist (llast 0) rtn level category i txt
10191 todo marker entry)
10192 (save-excursion
10193 (goto-char (point-min))
10194 (when (eq action 'sparse-tree) (org-overview))
10195 (while (re-search-forward re nil t)
10196 (catch :skip
10197 (and (eq action 'agenda) (org-agenda-skip))
10198 (setq todo (if (match-end 1) (match-string 2))
10199 tags (if (match-end 4) (match-string 4)))
10200 (goto-char (setq lspos (1+ (match-beginning 0))))
10201 (setq level (funcall outline-level)
10202 category (org-get-category))
10203 (setq i llast llast level)
10204 ;; remove tag lists from same and sublevels
10205 (while (>= i level)
10206 (when (setq entry (assoc i tags-alist))
10207 (setq tags-alist (delete entry tags-alist)))
10208 (setq i (1- i)))
10209 ;; add the nex tags
10210 (when tags
10211 (setq tags (mapcar 'downcase (org-split-string tags ":"))
10212 tags-alist
10213 (cons (cons level tags) tags-alist)))
10214 ;; compile tags for current headline
10215 (setq tags-list
10216 (if org-use-tag-inheritance
10217 (apply 'append (mapcar 'cdr tags-alist))
10218 tags))
10219 (when (and (or (not todo-only) todo)
10220 (eval matcher)
10221 (or (not org-agenda-skip-archived-trees)
10222 (not (member org-archive-tag tags-list))))
10223 ;; list this headline
10224 (if (eq action 'sparse-tree)
10225 (progn
10226 (org-show-context 'tags-tree))
10227 (setq txt (org-format-agenda-item
10229 (concat
10230 (if org-tags-match-list-sublevels
10231 (make-string (1- level) ?.) "")
10232 (org-get-heading))
10233 category tags-list))
10234 (goto-char lspos)
10235 (setq marker (org-agenda-new-marker))
10236 (org-add-props txt props
10237 'org-marker marker 'org-hd-marker marker 'category category)
10238 (push txt rtn))
10239 ;; if we are to skip sublevels, jump to end of subtree
10240 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
10241 (when (and (eq action 'sparse-tree)
10242 (not org-sparse-tree-open-archived-trees))
10243 (org-hide-archived-subtrees (point-min) (point-max)))
10244 (nreverse rtn)))
10246 (defvar todo-only) ;; dynamically scoped
10248 (defun org-tags-sparse-tree (&optional todo-only match)
10249 "Create a sparse tree according to tags string MATCH.
10250 MATCH can contain positive and negative selection of tags, like
10251 \"+WORK+URGENT-WITHBOSS\".
10252 If optional argument TODO_ONLY is non-nil, only select lines that are
10253 also TODO lines."
10254 (interactive "P")
10255 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10257 ;; FIXME: implement search for a specific level.
10258 (defun org-make-tags-matcher (match)
10259 "Create the TAGS//TODO matcher form for the selection string MATCH."
10260 ;; todo-only is scoped dynamically into this function, and the function
10261 ;; may change it it the matcher asksk for it.
10262 (unless match
10263 ;; Get a new match request, with completion
10264 (setq org-last-tags-completion-table
10265 (or org-tag-alist
10266 org-last-tags-completion-table))
10267 (setq match (completing-read
10268 "Match: " 'org-tags-completion-function nil nil nil
10269 'org-tags-history))) ; FIXME: Separate history for this?
10271 ;; Parse the string and create a lisp form
10272 (let ((match0 match)
10273 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|[A-Za-z_@0-9]+\\)")
10274 minus tag mm
10275 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10276 orterms term orlist re-p level-p)
10277 (if (string-match "/+" match)
10278 ;; match contains also a todo-matching request
10279 (progn
10280 (setq tagsmatch (substring match 0 (match-beginning 0))
10281 todomatch (substring match (match-end 0)))
10282 (if (string-match "^!" todomatch)
10283 (setq todo-only t todomatch (substring todomatch 1)))
10284 (if (string-match "^\\s-*$" todomatch)
10285 (setq todomatch nil)))
10286 ;; only matching tags
10287 (setq tagsmatch match todomatch nil))
10289 ;; Make the tags matcher
10290 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10291 (setq tagsmatcher t)
10292 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10293 (while (setq term (pop orterms))
10294 (while (and (equal (substring term -1) "\\") orterms)
10295 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10296 (while (string-match re term)
10297 (setq minus (and (match-end 1)
10298 (equal (match-string 1 term) "-"))
10299 tag (match-string 2 term)
10300 re-p (equal (string-to-char tag) ?{)
10301 level-p (match-end 3)
10302 mm (cond
10303 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10304 (level-p `(= level ,(string-to-number
10305 (match-string 3 term))))
10306 (t `(member ,(downcase tag) tags-list)))
10307 mm (if minus (list 'not mm) mm)
10308 term (substring term (match-end 0)))
10309 (push mm tagsmatcher))
10310 (push (if (> (length tagsmatcher) 1)
10311 (cons 'and tagsmatcher)
10312 (car tagsmatcher))
10313 orlist)
10314 (setq tagsmatcher nil))
10315 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
10317 ;; Make the todo matcher
10318 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10319 (setq todomatcher t)
10320 (setq orterms (org-split-string todomatch "|") orlist nil)
10321 (while (setq term (pop orterms))
10322 (while (string-match re term)
10323 (setq minus (and (match-end 1)
10324 (equal (match-string 1 term) "-"))
10325 kwd (match-string 2 term)
10326 re-p (equal (string-to-char kwd) ?{)
10327 term (substring term (match-end 0))
10328 mm (if re-p
10329 `(string-match ,(substring kwd 1 -1) todo)
10330 (list 'equal 'todo kwd))
10331 mm (if minus (list 'not mm) mm))
10332 (push mm todomatcher))
10333 (push (if (> (length todomatcher) 1)
10334 (cons 'and todomatcher)
10335 (car todomatcher))
10336 orlist)
10337 (setq todomatcher nil))
10338 (setq todomatcher (if (> (length orlist) 1)
10339 (cons 'or orlist) (car orlist))))
10341 ;; Return the string and lisp forms of the matcher
10342 (setq matcher (if todomatcher
10343 (list 'and tagsmatcher todomatcher)
10344 tagsmatcher))
10345 (cons match0 matcher)))
10347 (defun org-match-any-p (re list)
10348 "Does re match any element of list?"
10349 (setq list (mapcar (lambda (x) (string-match re x)) list))
10350 (delq nil list))
10352 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
10353 (defvar org-tags-overlay (org-make-overlay 1 1))
10354 (org-detach-overlay org-tags-overlay)
10356 (defun org-set-tags (&optional arg just-align)
10357 "Set the tags for the current headline.
10358 With prefix ARG, realign all tags in headings in the current buffer."
10359 (interactive "P")
10360 (let* ((re (concat "^" outline-regexp))
10361 (current (org-get-tags))
10362 table current-tags inherited-tags ; computed below when needed
10363 tags p0 c0 c1 rpl)
10364 (if arg
10365 (save-excursion
10366 (goto-char (point-min))
10367 (let (buffer-invisibility-spec) ; Emacs 21 compatibility
10368 (while (re-search-forward re nil t)
10369 (org-set-tags nil t)
10370 (end-of-line 1)))
10371 (message "All tags realigned to column %d" org-tags-column))
10372 (if just-align
10373 (setq tags current)
10374 ;; Get a new set of tags from the user
10375 (setq table (or org-tag-alist (org-get-buffer-tags))
10376 org-last-tags-completion-table table
10377 current-tags (org-split-string current ":")
10378 inherited-tags (nreverse
10379 (nthcdr (length current-tags)
10380 (nreverse (org-get-tags-at))))
10381 tags
10382 (if (or (eq t org-use-fast-tag-selection)
10383 (and org-use-fast-tag-selection
10384 (delq nil (mapcar 'cdr table))))
10385 (org-fast-tag-selection current-tags inherited-tags table)
10386 (let ((org-add-colon-after-tag-completion t))
10387 (org-trim
10388 (completing-read "Tags: " 'org-tags-completion-function
10389 nil nil current 'org-tags-history)))))
10390 (while (string-match "[-+&]+" tags)
10391 ;; No boolean logic, just a list
10392 (setq tags (replace-match ":" t t tags))))
10393 (if (string-match "\\`[\t ]*\\'" tags)
10394 (setq tags "")
10395 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10396 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10398 ;; Insert new tags at the correct column
10399 (beginning-of-line 1)
10400 (if (re-search-forward
10401 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10402 (point-at-eol) t)
10403 (progn
10404 (if (equal tags "")
10405 (setq rpl "")
10406 (goto-char (match-beginning 0))
10407 (setq c0 (current-column) p0 (point)
10408 c1 (max (1+ c0) (if (> org-tags-column 0)
10409 org-tags-column
10410 (- (- org-tags-column) (length tags))))
10411 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10412 (replace-match rpl)
10413 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
10414 tags)
10415 (error "Tags alignment failed")))))
10417 (defun org-tags-completion-function (string predicate &optional flag)
10418 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10419 (confirm (lambda (x) (stringp (car x)))))
10420 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10421 (setq s1 (match-string 1 string)
10422 s2 (match-string 2 string))
10423 (setq s1 "" s2 string))
10424 (cond
10425 ((eq flag nil)
10426 ;; try completion
10427 (setq rtn (try-completion s2 ctable confirm))
10428 (if (stringp rtn)
10429 (concat s1 s2 (substring rtn (length s2))
10430 (if (and org-add-colon-after-tag-completion
10431 (assoc rtn ctable))
10432 ":" "")))
10434 ((eq flag t)
10435 ;; all-completions
10436 (all-completions s2 ctable confirm)
10438 ((eq flag 'lambda)
10439 ;; exact match?
10440 (assoc s2 ctable)))
10443 (defun org-fast-tag-insert (kwd tags face &optional end)
10444 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
10445 (insert (format "%-12s" (concat kwd ":"))
10446 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10447 (or end "")))
10449 (defun org-fast-tag-show-exit (flag)
10450 (save-excursion
10451 (goto-line 3)
10452 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10453 (replace-match ""))
10454 (when flag
10455 (end-of-line 1)
10456 (move-to-column (- (window-width) 19) t)
10457 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10459 (defun org-set-current-tags-overlay (current prefix)
10460 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10461 (if (featurep 'xemacs)
10462 (org-overlay-display org-tags-overlay (concat prefix s)
10463 'secondary-selection)
10464 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10465 (org-overlay-display org-tags-overlay (concat prefix s)))))
10467 (defun org-fast-tag-selection (current inherited table)
10468 "Fast tag selection with single keys.
10469 CURRENT is the current list of tags in the headline, INHERITED is the
10470 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10471 possibly with grouping information.
10472 If the keys are nil, a-z are automatically assigned.
10473 Returns the new tags string, or nil to not change the current settings."
10474 (let* ((maxlen (apply 'max (mapcar
10475 (lambda (x)
10476 (if (stringp (car x)) (string-width (car x)) 0))
10477 table)))
10478 (buf (current-buffer))
10479 (buffer-tags nil)
10480 (fwidth (+ maxlen 3 1 3))
10481 (ncol (/ (- (window-width) 4) fwidth))
10482 (i-face 'org-done)
10483 (c-face 'org-tag)
10484 tg cnt e c char c1 c2 ntable tbl rtn
10485 ov-start ov-end ov-prefix
10486 (exit-after-next org-fast-tag-selection-single-key)
10487 groups ingroup)
10488 (save-excursion
10489 (beginning-of-line 1)
10490 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
10491 (setq ov-start (match-beginning 1)
10492 ov-end (match-end 1)
10493 ov-prefix "")
10494 (setq ov-start (1- (point-at-eol))
10495 ov-end (1+ ov-start))
10496 (skip-chars-forward "^\n\r")
10497 (setq ov-prefix
10498 (concat
10499 (buffer-substring (1- (point)) (point))
10500 (if (> (current-column) org-tags-column)
10502 (make-string (- org-tags-column (current-column)) ?\ ))))))
10503 (org-move-overlay org-tags-overlay ov-start ov-end)
10504 (save-window-excursion
10505 ;; FIXME: would it be better to keep the other windows?
10506 (delete-other-windows)
10507 (split-window-vertically)
10508 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
10509 (erase-buffer)
10510 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10511 (org-fast-tag-insert "Current" current c-face "\n\n")
10512 (org-fast-tag-show-exit exit-after-next)
10513 (org-set-current-tags-overlay current ov-prefix)
10514 (setq tbl table char ?a cnt 0)
10515 (while (setq e (pop tbl))
10516 (cond
10517 ((equal e '(:startgroup))
10518 (push '() groups) (setq ingroup t)
10519 (when (not (= cnt 0))
10520 (setq cnt 0)
10521 (insert "\n"))
10522 (insert "{ "))
10523 ((equal e '(:endgroup))
10524 (setq ingroup nil cnt 0)
10525 (insert "}\n"))
10527 (setq tg (car e) c2 nil)
10528 (if (cdr e)
10529 (setq c (cdr e))
10530 ;; automatically assign a character.
10531 (setq c1 (string-to-char
10532 (downcase (substring
10533 tg (if (= (string-to-char tg) ?@) 1 0)))))
10534 (if (or (rassoc c1 ntable) (rassoc c1 table))
10535 (while (or (rassoc char ntable) (rassoc char table))
10536 (setq char (1+ char)))
10537 (setq c2 c1))
10538 (setq c (or c2 char)))
10539 (if ingroup (push tg (car groups)))
10540 (setq tg (org-add-props tg nil 'face
10541 (cond
10542 ((member tg current) c-face)
10543 ((member tg inherited) i-face)
10544 (t nil))))
10545 (if (and (= cnt 0) (not ingroup)) (insert " "))
10546 (insert "[" c "] " tg (make-string
10547 (- fwidth 4 (length tg)) ?\ ))
10548 (push (cons tg c) ntable)
10549 (when (= (setq cnt (1+ cnt)) ncol)
10550 (insert "\n")
10551 (if ingroup (insert " "))
10552 (setq cnt 0)))))
10553 (setq ntable (nreverse ntable))
10554 (insert "\n")
10555 (goto-char (point-min))
10556 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
10557 (setq rtn
10558 (catch 'exit
10559 (while t
10560 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [C-c]: multi%s"
10561 (if groups " [!] no groups" ""))
10562 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10563 (cond
10564 ((= c ?\r) (throw 'exit t))
10565 ((= c ?!)
10566 (setq groups nil)
10567 (goto-char (point-min))
10568 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10569 ((= c ?\C-c)
10570 (org-fast-tag-show-exit
10571 (setq exit-after-next (not exit-after-next))))
10572 ((or (= c ?\C-g)
10573 (and (= c ?q) (not (rassoc c ntable))))
10574 (org-detach-overlay org-tags-overlay)
10575 (setq quit-flag t))
10576 ((= c ?\ )
10577 (setq current nil)
10578 (if exit-after-next (setq exit-after-next 'now)))
10579 ((= c ?\t)
10580 (condition-case nil
10581 (setq tg (completing-read
10582 "Tag: "
10583 (or buffer-tags
10584 (with-current-buffer buf
10585 (org-get-buffer-tags)))))
10586 (quit (setq tg "")))
10587 (when (string-match "\\S-" tg)
10588 (add-to-list 'buffer-tags (list tg))
10589 (if (member tg current)
10590 (setq current (delete tg current))
10591 (push tg current)))
10592 (if exit-after-next (setq exit-after-next 'now)))
10593 ((setq e (rassoc c ntable) tg (car e))
10594 (if (member tg current)
10595 (setq current (delete tg current))
10596 (loop for g in groups do
10597 (if (member tg g)
10598 (mapcar (lambda (x)
10599 (setq current (delete x current)))
10600 g)))
10601 (push tg current))
10602 (if exit-after-next (setq exit-after-next 'now))))
10604 ;; Create a sorted list
10605 (setq current
10606 (sort current
10607 (lambda (a b)
10608 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10609 (if (eq exit-after-next 'now) (throw 'exit t))
10610 (goto-char (point-min))
10611 (beginning-of-line 2)
10612 (delete-region (point) (point-at-eol))
10613 (org-fast-tag-insert "Current" current c-face)
10614 (org-set-current-tags-overlay current ov-prefix)
10615 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
10616 (setq tg (match-string 1))
10617 (add-text-properties (match-beginning 1) (match-end 1)
10618 (list 'face
10619 (cond
10620 ((member tg current) c-face)
10621 ((member tg inherited) i-face)
10622 (t nil)))))
10623 (goto-char (point-min)))))
10624 (org-detach-overlay org-tags-overlay)
10625 (if rtn
10626 (mapconcat 'identity current ":")
10627 nil))))
10629 (defun org-get-tags ()
10630 "Get the TAGS string in the current headline."
10631 (unless (org-on-heading-p t)
10632 (error "Not on a heading"))
10633 (save-excursion
10634 (beginning-of-line 1)
10635 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
10636 (org-match-string-no-properties 1)
10637 "")))
10639 (defun org-get-buffer-tags ()
10640 "Get a table of all tags used in the buffer, for completion."
10641 (let (tags)
10642 (save-excursion
10643 (goto-char (point-min))
10644 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
10645 (mapc (lambda (x) (add-to-list 'tags x))
10646 (org-split-string (org-match-string-no-properties 1) ":"))))
10647 (mapcar 'list tags)))
10649 ;;;; Timestamps
10651 (defvar org-last-changed-timestamp nil)
10652 (defvar org-time-was-given) ; dynamically scoped parameter
10653 (defvar org-ts-what) ; dynamically scoped parameter
10655 (defun org-time-stamp (arg)
10656 "Prompt for a date/time and insert a time stamp.
10657 If the user specifies a time like HH:MM, or if this command is called
10658 with a prefix argument, the time stamp will contain date and time.
10659 Otherwise, only the date will be included. All parts of a date not
10660 specified by the user will be filled in from the current date/time.
10661 So if you press just return without typing anything, the time stamp
10662 will represent the current date/time. If there is already a timestamp
10663 at the cursor, it will be modified."
10664 (interactive "P")
10665 (let (org-time-was-given time)
10666 (cond
10667 ((and (org-at-timestamp-p)
10668 (eq last-command 'org-time-stamp)
10669 (eq this-command 'org-time-stamp))
10670 (insert "--")
10671 (setq time (let ((this-command this-command))
10672 (org-read-date arg 'totime)))
10673 (org-insert-time-stamp time (or org-time-was-given arg)))
10674 ((org-at-timestamp-p)
10675 (setq time (let ((this-command this-command))
10676 (org-read-date arg 'totime)))
10677 (when (org-at-timestamp-p) ; just to get the match data
10678 (replace-match "")
10679 (setq org-last-changed-timestamp
10680 (org-insert-time-stamp time (or org-time-was-given arg))))
10681 (message "Timestamp updated"))
10683 (setq time (let ((this-command this-command))
10684 (org-read-date arg 'totime)))
10685 (org-insert-time-stamp time (or org-time-was-given arg))))))
10687 (defun org-time-stamp-inactive (&optional arg)
10688 "Insert an inactive time stamp.
10689 An inactive time stamp is enclosed in square brackets instead of angle
10690 brackets. It is inactive in the sense that it does not trigger agenda entries,
10691 does not link to the calendar and cannot be changed with the S-cursor keys.
10692 So these are more for recording a certain time/date."
10693 (interactive "P")
10694 (let (org-time-was-given time)
10695 (setq time (org-read-date arg 'totime))
10696 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
10698 (defvar org-date-ovl (org-make-overlay 1 1))
10699 (org-overlay-put org-date-ovl 'face 'org-warning)
10700 (org-detach-overlay org-date-ovl)
10702 (defvar org-ans1) ; dynamically scoped parameter
10703 (defvar org-ans2) ; dynamically scoped parameter
10705 (defun org-read-date (&optional with-time to-time from-string)
10706 "Read a date and make things smooth for the user.
10707 The prompt will suggest to enter an ISO date, but you can also enter anything
10708 which will at least partially be understood by `parse-time-string'.
10709 Unrecognized parts of the date will default to the current day, month, year,
10710 hour and minute. For example,
10711 3-2-5 --> 2003-02-05
10712 feb 15 --> currentyear-02-15
10713 sep 12 9 --> 2009-09-12
10714 12:45 --> today 12:45
10715 22 sept 0:34 --> currentyear-09-22 0:34
10716 12 --> currentyear-currentmonth-12
10717 Fri --> nearest Friday (today or later)
10718 +4 --> four days from today (only if +N is the only thing given)
10719 etc.
10720 The function understands only English month and weekday abbreviations,
10721 but this can be configured with the variables `parse-time-months' and
10722 `parse-time-weekdays'.
10724 While prompting, a calendar is popped up - you can also select the
10725 date with the mouse (button 1). The calendar shows a period of three
10726 months. To scroll it to other months, use the keys `>' and `<'.
10727 If you don't like the calendar, turn it off with
10728 \(setq org-popup-calendar-for-date-prompt nil)
10730 With optional argument TO-TIME, the date will immediately be converted
10731 to an internal time.
10732 With an optional argument WITH-TIME, the prompt will suggest to also
10733 insert a time. Note that when WITH-TIME is not set, you can still
10734 enter a time, and this function will inform the calling routine about
10735 this change. The calling routine may then choose to change the format
10736 used to insert the time stamp into the buffer to include the time."
10737 (require 'parse-time)
10738 (let* ((org-time-stamp-rounding-minutes
10739 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
10740 (ct (org-current-time))
10741 (default-time
10742 ;; Default time is either today, or, when entering a range,
10743 ;; the range start.
10744 (if (save-excursion
10745 (re-search-backward
10746 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10747 (- (point) 20) t))
10748 (apply
10749 'encode-time
10750 (mapcar (lambda(x) (or x 0))
10751 (parse-time-string (match-string 1))))
10752 ct))
10753 (calendar-move-hook nil)
10754 (view-diary-entries-initially nil)
10755 (view-calendar-holidays-initially nil)
10756 (timestr (format-time-string
10757 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
10758 (prompt (format "YYYY-MM-DD [%s]: " timestr))
10759 ans org-ans1 org-ans2 (deltadays 0)
10760 second minute hour day month year tl wday wday1)
10762 (cond
10763 (from-string (setq ans from-string))
10764 (org-popup-calendar-for-date-prompt
10765 (save-excursion
10766 (save-window-excursion
10767 (calendar)
10768 (calendar-forward-day (- (time-to-days default-time)
10769 (calendar-absolute-from-gregorian
10770 (calendar-current-date))))
10771 (org-eval-in-calendar nil)
10772 (let* ((old-map (current-local-map))
10773 (map (copy-keymap calendar-mode-map))
10774 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10775 (define-key map (kbd "RET") 'org-calendar-select)
10776 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
10777 'org-calendar-select-mouse)
10778 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
10779 'org-calendar-select-mouse)
10780 (define-key minibuffer-local-map [(meta shift left)]
10781 (lambda () (interactive)
10782 (org-eval-in-calendar '(calendar-backward-month 1))))
10783 (define-key minibuffer-local-map [(meta shift right)]
10784 (lambda () (interactive)
10785 (org-eval-in-calendar '(calendar-forward-month 1))))
10786 (define-key minibuffer-local-map [(shift up)]
10787 (lambda () (interactive)
10788 (org-eval-in-calendar '(calendar-backward-week 1))))
10789 (define-key minibuffer-local-map [(shift down)]
10790 (lambda () (interactive)
10791 (org-eval-in-calendar '(calendar-forward-week 1))))
10792 (define-key minibuffer-local-map [(shift left)]
10793 (lambda () (interactive)
10794 (org-eval-in-calendar '(calendar-backward-day 1))))
10795 (define-key minibuffer-local-map [(shift right)]
10796 (lambda () (interactive)
10797 (org-eval-in-calendar '(calendar-forward-day 1))))
10798 (define-key minibuffer-local-map ">"
10799 (lambda () (interactive)
10800 (org-eval-in-calendar '(scroll-calendar-left 1))))
10801 (define-key minibuffer-local-map "<"
10802 (lambda () (interactive)
10803 (org-eval-in-calendar '(scroll-calendar-right 1))))
10804 (unwind-protect
10805 (progn
10806 (use-local-map map)
10807 (setq ans (read-string prompt "" nil nil))
10808 (if (not (string-match "\\S-" ans)) (setq ans nil))
10809 (setq ans (or org-ans1 ans org-ans2)))
10810 (use-local-map old-map))))))
10811 (t ; Naked prompt only
10812 (setq ans (read-string prompt "" nil timestr))))
10813 (org-detach-overlay org-date-ovl)
10815 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" ans)
10816 (setq deltadays (string-to-number ans) ans ""))
10818 (if (string-match
10819 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10820 (progn
10821 (setq year (if (match-end 2)
10822 (string-to-number (match-string 2 ans))
10823 (string-to-number (format-time-string "%Y")))
10824 month (string-to-number (match-string 3 ans))
10825 day (string-to-number (match-string 4 ans)))
10826 (if (< year 100) (setq year (+ 2000 year)))
10827 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10828 t nil ans))))
10829 (setq tl (parse-time-string ans)
10830 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
10831 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
10832 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
10833 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
10834 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
10835 second (or (nth 0 tl) 0)
10836 wday (nth 6 tl))
10837 (setq day (+ day deltadays))
10838 (when (and wday (not (nth 3 tl)))
10839 ;; Weekday was given, but no day, so pick that day in the week
10840 ;; on or after the derived date.
10841 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10842 (unless (equal wday wday1)
10843 (setq day (+ day (% (- wday wday1 -7) 7)))))
10844 (if (and (boundp 'org-time-was-given)
10845 (nth 2 tl))
10846 (setq org-time-was-given t))
10847 (if (< year 100) (setq year (+ 2000 year)))
10848 (if to-time
10849 (encode-time second minute hour day month year)
10850 (if (or (nth 1 tl) (nth 2 tl))
10851 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
10852 (format "%04d-%02d-%02d" year month day)))))
10854 (defun org-eval-in-calendar (form)
10855 "Eval FORM in the calendar window and return to current window.
10856 Also, store the cursor date in variable org-ans2."
10857 (let ((sw (selected-window)))
10858 (select-window (get-buffer-window "*Calendar*"))
10859 (eval form)
10860 (when (calendar-cursor-to-date)
10861 (let* ((date (calendar-cursor-to-date))
10862 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10863 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10864 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10865 (select-window sw)))
10867 (defun org-calendar-select ()
10868 "Return to `org-read-date' with the date currently selected.
10869 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10870 (interactive)
10871 (when (calendar-cursor-to-date)
10872 (let* ((date (calendar-cursor-to-date))
10873 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10874 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10875 (if (active-minibuffer-window) (exit-minibuffer))))
10877 (defun org-insert-time-stamp (time &optional with-hm inactive pre post)
10878 "Insert a date stamp for the date given by the internal TIME.
10879 WITH-HM means, use the stamp format that includes the time of the day.
10880 INACTIVE means use square brackets instead of angular ones, so that the
10881 stamp will not contribute to the agenda.
10882 PRE and POST are optional strings to be inserted before and after the
10883 stamp.
10884 The command returns the inserted time stamp."
10885 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10886 stamp)
10887 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10888 (insert (or pre ""))
10889 (insert (setq stamp (format-time-string fmt time)))
10890 (insert (or post ""))
10891 stamp))
10893 (defun org-toggle-time-stamp-overlays ()
10894 "Toggle the use of custom time stamp formats."
10895 (interactive)
10896 (setq org-display-custom-times (not org-display-custom-times))
10897 (unless org-display-custom-times
10898 (let ((p (point-min)) (bmp (buffer-modified-p)))
10899 (while (setq p (next-single-property-change p 'display))
10900 (if (and (get-text-property p 'display)
10901 (eq (get-text-property p 'face) 'org-date))
10902 (remove-text-properties
10903 p (setq p (next-single-property-change p 'display))
10904 '(display t))))
10905 (set-buffer-modified-p bmp)))
10906 (if (featurep 'xemacs)
10907 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10908 (org-restart-font-lock)
10909 (setq org-table-may-need-update t)
10910 (if org-display-custom-times
10911 (message "Time stamps are overlayed with custom format")
10912 (message "Time stamp overlays removed")))
10914 (defun org-display-custom-time (beg end)
10915 "Overlay modified time stamp format over timestamp between BED and END."
10916 (let* ((t1 (save-match-data
10917 (org-parse-time-string (buffer-substring beg end) t)))
10918 (w1 (- end beg))
10919 (with-hm (and (nth 1 t1) (nth 2 t1)))
10920 (inactive (= (char-before (1- beg)) ?\[))
10921 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
10922 (time (org-fix-decoded-time t1))
10923 (str (org-add-props
10924 (format-time-string
10925 (substring tf 1 -1) (apply 'encode-time time))
10926 nil 'mouse-face 'highlight))
10927 (w2 (length str)))
10928 (if (not (= w2 w1))
10929 (add-text-properties (1+ beg) (+ 2 beg)
10930 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10931 (if (featurep 'xemacs)
10932 (progn
10933 (put-text-property beg end 'invisible t)
10934 (put-text-property beg end 'end-glyph (make-glyph str)))
10935 (put-text-property beg end 'display str))))
10937 (defun org-translate-time (string)
10938 "Translate all timestamps in STRING to custom format.
10939 But do this only if the variable `org-display-custom-times' is set."
10940 (when org-display-custom-times
10941 (save-match-data
10942 (let* ((start 0)
10943 (re org-ts-regexp-both)
10944 t1 with-hm inactive tf time str beg end)
10945 (while (setq start (string-match re string start))
10946 (setq beg (match-beginning 0)
10947 end (match-end 0)
10948 t1 (save-match-data
10949 (org-parse-time-string (substring string beg end) t))
10950 with-hm (and (nth 1 t1) (nth 2 t1))
10951 inactive (equal (substring string beg (1+ beg)) "[")
10952 tf (funcall (if with-hm 'cdr 'car)
10953 org-time-stamp-custom-formats)
10954 time (org-fix-decoded-time t1)
10955 str (format-time-string
10956 (concat
10957 (if inactive "[" "<") (substring tf 1 -1)
10958 (if inactive "]" ">"))
10959 (apply 'encode-time time))
10960 string (replace-match str t t string)
10961 start (+ start (length str)))))))
10962 string)
10964 (defun org-fix-decoded-time (time)
10965 "Set 0 instead of nil for the first 6 elements of time.
10966 Don't touch the rest."
10967 (let ((n 0))
10968 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10970 (defun org-days-to-time (timestamp-string)
10971 "Difference between TIMESTAMP-STRING and now in days."
10972 (- (time-to-days (org-time-string-to-time timestamp-string))
10973 (time-to-days (current-time))))
10975 (defun org-deadline-close (timestamp-string &optional ndays)
10976 "Is the time in TIMESTAMP-STRING close to the current date?"
10977 (and (< (org-days-to-time timestamp-string)
10978 (or ndays org-deadline-warning-days))
10979 (not (org-entry-is-done-p))))
10981 (defun org-calendar-select-mouse (ev)
10982 "Return to `org-read-date' with the date currently selected.
10983 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10984 (interactive "e")
10985 (mouse-set-point ev)
10986 (when (calendar-cursor-to-date)
10987 (let* ((date (calendar-cursor-to-date))
10988 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10989 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10990 (if (active-minibuffer-window) (exit-minibuffer))))
10992 (defun org-check-deadlines (ndays)
10993 "Check if there are any deadlines due or past due.
10994 A deadline is considered due if it happens within `org-deadline-warning-days'
10995 days from today's date. If the deadline appears in an entry marked DONE,
10996 it is not shown. The prefix arg NDAYS can be used to test that many
10997 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10998 (interactive "P")
10999 (let* ((org-warn-days
11000 (cond
11001 ((equal ndays '(4)) 100000)
11002 (ndays (prefix-numeric-value ndays))
11003 (t org-deadline-warning-days)))
11004 (case-fold-search nil)
11005 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11006 (callback
11007 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11009 (message "%d deadlines past-due or due within %d days"
11010 (org-occur regexp nil callback)
11011 org-warn-days)))
11013 (defun org-evaluate-time-range (&optional to-buffer)
11014 "Evaluate a time range by computing the difference between start and end.
11015 Normally the result is just printed in the echo area, but with prefix arg
11016 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11017 If the time range is actually in a table, the result is inserted into the
11018 next column.
11019 For time difference computation, a year is assumed to be exactly 365
11020 days in order to avoid rounding problems."
11021 (interactive "P")
11023 (org-clock-update-time-maybe)
11024 (save-excursion
11025 (unless (org-at-date-range-p)
11026 (goto-char (point-at-bol))
11027 (re-search-forward org-tr-regexp (point-at-eol) t))
11028 (if (not (org-at-date-range-p))
11029 (error "Not at a time-stamp range, and none found in current line")))
11030 (let* ((ts1 (match-string 1))
11031 (ts2 (match-string 2))
11032 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11033 (match-end (match-end 0))
11034 (time1 (org-time-string-to-time ts1))
11035 (time2 (org-time-string-to-time ts2))
11036 (t1 (time-to-seconds time1))
11037 (t2 (time-to-seconds time2))
11038 (diff (abs (- t2 t1)))
11039 (negative (< (- t2 t1) 0))
11040 ;; (ys (floor (* 365 24 60 60)))
11041 (ds (* 24 60 60))
11042 (hs (* 60 60))
11043 (fy "%dy %dd %02d:%02d")
11044 (fy1 "%dy %dd")
11045 (fd "%dd %02d:%02d")
11046 (fd1 "%dd")
11047 (fh "%02d:%02d")
11048 y d h m align)
11049 (if havetime
11050 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11052 d (floor (/ diff ds)) diff (mod diff ds)
11053 h (floor (/ diff hs)) diff (mod diff hs)
11054 m (floor (/ diff 60)))
11055 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11057 d (floor (+ (/ diff ds) 0.5))
11058 h 0 m 0))
11059 (if (not to-buffer)
11060 (message (org-make-tdiff-string y d h m))
11061 (when (org-at-table-p)
11062 (goto-char match-end)
11063 (setq align t)
11064 (and (looking-at " *|") (goto-char (match-end 0))))
11065 (if (looking-at
11066 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11067 (replace-match ""))
11068 (if negative (insert " -"))
11069 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11070 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11071 (insert " " (format fh h m))))
11072 (if align (org-table-align))
11073 (message "Time difference inserted")))))
11075 (defun org-make-tdiff-string (y d h m)
11076 (let ((fmt "")
11077 (l nil))
11078 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11079 l (push y l)))
11080 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11081 l (push d l)))
11082 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11083 l (push h l)))
11084 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11085 l (push m l)))
11086 (apply 'format fmt (nreverse l))))
11088 (defun org-time-string-to-time (s)
11089 (apply 'encode-time (org-parse-time-string s)))
11091 (defun org-parse-time-string (s &optional nodefault)
11092 "Parse the standard Org-mode time string.
11093 This should be a lot faster than the normal `parse-time-string'.
11094 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11095 hour and minute fields will be nil if not given."
11096 (if (string-match org-ts-regexp1 s)
11097 (list 0
11098 (if (or (match-beginning 8) (not nodefault))
11099 (string-to-number (or (match-string 8 s) "0")))
11100 (if (or (match-beginning 7) (not nodefault))
11101 (string-to-number (or (match-string 7 s) "0")))
11102 (string-to-number (match-string 4 s))
11103 (string-to-number (match-string 3 s))
11104 (string-to-number (match-string 2 s))
11105 nil nil nil)
11106 (make-list 9 0)))
11108 (defun org-timestamp-up (&optional arg)
11109 "Increase the date item at the cursor by one.
11110 If the cursor is on the year, change the year. If it is on the month or
11111 the day, change that.
11112 With prefix ARG, change by that many units."
11113 (interactive "p")
11114 (org-timestamp-change (prefix-numeric-value arg)))
11116 (defun org-timestamp-down (&optional arg)
11117 "Decrease the date item at the cursor by one.
11118 If the cursor is on the year, change the year. If it is on the month or
11119 the day, change that.
11120 With prefix ARG, change by that many units."
11121 (interactive "p")
11122 (org-timestamp-change (- (prefix-numeric-value arg))))
11124 (defun org-timestamp-up-day (&optional arg)
11125 "Increase the date in the time stamp by one day.
11126 With prefix ARG, change that many days."
11127 (interactive "p")
11128 (if (and (not (org-at-timestamp-p t))
11129 (org-on-heading-p))
11130 (org-todo 'up)
11131 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11133 (defun org-timestamp-down-day (&optional arg)
11134 "Decrease the date in the time stamp by one day.
11135 With prefix ARG, change that many days."
11136 (interactive "p")
11137 (if (and (not (org-at-timestamp-p t))
11138 (org-on-heading-p))
11139 (org-todo 'down)
11140 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11142 (defsubst org-pos-in-match-range (pos n)
11143 (and (match-beginning n)
11144 (<= (match-beginning n) pos)
11145 (>= (match-end n) pos)))
11147 (defun org-at-timestamp-p (&optional inactive-ok)
11148 "Determine if the cursor is in or at a timestamp."
11149 (interactive)
11150 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11151 (pos (point))
11152 (ans (or (looking-at tsr)
11153 (save-excursion
11154 (skip-chars-backward "^[<\n\r\t")
11155 (if (> (point) 1) (backward-char 1))
11156 (and (looking-at tsr)
11157 (> (- (match-end 0) pos) -1))))))
11158 (and (boundp 'org-ts-what)
11159 (setq org-ts-what
11160 (cond
11161 ((org-pos-in-match-range pos 2) 'year)
11162 ((org-pos-in-match-range pos 3) 'month)
11163 ((org-pos-in-match-range pos 7) 'hour)
11164 ((org-pos-in-match-range pos 8) 'minute)
11165 ((or (org-pos-in-match-range pos 4)
11166 (org-pos-in-match-range pos 5)) 'day)
11167 (t 'day))))
11168 ans))
11170 (defun org-timestamp-change (n &optional what)
11171 "Change the date in the time stamp at point.
11172 The date will be changed by N times WHAT. WHAT can be `day', `month',
11173 `year', `minute', `second'. If WHAT is not given, the cursor position
11174 in the timestamp determines what will be changed."
11175 (let ((pos (point))
11176 with-hm inactive
11177 org-ts-what
11178 ts time time0)
11179 (if (not (org-at-timestamp-p t))
11180 (error "Not at a timestamp"))
11181 (if (and (not what) (not (eq org-ts-what 'day))
11182 org-display-custom-times
11183 (get-text-property (point) 'display)
11184 (not (get-text-property (1- (point)) 'display)))
11185 (setq org-ts-what 'day))
11186 (setq org-ts-what (or what org-ts-what)
11187 with-hm (<= (abs (- (cdr org-ts-lengths)
11188 (- (match-end 0) (match-beginning 0))))
11190 inactive (= (char-after (match-beginning 0)) ?\[)
11191 ts (match-string 0))
11192 (replace-match "")
11193 (setq time0 (org-parse-time-string ts))
11194 (setq time
11195 (apply 'encode-time
11196 (append
11197 (list (or (car time0) 0))
11198 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
11199 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
11200 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
11201 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
11202 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
11203 (nthcdr 6 time0))))
11204 (if (eq what 'calendar)
11205 (let ((cal-date
11206 (save-excursion
11207 (save-match-data
11208 (set-buffer "*Calendar*")
11209 (calendar-cursor-to-date)))))
11210 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11211 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11212 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11213 (setcar time0 (or (car time0) 0))
11214 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11215 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
11216 (setq time (apply 'encode-time time0))))
11217 (setq org-last-changed-timestamp
11218 (org-insert-time-stamp time with-hm inactive))
11219 (org-clock-update-time-maybe)
11220 (goto-char pos)
11221 ;; Try to recenter the calendar window, if any
11222 (if (and org-calendar-follow-timestamp-change
11223 (get-buffer-window "*Calendar*" t)
11224 (memq org-ts-what '(day month year)))
11225 (org-recenter-calendar (time-to-days time)))))
11227 (defun org-recenter-calendar (date)
11228 "If the calendar is visible, recenter it to DATE."
11229 (let* ((win (selected-window))
11230 (cwin (get-buffer-window "*Calendar*" t))
11231 (calendar-move-hook nil))
11232 (when cwin
11233 (select-window cwin)
11234 (calendar-goto-date (if (listp date) date
11235 (calendar-gregorian-from-absolute date)))
11236 (select-window win))))
11238 (defun org-goto-calendar (&optional arg)
11239 "Go to the Emacs calendar at the current date.
11240 If there is a time stamp in the current line, go to that date.
11241 A prefix ARG can be used to force the current date."
11242 (interactive "P")
11243 (let ((tsr org-ts-regexp) diff
11244 (calendar-move-hook nil)
11245 (view-calendar-holidays-initially nil)
11246 (view-diary-entries-initially nil))
11247 (if (or (org-at-timestamp-p)
11248 (save-excursion
11249 (beginning-of-line 1)
11250 (looking-at (concat ".*" tsr))))
11251 (let ((d1 (time-to-days (current-time)))
11252 (d2 (time-to-days
11253 (org-time-string-to-time (match-string 1)))))
11254 (setq diff (- d2 d1))))
11255 (calendar)
11256 (calendar-goto-today)
11257 (if (and diff (not arg)) (calendar-forward-day diff))))
11259 (defun org-date-from-calendar ()
11260 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11261 If there is already a time stamp at the cursor position, update it."
11262 (interactive)
11263 (org-timestamp-change 0 'calendar))
11265 ;;; The clock for measuring work time.
11267 (defvar org-clock-marker (make-marker)
11268 "Marker recording the last clock-in.")
11270 (defun org-clock-in ()
11271 "Start the clock on the current item.
11272 If necessary, clock-out of the currently active clock."
11273 (interactive)
11274 (org-clock-out t)
11275 (let (ts)
11276 (save-excursion
11277 (org-back-to-heading t)
11278 (beginning-of-line 2)
11279 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
11280 (not (equal (match-string 1) org-clock-string)))
11281 (beginning-of-line 1))
11282 (insert "\n") (backward-char 1)
11283 (indent-relative)
11284 (insert org-clock-string " ")
11285 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
11286 (move-marker org-clock-marker (point) (buffer-base-buffer))
11287 (message "Clock started at %s" ts))))
11289 (defun org-clock-out (&optional fail-quietly)
11290 "Stop the currently running clock.
11291 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
11292 (interactive)
11293 (catch 'exit
11294 (if (not (marker-buffer org-clock-marker))
11295 (if fail-quietly (throw 'exit t) (error "No active clock")))
11296 (let (ts te s h m)
11297 (save-excursion
11298 (set-buffer (marker-buffer org-clock-marker))
11299 (goto-char org-clock-marker)
11300 (beginning-of-line 1)
11301 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
11302 (equal (match-string 1) org-clock-string))
11303 (setq ts (match-string 2))
11304 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
11305 (goto-char org-clock-marker)
11306 (insert "--")
11307 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
11308 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
11309 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
11310 h (floor (/ s 3600))
11311 s (- s (* 3600 h))
11312 m (floor (/ s 60))
11313 s (- s (* 60 s)))
11314 (insert " => " (format "%2d:%02d" h m))
11315 (move-marker org-clock-marker nil)
11316 (org-add-log-maybe 'clock-out)
11317 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
11319 (defun org-clock-cancel ()
11320 "Cancel the running clock be removing the start timestamp."
11321 (interactive)
11322 (if (not (marker-buffer org-clock-marker))
11323 (error "No active clock"))
11324 (save-excursion
11325 (set-buffer (marker-buffer org-clock-marker))
11326 (goto-char org-clock-marker)
11327 (delete-region (1- (point-at-bol)) (point-at-eol)))
11328 (message "Clock canceled"))
11330 (defvar org-clock-file-total-minutes nil
11331 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
11332 (make-variable-buffer-local 'org-clock-file-total-minutes)
11334 (defun org-clock-sum (&optional tstart tend)
11335 "Sum the times for each subtree.
11336 Puts the resulting times in minutes as a text property on each headline."
11337 (interactive)
11338 (let* ((bmp (buffer-modified-p))
11339 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
11340 org-clock-string
11341 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
11342 (lmax 30)
11343 (ltimes (make-vector lmax 0))
11344 (t1 0)
11345 (level 0)
11346 ts te dt
11347 time)
11348 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
11349 (save-excursion
11350 (goto-char (point-max))
11351 (while (re-search-backward re nil t)
11352 (if (match-end 2)
11353 ;; A time
11354 (setq ts (match-string 2)
11355 te (match-string 3)
11356 ts (time-to-seconds
11357 (apply 'encode-time (org-parse-time-string ts)))
11358 te (time-to-seconds
11359 (apply 'encode-time (org-parse-time-string te)))
11360 ts (if tstart (max ts tstart) ts)
11361 te (if tend (min te tend) te)
11362 dt (- te ts)
11363 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
11364 ;; A headline
11365 (setq level (- (match-end 1) (match-beginning 1)))
11366 (when (or (> t1 0) (> (aref ltimes level) 0))
11367 (loop for l from 0 to level do
11368 (aset ltimes l (+ (aref ltimes l) t1)))
11369 (setq t1 0 time (aref ltimes level))
11370 (loop for l from level to (1- lmax) do
11371 (aset ltimes l 0))
11372 (goto-char (match-beginning 0))
11373 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
11374 (setq org-clock-file-total-minutes (aref ltimes 0)))
11375 (set-buffer-modified-p bmp)))
11377 (defun org-clock-display (&optional total-only)
11378 "Show subtree times in the entire buffer.
11379 If TOTAL-ONLY is non-nil, only show the total time for the entire file
11380 in the echo area."
11381 (interactive)
11382 (org-remove-clock-overlays)
11383 (let (time h m p)
11384 (org-clock-sum)
11385 (unless total-only
11386 (save-excursion
11387 (goto-char (point-min))
11388 (while (setq p (next-single-property-change (point) :org-clock-minutes))
11389 (goto-char p)
11390 (when (setq time (get-text-property p :org-clock-minutes))
11391 (org-put-clock-overlay time (funcall outline-level))))
11392 (setq h (/ org-clock-file-total-minutes 60)
11393 m (- org-clock-file-total-minutes (* 60 h)))
11394 ;; Arrange to remove the overlays upon next change.
11395 (when org-remove-highlights-with-change
11396 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
11397 nil 'local))))
11398 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
11400 (defvar org-clock-overlays nil)
11401 (make-variable-buffer-local 'org-clock-overlays)
11403 (defun org-put-clock-overlay (time &optional level)
11404 "Put an overlays on the current line, displaying TIME.
11405 If LEVEL is given, prefix time with a corresponding number of stars.
11406 This creates a new overlay and stores it in `org-clock-overlays', so that it
11407 will be easy to remove."
11408 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
11409 (l (if level (org-get-legal-level level 0) 0))
11410 (off 0)
11411 ov tx)
11412 (move-to-column c)
11413 (unless (eolp) (skip-chars-backward "^ \t"))
11414 (skip-chars-backward " \t")
11415 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
11416 tx (concat (buffer-substring (1- (point)) (point))
11417 (make-string (+ off (max 0 (- c (current-column)))) ?.)
11418 (org-add-props (format "%s %2d:%02d%s"
11419 (make-string l ?*) h m
11420 (make-string (- 10 l) ?\ ))
11421 '(face secondary-selection))
11422 ""))
11423 (if (not (featurep 'xemacs))
11424 (org-overlay-put ov 'display tx)
11425 (org-overlay-put ov 'invisible t)
11426 (org-overlay-put ov 'end-glyph (make-glyph tx)))
11427 (push ov org-clock-overlays)))
11429 (defun org-remove-clock-overlays (&optional beg end noremove)
11430 "Remove the occur highlights from the buffer.
11431 BEG and END are ignored. If NOREMOVE is nil, remove this function
11432 from the `before-change-functions' in the current buffer."
11433 (interactive)
11434 (unless org-inhibit-highlight-removal
11435 (mapc 'org-delete-overlay org-clock-overlays)
11436 (setq org-clock-overlays nil)
11437 (unless noremove
11438 (remove-hook 'before-change-functions
11439 'org-remove-clock-overlays 'local))))
11441 (defun org-clock-out-if-current ()
11442 "Clock out if the current entry contains the running clock.
11443 This is used to stop the clock after a TODO entry is marked DONE."
11444 (when (and (equal state org-done-string)
11445 (equal (marker-buffer org-clock-marker) (current-buffer))
11446 (< (point) org-clock-marker)
11447 (> (save-excursion (outline-next-heading) (point))
11448 org-clock-marker))
11449 ;; Clock out, but don't accept a logging message for this.
11450 (let ((org-log-done (if (and (listp org-log-done)
11451 (member 'clock-out org-log-done))
11452 '(done)
11453 org-log-done)))
11454 (org-clock-out))))
11456 (add-hook 'org-after-todo-state-change-hook
11457 'org-clock-out-if-current)
11459 (defun org-check-running-clock ()
11460 "Check if the current buffer contains the running clock.
11461 If yes, offer to stop it and to save the buffer with the changes."
11462 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
11463 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
11464 (buffer-name))))
11465 (org-clock-out)
11466 (when (y-or-n-p "Save changed buffer?")
11467 (save-buffer))))
11469 (defun org-clock-report ()
11470 "Create a table containing a report about clocked time.
11471 If the buffer contains lines
11472 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
11474 #+END: clocktable
11475 then the table will be inserted between these lines, replacing whatever
11476 is was there before. If these lines are not in the buffer, the table
11477 is inserted at point, surrounded by the special lines.
11478 The BEGIN line can contain parameters. Allowed are:
11479 :maxlevel The maximum level to be included in the table. Default is 3.
11480 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
11481 (interactive)
11482 (org-remove-clock-overlays)
11483 (unless (org-find-dblock "clocktable")
11484 (org-create-dblock (list :name "clocktable"
11485 :maxlevel 2 :emphasize nil)))
11486 (org-update-dblock))
11488 (defun org-clock-update-time-maybe ()
11489 "If this is a CLOCK line, update it and return t.
11490 Otherwise, return nil."
11491 (interactive)
11492 (save-excursion
11493 (beginning-of-line 1)
11494 (skip-chars-forward " \t")
11495 (when (looking-at org-clock-string)
11496 (let ((re (concat "[ \t]*" org-clock-string
11497 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
11498 "\\([ \t]*=>.*\\)?"))
11499 ts te h m s)
11500 (if (not (looking-at re))
11502 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
11503 (end-of-line 1)
11504 (setq ts (match-string 1)
11505 te (match-string 2))
11506 (setq s (- (time-to-seconds
11507 (apply 'encode-time (org-parse-time-string te)))
11508 (time-to-seconds
11509 (apply 'encode-time (org-parse-time-string ts))))
11510 h (floor (/ s 3600))
11511 s (- s (* 3600 h))
11512 m (floor (/ s 60))
11513 s (- s (* 60 s)))
11514 (insert " => " (format "%2d:%02d" h m))
11515 t)))))
11517 (defun org-clock-special-range (key &optional time as-strings)
11518 "Return two times bordering a special time range.
11519 Key is a symbol specifying the range and can be one of `today', `yesterday',
11520 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
11521 A week starts Monday 0:00 and ends Sunday 24:00.
11522 The range is determined relative to TIME. TIME defaults to the current time.
11523 The return value is a cons cell with two internal times like the ones
11524 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
11525 the returned times will be formatted strings."
11526 (let* ((tm (decode-time (or time (current-time))))
11527 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
11528 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
11529 (dow (nth 6 tm))
11530 s1 m1 h1 d1 month1 y1 diff ts te fm)
11531 (cond
11532 ((eq key 'today)
11533 (setq h 0 m 0 h1 24 m1 0))
11534 ((eq key 'yesterday)
11535 (setq d (1- d) h 0 m 0 h1 24 m1 0))
11536 ((eq key 'thisweek)
11537 (setq diff (if (= dow 0) 6 (1- dow))
11538 m 0 h 0 d (- d diff) d1 (+ 7 d)))
11539 ((eq key 'lastweek)
11540 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
11541 m 0 h 0 d (- d diff) d1 (+ 7 d)))
11542 ((eq key 'thismonth)
11543 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
11544 ((eq key 'lastmonth)
11545 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
11546 ((eq key 'thisyear)
11547 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
11548 ((eq key 'lastyear)
11549 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
11550 (t (error "No such time block %s" key)))
11551 (setq ts (encode-time s m h d month y)
11552 te (encode-time (or s1 s) (or m1 m) (or h1 h)
11553 (or d1 d) (or month1 month) (or y1 y)))
11554 (setq fm (cdr org-time-stamp-formats))
11555 (if as-strings
11556 (cons (format-time-string fm ts) (format-time-string fm te))
11557 (cons ts te))))
11559 (defun org-dblock-write:clocktable (params)
11560 "Write the standard clocktable."
11561 (let ((hlchars '((1 . "*") (2 . ?/)))
11562 (emph nil)
11563 (ins (make-marker))
11564 ipos time h m p level hlc hdl maxlevel
11565 ts te cc block)
11566 (setq maxlevel (or (plist-get params :maxlevel) 3)
11567 emph (plist-get params :emphasize)
11568 ts (plist-get params :tstart)
11569 te (plist-get params :tend)
11570 block (plist-get params :block))
11571 (when block
11572 (setq cc (org-clock-special-range block nil t)
11573 ts (car cc) te (cdr cc)))
11574 (if ts (setq ts (time-to-seconds
11575 (apply 'encode-time (org-parse-time-string ts)))))
11576 (if te (setq te (time-to-seconds
11577 (apply 'encode-time (org-parse-time-string te)))))
11578 (move-marker ins (point))
11579 (setq ipos (point))
11580 ;; FIXME: does not yet use org-insert-time-stamp
11581 (insert-before-markers "Clock summary at ["
11582 (substring
11583 (format-time-string (cdr org-time-stamp-formats))
11584 1 -1)
11585 "]."
11586 (if block
11587 (format " Considered range is /%s/." block)
11589 "\n\n|L|Headline|Time|\n")
11590 (org-clock-sum ts te)
11591 (setq h (/ org-clock-file-total-minutes 60)
11592 m (- org-clock-file-total-minutes (* 60 h)))
11593 (insert-before-markers "|-\n|0|" "*Total file time*| "
11594 (format "*%d:%02d*" h m)
11595 "|\n")
11596 (goto-char (point-min))
11597 (while (setq p (next-single-property-change (point) :org-clock-minutes))
11598 (goto-char p)
11599 (when (setq time (get-text-property p :org-clock-minutes))
11600 (save-excursion
11601 (beginning-of-line 1)
11602 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
11603 (setq level (- (match-end 1) (match-beginning 1)))
11604 (<= level maxlevel))
11605 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
11606 hdl (match-string 2)
11607 h (/ time 60)
11608 m (- time (* 60 h)))
11609 (goto-char ins)
11610 (if (= level 1) (insert-before-markers "|-\n"))
11611 (insert-before-markers
11612 "| " (int-to-string level) "|" hlc hdl hlc " |"
11613 (make-string (1- level) ?|)
11615 (format "%d:%02d" h m)
11617 " |\n")))))
11618 (goto-char ins)
11619 (backward-delete-char 1)
11620 (goto-char ipos)
11621 (skip-chars-forward "^|")
11622 (org-table-align)))
11624 (defun org-collect-clock-time-entries ()
11625 "Return an internal list with clocking information.
11626 This list has one entry for each CLOCK interval.
11627 FIXME: describe the elements."
11628 (interactive)
11629 (let ((re (concat "^[ \t]*" org-clock-string
11630 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
11631 rtn beg end next cont level title total closedp leafp
11632 clockpos titlepos h m donep)
11633 (save-excursion
11634 (org-clock-sum)
11635 (goto-char (point-min))
11636 (while (re-search-forward re nil t)
11637 (setq clockpos (match-beginning 0)
11638 beg (match-string 1) end (match-string 2)
11639 cont (match-end 0))
11640 (setq beg (apply 'encode-time (org-parse-time-string beg))
11641 end (apply 'encode-time (org-parse-time-string end)))
11642 (org-back-to-heading t)
11643 (setq donep (org-entry-is-done-p))
11644 (setq titlepos (point)
11645 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
11646 h (/ total 60) m (- total (* 60 h))
11647 total (cons h m))
11648 (looking-at "\\(\\*+\\) +\\(.*\\)")
11649 (setq level (- (match-end 1) (match-beginning 1))
11650 title (org-match-string-no-properties 2))
11651 (save-excursion (outline-next-heading) (setq next (point)))
11652 (setq closedp (re-search-forward org-closed-time-regexp next t))
11653 (goto-char next)
11654 (setq leafp (and (looking-at "^\\*+ ")
11655 (<= (- (match-end 0) (point)) level)))
11656 (push (list beg end clockpos closedp donep
11657 total title titlepos level leafp)
11658 rtn)
11659 (goto-char cont)))
11660 (nreverse rtn)))
11662 ;;;; Agenda, and Diary Integration
11664 ;;; Define the Org-agenda-mode
11666 (defvar org-agenda-mode-map (make-sparse-keymap)
11667 "Keymap for `org-agenda-mode'.")
11669 (defvar org-agenda-menu) ; defined later in this file.
11670 (defvar org-agenda-follow-mode nil)
11671 (defvar org-agenda-show-log nil)
11672 (defvar org-agenda-redo-command nil)
11673 (defvar org-agenda-mode-hook nil)
11674 (defvar org-agenda-type nil)
11675 (defvar org-agenda-force-single-file nil)
11677 (defun org-agenda-mode ()
11678 "Mode for time-sorted view on action items in Org-mode files.
11680 The following commands are available:
11682 \\{org-agenda-mode-map}"
11683 (interactive)
11684 (kill-all-local-variables)
11685 (setq org-agenda-undo-list nil
11686 org-agenda-pending-undo-list nil)
11687 (setq major-mode 'org-agenda-mode)
11688 (setq mode-name "Org-Agenda")
11689 (use-local-map org-agenda-mode-map)
11690 (easy-menu-add org-agenda-menu)
11691 (if org-startup-truncated (setq truncate-lines t))
11692 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
11693 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
11694 (unless org-agenda-keep-modes
11695 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
11696 org-agenda-show-log nil))
11697 (easy-menu-change
11698 '("Agenda") "Agenda Files"
11699 (append
11700 (list
11701 (vector
11702 (if (get 'org-agenda-files 'org-restrict)
11703 "Restricted to single file"
11704 "Edit File List")
11705 '(org-edit-agenda-file-list)
11706 (not (get 'org-agenda-files 'org-restrict)))
11707 "--")
11708 (mapcar 'org-file-menu-entry (org-agenda-files))))
11709 (org-agenda-set-mode-name)
11710 (apply
11711 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
11712 (list 'org-agenda-mode-hook)))
11714 (substitute-key-definition 'undo 'org-agenda-undo
11715 org-agenda-mode-map global-map)
11716 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
11717 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
11718 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
11719 (define-key org-agenda-mode-map "\C-k" 'org-agenda-kill)
11720 (define-key org-agenda-mode-map "\C-c$" 'org-agenda-archive)
11721 (define-key org-agenda-mode-map "$" 'org-agenda-archive)
11722 (define-key org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
11723 (define-key org-agenda-mode-map " " 'org-agenda-show)
11724 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
11725 (define-key org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
11726 (define-key org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
11727 (define-key org-agenda-mode-map "o" 'delete-other-windows)
11728 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
11729 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
11730 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
11731 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
11732 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
11733 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
11734 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
11735 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
11736 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
11737 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
11738 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
11740 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
11741 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
11742 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
11743 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
11744 (while l (define-key org-agenda-mode-map
11745 (int-to-string (pop l)) 'digit-argument)))
11747 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
11748 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
11749 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
11750 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
11751 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
11752 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
11753 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
11754 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
11755 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
11756 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
11757 (define-key org-agenda-mode-map "n" 'next-line)
11758 (define-key org-agenda-mode-map "p" 'previous-line)
11759 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
11760 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
11761 (define-key org-agenda-mode-map "," 'org-agenda-priority)
11762 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
11763 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
11764 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
11765 (eval-after-load "calendar"
11766 '(define-key calendar-mode-map org-calendar-to-agenda-key
11767 'org-calendar-goto-agenda))
11768 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
11769 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
11770 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
11771 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
11772 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
11773 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
11774 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
11775 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
11776 (define-key org-agenda-mode-map "O" 'org-agenda-clock-out)
11777 (define-key org-agenda-mode-map "X" 'org-agenda-clock-cancel)
11778 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
11779 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
11780 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
11781 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
11782 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
11783 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
11784 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
11785 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11786 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
11787 "Local keymap for agenda entries from Org-mode.")
11789 (define-key org-agenda-keymap
11790 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
11791 (define-key org-agenda-keymap
11792 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
11793 (when org-agenda-mouse-1-follows-link
11794 (define-key org-agenda-keymap [follow-link] 'mouse-face))
11795 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
11796 '("Agenda"
11797 ("Agenda Files")
11798 "--"
11799 ["Show" org-agenda-show t]
11800 ["Go To (other window)" org-agenda-goto t]
11801 ["Go To (this window)" org-agenda-switch-to t]
11802 ["Follow Mode" org-agenda-follow-mode
11803 :style toggle :selected org-agenda-follow-mode :active t]
11804 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
11805 "--"
11806 ["Cycle TODO" org-agenda-todo t]
11807 ["Archive subtree" org-agenda-archive t]
11808 ["Delete subtree" org-agenda-kill t]
11809 "--"
11810 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
11811 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
11812 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
11813 "--"
11814 ("Tags"
11815 ["Show all Tags" org-agenda-show-tags t]
11816 ["Set Tags" org-agenda-set-tags t])
11817 ("Date/Schedule"
11818 ["Schedule" org-agenda-schedule t]
11819 ["Set Deadline" org-agenda-deadline t]
11820 "--"
11821 ["Change date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
11822 ["Change date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
11823 ["Change date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
11824 ("Priority"
11825 ["Set Priority" org-agenda-priority t]
11826 ["Increase Priority" org-agenda-priority-up t]
11827 ["Decrease Priority" org-agenda-priority-down t]
11828 ["Show Priority" org-agenda-show-priority t])
11829 ("Calendar/Diary"
11830 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
11831 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
11832 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
11833 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
11834 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
11835 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
11836 "--"
11837 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
11838 "--"
11839 ("View"
11840 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
11841 :style radio :selected (equal org-agenda-ndays 1)]
11842 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
11843 :style radio :selected (equal org-agenda-ndays 7)]
11844 "--"
11845 ["Show Logbook entries" org-agenda-log-mode
11846 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
11847 ["Include Diary" org-agenda-toggle-diary
11848 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
11849 ["Use Time Grid" org-agenda-toggle-time-grid
11850 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
11851 ["Rebuild buffer" org-agenda-redo t]
11852 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
11853 "--"
11854 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
11855 "--"
11856 ["Quit" org-agenda-quit t]
11857 ["Exit and Release Buffers" org-agenda-exit t]
11860 ;;; Agenda undo
11862 (defvar org-agenda-allow-remote-undo t
11863 "Non-nil means, allow remote undo from the agenda buffer.")
11864 (defvar org-agenda-undo-list nil
11865 "List of undoable operations in the agenda since last refresh.")
11866 (defvar org-agenda-undo-has-started-in nil
11867 "Buffers that have already seen `undo-start' in the current undo sequence.")
11868 (defvar org-agenda-pending-undo-list nil
11869 "In a series of undo commands, this is the list of remaning undo items.")
11871 (defmacro org-with-remote-undo (_buffer &rest _body)
11872 "Execute BODY while recording undo information in two buffers."
11873 (declare (indent 1) (debug t))
11874 `(let ((_cline (org-current-line))
11875 (_cmd this-command)
11876 (_buf1 (current-buffer))
11877 (_buf2 ,_buffer)
11878 (_undo1 buffer-undo-list)
11879 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
11880 _c1 _c2)
11881 ,@_body
11882 (when org-agenda-allow-remote-undo
11883 (setq _c1 (org-verify-change-for-undo
11884 _undo1 (with-current-buffer _buf1 buffer-undo-list))
11885 _c2 (org-verify-change-for-undo
11886 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
11887 (when (or _c1 _c2)
11888 ;; make sure there are undo boundaries
11889 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
11890 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
11891 ;; remember which buffer to undo
11892 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
11893 org-agenda-undo-list)))))
11895 (defun org-agenda-undo ()
11896 "Undo a remote editing step in the agenda.
11897 This undoes changes both in the agenda buffer and in the remote buffer
11898 that have been changed along."
11899 (interactive)
11900 (or org-agenda-allow-remote-undo
11901 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
11902 (if (not (eq this-command last-command))
11903 (setq org-agenda-undo-has-started-in nil
11904 org-agenda-pending-undo-list org-agenda-undo-list))
11905 (if (not org-agenda-pending-undo-list)
11906 (error "No further undo information"))
11907 (let* ((entry (pop org-agenda-pending-undo-list))
11908 buf line cmd rembuf)
11909 (setq cmd (pop entry) line (pop entry))
11910 (setq rembuf (nth 2 entry))
11911 (org-with-remote-undo rembuf
11912 (while (bufferp (setq buf (pop entry)))
11913 (if (pop entry)
11914 (with-current-buffer buf
11915 (let ((last-undo-buffer buf)
11916 buffer-read-only)
11917 (unless (memq buf org-agenda-undo-has-started-in)
11918 (push buf org-agenda-undo-has-started-in)
11919 (make-local-variable 'pending-undo-list)
11920 (undo-start))
11921 (while (and pending-undo-list
11922 (listp pending-undo-list)
11923 (not (car pending-undo-list)))
11924 (pop pending-undo-list))
11925 (undo-more 1))))))
11926 (goto-line line)
11927 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
11929 (defun org-verify-change-for-undo (l1 l2)
11930 "Verify that a real change occurred between the undo lists L1 and L2."
11931 (while (and l1 (listp l1) (null (car l1))) (pop l1))
11932 (while (and l2 (listp l2) (null (car l2))) (pop l2))
11933 (not (eq l1 l2)))
11935 ;;; Agenda dispatch
11937 (defvar org-agenda-restrict nil)
11938 (defvar org-agenda-restrict-begin (make-marker))
11939 (defvar org-agenda-restrict-end (make-marker))
11940 (defvar org-agenda-last-dispatch-buffer nil)
11942 ;;;###autoload
11943 (defun org-agenda (arg)
11944 "Dispatch agenda commands to collect entries to the agenda buffer.
11945 Prompts for a character to select a command. Any prefix arg will be passed
11946 on to the selected command. The default selections are:
11948 a Call `org-agenda-list' to display the agenda for current day or week.
11949 t Call `org-todo-list' to display the global todo list.
11950 T Call `org-todo-list' to display the global todo list, select only
11951 entries with a specific TODO keyword (the user gets a prompt).
11952 m Call `org-tags-view' to display headlines with tags matching
11953 a condition (the user is prompted for the condition).
11954 M Like `m', but select only TODO entries, no ordinary headlines.
11955 l Create a timeeline for the current buffer.
11957 More commands can be added by configuring the variable
11958 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
11959 searches can be pre-defined in this way.
11961 If the current buffer is in Org-mode and visiting a file, you can also
11962 first press `1' to indicate that the agenda should be temporarily (until the
11963 next use of \\[org-agenda]) restricted to the current file."
11964 (interactive "P")
11965 (catch 'exit
11966 (let* ((buf (current-buffer))
11967 (bfn (buffer-file-name (buffer-base-buffer)))
11968 (restrict-ok (and bfn (org-mode-p)))
11969 (custom org-agenda-custom-commands)
11970 c entry key type match lprops header)
11971 ;; Turn off restriction
11972 (put 'org-agenda-files 'org-restrict nil)
11973 (setq org-agenda-restrict nil)
11974 (move-marker org-agenda-restrict-begin nil)
11975 (move-marker org-agenda-restrict-end nil)
11976 ;; Remember where this call originated
11977 (setq org-agenda-last-dispatch-buffer (current-buffer))
11978 (save-window-excursion
11979 (delete-other-windows)
11980 (switch-to-buffer-other-window " *Agenda Commands*")
11981 (erase-buffer)
11982 (insert (eval-when-compile
11983 (let ((header
11984 "Press key for an agenda command:
11985 -------------------------------- C Configure custom agenda commands
11986 a Agenda for current week or day
11987 t List of all TODO entries T Entries with special TODO kwd
11988 m Match a TAGS query M Like m, but only TODO entries
11989 L Timeline for current buffer # List stuck projects (!=configure)
11991 (start 0))
11992 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
11993 (setq start (match-end 0))
11994 (add-text-properties (match-beginning 2) (match-end 2)
11995 '(face bold) header))
11996 header)))
11997 (while (setq entry (pop custom))
11998 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
11999 (insert (format "\n%-4s%-14s: %s"
12000 (org-add-props (copy-sequence key)
12001 '(face bold))
12002 (cond
12003 ((stringp type) type)
12004 ((eq type 'tags) "Tags query")
12005 ((eq type 'todo) "TODO keyword")
12006 ((eq type 'tags-tree) "Tags (TODO)")
12007 ((eq type 'tags-tree) "Tags tree")
12008 ((eq type 'todo-tree) "TODO kwd tree")
12009 ((eq type 'occur-tree) "Occur tree")
12010 ((functionp type) (symbol-name type))
12011 (t "???"))
12012 (if (stringp match)
12013 (org-add-props match nil 'face 'org-warning)
12014 (format "set of %d commands" (+ -2 (length entry)))))))
12015 (if restrict-ok
12016 (insert "\n"
12017 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
12019 (goto-char (point-min))
12020 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
12021 (message "Press key for agenda command%s"
12022 (if restrict-ok ", or [1] or [0] to restrict" ""))
12023 (setq c (read-char-exclusive))
12024 (message "")
12025 (when (memq c '(?L ?1 ?0))
12026 (if restrict-ok
12027 (put 'org-agenda-files 'org-restrict (list bfn))
12028 (error "Cannot restrict agenda to current buffer"))
12029 (with-current-buffer " *Agenda Commands*"
12030 (goto-char (point-max))
12031 (delete-region (point-at-bol) (point))
12032 (goto-char (point-min)))
12033 (when (eq c ?0)
12034 (setq org-agenda-restrict t)
12035 (with-current-buffer buf
12036 (if (org-region-active-p)
12037 (progn
12038 (move-marker org-agenda-restrict-begin (region-beginning))
12039 (move-marker org-agenda-restrict-end (region-end)))
12040 (save-excursion
12041 (org-back-to-heading t)
12042 (move-marker org-agenda-restrict-begin (point))
12043 (move-marker org-agenda-restrict-end
12044 (progn (org-end-of-subtree t)))))))
12045 (unless (eq c ?L)
12046 (message "Press key for agenda command%s"
12047 (if restrict-ok " (restricted to current file)" ""))
12048 (setq c (read-char-exclusive)))
12049 (message "")))
12050 (require 'calendar) ; FIXME: can we avoid this for some commands?
12051 ;; For example the todo list should not need it (but does...)
12052 (cond
12053 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
12054 (if (symbolp (nth 1 entry))
12055 (progn
12056 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
12057 lprops (nth 3 entry))
12058 (cond
12059 ((eq type 'tags)
12060 (org-let lprops '(org-tags-view current-prefix-arg match)))
12061 ((eq type 'tags-todo)
12062 (org-let lprops '(org-tags-view '(4) match)))
12063 ((eq type 'todo)
12064 (org-let lprops '(org-todo-list match)))
12065 ((eq type 'tags-tree)
12066 (org-check-for-org-mode)
12067 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
12068 ((eq type 'todo-tree)
12069 (org-check-for-org-mode)
12070 (org-let lprops
12071 '(org-occur (concat "^" outline-regexp "[ \t]*"
12072 (regexp-quote match) "\\>"))))
12073 ((eq type 'occur-tree)
12074 (org-check-for-org-mode)
12075 (org-let lprops '(org-occur match)))
12076 ((fboundp type)
12077 (org-let lprops '(funcall type match)))
12078 (t (error "Invalid custom agenda command type %s" type))))
12079 (org-run-agenda-series (cddr entry))))
12080 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
12081 ((equal c ?a) (call-interactively 'org-agenda-list))
12082 ((equal c ?t) (call-interactively 'org-todo-list))
12083 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
12084 ((equal c ?m) (call-interactively 'org-tags-view))
12085 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
12086 ((equal c ?L)
12087 (unless restrict-ok
12088 (error "This is not an Org-mode file"))
12089 (org-call-with-arg 'org-timeline arg))
12090 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
12091 ((equal c ?!) (customize-variable 'org-stuck-projects))
12092 (t (error "Invalid key"))))))
12094 ;; FIXME: what is the meaning of WINDOW?????
12095 (defun org-run-agenda-series (series &optional window)
12096 (org-prepare-agenda)
12097 (let* ((org-agenda-multi t)
12098 (redo (list 'org-run-agenda-series (list 'quote series)))
12099 (org-select-agenda-window t)
12100 (cmds (car series))
12101 (gprops (nth 1 series))
12102 match ;; The byte compiler incorrectly complains about this. Keep it!
12103 cmd type lprops)
12104 (while (setq cmd (pop cmds))
12105 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
12106 (cond
12107 ((eq type 'agenda)
12108 (call-interactively 'org-agenda-list))
12109 ((eq type 'alltodo)
12110 (call-interactively 'org-todo-list))
12111 ((eq type 'tags)
12112 (org-let2 gprops lprops
12113 '(org-tags-view current-prefix-arg match)))
12114 ((eq type 'tags-todo)
12115 (org-let2 gprops lprops
12116 '(org-tags-view '(4) match)))
12117 ((eq type 'todo)
12118 (org-let2 gprops lprops
12119 '(org-todo-list match)))
12120 ((fboundp type)
12121 (org-let2 gprops lprops
12122 '(funcall type match)))
12123 (t (error "Invalid type in command series"))))
12124 (widen)
12125 (setq org-agenda-redo-command redo)
12126 (goto-char (point-min)))
12127 (org-finalize-agenda))
12129 ;;;###autoload
12130 (defmacro org-batch-agenda (cmd-key &rest parameters)
12131 "Run an agenda command in batch mode, send result to STDOUT.
12132 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
12133 Paramters are alternating variable names and values that will be bound
12134 before running the agenda command."
12135 (let (pars)
12136 (while parameters
12137 (push (list (pop parameters) (if parameters (pop parameters))) pars))
12138 (flet ((read-char-exclusive () (string-to-char cmd-key)))
12139 (eval (list 'let (nreverse pars) '(org-agenda nil))))
12140 (set-buffer "*Org Agenda*")
12141 (princ (buffer-string))))
12143 (defmacro org-no-read-only (&rest body)
12144 "Inhibit read-only for BODY."
12145 `(let ((inhibit-read-only t)) ,@body))
12147 (defun org-check-for-org-mode ()
12148 "Make sure current buffer is in org-mode. Error if not."
12149 (or (org-mode-p)
12150 (error "Cannot execute org-mode agenda command on buffer in %s."
12151 major-mode)))
12153 (defun org-fit-agenda-window ()
12154 "Fit the window to the buffer size."
12155 (and org-fit-agenda-window
12156 (memq org-agenda-window-setup '(reorganize-frame))
12157 (fboundp 'fit-window-to-buffer)
12158 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
12159 (/ (frame-height) 2))))
12161 ;;; Agenda file list
12163 (defun org-agenda-files (&optional unrestricted)
12164 "Get the list of agenda files.
12165 Optional UNRESTRICTED means return the full list even if a restriction
12166 is currently in place."
12167 (cond
12168 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12169 ((stringp org-agenda-files) (org-read-agenda-file-list))
12170 ((listp org-agenda-files) org-agenda-files)
12171 (t (error "Invalid value of `org-agenda-files'"))))
12173 (defun org-edit-agenda-file-list ()
12174 "Edit the list of agenda files.
12175 Depending on setup, this either uses customize to edit the variable
12176 `org-agenda-files', or it visits the file that is holding the list. In the
12177 latter case, the buffer is set up in a way that saving it automatically kills
12178 the buffer and restores the previous window configuration."
12179 (interactive)
12180 (if (stringp org-agenda-files)
12181 (let ((cw (current-window-configuration)))
12182 (find-file org-agenda-files)
12183 (org-set-local 'org-window-configuration cw)
12184 (org-add-hook 'after-save-hook
12185 (lambda ()
12186 (set-window-configuration
12187 (prog1 org-window-configuration
12188 (kill-buffer (current-buffer))))
12189 (org-install-agenda-files-menu)
12190 (message "New agenda file list installed"))
12191 nil 'local)
12192 (message (substitute-command-keys
12193 "Edit list and finish with \\[save-buffer]")))
12194 (customize-variable 'org-agenda-files)))
12196 (defun org-store-new-agenda-file-list (list)
12197 "Set new value for the agenda file list and save it correcly."
12198 (if (stringp org-agenda-files)
12199 (let ((f org-agenda-files) b)
12200 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12201 (with-temp-file f
12202 (insert (mapconcat 'identity list "\n") "\n")))
12203 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12204 (setq org-agenda-files list)
12205 (customize-save-variable 'org-agenda-files org-agenda-files))))
12207 (defun org-read-agenda-file-list ()
12208 "Read the list of agenda files from a file."
12209 (when (stringp org-agenda-files)
12210 (with-temp-buffer
12211 (insert-file-contents org-agenda-files)
12212 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12215 ;;;###autoload
12216 (defun org-cycle-agenda-files ()
12217 "Cycle through the files in `org-agenda-files'.
12218 If the current buffer visits an agenda file, find the next one in the list.
12219 If the current buffer does not, find the first agenda file."
12220 (interactive)
12221 (let* ((fs (org-agenda-files t))
12222 (files (append fs (list (car fs))))
12223 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12224 file)
12225 (unless files (error "No agenda files"))
12226 (catch 'exit
12227 (while (setq file (pop files))
12228 (if (equal (file-truename file) tcf)
12229 (when (car files)
12230 (find-file (car files))
12231 (throw 'exit t))))
12232 (find-file (car fs)))))
12234 (defun org-agenda-file-to-end ()
12235 "Move/add the current file to the end of the agenda file list.
12236 If the file is not present in the list, it is appended to the list. If it is
12237 present, it is moved there."
12238 (interactive)
12239 (org-agenda-file-to-front 'to-end))
12241 (defun org-agenda-file-to-front (&optional to-end)
12242 "Move/add the current file to the top of the agenda file list.
12243 If the file is not present in the list, it is added to the front. If it is
12244 present, it is moved there. With optional argument TO-END, add/move to the
12245 end of the list."
12246 (interactive "P")
12247 (let ((file-alist (mapcar (lambda (x)
12248 (cons (file-truename x) x))
12249 (org-agenda-files t)))
12250 (ctf (file-truename buffer-file-name))
12251 x had)
12252 (setq x (assoc ctf file-alist) had x)
12254 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12255 (if to-end
12256 (setq file-alist (append (delq x file-alist) (list x)))
12257 (setq file-alist (cons x (delq x file-alist))))
12258 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12259 (org-install-agenda-files-menu)
12260 (message "File %s to %s of agenda file list"
12261 (if had "moved" "added") (if to-end "end" "front"))))
12263 (defun org-remove-file (&optional file)
12264 "Remove current file from the list of files in variable `org-agenda-files'.
12265 These are the files which are being checked for agenda entries.
12266 Optional argument FILE means, use this file instead of the current."
12267 (interactive)
12268 (let* ((file (or file buffer-file-name))
12269 (true-file (file-truename file))
12270 (afile (abbreviate-file-name file))
12271 (files (delq nil (mapcar
12272 (lambda (x)
12273 (if (equal true-file
12274 (file-truename x))
12275 nil x))
12276 (org-agenda-files t)))))
12277 (if (not (= (length files) (length (org-agenda-files t))))
12278 (progn
12279 (org-store-new-agenda-file-list files)
12280 (org-install-agenda-files-menu)
12281 (message "Removed file: %s" afile))
12282 (message "File was not in list: %s" afile))))
12284 (defun org-file-menu-entry (file)
12285 (vector file (list 'find-file file) t))
12287 (defun org-check-agenda-file (file)
12288 "Make sure FILE exists. If not, ask user what to do."
12289 (when (not (file-exists-p file))
12290 (message "non-existent file %s. [R]emove from list or [A]bort?"
12291 (abbreviate-file-name file))
12292 (let ((r (downcase (read-char-exclusive))))
12293 (cond
12294 ((equal r ?r)
12295 (org-remove-file file)
12296 (throw 'nextfile t))
12297 (t (error "Abort"))))))
12299 ;;; Agenda prepare and finalize
12301 (defvar org-agenda-multi nil) ; dynammically scoped
12302 (defvar org-agenda-buffer-name "*Org Agenda*")
12303 (defvar org-pre-agenda-window-conf nil)
12304 (defun org-prepare-agenda ()
12305 (if org-agenda-multi
12306 (progn
12307 (setq buffer-read-only nil)
12308 (goto-char (point-max))
12309 (unless (= (point) 1)
12310 (insert "\n" (make-string (window-width) ?=) "\n"))
12311 (narrow-to-region (point) (point-max)))
12312 (org-agenda-maybe-reset-markers 'force)
12313 (org-prepare-agenda-buffers (org-agenda-files))
12314 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
12315 (awin (get-buffer-window abuf)))
12316 (cond
12317 ((equal (current-buffer) abuf) nil)
12318 (awin (select-window awin))
12319 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
12320 ((equal org-agenda-window-setup 'current-window)
12321 (switch-to-buffer abuf))
12322 ((equal org-agenda-window-setup 'other-window)
12323 (switch-to-buffer-other-window abuf))
12324 ((equal org-agenda-window-setup 'other-frame)
12325 (switch-to-buffer-other-frame abuf))
12326 ((equal org-agenda-window-setup 'reorganize-frame)
12327 (delete-other-windows)
12328 (switch-to-buffer-other-window abuf))))
12329 (setq buffer-read-only nil)
12330 (erase-buffer)
12331 (org-agenda-mode))
12332 (setq buffer-read-only nil))
12334 (defun org-finalize-agenda ()
12335 "Finishing touch for the agenda buffer, called just before displaying it."
12336 (unless org-agenda-multi
12337 (org-agenda-align-tags)
12338 (save-excursion
12339 (let ((buffer-read-only))
12340 (goto-char (point-min))
12341 (while (org-activate-bracket-links (point-max))
12342 (add-text-properties (match-beginning 0) (match-end 0)
12343 '(face org-link))))
12344 (run-hooks 'org-finalize-agenda-hook))))
12346 (defun org-prepare-agenda-buffers (files)
12347 "Create buffers for all agenda files, protect archived trees and comments."
12348 (interactive)
12349 (let ((pa '(:org-archived t))
12350 (pc '(:org-comment t))
12351 (pall '(:org-archived t :org-comment t))
12352 (rea (concat ":" org-archive-tag ":"))
12353 bmp file re)
12354 (save-excursion
12355 (while (setq file (pop files))
12356 (org-check-agenda-file file)
12357 (set-buffer (org-get-agenda-file-buffer file))
12358 (widen)
12359 (setq bmp (buffer-modified-p))
12360 (save-excursion
12361 (remove-text-properties (point-min) (point-max) pall)
12362 (when org-agenda-skip-archived-trees
12363 (goto-char (point-min))
12364 (while (re-search-forward rea nil t)
12365 (if (org-on-heading-p)
12366 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12367 (goto-char (point-min))
12368 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12369 (while (re-search-forward re nil t)
12370 (add-text-properties
12371 (match-beginning 0) (org-end-of-subtree t) pc)))
12372 (set-buffer-modified-p bmp)))))
12374 (defvar org-agenda-skip-function nil
12375 "Function to be called at each match during agenda construction.
12376 If this function return nil, the current match should not be skipped.
12377 Otherwise, the function must return a position from where the search
12378 should be continued.
12379 Never set this variable using `setq' or so, because then it will apply
12380 to all future agenda commands. Instead, bind it with `let' to scope
12381 it dynamically into the agenda-constructing command.")
12383 (defun org-agenda-skip ()
12384 "Throw to `:skip' in places that should be skipped."
12385 (let ((p (point-at-bol)) to)
12386 (and org-agenda-skip-archived-trees
12387 (get-text-property p :org-archived)
12388 (org-end-of-subtree t)
12389 (throw :skip t))
12390 (and (get-text-property p :org-comment)
12391 (org-end-of-subtree t)
12392 (throw :skip t))
12393 (if (equal (char-after p) ?#) (throw :skip t))
12394 (when (and (functionp org-agenda-skip-function)
12395 (setq to (save-excursion
12396 (save-match-data
12397 (funcall org-agenda-skip-function)))))
12398 (goto-char to)
12399 (throw :skip t))))
12401 (defvar org-agenda-markers nil
12402 "List of all currently active markers created by `org-agenda'.")
12403 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
12404 "Creation time of the last agenda marker.")
12406 (defun org-agenda-new-marker (&optional pos)
12407 "Return a new agenda marker.
12408 Org-mode keeps a list of these markers and resets them when they are
12409 no longer in use."
12410 (let ((m (copy-marker (or pos (point)))))
12411 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
12412 (push m org-agenda-markers)
12415 (defun org-agenda-maybe-reset-markers (&optional force)
12416 "Reset markers created by `org-agenda'. But only if they are old enough."
12417 (if (or (and force (not org-agenda-multi))
12418 (> (- (time-to-seconds (current-time))
12419 org-agenda-last-marker-time)
12421 (while org-agenda-markers
12422 (move-marker (pop org-agenda-markers) nil))))
12424 (defvar org-agenda-new-buffers nil
12425 "Buffers created to visit agenda files.")
12427 (defun org-get-agenda-file-buffer (file)
12428 "Get a buffer visiting FILE. If the buffer needs to be created, add
12429 it to the list of buffers which might be released later."
12430 (let ((buf (find-buffer-visiting file)))
12431 (if buf
12432 buf ; just return it
12433 ;; Make a new buffer and remember it
12434 (setq buf (find-file-noselect file))
12435 (if buf (push buf org-agenda-new-buffers))
12436 buf)))
12438 (defun org-release-buffers (blist)
12439 "Release all buffers in list, asking the user for confirmation when needed.
12440 When a buffer is unmodified, it is just killed. When modified, it is saved
12441 \(if the user agrees) and then killed."
12442 (let (buf file)
12443 (while (setq buf (pop blist))
12444 (setq file (buffer-file-name buf))
12445 (when (and (buffer-modified-p buf)
12446 file
12447 (y-or-n-p (format "Save file %s? " file)))
12448 (with-current-buffer buf (save-buffer)))
12449 (kill-buffer buf))))
12451 (defvar org-category-table nil)
12452 (defun org-get-category-table ()
12453 "Get the table of categories and positions in current buffer."
12454 (let (tbl)
12455 (save-excursion
12456 (goto-char (point-min))
12457 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
12458 (push (cons (point) (org-trim (match-string 2))) tbl)))
12459 tbl))
12461 (defun org-get-category (&optional pos)
12462 "Get the category applying to position POS."
12463 (if (not org-category-table)
12464 (cond
12465 ((null org-category)
12466 (setq org-category
12467 (if buffer-file-name
12468 (file-name-sans-extension
12469 (file-name-nondirectory buffer-file-name))
12470 "???")))
12471 ((symbolp org-category) (symbol-name org-category))
12472 (t org-category))
12473 (let ((tbl org-category-table)
12474 (pos (or pos (point))))
12475 (while (and tbl (> (caar tbl) pos))
12476 (pop tbl))
12477 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
12478 org-category-table))))))
12479 ;;; Agenda timeline
12481 (defun org-timeline (&optional include-all)
12482 "Show a time-sorted view of the entries in the current org file.
12483 Only entries with a time stamp of today or later will be listed. With
12484 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
12485 under the current date.
12486 If the buffer contains an active region, only check the region for
12487 dates."
12488 (interactive "P")
12489 (require 'calendar)
12490 (org-compile-prefix-format 'timeline)
12491 (org-set-sorting-strategy 'timeline)
12492 (let* ((dopast t)
12493 (dotodo include-all)
12494 (doclosed org-agenda-show-log)
12495 (entry buffer-file-name)
12496 (date (calendar-current-date))
12497 (win (selected-window))
12498 (pos1 (point))
12499 (beg (if (org-region-active-p) (region-beginning) (point-min)))
12500 (end (if (org-region-active-p) (region-end) (point-max)))
12501 (day-numbers (org-get-all-dates beg end 'no-ranges
12502 t doclosed ; always include today
12503 org-timeline-show-empty-dates))
12504 (today (time-to-days (current-time)))
12505 (past t)
12506 args
12507 s e rtn d emptyp)
12508 (setq org-agenda-redo-command
12509 (list 'progn
12510 (list 'switch-to-buffer-other-window (current-buffer))
12511 (list 'org-timeline (list 'quote include-all))))
12512 (if (not dopast)
12513 ;; Remove past dates from the list of dates.
12514 (setq day-numbers (delq nil (mapcar (lambda(x)
12515 (if (>= x today) x nil))
12516 day-numbers))))
12517 (org-prepare-agenda)
12518 (if doclosed (push :closed args))
12519 (push :timestamp args)
12520 (if dotodo (push :todo args))
12521 (while (setq d (pop day-numbers))
12522 (if (and (listp d) (eq (car d) :omitted))
12523 (progn
12524 (setq s (point))
12525 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
12526 (put-text-property s (1- (point)) 'face 'org-level-3))
12527 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
12528 (if (and (>= d today)
12529 dopast
12530 past)
12531 (progn
12532 (setq past nil)
12533 (insert (make-string 79 ?-) "\n")))
12534 (setq date (calendar-gregorian-from-absolute d))
12535 (setq s (point))
12536 (setq rtn (and (not emptyp)
12537 (apply 'org-agenda-get-day-entries
12538 entry date args)))
12539 (if (or rtn (equal d today) org-timeline-show-empty-dates)
12540 (progn
12541 (insert (calendar-day-name date) " "
12542 (number-to-string (extract-calendar-day date)) " "
12543 (calendar-month-name (extract-calendar-month date)) " "
12544 (number-to-string (extract-calendar-year date)) "\n")
12545 (put-text-property s (1- (point)) 'face
12546 'org-level-3)
12547 (if (equal d today)
12548 (put-text-property s (1- (point)) 'org-today t))
12549 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
12550 (put-text-property s (1- (point)) 'day d)))))
12551 (goto-char (point-min))
12552 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
12553 (point-min)))
12554 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
12555 (org-finalize-agenda)
12556 (setq buffer-read-only t)
12557 (when (not org-select-agenda-window)
12558 (select-window win)
12559 (goto-char pos1))))
12560 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
12561 "Return a list of all relevant day numbers from BEG to END buffer positions.
12562 If NO-RANGES is non-nil, include only the start and end dates of a range,
12563 not every single day in the range. If FORCE-TODAY is non-nil, make
12564 sure that TODAY is included in the list. If INACTIVE is non-nil, also
12565 inactive time stamps (those in square brackets) are included.
12566 When EMPTY is non-nil, also include days without any entries."
12567 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
12568 dates dates1 date day day1 day2 ts1 ts2)
12569 (if force-today
12570 (setq dates (list (time-to-days (current-time)))))
12571 (save-excursion
12572 (goto-char beg)
12573 (while (re-search-forward re end t)
12574 (setq day (time-to-days (org-time-string-to-time
12575 (substring (match-string 1) 0 10))))
12576 (or (memq day dates) (push day dates)))
12577 (unless no-ranges
12578 (goto-char beg)
12579 (while (re-search-forward org-tr-regexp end t)
12580 (setq ts1 (substring (match-string 1) 0 10)
12581 ts2 (substring (match-string 2) 0 10)
12582 day1 (time-to-days (org-time-string-to-time ts1))
12583 day2 (time-to-days (org-time-string-to-time ts2)))
12584 (while (< (setq day1 (1+ day1)) day2)
12585 (or (memq day1 dates) (push day1 dates)))))
12586 (setq dates (sort dates '<))
12587 (when empty
12588 (while (setq day (pop dates))
12589 (setq day2 (car dates))
12590 (push day dates1)
12591 (when (and day2 empty)
12592 (if (or (eq empty t)
12593 (and (numberp empty) (<= (- day2 day) empty)))
12594 (while (< (setq day (1+ day)) day2)
12595 (push (list day) dates1))
12596 (push (cons :omitted (- day2 day)) dates1))))
12597 (setq dates (nreverse dates1)))
12598 dates)))
12600 ;;; Agenda Daily/Weekly
12602 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
12603 (defvar org-agenda-last-arguments nil
12604 "The arguments of the previous call to org-agenda")
12605 (defvar org-starting-day nil) ; local variable in the agenda buffer
12606 (defvar org-include-all-loc nil) ; local variable
12609 ;;;###autoload
12610 (defun org-agenda-list (&optional include-all start-day ndays)
12611 "Produce a weekly view from all files in variable `org-agenda-files'.
12612 The view will be for the current week, but from the overview buffer you
12613 will be able to go to other weeks.
12614 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
12615 also be shown, under the current date.
12616 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
12617 on the days are also shown. See the variable `org-log-done' for how
12618 to turn on logging.
12619 START-DAY defaults to TODAY, or to the most recent match for the weekday
12620 given in `org-agenda-start-on-weekday'.
12621 NDAYS defaults to `org-agenda-ndays'."
12622 (interactive "P")
12623 (if org-agenda-overriding-arguments
12624 (setq include-all (car org-agenda-overriding-arguments)
12625 start-day (nth 1 org-agenda-overriding-arguments)
12626 ndays (nth 2 org-agenda-overriding-arguments)))
12627 (setq org-agenda-last-arguments (list include-all start-day ndays))
12628 (org-compile-prefix-format 'agenda)
12629 (org-set-sorting-strategy 'agenda)
12630 (require 'calendar)
12631 (let* ((org-agenda-start-on-weekday
12632 (if (or (equal ndays 1)
12633 (and (null ndays) (equal 1 org-agenda-ndays)))
12634 nil org-agenda-start-on-weekday))
12635 (thefiles (org-agenda-files))
12636 (files thefiles)
12637 (win (selected-window))
12638 (today (time-to-days (current-time)))
12639 (sd (or start-day today))
12640 (start (if (or (null org-agenda-start-on-weekday)
12641 (< org-agenda-ndays 7))
12643 (let* ((nt (calendar-day-of-week
12644 (calendar-gregorian-from-absolute sd)))
12645 (n1 org-agenda-start-on-weekday)
12646 (d (- nt n1)))
12647 (- sd (+ (if (< d 0) 7 0) d)))))
12648 (day-numbers (list start))
12649 (inhibit-redisplay t)
12650 s e rtn rtnall file date d start-pos end-pos todayp nd)
12651 (setq org-agenda-redo-command
12652 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
12653 ;; Make the list of days
12654 (setq ndays (or ndays org-agenda-ndays)
12655 nd ndays)
12656 (while (> ndays 1)
12657 (push (1+ (car day-numbers)) day-numbers)
12658 (setq ndays (1- ndays)))
12659 (setq day-numbers (nreverse day-numbers))
12660 (org-prepare-agenda)
12661 (org-set-local 'org-starting-day (car day-numbers))
12662 (org-set-local 'org-include-all-loc include-all)
12663 (when (and (or include-all org-agenda-include-all-todo)
12664 (member today day-numbers))
12665 (setq files thefiles
12666 rtnall nil)
12667 (while (setq file (pop files))
12668 (catch 'nextfile
12669 (org-check-agenda-file file)
12670 (setq date (calendar-gregorian-from-absolute today)
12671 rtn (org-agenda-get-day-entries
12672 file date :todo))
12673 (setq rtnall (append rtnall rtn))))
12674 (when rtnall
12675 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
12676 (add-text-properties (point-min) (1- (point))
12677 (list 'face 'org-level-3))
12678 (insert (org-finalize-agenda-entries rtnall) "\n")))
12679 (setq s (point))
12680 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
12681 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
12682 (while (setq d (pop day-numbers))
12683 (setq date (calendar-gregorian-from-absolute d)
12684 s (point))
12685 (if (or (setq todayp (= d today))
12686 (and (not start-pos) (= d sd)))
12687 (setq start-pos (point))
12688 (if (and start-pos (not end-pos))
12689 (setq end-pos (point))))
12690 (setq files thefiles
12691 rtnall nil)
12692 (while (setq file (pop files))
12693 (catch 'nextfile
12694 (org-check-agenda-file file)
12695 (if org-agenda-show-log
12696 (setq rtn (org-agenda-get-day-entries
12697 file date
12698 :deadline :scheduled :timestamp :closed))
12699 (setq rtn (org-agenda-get-day-entries
12700 file date
12701 :deadline :scheduled :timestamp)))
12702 (setq rtnall (append rtnall rtn))))
12703 (if org-agenda-include-diary
12704 (progn
12705 (require 'diary-lib)
12706 (setq rtn (org-get-entries-from-diary date))
12707 (setq rtnall (append rtnall rtn))))
12708 (if (or rtnall org-agenda-show-all-dates)
12709 (progn
12710 (insert (format "%-9s %2d %s %4d\n"
12711 (calendar-day-name date)
12712 (extract-calendar-day date)
12713 (calendar-month-name (extract-calendar-month date))
12714 (extract-calendar-year date)))
12715 (put-text-property s (1- (point)) 'face
12716 'org-level-3)
12717 (if todayp (put-text-property s (1- (point)) 'org-today t))
12719 (if rtnall (insert
12720 (org-finalize-agenda-entries
12721 (org-agenda-add-time-grid-maybe
12722 rtnall nd todayp))
12723 "\n"))
12724 (put-text-property s (1- (point)) 'day d))))
12725 (goto-char (point-min))
12726 (org-fit-agenda-window)
12727 (unless (and (pos-visible-in-window-p (point-min))
12728 (pos-visible-in-window-p (point-max)))
12729 (goto-char (1- (point-max)))
12730 (recenter -1)
12731 (if (not (pos-visible-in-window-p (or start-pos 1)))
12732 (progn
12733 (goto-char (or start-pos 1))
12734 (recenter 1))))
12735 (goto-char (or start-pos 1))
12736 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
12737 (org-finalize-agenda)
12738 (setq buffer-read-only t)
12739 (if (not org-select-agenda-window) (select-window win))
12740 (message "")))
12742 ;;; Agenda TODO list
12744 (defvar org-select-this-todo-keyword nil)
12745 (defvar org-last-arg nil)
12747 ;;;###autoload
12748 (defun org-todo-list (arg)
12749 "Show all TODO entries from all agenda file in a single list.
12750 The prefix arg can be used to select a specific TODO keyword and limit
12751 the list to these. When using \\[universal-argument], you will be prompted
12752 for a keyword. A numeric prefix directly selects the Nth keyword in
12753 `org-todo-keywords'."
12754 (interactive "P")
12755 (require 'calendar)
12756 (org-compile-prefix-format 'todo)
12757 (org-set-sorting-strategy 'todo)
12758 (let* ((today (time-to-days (current-time)))
12759 (date (calendar-gregorian-from-absolute today))
12760 (win (selected-window))
12761 (kwds org-todo-keywords)
12762 (completion-ignore-case t)
12763 (org-select-this-todo-keyword
12764 (if (stringp arg) arg
12765 (and arg (integerp arg) (> arg 0)
12766 (nth (1- arg) org-todo-keywords))))
12767 rtn rtnall files file pos)
12768 (when (equal arg '(4))
12769 (setq org-select-this-todo-keyword
12770 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
12771 nil t)))
12772 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
12773 (org-prepare-agenda)
12774 (org-set-local 'org-last-arg arg)
12775 (org-set-local 'org-todo-keywords kwds)
12776 (setq org-agenda-redo-command
12777 '(org-todo-list (or current-prefix-arg org-last-arg)))
12778 (setq files (org-agenda-files)
12779 rtnall nil)
12780 (while (setq file (pop files))
12781 (catch 'nextfile
12782 (org-check-agenda-file file)
12783 (setq rtn (org-agenda-get-day-entries file date :todo))
12784 (setq rtnall (append rtnall rtn))))
12785 (if org-agenda-overriding-header
12786 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
12787 nil 'face 'org-level-3) "\n")
12788 (insert "Global list of TODO items of type: ")
12789 (add-text-properties (point-min) (1- (point))
12790 (list 'face 'org-level-3))
12791 (setq pos (point))
12792 (insert (or org-select-this-todo-keyword "ALL") "\n")
12793 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
12794 (setq pos (point))
12795 (unless org-agenda-multi
12796 (insert
12797 "Available with `N r': (0)ALL "
12798 (let ((n 0))
12799 (mapconcat (lambda (x)
12800 (format "(%d)%s" (setq n (1+ n)) x))
12801 org-todo-keywords " "))
12802 "\n"))
12803 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
12804 (when rtnall
12805 (insert (org-finalize-agenda-entries rtnall) "\n"))
12806 (goto-char (point-min))
12807 (org-fit-agenda-window)
12808 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
12809 (org-finalize-agenda)
12810 (setq buffer-read-only t)
12811 (if (not org-select-agenda-window) (select-window win))))
12813 ;;; Agenda tags match
12815 ;;;###autoload
12816 (defun org-tags-view (&optional todo-only match)
12817 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
12818 The prefix arg TODO-ONLY limits the search to TODO entries."
12819 (interactive "P")
12820 (org-compile-prefix-format 'tags)
12821 (org-set-sorting-strategy 'tags)
12822 (let* ((org-tags-match-list-sublevels
12823 (if todo-only t org-tags-match-list-sublevels))
12824 (win (selected-window))
12825 (completion-ignore-case t)
12826 rtn rtnall files file pos matcher
12827 buffer)
12828 (setq matcher (org-make-tags-matcher match)
12829 match (car matcher) matcher (cdr matcher))
12830 (org-prepare-agenda)
12831 (setq org-agenda-redo-command
12832 (list 'org-tags-view (list 'quote todo-only)
12833 (list 'if 'current-prefix-arg nil match)))
12834 (setq files (org-agenda-files)
12835 rtnall nil)
12836 (while (setq file (pop files))
12837 (catch 'nextfile
12838 (org-check-agenda-file file)
12839 (setq buffer (if (file-exists-p file)
12840 (org-get-agenda-file-buffer file)
12841 (error "No such file %s" file)))
12842 (if (not buffer)
12843 ;; If file does not exist, merror message to agenda
12844 (setq rtn (list
12845 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
12846 rtnall (append rtnall rtn))
12847 (with-current-buffer buffer
12848 (unless (org-mode-p)
12849 (error "Agenda file %s is not in `org-mode'" file))
12850 (setq org-category-table (org-get-category-table))
12851 (save-excursion
12852 (save-restriction
12853 (if org-agenda-restrict
12854 (narrow-to-region org-agenda-restrict-begin
12855 org-agenda-restrict-end)
12856 (widen))
12857 (setq rtn (org-scan-tags 'agenda matcher todo-only))
12858 (setq rtnall (append rtnall rtn))))))))
12859 (if org-agenda-overriding-header
12860 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
12861 nil 'face 'org-level-3) "\n")
12862 (insert "Headlines with TAGS match: ")
12863 (add-text-properties (point-min) (1- (point))
12864 (list 'face 'org-level-3))
12865 (setq pos (point))
12866 (insert match "\n")
12867 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
12868 (setq pos (point))
12869 (unless org-agenda-multi
12870 (insert "Press `C-u r' to search again with new search string\n"))
12871 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
12872 (when rtnall
12873 (insert (org-finalize-agenda-entries rtnall) "\n"))
12874 (goto-char (point-min))
12875 (org-fit-agenda-window)
12876 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
12877 (org-finalize-agenda)
12878 (setq buffer-read-only t)
12879 (if (not org-select-agenda-window) (select-window win))))
12881 ;;; Agenda Finding stuck projects
12883 (defvar org-agenda-skip-regexp nil
12884 "Regular expression used in skipping subtrees for the agenda.
12885 This is basically a temporary global variable that can be set and then
12886 used by user-defined selections using `org-agenda-skip-function'.")
12888 (defvar org-agenda-overriding-header nil
12889 "When this is set during todo and tags searches, will replace header.")
12891 (defun org-agenda-skip-subtree-when-regexp-matches ()
12892 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
12893 If yes, it returns the end position of this tree, causing agenda commands
12894 to skip this subtree. This is a function that can be put into
12895 `org-agenda-skip-function' for the duration of a command."
12896 (save-match-data
12897 (let ((end (save-excursion (org-end-of-subtree t)))
12898 skip)
12899 (save-excursion
12900 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
12901 (and skip end))))
12903 (defun org-agenda-list-stuck-projects (&rest ignore)
12904 "Create agenda view for projects that are stuck.
12905 Stuck projects are project that have no next actions. For the definitions
12906 of what a project is and how to check if it stuck, customize the variable
12907 `org-stuck-projects'.
12908 MATCH is being ignored."
12909 (interactive)
12910 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
12911 (org-agenda-overriding-header "List of stuck projects: ")
12912 (matcher (nth 0 org-stuck-projects))
12913 (todo (nth 1 org-stuck-projects))
12914 (tags (nth 2 org-stuck-projects))
12915 (todo-re (concat "^\\*+[ \t]+\\("
12916 (mapconcat 'identity todo "\\|")
12917 "\\)\\>"))
12918 (tags-re (concat "^\\*+.*:\\("
12919 (mapconcat 'identity tags "\\|")
12920 "\\):[a-zA-Z0-9_@:]*[ \t]*$")))
12922 (setq org-agenda-skip-regexp
12923 (cond
12924 ((and todo tags)
12925 (concat todo-re "\\|" tags-re))
12926 (todo todo-re)
12927 (tags tags-re)
12928 (t (error "No information how to identify unstuck projects"))))
12929 (org-tags-view nil matcher)))
12932 ;;; Diary integration
12934 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
12936 (defun org-get-entries-from-diary (date)
12937 "Get the (Emacs Calendar) diary entries for DATE."
12938 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
12939 (diary-display-hook '(fancy-diary-display))
12940 (list-diary-entries-hook
12941 (cons 'org-diary-default-entry list-diary-entries-hook))
12942 (diary-file-name-prefix-function nil) ; turn this feature off
12943 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
12944 entries
12945 (org-disable-agenda-to-diary t))
12946 (save-excursion
12947 (save-window-excursion
12948 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
12949 (if (not (get-buffer fancy-diary-buffer))
12950 (setq entries nil)
12951 (with-current-buffer fancy-diary-buffer
12952 (setq buffer-read-only nil)
12953 (if (= (point-max) 1)
12954 ;; No entries
12955 (setq entries nil)
12956 ;; Omit the date and other unnecessary stuff
12957 (org-agenda-cleanup-fancy-diary)
12958 ;; Add prefix to each line and extend the text properties
12959 (if (= (point-max) 1)
12960 (setq entries nil)
12961 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
12962 (set-buffer-modified-p nil)
12963 (kill-buffer fancy-diary-buffer)))
12964 (when entries
12965 (setq entries (org-split-string entries "\n"))
12966 (setq entries
12967 (mapcar
12968 (lambda (x)
12969 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
12970 ;; Extend the text properties to the beginning of the line
12971 (org-add-props x (text-properties-at (1- (length x)) x)))
12972 entries)))))
12974 (defun org-agenda-cleanup-fancy-diary ()
12975 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
12976 This gets rid of the date, the underline under the date, and
12977 the dummy entry installed by `org-mode' to ensure non-empty diary for each
12978 date. It also removes lines that contain only whitespace."
12979 (goto-char (point-min))
12980 (if (looking-at ".*?:[ \t]*")
12981 (progn
12982 (replace-match "")
12983 (re-search-forward "\n=+$" nil t)
12984 (replace-match "")
12985 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
12986 (re-search-forward "\n=+$" nil t)
12987 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
12988 (goto-char (point-min))
12989 (while (re-search-forward "^ +\n" nil t)
12990 (replace-match ""))
12991 (goto-char (point-min))
12992 (if (re-search-forward "^Org-mode dummy\n?" nil t)
12993 (replace-match "")))
12995 ;; Make sure entries from the diary have the right text properties.
12996 (eval-after-load "diary-lib"
12997 '(if (boundp 'diary-modify-entry-list-string-function)
12998 ;; We can rely on the hook, nothing to do
13000 ;; Hook not avaiable, must use advice to make this work
13001 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
13002 "Make the position visible."
13003 (if (and org-disable-agenda-to-diary ;; called from org-agenda
13004 (stringp string)
13005 buffer-file-name)
13006 (setq string (org-modify-diary-entry-string string))))))
13008 (defun org-modify-diary-entry-string (string)
13009 "Add text properties to string, allowing org-mode to act on it."
13010 (org-add-props string nil
13011 'mouse-face 'highlight
13012 'keymap org-agenda-keymap
13013 'help-echo (format "mouse-2 or RET jump to diary file %s"
13014 (abbreviate-file-name buffer-file-name))
13015 'org-agenda-diary-link t
13016 'org-marker (org-agenda-new-marker (point-at-bol))))
13018 (defun org-diary-default-entry ()
13019 "Add a dummy entry to the diary.
13020 Needed to avoid empty dates which mess up holiday display."
13021 ;; Catch the error if dealing with the new add-to-diary-alist
13022 (when org-disable-agenda-to-diary
13023 (condition-case nil
13024 (add-to-diary-list original-date "Org-mode dummy" "")
13025 (error
13026 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
13028 ;;;###autoload
13029 (defun org-diary (&rest args)
13030 "Return diary information from org-files.
13031 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
13032 It accesses org files and extracts information from those files to be
13033 listed in the diary. The function accepts arguments specifying what
13034 items should be listed. The following arguments are allowed:
13036 :timestamp List the headlines of items containing a date stamp or
13037 date range matching the selected date. Deadlines will
13038 also be listed, on the expiration day.
13040 :deadline List any deadlines past due, or due within
13041 `org-deadline-warning-days'. The listing occurs only
13042 in the diary for *today*, not at any other date. If
13043 an entry is marked DONE, it is no longer listed.
13045 :scheduled List all items which are scheduled for the given date.
13046 The diary for *today* also contains items which were
13047 scheduled earlier and are not yet marked DONE.
13049 :todo List all TODO items from the org-file. This may be a
13050 long list - so this is not turned on by default.
13051 Like deadlines, these entries only show up in the
13052 diary for *today*, not at any other date.
13054 The call in the diary file should look like this:
13056 &%%(org-diary) ~/path/to/some/orgfile.org
13058 Use a separate line for each org file to check. Or, if you omit the file name,
13059 all files listed in `org-agenda-files' will be checked automatically:
13061 &%%(org-diary)
13063 If you don't give any arguments (as in the example above), the default
13064 arguments (:deadline :scheduled :timestamp) are used. So the example above may
13065 also be written as
13067 &%%(org-diary :deadline :timestamp :scheduled)
13069 The function expects the lisp variables `entry' and `date' to be provided
13070 by the caller, because this is how the calendar works. Don't use this
13071 function from a program - use `org-agenda-get-day-entries' instead."
13072 (org-agenda-maybe-reset-markers)
13073 (org-compile-prefix-format 'agenda)
13074 (org-set-sorting-strategy 'agenda)
13075 (setq args (or args '(:deadline :scheduled :timestamp)))
13076 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
13077 (list entry)
13078 (org-agenda-files t)))
13079 file rtn results)
13080 ;; If this is called during org-agenda, don't return any entries to
13081 ;; the calendar. Org Agenda will list these entries itself.
13082 (if org-disable-agenda-to-diary (setq files nil))
13083 (while (setq file (pop files))
13084 (setq rtn (apply 'org-agenda-get-day-entries file date args))
13085 (setq results (append results rtn)))
13086 (if results
13087 (concat (org-finalize-agenda-entries results) "\n"))))
13089 ;;; Agenda entry finders
13091 (defun org-agenda-get-day-entries (file date &rest args)
13092 "Does the work for `org-diary' and `org-agenda'.
13093 FILE is the path to a file to be checked for entries. DATE is date like
13094 the one returned by `calendar-current-date'. ARGS are symbols indicating
13095 which kind of entries should be extracted. For details about these, see
13096 the documentation of `org-diary'."
13097 (setq args (or args '(:deadline :scheduled :timestamp)))
13098 (let* ((org-startup-with-deadline-check nil)
13099 (org-startup-folded nil)
13100 (org-startup-align-all-tables nil)
13101 (buffer (if (file-exists-p file)
13102 (org-get-agenda-file-buffer file)
13103 (error "No such file %s" file)))
13104 arg results rtn)
13105 (if (not buffer)
13106 ;; If file does not exist, make sure an error message ends up in diary
13107 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
13108 (with-current-buffer buffer
13109 (unless (org-mode-p)
13110 (error "Agenda file %s is not in `org-mode'" file))
13111 (setq org-category-table (org-get-category-table))
13112 (let ((case-fold-search nil))
13113 (save-excursion
13114 (save-restriction
13115 (if org-agenda-restrict
13116 (narrow-to-region org-agenda-restrict-begin
13117 org-agenda-restrict-end)
13118 (widen))
13119 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
13120 (while (setq arg (pop args))
13121 (cond
13122 ((and (eq arg :todo)
13123 (equal date (calendar-current-date)))
13124 (setq rtn (org-agenda-get-todos))
13125 (setq results (append results rtn)))
13126 ((eq arg :timestamp)
13127 (setq rtn (org-agenda-get-blocks))
13128 (setq results (append results rtn))
13129 (setq rtn (org-agenda-get-timestamps))
13130 (setq results (append results rtn)))
13131 ((eq arg :scheduled)
13132 (setq rtn (org-agenda-get-scheduled))
13133 (setq results (append results rtn)))
13134 ((eq arg :closed)
13135 (setq rtn (org-agenda-get-closed))
13136 (setq results (append results rtn)))
13137 ((and (eq arg :deadline)
13138 (equal date (calendar-current-date)))
13139 (setq rtn (org-agenda-get-deadlines))
13140 (setq results (append results rtn))))))))
13141 results))))
13143 (defun org-entry-is-done-p ()
13144 "Is the current entry marked DONE?"
13145 (save-excursion
13146 (and (re-search-backward "[\r\n]\\*" nil t)
13147 (looking-at org-nl-done-regexp))))
13149 (defun org-at-date-range-p (&optional inactive-ok)
13150 "Is the cursor inside a date range?"
13151 (interactive)
13152 (save-excursion
13153 (catch 'exit
13154 (let ((pos (point)))
13155 (skip-chars-backward "^[<\r\n")
13156 (skip-chars-backward "<[")
13157 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13158 (>= (match-end 0) pos)
13159 (throw 'exit t))
13160 (skip-chars-backward "^<[\r\n")
13161 (skip-chars-backward "<[")
13162 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13163 (>= (match-end 0) pos)
13164 (throw 'exit t)))
13165 nil)))
13167 (defun org-agenda-get-todos ()
13168 "Return the TODO information for agenda display."
13169 (let* ((props (list 'face nil
13170 'done-face 'org-done
13171 'org-not-done-regexp org-not-done-regexp
13172 'mouse-face 'highlight
13173 'keymap org-agenda-keymap
13174 'help-echo
13175 (format "mouse-2 or RET jump to org file %s"
13176 (abbreviate-file-name buffer-file-name))))
13177 (regexp (concat "[\n\r]\\*+ *\\("
13178 (if org-select-this-todo-keyword
13179 (concat "\\<\\(" org-select-this-todo-keyword
13180 "\\)\\>")
13181 org-not-done-regexp)
13182 "[^\n\r]*\\)"))
13183 (deadline-re (concat ".*\\(\n[^*].*\\)?" org-deadline-time-regexp))
13184 (sched-re (concat ".*\\(\n[^*].*\\)?" org-scheduled-time-regexp))
13185 ; FIXME why was this wrong? (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
13186 marker priority category tags
13187 ee txt)
13188 (goto-char (point-min))
13189 (while (re-search-forward regexp nil t)
13190 (catch :skip
13191 (save-match-data
13192 (beginning-of-line)
13193 (when (or (and org-agenda-todo-ignore-scheduled
13194 (looking-at sched-re))
13195 (and org-agenda-todo-ignore-deadlines
13196 (looking-at deadline-re)
13197 (org-deadline-close (match-string 2))))
13199 ;; FIXME: the following test also happens below, but we need it here
13200 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
13201 (throw :skip nil)))
13202 (org-agenda-skip)
13203 (goto-char (match-beginning 1))
13204 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
13205 category (org-get-category)
13206 tags (org-get-tags-at (point))
13207 txt (org-format-agenda-item "" (match-string 1) category tags)
13208 priority
13209 (+ (org-get-priority txt)
13210 (if org-todo-kwd-priority-p
13211 (- org-todo-kwd-max-priority -2
13212 (length
13213 (member (match-string 2) org-todo-keywords)))
13214 1)))
13215 (org-add-props txt props
13216 'org-marker marker 'org-hd-marker marker
13217 'priority priority 'category category)
13218 (push txt ee)
13219 (if org-agenda-todo-list-sublevels
13220 (goto-char (match-end 1))
13221 (org-end-of-subtree 'invisible))))
13222 (nreverse ee)))
13224 (defconst org-agenda-no-heading-message
13225 "No heading for this item in buffer or region.")
13227 (defun org-agenda-get-timestamps ()
13228 "Return the date stamp information for agenda display."
13229 (let* ((props (list 'face nil
13230 'org-not-done-regexp org-not-done-regexp
13231 'mouse-face 'highlight
13232 'keymap org-agenda-keymap
13233 'help-echo
13234 (format "mouse-2 or RET jump to org file %s"
13235 (abbreviate-file-name buffer-file-name))))
13236 (regexp (regexp-quote
13237 (substring
13238 (format-time-string
13239 (car org-time-stamp-formats)
13240 (apply 'encode-time ; DATE bound by calendar
13241 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
13242 0 11)))
13243 marker hdmarker deadlinep scheduledp donep tmp priority category
13244 ee txt timestr tags)
13245 (goto-char (point-min))
13246 (while (re-search-forward regexp nil t)
13247 (catch :skip
13248 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
13249 (org-agenda-skip)
13250 (setq marker (org-agenda-new-marker (match-beginning 0))
13251 category (org-get-category (match-beginning 0))
13252 tmp (buffer-substring (max (point-min)
13253 (- (match-beginning 0)
13254 org-ds-keyword-length))
13255 (match-beginning 0))
13256 timestr (buffer-substring (match-beginning 0) (point-at-eol))
13257 deadlinep (string-match org-deadline-regexp tmp)
13258 scheduledp (string-match org-scheduled-regexp tmp)
13259 donep (org-entry-is-done-p))
13260 (and org-agenda-skip-scheduled-if-done
13261 scheduledp donep
13262 (throw :skip t))
13263 (if (string-match ">" timestr)
13264 ;; substring should only run to end of time stamp
13265 (setq timestr (substring timestr 0 (match-end 0))))
13266 (save-excursion
13267 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
13268 (progn
13269 (goto-char (match-end 1))
13270 (setq hdmarker (org-agenda-new-marker)
13271 tags (org-get-tags-at))
13272 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
13273 (setq txt (org-format-agenda-item
13274 (format "%s%s"
13275 (if deadlinep "Deadline: " "")
13276 (if scheduledp "Scheduled: " ""))
13277 (match-string 1) category tags timestr)))
13278 (setq txt org-agenda-no-heading-message))
13279 (setq priority (org-get-priority txt))
13280 (org-add-props txt props
13281 'org-marker marker 'org-hd-marker hdmarker)
13282 (if deadlinep
13283 (org-add-props txt nil
13284 'face (if donep 'org-done 'org-warning)
13285 'undone-face 'org-warning 'done-face 'org-done
13286 'category category 'priority (+ 100 priority))
13287 (if scheduledp
13288 (org-add-props txt nil
13289 'face 'org-scheduled-today
13290 'undone-face 'org-scheduled-today 'done-face 'org-done
13291 'category category 'priority (+ 99 priority))
13292 (org-add-props txt nil 'priority priority 'category category)))
13293 (push txt ee))
13294 (outline-next-heading)))
13295 (nreverse ee)))
13297 (defun org-agenda-get-closed ()
13298 "Return the logged TODO entries for agenda display."
13299 (let* ((props (list 'mouse-face 'highlight
13300 'org-not-done-regexp org-not-done-regexp
13301 'keymap org-agenda-keymap
13302 'help-echo
13303 (format "mouse-2 or RET jump to org file %s"
13304 (abbreviate-file-name buffer-file-name))))
13305 (regexp (concat
13306 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
13307 (regexp-quote
13308 (substring
13309 (format-time-string
13310 (car org-time-stamp-formats)
13311 (apply 'encode-time ; DATE bound by calendar
13312 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
13313 1 11))))
13314 marker hdmarker priority category tags closedp
13315 ee txt timestr)
13316 (goto-char (point-min))
13317 (while (re-search-forward regexp nil t)
13318 (catch :skip
13319 (org-agenda-skip)
13320 (setq marker (org-agenda-new-marker (match-beginning 0))
13321 closedp (equal (match-string 1) org-closed-string)
13322 category (org-get-category (match-beginning 0))
13323 timestr (buffer-substring (match-beginning 0) (point-at-eol))
13324 ;; donep (org-entry-is-done-p)
13326 (if (string-match "\\]" timestr)
13327 ;; substring should only run to end of time stamp
13328 (setq timestr (substring timestr 0 (match-end 0))))
13329 (save-excursion
13330 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
13331 (progn
13332 (goto-char (match-end 1))
13333 (setq hdmarker (org-agenda-new-marker)
13334 tags (org-get-tags-at))
13335 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
13336 (setq txt (org-format-agenda-item
13337 (if closedp "Closed: " "Clocked: ")
13338 (match-string 1) category tags timestr)))
13339 (setq txt org-agenda-no-heading-message))
13340 (setq priority 100000)
13341 (org-add-props txt props
13342 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
13343 'priority priority 'category category
13344 'undone-face 'org-warning 'done-face 'org-done)
13345 (push txt ee))
13346 (outline-next-heading)))
13347 (nreverse ee)))
13349 (defun org-agenda-get-deadlines ()
13350 "Return the deadline information for agenda display."
13351 (let* ((wdays org-deadline-warning-days)
13352 (props (list 'mouse-face 'highlight
13353 'org-not-done-regexp org-not-done-regexp
13354 'keymap org-agenda-keymap
13355 'help-echo
13356 (format "mouse-2 or RET jump to org file %s"
13357 (abbreviate-file-name buffer-file-name))))
13358 (regexp org-deadline-time-regexp)
13359 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
13360 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
13361 d2 diff pos pos1 category tags
13362 ee txt head face)
13363 (goto-char (point-min))
13364 (while (re-search-forward regexp nil t)
13365 (catch :skip
13366 (org-agenda-skip)
13367 (setq pos (1- (match-beginning 1))
13368 d2 (time-to-days
13369 (org-time-string-to-time (match-string 1)))
13370 diff (- d2 d1))
13371 ;; When to show a deadline in the calendar:
13372 ;; If the expiration is within wdays warning time.
13373 ;; Past-due deadlines are only shown on the current date
13374 (if (and (< diff wdays) todayp (not (= diff 0)))
13375 (save-excursion
13376 (setq category (org-get-category))
13377 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
13378 (progn
13379 (goto-char (match-end 0))
13380 (setq pos1 (match-end 1))
13381 (setq tags (org-get-tags-at pos1))
13382 (setq head (buffer-substring-no-properties
13383 (point)
13384 (progn (skip-chars-forward "^\r\n")
13385 (point))))
13386 (if (string-match org-looking-at-done-regexp head)
13387 (setq txt nil)
13388 (setq txt (org-format-agenda-item
13389 (format "In %3d d.: " diff) head category tags))))
13390 (setq txt org-agenda-no-heading-message))
13391 (when txt
13392 (setq face (cond ((<= diff 0) 'org-warning)
13393 ((<= diff 5) 'org-upcoming-deadline)
13394 (t nil)))
13395 (org-add-props txt props
13396 'org-marker (org-agenda-new-marker pos)
13397 'org-hd-marker (org-agenda-new-marker pos1)
13398 'priority (+ (- 10 diff) (org-get-priority txt))
13399 'category category
13400 'face face 'undone-face face 'done-face 'org-done)
13401 (push txt ee))))))
13402 ee))
13404 (defun org-agenda-get-scheduled ()
13405 "Return the scheduled information for agenda display."
13406 (let* ((props (list 'face 'org-scheduled-previously
13407 'org-not-done-regexp org-not-done-regexp
13408 'undone-face 'org-scheduled-previously
13409 'done-face 'org-done
13410 'mouse-face 'highlight
13411 'keymap org-agenda-keymap
13412 'help-echo
13413 (format "mouse-2 or RET jump to org file %s"
13414 (abbreviate-file-name buffer-file-name))))
13415 (regexp org-scheduled-time-regexp)
13416 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
13417 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
13418 d2 diff pos pos1 category tags donep
13419 ee txt head)
13420 (goto-char (point-min))
13421 (while (re-search-forward regexp nil t)
13422 (catch :skip
13423 (org-agenda-skip)
13424 (setq pos (1- (match-beginning 1))
13425 d2 (time-to-days
13426 (org-time-string-to-time (match-string 1)))
13427 diff (- d2 d1))
13428 ;; When to show a scheduled item in the calendar:
13429 ;; If it is on or past the date.
13430 (if (and (< diff 0) todayp)
13431 (save-excursion
13432 (setq category (org-get-category))
13433 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
13434 (progn
13435 (goto-char (match-end 0))
13436 (setq pos1 (match-end 1))
13437 (setq tags (org-get-tags-at))
13438 (setq head (buffer-substring-no-properties
13439 (point)
13440 (progn (skip-chars-forward "^\r\n") (point))))
13441 (if (string-match org-looking-at-done-regexp head)
13442 (setq txt nil)
13443 (setq txt (org-format-agenda-item
13444 (format "Sched.%2dx: " (- 1 diff)) head
13445 category tags))))
13446 (setq txt org-agenda-no-heading-message))
13447 (when txt
13448 (org-add-props txt props
13449 'org-marker (org-agenda-new-marker pos)
13450 'org-hd-marker (org-agenda-new-marker pos1)
13451 'priority (+ (- 5 diff) (org-get-priority txt))
13452 'category category)
13453 (push txt ee))))))
13454 ee))
13456 (defun org-agenda-get-blocks ()
13457 "Return the date-range information for agenda display."
13458 (let* ((props (list 'face nil
13459 'org-not-done-regexp org-not-done-regexp
13460 'mouse-face 'highlight
13461 'keymap org-agenda-keymap
13462 'help-echo
13463 (format "mouse-2 or RET jump to org file %s"
13464 (abbreviate-file-name buffer-file-name))))
13465 (regexp org-tr-regexp)
13466 (d0 (calendar-absolute-from-gregorian date))
13467 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
13468 (goto-char (point-min))
13469 (while (re-search-forward regexp nil t)
13470 (catch :skip
13471 (org-agenda-skip)
13472 (setq pos (point))
13473 (setq timestr (match-string 0)
13474 s1 (match-string 1)
13475 s2 (match-string 2)
13476 d1 (time-to-days (org-time-string-to-time s1))
13477 d2 (time-to-days (org-time-string-to-time s2)))
13478 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
13479 ;; Only allow days between the limits, because the normal
13480 ;; date stamps will catch the limits.
13481 (save-excursion
13482 (setq marker (org-agenda-new-marker (point)))
13483 (setq category (org-get-category))
13484 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
13485 (progn
13486 (setq hdmarker (org-agenda-new-marker (match-end 1)))
13487 (goto-char (match-end 1))
13488 (setq tags (org-get-tags-at))
13489 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
13490 (setq txt (org-format-agenda-item
13491 (format (if (= d1 d2) "" "(%d/%d): ")
13492 (1+ (- d0 d1)) (1+ (- d2 d1)))
13493 (match-string 1) category tags
13494 (if (= d0 d1) timestr))))
13495 (setq txt org-agenda-no-heading-message))
13496 (org-add-props txt props
13497 'org-marker marker 'org-hd-marker hdmarker
13498 'priority (org-get-priority txt) 'category category)
13499 (push txt ee)))
13500 (goto-char pos)))
13501 ;; Sort the entries by expiration date.
13502 (nreverse ee)))
13504 ;;; Agenda presentation and sorting
13506 ;; FIXME: should I allow spaces around the dash?
13507 (defconst org-plain-time-of-day-regexp
13508 (concat
13509 "\\(\\<[012]?[0-9]"
13510 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
13511 "\\(--?"
13512 "\\(\\<[012]?[0-9]"
13513 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
13514 "\\)?")
13515 "Regular expression to match a plain time or time range.
13516 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
13517 groups carry important information:
13518 0 the full match
13519 1 the first time, range or not
13520 8 the second time, if it is a range.")
13522 (defconst org-stamp-time-of-day-regexp
13523 (concat
13524 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
13525 "\\([012][0-9]:[0-5][0-9]\\)>"
13526 "\\(--?"
13527 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
13528 "Regular expression to match a timestamp time or time range.
13529 After a match, the following groups carry important information:
13530 0 the full match
13531 1 date plus weekday, for backreferencing to make sure both times on same day
13532 2 the first time, range or not
13533 4 the second time, if it is a range.")
13535 (defvar org-prefix-has-time nil
13536 "A flag, set by `org-compile-prefix-format'.
13537 The flag is set if the currently compiled format contains a `%t'.")
13538 (defvar org-prefix-has-tag nil
13539 "A flag, set by `org-compile-prefix-format'.
13540 The flag is set if the currently compiled format contains a `%T'.")
13542 (defun org-format-agenda-item (extra txt &optional category tags dotime
13543 noprefix)
13544 "Format TXT to be inserted into the agenda buffer.
13545 In particular, it adds the prefix and corresponding text properties. EXTRA
13546 must be a string and replaces the `%s' specifier in the prefix format.
13547 CATEGORY (string, symbol or nil) may be used to overrule the default
13548 category taken from local variable or file name. It will replace the `%c'
13549 specifier in the format. DOTIME, when non-nil, indicates that a
13550 time-of-day should be extracted from TXT for sorting of this entry, and for
13551 the `%t' specifier in the format. When DOTIME is a string, this string is
13552 searched for a time before TXT is. NOPREFIX is a flag and indicates that
13553 only the correctly processes TXT should be returned - this is used by
13554 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
13555 (save-match-data
13556 ;; Diary entries sometimes have extra whitespace at the beginning
13557 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
13558 (let* ((category (or category
13559 org-category
13560 (if buffer-file-name
13561 (file-name-sans-extension
13562 (file-name-nondirectory buffer-file-name))
13563 "")))
13564 (tag (if tags (nth (1- (length tags)) tags) ""))
13565 time ;; needed for the eval of the prefix format
13566 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
13567 (time-of-day (and dotime (org-get-time-of-day ts)))
13568 stamp plain s0 s1 s2 rtn)
13569 (when (and dotime time-of-day org-prefix-has-time)
13570 ;; Extract starting and ending time and move them to prefix
13571 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
13572 (setq plain (string-match org-plain-time-of-day-regexp ts)))
13573 (setq s0 (match-string 0 ts)
13574 s1 (match-string (if plain 1 2) ts)
13575 s2 (match-string (if plain 8 4) ts))
13577 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
13578 ;; them, we might want to remove them there to avoid duplication.
13579 ;; The user can turn this off with a variable.
13580 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
13581 (string-match (concat (regexp-quote s0) " *") txt)
13582 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
13583 (= (match-beginning 0) 0)
13585 (setq txt (replace-match "" nil nil txt))))
13586 ;; Normalize the time(s) to 24 hour
13587 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
13588 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
13590 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
13591 ;; Tags are in the string
13592 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
13593 (and org-agenda-remove-tags-when-in-prefix
13594 org-prefix-has-tag))
13595 (setq txt (replace-match "" t t txt))
13596 (setq txt (replace-match
13597 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
13598 (match-string 2 txt))
13599 t t txt))))
13601 ;; Create the final string
13602 (if noprefix
13603 (setq rtn txt)
13604 ;; Prepare the variables needed in the eval of the compiled format
13605 (setq time (cond (s2 (concat s1 "-" s2))
13606 (s1 (concat s1 "......"))
13607 (t ""))
13608 extra (or extra "")
13609 category (if (symbolp category) (symbol-name category) category))
13610 ;; Evaluate the compiled format
13611 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
13613 ;; And finally add the text properties
13614 (org-add-props rtn nil
13615 'category (downcase category) 'tags tags
13616 'prefix-length (- (length rtn) (length txt))
13617 'time-of-day time-of-day
13618 'dotime dotime))))
13620 (defvar org-agenda-sorting-strategy)
13621 (defvar org-agenda-sorting-strategy-selected nil)
13623 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
13624 (catch 'exit
13625 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
13626 ((and todayp (member 'today (car org-agenda-time-grid))))
13627 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
13628 ((member 'weekly (car org-agenda-time-grid)))
13629 (t (throw 'exit list)))
13630 (let* ((have (delq nil (mapcar
13631 (lambda (x) (get-text-property 1 'time-of-day x))
13632 list)))
13633 (string (nth 1 org-agenda-time-grid))
13634 (gridtimes (nth 2 org-agenda-time-grid))
13635 (req (car org-agenda-time-grid))
13636 (remove (member 'remove-match req))
13637 new time)
13638 (if (and (member 'require-timed req) (not have))
13639 ;; don't show empty grid
13640 (throw 'exit list))
13641 (while (setq time (pop gridtimes))
13642 (unless (and remove (member time have))
13643 (setq time (int-to-string time))
13644 (push (org-format-agenda-item
13645 nil string "" nil
13646 (concat (substring time 0 -2) ":" (substring time -2)))
13647 new)
13648 (put-text-property
13649 1 (length (car new)) 'face 'org-time-grid (car new))))
13650 (if (member 'time-up org-agenda-sorting-strategy-selected)
13651 (append new list)
13652 (append list new)))))
13654 (defun org-compile-prefix-format (key)
13655 "Compile the prefix format into a Lisp form that can be evaluated.
13656 The resulting form is returned and stored in the variable
13657 `org-prefix-format-compiled'."
13658 (setq org-prefix-has-time nil org-prefix-has-tag nil)
13659 (let ((s (cond
13660 ((stringp org-agenda-prefix-format)
13661 org-agenda-prefix-format)
13662 ((assq key org-agenda-prefix-format)
13663 (cdr (assq key org-agenda-prefix-format)))
13664 (t " %-12:c%?-12t% s")))
13665 (start 0)
13666 varform vars var e c f opt)
13667 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
13668 s start)
13669 (setq var (cdr (assoc (match-string 4 s)
13670 '(("c" . category) ("t" . time) ("s" . extra)
13671 ("T" . tag))))
13672 c (or (match-string 3 s) "")
13673 opt (match-beginning 1)
13674 start (1+ (match-beginning 0)))
13675 (if (equal var 'time) (setq org-prefix-has-time t))
13676 (if (equal var 'tag) (setq org-prefix-has-tag t))
13677 (setq f (concat "%" (match-string 2 s) "s"))
13678 (if opt
13679 (setq varform
13680 `(if (equal "" ,var)
13682 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
13683 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
13684 (setq s (replace-match "%s" t nil s))
13685 (push varform vars))
13686 (setq vars (nreverse vars))
13687 (setq org-prefix-format-compiled `(format ,s ,@vars))))
13689 (defun org-set-sorting-strategy (key)
13690 (if (symbolp (car org-agenda-sorting-strategy))
13691 ;; the old format
13692 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
13693 (setq org-agenda-sorting-strategy-selected
13694 (or (cdr (assq key org-agenda-sorting-strategy))
13695 (cdr (assq 'agenda org-agenda-sorting-strategy))
13696 '(time-up category-keep priority-down)))))
13698 (defun org-get-time-of-day (s &optional string mod24)
13699 "Check string S for a time of day.
13700 If found, return it as a military time number between 0 and 2400.
13701 If not found, return nil.
13702 The optional STRING argument forces conversion into a 5 character wide string
13703 HH:MM."
13704 (save-match-data
13705 (when
13707 (string-match
13708 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
13709 (string-match
13710 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
13711 (let* ((h (string-to-number (match-string 1 s)))
13712 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
13713 (ampm (if (match-end 4) (downcase (match-string 4 s))))
13714 (am-p (equal ampm "am"))
13715 (h1 (cond ((not ampm) h)
13716 ((= h 12) (if am-p 0 12))
13717 (t (+ h (if am-p 0 12)))))
13718 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
13719 (mod h1 24) h1))
13720 (t0 (+ (* 100 h2) m))
13721 (t1 (concat (if (>= h1 24) "+" " ")
13722 (if (< t0 100) "0" "")
13723 (if (< t0 10) "0" "")
13724 (int-to-string t0))))
13725 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
13727 (defun org-finalize-agenda-entries (list &optional nosort)
13728 "Sort and concatenate the agenda items."
13729 (setq list (mapcar 'org-agenda-highlight-todo list))
13730 (if nosort
13731 list
13732 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
13734 (defun org-agenda-highlight-todo (x)
13735 (let (re pl)
13736 (if (eq x 'line)
13737 (save-excursion
13738 (beginning-of-line 1)
13739 (setq re (get-text-property (point) 'org-not-done-regexp))
13740 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
13741 (and (looking-at (concat "[ \t]*\\.*" re))
13742 (add-text-properties (match-beginning 0) (match-end 0)
13743 '(face org-todo))))
13744 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
13745 pl (get-text-property 0 'prefix-length x))
13746 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
13747 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
13748 '(face org-todo) x))
13749 x)))
13751 (defsubst org-cmp-priority (a b)
13752 "Compare the priorities of string A and B."
13753 (let ((pa (or (get-text-property 1 'priority a) 0))
13754 (pb (or (get-text-property 1 'priority b) 0)))
13755 (cond ((> pa pb) +1)
13756 ((< pa pb) -1)
13757 (t nil))))
13759 (defsubst org-cmp-category (a b)
13760 "Compare the string values of categories of strings A and B."
13761 (let ((ca (or (get-text-property 1 'category a) ""))
13762 (cb (or (get-text-property 1 'category b) "")))
13763 (cond ((string-lessp ca cb) -1)
13764 ((string-lessp cb ca) +1)
13765 (t nil))))
13767 (defsubst org-cmp-tag (a b)
13768 "Compare the string values of categories of strings A and B."
13769 (let ((ta (car (last (get-text-property 1 'tags a))))
13770 (tb (car (last (get-text-property 1 'tags b)))))
13771 (cond ((not ta) +1)
13772 ((not tb) -1)
13773 ((string-lessp ta tb) -1)
13774 ((string-lessp tb ta) +1)
13775 (t nil))))
13777 (defsubst org-cmp-time (a b)
13778 "Compare the time-of-day values of strings A and B."
13779 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
13780 (ta (or (get-text-property 1 'time-of-day a) def))
13781 (tb (or (get-text-property 1 'time-of-day b) def)))
13782 (cond ((< ta tb) -1)
13783 ((< tb ta) +1)
13784 (t nil))))
13786 (defun org-entries-lessp (a b)
13787 "Predicate for sorting agenda entries."
13788 ;; The following variables will be used when the form is evaluated.
13789 (let* ((time-up (org-cmp-time a b))
13790 (time-down (if time-up (- time-up) nil))
13791 (priority-up (org-cmp-priority a b))
13792 (priority-down (if priority-up (- priority-up) nil))
13793 (category-up (org-cmp-category a b))
13794 (category-down (if category-up (- category-up) nil))
13795 (category-keep (if category-up +1 nil))
13796 (tag-up (org-cmp-tag a b))
13797 (tag-down (if tag-up (- tag-up) nil)))
13798 (cdr (assoc
13799 (eval (cons 'or org-agenda-sorting-strategy-selected))
13800 '((-1 . t) (1 . nil) (nil . nil))))))
13802 ;;; Agenda commands
13804 (defun org-agenda-check-type (error &rest types)
13805 "Check if agenda buffer is of allowed type.
13806 If ERROR is non-nil, throw an error, otherwise just return nil."
13807 (if (memq org-agenda-type types)
13809 (if error
13810 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
13811 nil)))
13813 (defun org-agenda-quit ()
13814 "Exit agenda by removing the window or the buffer."
13815 (interactive)
13816 (let ((buf (current-buffer)))
13817 (if (not (one-window-p)) (delete-window))
13818 (kill-buffer buf)
13819 (org-agenda-maybe-reset-markers 'force))
13820 ;; Maybe restore the pre-agenda window configuration.
13821 (and org-agenda-restore-windows-after-quit
13822 (not (eq org-agenda-window-setup 'other-frame))
13823 org-pre-agenda-window-conf
13824 (set-window-configuration org-pre-agenda-window-conf)))
13826 (defun org-agenda-exit ()
13827 "Exit agenda by removing the window or the buffer.
13828 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
13829 Org-mode buffers visited directly by the user will not be touched."
13830 (interactive)
13831 (org-release-buffers org-agenda-new-buffers)
13832 (setq org-agenda-new-buffers nil)
13833 (org-agenda-quit))
13835 (defun org-save-all-org-buffers ()
13836 "Save all Org-mode buffers without user confirmation."
13837 (interactive)
13838 (message "Saving all Org-mode buffers...")
13839 (save-some-buffers t 'org-mode-p)
13840 (message "Saving all Org-mode buffers... done"))
13842 (defun org-agenda-redo ()
13843 "Rebuild Agenda.
13844 When this is the global TODO list, a prefix argument will be interpreted."
13845 (interactive)
13846 (let* ((org-agenda-keep-modes t)
13847 (line (org-current-line))
13848 (window-line (- line (org-current-line (window-start)))))
13849 (message "Rebuilding agenda buffer...")
13850 (eval org-agenda-redo-command)
13851 (setq org-agenda-undo-list nil
13852 org-agenda-pending-undo-list nil)
13853 (message "Rebuilding agenda buffer...done")
13854 (goto-line line)
13855 (recenter window-line)))
13857 (defun org-agenda-goto-today ()
13858 "Go to today."
13859 (interactive)
13860 (org-agenda-check-type t 'timeline 'agenda)
13861 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
13862 (cond
13863 (tdpos (goto-char tdpos))
13864 ((eq org-agenda-type 'agenda)
13865 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
13866 (setf (nth 1 org-agenda-overriding-arguments) nil)
13867 (org-agenda-redo)
13868 (org-agenda-find-today-or-agenda)))
13869 (t (error "Cannot find today")))))
13871 (defun org-agenda-find-today-or-agenda ()
13872 (goto-char
13873 (or (text-property-any (point-min) (point-max) 'org-today t)
13874 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
13875 (point-min))))
13877 (defun org-agenda-later (arg)
13878 "Go forward in time by `org-agenda-ndays' days.
13879 With prefix ARG, go forward that many times `org-agenda-ndays'."
13880 (interactive "p")
13881 (org-agenda-check-type t 'agenda)
13882 (let ((org-agenda-overriding-arguments
13883 (list (car org-agenda-last-arguments)
13884 (+ org-starting-day (* arg org-agenda-ndays))
13885 nil t)))
13886 (org-agenda-redo)
13887 (org-agenda-find-today-or-agenda)))
13889 (defun org-agenda-earlier (arg)
13890 "Go back in time by `org-agenda-ndays' days.
13891 With prefix ARG, go back that many times `org-agenda-ndays'."
13892 (interactive "p")
13893 (org-agenda-check-type t 'agenda)
13894 (let ((org-agenda-overriding-arguments
13895 (list (car org-agenda-last-arguments)
13896 (- org-starting-day (* arg org-agenda-ndays))
13897 nil t)))
13898 (org-agenda-redo)
13899 (org-agenda-find-today-or-agenda)))
13901 (defun org-agenda-week-view ()
13902 "Switch to weekly view for agenda."
13903 (interactive)
13904 (org-agenda-check-type t 'agenda)
13905 (if (= org-agenda-ndays 7)
13906 (error "This is already the week view"))
13907 (setq org-agenda-ndays 7)
13908 (let ((org-agenda-overriding-arguments
13909 (list (car org-agenda-last-arguments)
13910 (or (get-text-property (point) 'day)
13911 org-starting-day)
13912 nil t)))
13913 (org-agenda-redo)
13914 (org-agenda-find-today-or-agenda))
13915 (org-agenda-set-mode-name)
13916 (message "Switched to week view"))
13918 (defun org-agenda-day-view ()
13919 "Switch to daily view for agenda."
13920 (interactive)
13921 (org-agenda-check-type t 'agenda)
13922 (if (= org-agenda-ndays 1)
13923 (error "This is already the day view"))
13924 (setq org-agenda-ndays 1)
13925 (let ((org-agenda-overriding-arguments
13926 (list (car org-agenda-last-arguments)
13927 (or (get-text-property (point) 'day)
13928 org-starting-day)
13929 nil t)))
13930 (org-agenda-redo)
13931 (org-agenda-find-today-or-agenda))
13932 (org-agenda-set-mode-name)
13933 (message "Switched to day view"))
13935 (defun org-agenda-next-date-line (&optional arg)
13936 "Jump to the next line indicating a date in agenda buffer."
13937 (interactive "p")
13938 (org-agenda-check-type t 'agenda 'timeline)
13939 (beginning-of-line 1)
13940 (if (looking-at "^\\S-") (forward-char 1))
13941 (if (not (re-search-forward "^\\S-" nil t arg))
13942 (progn
13943 (backward-char 1)
13944 (error "No next date after this line in this buffer")))
13945 (goto-char (match-beginning 0)))
13947 (defun org-agenda-previous-date-line (&optional arg)
13948 "Jump to the previous line indicating a date in agenda buffer."
13949 (interactive "p")
13950 (org-agenda-check-type t 'agenda 'timeline)
13951 (beginning-of-line 1)
13952 (if (not (re-search-backward "^\\S-" nil t arg))
13953 (error "No previous date before this line in this buffer")))
13955 ;; Initialize the highlight
13956 (defvar org-hl (org-make-overlay 1 1))
13957 (org-overlay-put org-hl 'face 'highlight)
13959 (defun org-highlight (begin end &optional buffer)
13960 "Highlight a region with overlay."
13961 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
13962 org-hl begin end (or buffer (current-buffer))))
13964 (defun org-unhighlight ()
13965 "Detach overlay INDEX."
13966 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
13969 (defun org-agenda-follow-mode ()
13970 "Toggle follow mode in an agenda buffer."
13971 (interactive)
13972 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
13973 (org-agenda-set-mode-name)
13974 (message "Follow mode is %s"
13975 (if org-agenda-follow-mode "on" "off")))
13977 (defun org-agenda-log-mode ()
13978 "Toggle log mode in an agenda buffer."
13979 (interactive)
13980 (org-agenda-check-type t 'agenda 'timeline)
13981 (setq org-agenda-show-log (not org-agenda-show-log))
13982 (org-agenda-set-mode-name)
13983 (org-agenda-redo)
13984 (message "Log mode is %s"
13985 (if org-agenda-show-log "on" "off")))
13987 (defun org-agenda-toggle-diary ()
13988 "Toggle diary inclusion in an agenda buffer."
13989 (interactive)
13990 (org-agenda-check-type t 'agenda)
13991 (setq org-agenda-include-diary (not org-agenda-include-diary))
13992 (org-agenda-redo)
13993 (org-agenda-set-mode-name)
13994 (message "Diary inclusion turned %s"
13995 (if org-agenda-include-diary "on" "off")))
13997 (defun org-agenda-toggle-time-grid ()
13998 "Toggle time grid in an agenda buffer."
13999 (interactive)
14000 (org-agenda-check-type t 'agenda)
14001 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
14002 (org-agenda-redo)
14003 (org-agenda-set-mode-name)
14004 (message "Time-grid turned %s"
14005 (if org-agenda-use-time-grid "on" "off")))
14007 (defun org-agenda-set-mode-name ()
14008 "Set the mode name to indicate all the small mode settings."
14009 (setq mode-name
14010 (concat "Org-Agenda"
14011 (if (equal org-agenda-ndays 1) " Day" "")
14012 (if (equal org-agenda-ndays 7) " Week" "")
14013 (if org-agenda-follow-mode " Follow" "")
14014 (if org-agenda-include-diary " Diary" "")
14015 (if org-agenda-use-time-grid " Grid" "")
14016 (if org-agenda-show-log " Log" "")))
14017 (force-mode-line-update))
14019 (defun org-agenda-post-command-hook ()
14020 (and (eolp) (not (bolp)) (backward-char 1))
14021 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
14022 (if (and org-agenda-follow-mode
14023 (get-text-property (point) 'org-marker))
14024 (org-agenda-show)))
14026 (defun org-agenda-show-priority ()
14027 "Show the priority of the current item.
14028 This priority is composed of the main priority given with the [#A] cookies,
14029 and by additional input from the age of a schedules or deadline entry."
14030 (interactive)
14031 (let* ((pri (get-text-property (point-at-bol) 'priority)))
14032 (message "Priority is %d" (if pri pri -1000))))
14034 (defun org-agenda-show-tags ()
14035 "Show the tags applicable to the current item."
14036 (interactive)
14037 (let* ((tags (get-text-property (point-at-bol) 'tags)))
14038 (if tags
14039 (message "Tags are :%s:"
14040 (org-no-properties (mapconcat 'identity tags ":")))
14041 (message "No tags associated with this line"))))
14043 (defun org-agenda-goto (&optional highlight)
14044 "Go to the Org-mode file which contains the item at point."
14045 (interactive)
14046 (let* ((marker (or (get-text-property (point) 'org-marker)
14047 (org-agenda-error)))
14048 (buffer (marker-buffer marker))
14049 (pos (marker-position marker)))
14050 (switch-to-buffer-other-window buffer)
14051 (widen)
14052 (goto-char pos)
14053 (when (org-mode-p)
14054 (org-show-context 'agenda)
14055 (save-excursion
14056 (and (outline-next-heading)
14057 (org-flag-heading nil)))) ; show the next heading
14058 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
14060 (defun org-agenda-kill ()
14061 "Kill the entry or subtree belonging to the current agenda entry."
14062 (interactive)
14063 (let* ((marker (or (get-text-property (point) 'org-marker)
14064 (org-agenda-error)))
14065 (hdmarker (get-text-property (point) 'org-hd-marker))
14066 (buffer (marker-buffer marker))
14067 (pos (marker-position marker))
14068 dbeg dend (n 0) conf)
14069 (org-with-remote-undo buffer
14070 (with-current-buffer buffer
14071 (save-excursion
14072 (goto-char pos)
14073 (if (org-mode-p)
14074 (setq dbeg (progn (org-back-to-heading t) (point))
14075 dend (org-end-of-subtree t))
14076 (setq dbeg (point-at-bol)
14077 dend (min (point-max) (1+ (point-at-eol)))))
14078 (goto-char dbeg)
14079 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
14080 (setq conf (or (eq t org-agenda-confirm-kill)
14081 (and (numberp org-agenda-confirm-kill)
14082 (> n org-agenda-confirm-kill))))
14083 (and conf
14084 (not (y-or-n-p
14085 (format "Delete entry with %d lines in buffer \"%s\"? "
14086 n (buffer-name buffer))))
14087 (error "Abort"))
14088 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
14089 (with-current-buffer buffer (delete-region dbeg dend))
14090 (message "Agenda item and source killed"))))
14092 (defun org-agenda-archive ()
14093 "Kill the entry or subtree belonging to the current agenda entry."
14094 (interactive)
14095 (let* ((marker (or (get-text-property (point) 'org-marker)
14096 (org-agenda-error)))
14097 (hdmarker (get-text-property (point) 'org-hd-marker))
14098 (buffer (marker-buffer marker))
14099 (pos (marker-position marker))
14100 dbeg dend txt n conf)
14101 (org-with-remote-undo buffer
14102 (with-current-buffer buffer
14103 (if (org-mode-p)
14104 (save-excursion
14105 (goto-char pos)
14106 (org-remove-subtree-entries-from-agenda)
14107 (org-back-to-heading t)
14108 (org-archive-subtree))
14109 (error "Archiving works only in Org-mode files"))))))
14111 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
14112 "Remove all lines in the agenda that correspond to a given subtree.
14113 The subtree is the one in buffer BUF, starting at BEG and ending at END.
14114 If this information is not given, the function uses the tree at point."
14115 (let ((buf (or buf (current-buffer))) m p)
14116 (save-excursion
14117 (unless (and beg end)
14118 (org-back-to-heading t)
14119 (setq beg (point))
14120 (org-end-of-subtree t)
14121 (setq end (point)))
14122 (set-buffer (get-buffer org-agenda-buffer-name))
14123 (save-excursion
14124 (goto-char (point-max))
14125 (beginning-of-line 1)
14126 (while (not (bobp))
14127 (when (and (setq m (get-text-property (point) 'org-marker))
14128 (equal buf (marker-buffer m))
14129 (setq p (marker-position m))
14130 (>= p beg)
14131 (<= p end))
14132 (let (buffer-read-only)
14133 (delete-region (point-at-bol) (1+ (point-at-eol)))))
14134 (beginning-of-line 0))))))
14136 (defun org-agenda-open-link ()
14137 "Follow the link in the current line, if any."
14138 (interactive)
14139 (let ((eol (point-at-eol)))
14140 (save-excursion
14141 (if (or (re-search-forward org-bracket-link-regexp eol t)
14142 (re-search-forward org-angle-link-re eol t)
14143 (re-search-forward org-plain-link-re eol t))
14144 (call-interactively 'org-open-at-point)
14145 (error "No link in current line")))))
14147 (defun org-agenda-switch-to (&optional delete-other-windows)
14148 "Go to the Org-mode file which contains the item at point."
14149 (interactive)
14150 (let* ((marker (or (get-text-property (point) 'org-marker)
14151 (org-agenda-error)))
14152 (buffer (marker-buffer marker))
14153 (pos (marker-position marker)))
14154 (switch-to-buffer buffer)
14155 (and delete-other-windows (delete-other-windows))
14156 (widen)
14157 (goto-char pos)
14158 (when (org-mode-p)
14159 (org-show-context 'agenda)
14160 (save-excursion
14161 (and (outline-next-heading)
14162 (org-flag-heading nil)))))) ; show the next heading
14164 (defun org-agenda-goto-mouse (ev)
14165 "Go to the Org-mode file which contains the item at the mouse click."
14166 (interactive "e")
14167 (mouse-set-point ev)
14168 (org-agenda-goto))
14170 (defun org-agenda-show ()
14171 "Display the Org-mode file which contains the item at point."
14172 (interactive)
14173 (let ((win (selected-window)))
14174 (org-agenda-goto t)
14175 (select-window win)))
14177 (defun org-agenda-recenter (arg)
14178 "Display the Org-mode file which contains the item at point and recenter."
14179 (interactive "P")
14180 (let ((win (selected-window)))
14181 (org-agenda-goto t)
14182 (recenter arg)
14183 (select-window win)))
14185 (defun org-agenda-show-mouse (ev)
14186 "Display the Org-mode file which contains the item at the mouse click."
14187 (interactive "e")
14188 (mouse-set-point ev)
14189 (org-agenda-show))
14191 (defun org-agenda-check-no-diary ()
14192 "Check if the entry is a diary link and abort if yes."
14193 (if (get-text-property (point) 'org-agenda-diary-link)
14194 (org-agenda-error)))
14196 (defun org-agenda-error ()
14197 (error "Command not allowed in this line"))
14199 (defun org-agenda-tree-to-indirect-buffer ()
14200 "Show the subtree corresponding to the current entry in an indirect buffer.
14201 This calls the command `org-tree-to-indirect-buffer' from the original
14202 Org-mode buffer.
14203 With numerical prefix arg ARG, go up to this level and then take that tree.
14204 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
14205 dedicated frame)."
14206 (interactive)
14207 (org-agenda-check-no-diary)
14208 (let* ((marker (or (get-text-property (point) 'org-marker)
14209 (org-agenda-error)))
14210 (buffer (marker-buffer marker))
14211 (pos (marker-position marker)))
14212 (with-current-buffer buffer
14213 (save-excursion
14214 (goto-char pos)
14215 (call-interactively 'org-tree-to-indirect-buffer)))))
14217 (defvar org-last-heading-marker (make-marker)
14218 "Marker pointing to the headline that last changed its TODO state
14219 by a remote command from the agenda.")
14221 (defun org-agenda-todo (&optional arg)
14222 "Cycle TODO state of line at point, also in Org-mode file.
14223 This changes the line at point, all other lines in the agenda referring to
14224 the same tree node, and the headline of the tree node in the Org-mode file."
14225 (interactive "P")
14226 (org-agenda-check-no-diary)
14227 (let* ((col (current-column))
14228 (marker (or (get-text-property (point) 'org-marker)
14229 (org-agenda-error)))
14230 (buffer (marker-buffer marker))
14231 (pos (marker-position marker))
14232 (hdmarker (get-text-property (point) 'org-hd-marker))
14233 (buffer-read-only nil)
14234 newhead)
14235 (org-with-remote-undo buffer
14236 (with-current-buffer buffer
14237 (widen)
14238 (goto-char pos)
14239 (org-show-context 'agenda)
14240 (save-excursion
14241 (and (outline-next-heading)
14242 (org-flag-heading nil))) ; show the next heading
14243 (org-todo arg)
14244 (and (bolp) (forward-char 1))
14245 (setq newhead (org-get-heading))
14246 (save-excursion
14247 (org-back-to-heading)
14248 (move-marker org-last-heading-marker (point))))
14249 (beginning-of-line 1)
14250 (save-excursion
14251 (org-agenda-change-all-lines newhead hdmarker 'fixface))
14252 (move-to-column col))))
14254 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
14255 "Change all lines in the agenda buffer which match HDMARKER.
14256 The new content of the line will be NEWHEAD (as modified by
14257 `org-format-agenda-item'). HDMARKER is checked with
14258 `equal' against all `org-hd-marker' text properties in the file.
14259 If FIXFACE is non-nil, the face of each item is modified acording to
14260 the new TODO state."
14261 (let* ((buffer-read-only nil)
14262 props m pl undone-face done-face finish new dotime cat tags)
14263 (save-excursion
14264 (goto-char (point-max))
14265 (beginning-of-line 1)
14266 (while (not finish)
14267 (setq finish (bobp))
14268 (when (and (setq m (get-text-property (point) 'org-hd-marker))
14269 (equal m hdmarker))
14270 (setq props (text-properties-at (point))
14271 dotime (get-text-property (point) 'dotime)
14272 cat (get-text-property (point) 'category)
14273 tags (get-text-property (point) 'tags)
14274 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
14275 pl (get-text-property (point) 'prefix-length)
14276 undone-face (get-text-property (point) 'undone-face)
14277 done-face (get-text-property (point) 'done-face))
14278 (move-to-column pl)
14279 (cond
14280 ((equal new "")
14281 (beginning-of-line 1)
14282 (and (looking-at ".*\n?") (replace-match "")))
14283 ((looking-at ".*")
14284 (replace-match new t t)
14285 (beginning-of-line 1)
14286 (add-text-properties (point-at-bol) (point-at-eol) props)
14287 (when fixface
14288 (add-text-properties
14289 (point-at-bol) (point-at-eol)
14290 (list 'face
14291 (if org-last-todo-state-is-todo
14292 undone-face done-face))))
14293 (org-agenda-highlight-todo 'line)
14294 (beginning-of-line 1))
14295 (t (error "Line update did not work"))))
14296 (beginning-of-line 0)))
14297 (org-finalize-agenda)))
14299 (defun org-agenda-align-tags (&optional line)
14300 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
14301 (let ((buffer-read-only))
14302 (save-excursion
14303 (goto-char (if line (point-at-bol) (point-min)))
14304 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
14305 (if line (point-at-eol) nil) t)
14306 (delete-region (match-beginning 1) (match-end 1))
14307 (goto-char (match-beginning 1))
14308 (insert (org-add-props
14309 (make-string (max 1 (- org-agenda-align-tags-to-column
14310 (current-column))) ?\ )
14311 (text-properties-at (point))))))))
14313 (defun org-agenda-priority-up ()
14314 "Increase the priority of line at point, also in Org-mode file."
14315 (interactive)
14316 (org-agenda-priority 'up))
14318 (defun org-agenda-priority-down ()
14319 "Decrease the priority of line at point, also in Org-mode file."
14320 (interactive)
14321 (org-agenda-priority 'down))
14323 (defun org-agenda-priority (&optional force-direction)
14324 "Set the priority of line at point, also in Org-mode file.
14325 This changes the line at point, all other lines in the agenda referring to
14326 the same tree node, and the headline of the tree node in the Org-mode file."
14327 (interactive)
14328 (org-agenda-check-no-diary)
14329 (let* ((marker (or (get-text-property (point) 'org-marker)
14330 (org-agenda-error)))
14331 (buffer (marker-buffer marker))
14332 (pos (marker-position marker))
14333 (hdmarker (get-text-property (point) 'org-hd-marker))
14334 (buffer-read-only nil)
14335 newhead)
14336 (org-with-remote-undo buffer
14337 (with-current-buffer buffer
14338 (widen)
14339 (goto-char pos)
14340 (org-show-context 'agenda)
14341 (save-excursion
14342 (and (outline-next-heading)
14343 (org-flag-heading nil))) ; show the next heading
14344 (funcall 'org-priority force-direction)
14345 (end-of-line 1)
14346 (setq newhead (org-get-heading)))
14347 (org-agenda-change-all-lines newhead hdmarker)
14348 (beginning-of-line 1))))
14350 (defun org-get-tags-at (&optional pos)
14351 "Get a list of all headline tags applicable at POS.
14352 POS defaults to point. If tags are inherited, the list contains
14353 the targets in the same sequence as the headlines appear, i.e.
14354 the tags of the current headline come last."
14355 (interactive)
14356 (let (tags)
14357 (save-excursion
14358 (goto-char (or pos (point)))
14359 (save-match-data
14360 (org-back-to-heading t)
14361 (condition-case nil
14362 (while t
14363 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
14364 (setq tags (append (org-split-string
14365 (org-match-string-no-properties 1) ":")
14366 tags)))
14367 (or org-use-tag-inheritance (error ""))
14368 (org-up-heading-all 1))
14369 (error nil))))
14370 tags))
14372 ;; FIXME: should fix the tags property of the agenda line.
14373 (defun org-agenda-set-tags ()
14374 "Set tags for the current headline."
14375 (interactive)
14376 (org-agenda-check-no-diary)
14377 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
14378 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
14379 (org-agenda-error)))
14380 (buffer (marker-buffer hdmarker))
14381 (pos (marker-position hdmarker))
14382 (buffer-read-only nil)
14383 newhead)
14384 (org-with-remote-undo buffer
14385 (with-current-buffer buffer
14386 (widen)
14387 (goto-char pos)
14388 (org-show-context 'agenda)
14389 (save-excursion
14390 (and (outline-next-heading)
14391 (org-flag-heading nil))) ; show the next heading
14392 (call-interactively 'org-set-tags)
14393 (end-of-line 1)
14394 (setq newhead (org-get-heading)))
14395 (org-agenda-change-all-lines newhead hdmarker)
14396 (beginning-of-line 1))))
14398 (defun org-agenda-toggle-archive-tag ()
14399 "Toggle the archive tag for the current entry."
14400 (interactive)
14401 (org-agenda-check-no-diary)
14402 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
14403 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
14404 (org-agenda-error)))
14405 (buffer (marker-buffer hdmarker))
14406 (pos (marker-position hdmarker))
14407 (buffer-read-only nil)
14408 newhead)
14409 (org-with-remote-undo buffer
14410 (with-current-buffer buffer
14411 (widen)
14412 (goto-char pos)
14413 (org-show-context 'agenda)
14414 (save-excursion
14415 (and (outline-next-heading)
14416 (org-flag-heading nil))) ; show the next heading
14417 (call-interactively 'org-toggle-archive-tag)
14418 (end-of-line 1)
14419 (setq newhead (org-get-heading)))
14420 (org-agenda-change-all-lines newhead hdmarker)
14421 (beginning-of-line 1))))
14423 (defun org-agenda-date-later (arg &optional what)
14424 "Change the date of this item to one day later."
14425 (interactive "p")
14426 (org-agenda-check-type t 'agenda 'timeline)
14427 (org-agenda-check-no-diary)
14428 (let* ((marker (or (get-text-property (point) 'org-marker)
14429 (org-agenda-error)))
14430 (buffer (marker-buffer marker))
14431 (pos (marker-position marker)))
14432 (org-with-remote-undo buffer
14433 (with-current-buffer buffer
14434 (widen)
14435 (goto-char pos)
14436 (if (not (org-at-timestamp-p))
14437 (error "Cannot find time stamp"))
14438 (org-timestamp-change arg (or what 'day)))
14439 (org-agenda-show-new-time marker org-last-changed-timestamp))
14440 (message "Time stamp changed to %s" org-last-changed-timestamp)))
14442 (defun org-agenda-date-earlier (arg &optional what)
14443 "Change the date of this item to one day earlier."
14444 (interactive "p")
14445 (org-agenda-date-later (- arg) what))
14447 (defun org-agenda-show-new-time (marker stamp)
14448 "Show new date stamp via text properties."
14449 ;; We use text properties to make this undoable
14450 (let ((buffer-read-only nil)
14451 ovs ov)
14452 (setq stamp (concat " => " stamp))
14453 (save-excursion
14454 (goto-char (point-max))
14455 (while (not (bobp))
14456 (when (equal marker (get-text-property (point) 'org-marker))
14457 (move-to-column (- (window-width) (length stamp)) t)
14458 (if (featurep 'xemacs)
14459 ;; Use `duplicable' property to trigger undo recording
14460 (let ((ex (make-extent nil nil))
14461 (gl (make-glyph stamp)))
14462 (set-glyph-face gl 'secondary-selection)
14463 (set-extent-properties
14464 ex (list 'invisible t 'end-glyph gl 'duplicable t))
14465 (insert-extent ex (1- (point)) (point-at-eol)))
14466 (add-text-properties
14467 (1- (point)) (point-at-eol)
14468 (list 'display (org-add-props stamp nil
14469 'face 'secondary-selection))))
14470 (beginning-of-line 1))
14471 (beginning-of-line 0)))))
14473 (defun org-agenda-date-prompt (arg)
14474 "Change the date of this item. Date is prompted for, with default today.
14475 The prefix ARG is passed to the `org-time-stamp' command and can therefore
14476 be used to request time specification in the time stamp."
14477 (interactive "P")
14478 (org-agenda-check-type t 'agenda 'timeline)
14479 (org-agenda-check-no-diary)
14480 (let* ((marker (or (get-text-property (point) 'org-marker)
14481 (org-agenda-error)))
14482 (buffer (marker-buffer marker))
14483 (pos (marker-position marker)))
14484 (org-with-remote-undo buffer
14485 (with-current-buffer buffer
14486 (widen)
14487 (goto-char pos)
14488 (if (not (org-at-timestamp-p))
14489 (error "Cannot find time stamp"))
14490 (org-time-stamp arg)
14491 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
14493 (defun org-agenda-schedule (arg)
14494 "Schedule the item at point."
14495 (interactive "P")
14496 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
14497 (org-agenda-check-no-diary)
14498 (let* ((marker (or (get-text-property (point) 'org-marker)
14499 (org-agenda-error)))
14500 (buffer (marker-buffer marker))
14501 (pos (marker-position marker))
14502 (org-insert-labeled-timestamps-at-point nil)
14504 (org-with-remote-undo buffer
14505 (with-current-buffer buffer
14506 (widen)
14507 (goto-char pos)
14508 (setq ts (org-schedule))
14509 (message "Item scheduled for %s" ts)))))
14511 (defun org-agenda-deadline (arg)
14512 "Schedule the item at point."
14513 (interactive "P")
14514 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
14515 (org-agenda-check-no-diary)
14516 (let* ((marker (or (get-text-property (point) 'org-marker)
14517 (org-agenda-error)))
14518 (buffer (marker-buffer marker))
14519 (pos (marker-position marker))
14520 (org-insert-labeled-timestamps-at-point nil)
14522 (org-with-remote-undo buffer
14523 (with-current-buffer buffer
14524 (widen)
14525 (goto-char pos)
14526 (setq ts (org-deadline))
14527 (message "Deadline for this item set to %s" ts)))))
14529 (defun org-get-heading ()
14530 "Return the heading of the current entry, without the stars."
14531 (save-excursion
14532 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
14533 (if (and (re-search-backward "[\r\n]\\*" nil t)
14534 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
14535 (match-string 1)
14536 "")))
14538 (defun org-agenda-clock-in (&optional arg)
14539 "Start the clock on the currently selected item."
14540 (interactive "P")
14541 (org-agenda-check-no-diary)
14542 (let* ((marker (or (get-text-property (point) 'org-marker)
14543 (org-agenda-error)))
14544 (pos (marker-position marker)))
14545 (org-with-remote-undo (marker-buffer marker)
14546 (with-current-buffer (marker-buffer marker)
14547 (widen)
14548 (goto-char pos)
14549 (org-clock-in)))))
14551 (defun org-agenda-clock-out (&optional arg)
14552 "Stop the currently running clock."
14553 (interactive "P")
14554 (unless (marker-buffer org-clock-marker)
14555 (error "No running clock"))
14556 (org-with-remote-undo (marker-buffer org-clock-marker)
14557 (org-clock-out)))
14559 (defun org-agenda-clock-cancel (&optional arg)
14560 "Cancel the currently running clock."
14561 (interactive "P")
14562 (unless (marker-buffer org-clock-marker)
14563 (error "No running clock"))
14564 (org-with-remote-undo (marker-buffer org-clock-marker)
14565 (org-clock-cancel)))
14567 (defun org-agenda-diary-entry ()
14568 "Make a diary entry, like the `i' command from the calendar.
14569 All the standard commands work: block, weekly etc."
14570 (interactive)
14571 (org-agenda-check-type t 'agenda 'timeline)
14572 (require 'diary-lib)
14573 (let* ((char (progn
14574 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
14575 (read-char-exclusive)))
14576 (cmd (cdr (assoc char
14577 '((?d . insert-diary-entry)
14578 (?w . insert-weekly-diary-entry)
14579 (?m . insert-monthly-diary-entry)
14580 (?y . insert-yearly-diary-entry)
14581 (?a . insert-anniversary-diary-entry)
14582 (?b . insert-block-diary-entry)
14583 (?c . insert-cyclic-diary-entry)))))
14584 (oldf (symbol-function 'calendar-cursor-to-date))
14585 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
14586 (point (point))
14587 (mark (or (mark t) (point))))
14588 (unless cmd
14589 (error "No command associated with <%c>" char))
14590 (unless (and (get-text-property point 'day)
14591 (or (not (equal ?b char))
14592 (get-text-property mark 'day)))
14593 (error "Don't know which date to use for diary entry"))
14594 ;; We implement this by hacking the `calendar-cursor-to-date' function
14595 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
14596 (let ((calendar-mark-ring
14597 (list (calendar-gregorian-from-absolute
14598 (or (get-text-property mark 'day)
14599 (get-text-property point 'day))))))
14600 (unwind-protect
14601 (progn
14602 (fset 'calendar-cursor-to-date
14603 (lambda (&optional error)
14604 (calendar-gregorian-from-absolute
14605 (get-text-property point 'day))))
14606 (call-interactively cmd))
14607 (fset 'calendar-cursor-to-date oldf)))))
14610 (defun org-agenda-execute-calendar-command (cmd)
14611 "Execute a calendar command from the agenda, with the date associated to
14612 the cursor position."
14613 (org-agenda-check-type t 'agenda 'timeline)
14614 (require 'diary-lib)
14615 (unless (get-text-property (point) 'day)
14616 (error "Don't know which date to use for calendar command"))
14617 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
14618 (point (point))
14619 (date (calendar-gregorian-from-absolute
14620 (get-text-property point 'day)))
14621 (displayed-day (extract-calendar-day date))
14622 (displayed-month (extract-calendar-month date))
14623 (displayed-year (extract-calendar-year date)))
14624 (unwind-protect
14625 (progn
14626 (fset 'calendar-cursor-to-date
14627 (lambda (&optional error)
14628 (calendar-gregorian-from-absolute
14629 (get-text-property point 'day))))
14630 (call-interactively cmd))
14631 (fset 'calendar-cursor-to-date oldf))))
14633 (defun org-agenda-phases-of-moon ()
14634 "Display the phases of the moon for the 3 months around the cursor date."
14635 (interactive)
14636 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
14638 (defun org-agenda-holidays ()
14639 "Display the holidays for the 3 months around the cursor date."
14640 (interactive)
14641 (org-agenda-execute-calendar-command 'list-calendar-holidays))
14643 (defun org-agenda-sunrise-sunset (arg)
14644 "Display sunrise and sunset for the cursor date.
14645 Latitude and longitude can be specified with the variables
14646 `calendar-latitude' and `calendar-longitude'. When called with prefix
14647 argument, latitude and longitude will be prompted for."
14648 (interactive "P")
14649 (let ((calendar-longitude (if arg nil calendar-longitude))
14650 (calendar-latitude (if arg nil calendar-latitude))
14651 (calendar-location-name
14652 (if arg "the given coordinates" calendar-location-name)))
14653 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
14655 (defun org-agenda-goto-calendar ()
14656 "Open the Emacs calendar with the date at the cursor."
14657 (interactive)
14658 (org-agenda-check-type t 'agenda 'timeline)
14659 (let* ((day (or (get-text-property (point) 'day)
14660 (error "Don't know which date to open in calendar")))
14661 (date (calendar-gregorian-from-absolute day))
14662 (calendar-move-hook nil)
14663 (view-calendar-holidays-initially nil)
14664 (view-diary-entries-initially nil))
14665 (calendar)
14666 (calendar-goto-date date)))
14668 (defun org-calendar-goto-agenda ()
14669 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
14670 This is a command that has to be installed in `calendar-mode-map'."
14671 (interactive)
14672 (org-agenda-list nil (calendar-absolute-from-gregorian
14673 (calendar-cursor-to-date))
14674 nil))
14676 (defun org-agenda-convert-date ()
14677 (interactive)
14678 (org-agenda-check-type t 'agenda 'timeline)
14679 (let ((day (get-text-property (point) 'day))
14680 date s)
14681 (unless day
14682 (error "Don't know which date to convert"))
14683 (setq date (calendar-gregorian-from-absolute day))
14684 (setq s (concat
14685 "Gregorian: " (calendar-date-string date) "\n"
14686 "ISO: " (calendar-iso-date-string date) "\n"
14687 "Day of Yr: " (calendar-day-of-year-string date) "\n"
14688 "Julian: " (calendar-julian-date-string date) "\n"
14689 "Astron. JD: " (calendar-astro-date-string date)
14690 " (Julian date number at noon UTC)\n"
14691 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
14692 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
14693 "French: " (calendar-french-date-string date) "\n"
14694 "Mayan: " (calendar-mayan-date-string date) "\n"
14695 "Coptic: " (calendar-coptic-date-string date) "\n"
14696 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
14697 "Persian: " (calendar-persian-date-string date) "\n"
14698 "Chinese: " (calendar-chinese-date-string date) "\n"))
14699 (with-output-to-temp-buffer "*Dates*"
14700 (princ s))
14701 (if (fboundp 'fit-window-to-buffer)
14702 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
14705 ;;;; Embedded LaTeX
14707 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14708 "Keymap for the minor `org-cdlatex-mode'.")
14710 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14711 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14712 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14713 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14714 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14716 (defvar org-cdlatex-texmathp-advice-is-done nil
14717 "Flag remembering if we have applied the advice to texmathp already.")
14719 (define-minor-mode org-cdlatex-mode
14720 "Toggle the minor `org-cdlatex-mode'.
14721 This mode supports entering LaTeX environment and math in LaTeX fragments
14722 in Org-mode.
14723 \\{org-cdlatex-mode-map}"
14724 nil " OCDL" nil
14725 (when org-cdlatex-mode (require 'cdlatex))
14726 (unless org-cdlatex-texmathp-advice-is-done
14727 (setq org-cdlatex-texmathp-advice-is-done t)
14728 (defadvice texmathp (around org-math-always-on activate)
14729 "Always return t in org-mode buffers.
14730 This is because we want to insert math symbols without dollars even outside
14731 the LaTeX math segments. If Orgmode thinks that point is actually inside
14732 en embedded LaTeX fragement, let texmathp do its job.
14733 \\[org-cdlatex-mode-map]"
14734 (interactive)
14735 (let (p)
14736 (cond
14737 ((not (org-mode-p)) ad-do-it)
14738 ((eq this-command 'cdlatex-math-symbol)
14739 (setq ad-return-value t
14740 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14742 (let ((p (org-inside-LaTeX-fragment-p)))
14743 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14744 (setq ad-return-value t
14745 texmathp-why '("Org-mode embedded math" . 0))
14746 (if p ad-do-it)))))))))
14748 (defun turn-on-org-cdlatex ()
14749 "Unconditionally turn on `org-cdlatex-mode'."
14750 (org-cdlatex-mode 1))
14752 (defun org-inside-LaTeX-fragment-p ()
14753 "Test if point is inside a LaTeX fragment.
14754 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14755 sequence appearing also before point.
14756 Even though the matchers for math are configurable, this function assumes
14757 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14758 delimiters are skipped when they have been removed by customization.
14759 The return value is nil, or a cons cell with the delimiter and
14760 and the position of this delimiter.
14762 This function does a reasonably good job, but can locally be fooled by
14763 for example currency specifications. For example it will assume being in
14764 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14765 fragments that are properly closed, but during editing, we have to live
14766 with the uncertainty caused by missing closing delimiters. This function
14767 looks only before point, not after."
14768 (catch 'exit
14769 (let ((pos (point))
14770 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14771 (lim (progn
14772 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14773 (point)))
14774 dd-on str (start 0) m re)
14775 (goto-char pos)
14776 (when dodollar
14777 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14778 re (nth 1 (assoc "$" org-latex-regexps)))
14779 (while (string-match re str start)
14780 (cond
14781 ((= (match-end 0) (length str))
14782 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
14783 ((= (match-end 0) (- (length str) 5))
14784 (throw 'exit nil))
14785 (t (setq start (match-end 0))))))
14786 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14787 (goto-char pos)
14788 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14789 (and (match-beginning 2) (throw 'exit nil))
14790 ;; count $$
14791 (while (re-search-backward "\\$\\$" lim t)
14792 (setq dd-on (not dd-on)))
14793 (goto-char pos)
14794 (if dd-on (cons "$$" m))))))
14797 (defun org-try-cdlatex-tab ()
14798 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14799 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14800 - inside a LaTeX fragment, or
14801 - after the first word in a line, where an abbreviation expansion could
14802 insert a LaTeX environment."
14803 (when org-cdlatex-mode
14804 (cond
14805 ((save-excursion
14806 (skip-chars-backward "a-zA-Z0-9*")
14807 (skip-chars-backward " \t")
14808 (bolp))
14809 (cdlatex-tab) t)
14810 ((org-inside-LaTeX-fragment-p)
14811 (cdlatex-tab) t)
14812 (t nil))))
14814 (defun org-cdlatex-underscore-caret (&optional arg)
14815 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14816 Revert to the normal definition outside of these fragments."
14817 (interactive "P")
14818 (if (org-inside-LaTeX-fragment-p)
14819 (call-interactively 'cdlatex-sub-superscript)
14820 (let (org-cdlatex-mode)
14821 (call-interactively (key-binding (vector last-input-event))))))
14823 (defun org-cdlatex-math-modify (&optional arg)
14824 "Execute `cdlatex-math-modify' in LaTeX fragments.
14825 Revert to the normal definition outside of these fragments."
14826 (interactive "P")
14827 (if (org-inside-LaTeX-fragment-p)
14828 (call-interactively 'cdlatex-math-modify)
14829 (let (org-cdlatex-mode)
14830 (call-interactively (key-binding (vector last-input-event))))))
14832 (defvar org-latex-fragment-image-overlays nil
14833 "List of overlays carrying the images of latex fragments.")
14834 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14836 (defun org-remove-latex-fragment-image-overlays ()
14837 "Remove all overlays with LaTeX fragment images in current buffer."
14838 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14839 (setq org-latex-fragment-image-overlays nil))
14841 (defun org-preview-latex-fragment (&optional subtree)
14842 "Preview the LaTeX fragment at point, or all locally or globally.
14843 If the cursor is in a LaTeX fragment, create the image and overlay
14844 it over the source code. If there is no fragment at point, display
14845 all fragments in the current text, from one headline to the next. With
14846 prefix SUBTREE, display all fragments in the current subtree. With a
14847 double prefix `C-u C-u', or when the cursor is before the first headline,
14848 display all fragments in the buffer.
14849 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14850 (interactive "P")
14851 (org-remove-latex-fragment-image-overlays)
14852 (save-excursion
14853 (save-restriction
14854 (let (beg end at msg)
14855 (cond
14856 ((or (equal subtree '(16))
14857 (not (save-excursion
14858 (re-search-backward (concat "^" outline-regexp) nil t))))
14859 (setq beg (point-min) end (point-max)
14860 msg "Creating images for buffer...%s"))
14861 ((equal subtree '(4))
14862 (org-back-to-heading)
14863 (setq beg (point) end (org-end-of-subtree t)
14864 msg "Creating images for subtree...%s"))
14866 (if (setq at (org-inside-LaTeX-fragment-p))
14867 (goto-char (max (point-min) (- (cdr at) 2)))
14868 (org-back-to-heading))
14869 (setq beg (point) end (progn (outline-next-heading) (point))
14870 msg (if at "Creating image...%s"
14871 "Creating images for entry...%s"))))
14872 (message msg "")
14873 (narrow-to-region beg end)
14874 (org-format-latex
14875 (concat "ltxpng/" (file-name-sans-extension
14876 (file-name-nondirectory
14877 buffer-file-name)))
14878 default-directory 'overlays msg at)
14879 (message msg "done. Use `C-c C-c' to remove images.")))))
14881 (defvar org-latex-regexps
14882 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14883 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14884 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14885 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
14886 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14887 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
14888 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
14889 "Regular expressions for matching embedded LaTeX.")
14891 (defun org-format-latex (prefix &optional dir overlays msg at)
14892 "Replace LaTeX fragments with links to an image, and produce images."
14893 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14894 (let* ((prefixnodir (file-name-nondirectory prefix))
14895 (absprefix (expand-file-name prefix dir))
14896 (todir (file-name-directory absprefix))
14897 (opt org-format-latex-options)
14898 (matchers (plist-get opt :matchers))
14899 (re-list org-latex-regexps)
14900 (cnt 0) txt link beg end re e oldfiles
14901 m n block linkfile movefile ov)
14902 ;; Make sure the directory exists
14903 (or (file-directory-p todir) (make-directory todir))
14904 ;; Check if there are old images files with this prefix, and remove them
14905 (setq oldfiles (directory-files
14906 todir 'full
14907 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
14908 (while oldfiles (delete-file (pop oldfiles)))
14909 ;; Check the different regular expressions
14910 (while (setq e (pop re-list))
14911 (setq m (car e) re (nth 1 e) n (nth 2 e)
14912 block (if (nth 3 e) "\n\n" ""))
14913 (when (member m matchers)
14914 (goto-char (point-min))
14915 (while (re-search-forward re nil t)
14916 (when (or (not at) (equal (cdr at) (match-beginning n)))
14917 (setq txt (match-string n)
14918 beg (match-beginning n) end (match-end n)
14919 cnt (1+ cnt)
14920 linkfile (format "%s_%04d.png" prefix cnt)
14921 movefile (format "%s_%04d.png" absprefix cnt)
14922 link (concat block "[[file:" linkfile "]]" block))
14923 (if msg (message msg cnt))
14924 (goto-char beg)
14925 (org-create-formula-image
14926 txt movefile opt)
14927 (if overlays
14928 (progn
14929 (setq ov (org-make-overlay beg end))
14930 (if (featurep 'xemacs)
14931 (progn
14932 (org-overlay-put ov 'invisible t)
14933 (org-overlay-put
14934 ov 'end-glyph
14935 (make-glyph (vector 'png :file movefile))))
14936 (org-overlay-put
14937 ov 'display
14938 (list 'image :type 'png :file movefile :ascent 'center)))
14939 (push ov org-latex-fragment-image-overlays)
14940 (goto-char end))
14941 (delete-region beg end)
14942 (insert link))))))))
14944 ;; This function borrows from Ganesh Swami's latex2png.el
14945 (defun org-create-formula-image (string tofile options)
14946 (let* ((tmpdir (if (featurep 'xemacs)
14947 (temp-directory)
14948 temporary-file-directory))
14949 (texfilebase (make-temp-name
14950 (expand-file-name "orgtex" tmpdir)))
14952 ;(texfilebase (make-temp-file "orgtex"))
14953 ; (dummy (delete-file texfilebase))
14954 (texfile (concat texfilebase ".tex"))
14955 (dvifile (concat texfilebase ".dvi"))
14956 (pngfile (concat texfilebase ".png"))
14957 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
14958 (fg (or (plist-get options :foreground) "Black"))
14959 (bg (or (plist-get options :background) "Transparent")))
14960 (with-temp-file texfile
14961 (insert "\\documentclass{article}
14962 \\usepackage{fullpage}
14963 \\usepackage{amssymb}
14964 \\usepackage[usenames]{color}
14965 \\usepackage{amsmath}
14966 \\usepackage{latexsym}
14967 \\usepackage[mathscr]{eucal}
14968 \\pagestyle{empty}
14969 \\begin{document}\n" string "\n\\end{document}\n"))
14970 (let ((dir default-directory))
14971 (condition-case nil
14972 (progn
14973 (cd tmpdir)
14974 (call-process "latex" nil nil nil texfile))
14975 (error nil))
14976 (cd dir))
14977 (if (not (file-exists-p dvifile))
14978 (progn (message "Failed to create dvi file from %s" texfile) nil)
14979 (call-process "dvipng" nil nil nil
14980 "-E" "-fg" fg "-bg" bg
14981 "-x" scale "-y" scale "-T" "tight"
14982 "-o" pngfile
14983 dvifile)
14984 (if (not (file-exists-p pngfile))
14985 (progn (message "Failed to create png file from %s" texfile) nil)
14986 ;; Use the requested file name and clean up
14987 (copy-file pngfile tofile 'replace)
14988 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14989 (delete-file (concat texfilebase e)))
14990 pngfile))))
14992 ;;;; Exporting
14994 ;;; Variables, constants, and parameter plists
14996 (defconst org-level-max 20)
14998 (defvar org-export-html-preamble nil
14999 "Preamble, to be inserted just after <body>. Set by publishing functions.")
15000 (defvar org-export-html-postamble nil
15001 "Preamble, to be inserted just before </body>. Set by publishing functions.")
15002 (defvar org-export-html-auto-preamble t
15003 "Should default preamble be inserted? Set by publishing functions.")
15004 (defvar org-export-html-auto-postamble t
15005 "Should default postamble be inserted? Set by publishing functions.")
15006 (defvar org-current-export-file nil) ; dynamically scoped parameter
15007 (defvar org-current-export-dir nil) ; dynamically scoped parameter
15010 (defconst org-export-plist-vars
15011 '((:language . org-export-default-language)
15012 (:customtime . org-display-custom-times)
15013 (:headline-levels . org-export-headline-levels)
15014 (:section-numbers . org-export-with-section-numbers)
15015 (:table-of-contents . org-export-with-toc)
15016 (:archived-trees . org-export-with-archived-trees)
15017 (:emphasize . org-export-with-emphasize)
15018 (:sub-superscript . org-export-with-sub-superscripts)
15019 (:TeX-macros . org-export-with-TeX-macros)
15020 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
15021 (:fixed-width . org-export-with-fixed-width)
15022 (:timestamps . org-export-with-timestamps)
15023 (:tables . org-export-with-tables)
15024 (:table-auto-headline . org-export-highlight-first-table-line)
15025 (:style . org-export-html-style)
15026 (:convert-org-links . org-export-html-link-org-files-as-html)
15027 (:inline-images . org-export-html-inline-images)
15028 (:expand-quoted-html . org-export-html-expand)
15029 (:timestamp . org-export-html-with-timestamp)
15030 (:publishing-directory . org-export-publishing-directory)
15031 (:preamble . org-export-html-preamble)
15032 (:postamble . org-export-html-postamble)
15033 (:auto-preamble . org-export-html-auto-preamble)
15034 (:auto-postamble . org-export-html-auto-postamble)
15035 (:author . user-full-name)
15036 (:email . user-mail-address)))
15038 (defun org-default-export-plist ()
15039 "Return the property list with default settings for the export variables."
15040 (let ((l org-export-plist-vars) rtn e)
15041 (while (setq e (pop l))
15042 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
15043 rtn))
15045 (defun org-infile-export-plist ()
15046 "Return the property list with file-local settings for export."
15047 (save-excursion
15048 (goto-char 0)
15049 (let ((re (org-make-options-regexp
15050 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
15051 p key val text options)
15052 (while (re-search-forward re nil t)
15053 (setq key (org-match-string-no-properties 1)
15054 val (org-match-string-no-properties 2))
15055 (cond
15056 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
15057 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
15058 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
15059 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
15060 ((string-equal key "TEXT")
15061 (setq text (if text (concat text "\n" val) val)))
15062 ((string-equal key "OPTIONS") (setq options val))))
15063 (setq p (plist-put p :text text))
15064 (when options
15065 (let ((op '(("H" . :headline-levels)
15066 ("num" . :section-numbers)
15067 ("toc" . :table-of-contents)
15068 ("\\n" . :preserve-breaks)
15069 ("@" . :expand-quoted-html)
15070 (":" . :fixed-width)
15071 ("|" . :tables)
15072 ("^" . :sub-superscript)
15073 ("*" . :emphasize)
15074 ("TeX" . :TeX-macros)
15075 ("LaTeX" . :LaTeX-fragments)))
15077 (while (setq o (pop op))
15078 (if (string-match (concat (regexp-quote (car o))
15079 ":\\([^ \t\n\r;,.]*\\)")
15080 options)
15081 (setq p (plist-put p (cdr o)
15082 (car (read-from-string
15083 (match-string 1 options)))))))))
15084 p)))
15086 (defun org-combine-plists (&rest plists)
15087 "Create a single property list from all plists in PLISTS.
15088 The process starts by copying the last list, and then setting properties
15089 from the other lists. Settings in the first list are the most significant
15090 ones and overrule settings in the other lists."
15091 (let ((rtn (copy-sequence (pop plists)))
15092 p v ls)
15093 (while plists
15094 (setq ls (pop plists))
15095 (while ls
15096 (setq p (pop ls) v (pop ls))
15097 (setq rtn (plist-put rtn p v))))
15098 rtn))
15100 (defun org-export-directory (type plist)
15101 (let* ((val (plist-get plist :publishing-directory))
15102 (dir (if (listp val)
15103 (or (cdr (assoc type val)) ".")
15104 val)))
15105 dir))
15107 (defun org-export-find-first-heading-line (list)
15108 "Remove all lines from LIST which are before the first headline."
15109 (let ((orig-list list)
15110 (re (concat "^" outline-regexp)))
15111 (while (and list
15112 (not (string-match re (car list))))
15113 (pop list))
15114 (or list orig-list)))
15116 (defun org-skip-comments (lines)
15117 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
15118 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
15119 (re2 "^\\(\\*+\\)[ \t\n\r]")
15120 rtn line level)
15121 (while (setq line (pop lines))
15122 (cond
15123 ((and (string-match re1 line)
15124 (setq level (- (match-end 1) (match-beginning 1))))
15125 ;; Beginning of a COMMENT subtree. Skip it.
15126 (while (and (setq line (pop lines))
15127 (or (not (string-match re2 line))
15128 (> (- (match-end 1) (match-beginning 1)) level))))
15129 (setq lines (cons line lines)))
15130 ((string-match "^#" line)
15131 ;; an ordinary comment line
15133 ((and org-export-table-remove-special-lines
15134 (string-match "^[ \t]*|" line)
15135 (or (string-match "^[ \t]*| *[!_^] *|" line)
15136 (and (string-match "| *<[0-9]+> *|" line)
15137 (not (string-match "| *[^ <|]" line)))))
15138 ;; a special table line that should be removed
15140 (t (setq rtn (cons line rtn)))))
15141 (nreverse rtn)))
15143 (defun org-export (&optional arg)
15144 (interactive)
15145 (let ((help "[t] insert the export option template
15146 \[v] limit export to visible part of outline tree
15148 \[a] export as ASCII
15149 \[h] export as HTML
15150 \[b] export as HTML and browse immediately
15151 \[x] export as XOXO
15153 \[i] export current file as iCalendar file
15154 \[I] export all agenda files as iCalendar files
15155 \[c] export agenda files into combined iCalendar file
15157 \[F] publish current file
15158 \[P] publish current project
15159 \[X] publish... (project will be prompted for)
15160 \[A] publish all projects")
15161 (cmds
15162 '((?t . org-insert-export-options-template)
15163 (?v . org-export-visible)
15164 (?a . org-export-as-ascii)
15165 (?h . org-export-as-html)
15166 (?b . org-export-as-html-and-open)
15167 (?x . org-export-as-xoxo)
15168 (?i . org-export-icalendar-this-file)
15169 (?I . org-export-icalendar-all-agenda-files)
15170 (?c . org-export-icalendar-combine-agenda-files)
15171 (?F . org-publish-current-file)
15172 (?P . org-publish-current-project)
15173 (?X . org-publish)
15174 (?A . org-publish-all)))
15175 r1 r2 ass)
15176 (save-window-excursion
15177 (delete-other-windows)
15178 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
15179 (princ help))
15180 (message "Select command: ")
15181 (setq r1 (read-char-exclusive)))
15182 (setq r2 (if (< r1 27) (+ r1 96) r1))
15183 (if (setq ass (assq r2 cmds))
15184 (call-interactively (cdr ass))
15185 (error "No command associated with key %c" r1))))
15187 (defconst org-html-entities
15188 '(("nbsp")
15189 ("iexcl")
15190 ("cent")
15191 ("pound")
15192 ("curren")
15193 ("yen")
15194 ("brvbar")
15195 ("sect")
15196 ("uml")
15197 ("copy")
15198 ("ordf")
15199 ("laquo")
15200 ("not")
15201 ("shy")
15202 ("reg")
15203 ("macr")
15204 ("deg")
15205 ("plusmn")
15206 ("sup2")
15207 ("sup3")
15208 ("acute")
15209 ("micro")
15210 ("para")
15211 ("middot")
15212 ("odot"."o")
15213 ("star"."*")
15214 ("cedil")
15215 ("sup1")
15216 ("ordm")
15217 ("raquo")
15218 ("frac14")
15219 ("frac12")
15220 ("frac34")
15221 ("iquest")
15222 ("Agrave")
15223 ("Aacute")
15224 ("Acirc")
15225 ("Atilde")
15226 ("Auml")
15227 ("Aring") ("AA"."&Aring;")
15228 ("AElig")
15229 ("Ccedil")
15230 ("Egrave")
15231 ("Eacute")
15232 ("Ecirc")
15233 ("Euml")
15234 ("Igrave")
15235 ("Iacute")
15236 ("Icirc")
15237 ("Iuml")
15238 ("ETH")
15239 ("Ntilde")
15240 ("Ograve")
15241 ("Oacute")
15242 ("Ocirc")
15243 ("Otilde")
15244 ("Ouml")
15245 ("times")
15246 ("Oslash")
15247 ("Ugrave")
15248 ("Uacute")
15249 ("Ucirc")
15250 ("Uuml")
15251 ("Yacute")
15252 ("THORN")
15253 ("szlig")
15254 ("agrave")
15255 ("aacute")
15256 ("acirc")
15257 ("atilde")
15258 ("auml")
15259 ("aring")
15260 ("aelig")
15261 ("ccedil")
15262 ("egrave")
15263 ("eacute")
15264 ("ecirc")
15265 ("euml")
15266 ("igrave")
15267 ("iacute")
15268 ("icirc")
15269 ("iuml")
15270 ("eth")
15271 ("ntilde")
15272 ("ograve")
15273 ("oacute")
15274 ("ocirc")
15275 ("otilde")
15276 ("ouml")
15277 ("divide")
15278 ("oslash")
15279 ("ugrave")
15280 ("uacute")
15281 ("ucirc")
15282 ("uuml")
15283 ("yacute")
15284 ("thorn")
15285 ("yuml")
15286 ("fnof")
15287 ("Alpha")
15288 ("Beta")
15289 ("Gamma")
15290 ("Delta")
15291 ("Epsilon")
15292 ("Zeta")
15293 ("Eta")
15294 ("Theta")
15295 ("Iota")
15296 ("Kappa")
15297 ("Lambda")
15298 ("Mu")
15299 ("Nu")
15300 ("Xi")
15301 ("Omicron")
15302 ("Pi")
15303 ("Rho")
15304 ("Sigma")
15305 ("Tau")
15306 ("Upsilon")
15307 ("Phi")
15308 ("Chi")
15309 ("Psi")
15310 ("Omega")
15311 ("alpha")
15312 ("beta")
15313 ("gamma")
15314 ("delta")
15315 ("epsilon")
15316 ("varepsilon"."&epsilon;")
15317 ("zeta")
15318 ("eta")
15319 ("theta")
15320 ("iota")
15321 ("kappa")
15322 ("lambda")
15323 ("mu")
15324 ("nu")
15325 ("xi")
15326 ("omicron")
15327 ("pi")
15328 ("rho")
15329 ("sigmaf") ("varsigma"."&sigmaf;")
15330 ("sigma")
15331 ("tau")
15332 ("upsilon")
15333 ("phi")
15334 ("chi")
15335 ("psi")
15336 ("omega")
15337 ("thetasym") ("vartheta"."&thetasym;")
15338 ("upsih")
15339 ("piv")
15340 ("bull") ("bullet"."&bull;")
15341 ("hellip") ("dots"."&hellip;")
15342 ("prime")
15343 ("Prime")
15344 ("oline")
15345 ("frasl")
15346 ("weierp")
15347 ("image")
15348 ("real")
15349 ("trade")
15350 ("alefsym")
15351 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
15352 ("uarr") ("uparrow"."&uarr;")
15353 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
15354 ("darr")("downarrow"."&darr;")
15355 ("harr") ("leftrightarrow"."&harr;")
15356 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
15357 ("lArr") ("Leftarrow"."&lArr;")
15358 ("uArr") ("Uparrow"."&uArr;")
15359 ("rArr") ("Rightarrow"."&rArr;")
15360 ("dArr") ("Downarrow"."&dArr;")
15361 ("hArr") ("Leftrightarrow"."&hArr;")
15362 ("forall")
15363 ("part") ("partial"."&part;")
15364 ("exist") ("exists"."&exist;")
15365 ("empty") ("emptyset"."&empty;")
15366 ("nabla")
15367 ("isin") ("in"."&isin;")
15368 ("notin")
15369 ("ni")
15370 ("prod")
15371 ("sum")
15372 ("minus")
15373 ("lowast") ("ast"."&lowast;")
15374 ("radic")
15375 ("prop") ("proptp"."&prop;")
15376 ("infin") ("infty"."&infin;")
15377 ("ang") ("angle"."&ang;")
15378 ("and") ("vee"."&and;")
15379 ("or") ("wedge"."&or;")
15380 ("cap")
15381 ("cup")
15382 ("int")
15383 ("there4")
15384 ("sim")
15385 ("cong") ("simeq"."&cong;")
15386 ("asymp")("approx"."&asymp;")
15387 ("ne") ("neq"."&ne;")
15388 ("equiv")
15389 ("le")
15390 ("ge")
15391 ("sub") ("subset"."&sub;")
15392 ("sup") ("supset"."&sup;")
15393 ("nsub")
15394 ("sube")
15395 ("supe")
15396 ("oplus")
15397 ("otimes")
15398 ("perp")
15399 ("sdot") ("cdot"."&sdot;")
15400 ("lceil")
15401 ("rceil")
15402 ("lfloor")
15403 ("rfloor")
15404 ("lang")
15405 ("rang")
15406 ("loz") ("Diamond"."&loz;")
15407 ("spades") ("spadesuit"."&spades;")
15408 ("clubs") ("clubsuit"."&clubs;")
15409 ("hearts") ("diamondsuit"."&hearts;")
15410 ("diams") ("diamondsuit"."&diams;")
15411 ("quot")
15412 ("amp")
15413 ("lt")
15414 ("gt")
15415 ("OElig")
15416 ("oelig")
15417 ("Scaron")
15418 ("scaron")
15419 ("Yuml")
15420 ("circ")
15421 ("tilde")
15422 ("ensp")
15423 ("emsp")
15424 ("thinsp")
15425 ("zwnj")
15426 ("zwj")
15427 ("lrm")
15428 ("rlm")
15429 ("ndash")
15430 ("mdash")
15431 ("lsquo")
15432 ("rsquo")
15433 ("sbquo")
15434 ("ldquo")
15435 ("rdquo")
15436 ("bdquo")
15437 ("dagger")
15438 ("Dagger")
15439 ("permil")
15440 ("lsaquo")
15441 ("rsaquo")
15442 ("euro")
15444 ("arccos"."arccos")
15445 ("arcsin"."arcsin")
15446 ("arctan"."arctan")
15447 ("arg"."arg")
15448 ("cos"."cos")
15449 ("cosh"."cosh")
15450 ("cot"."cot")
15451 ("coth"."coth")
15452 ("csc"."csc")
15453 ("deg"."deg")
15454 ("det"."det")
15455 ("dim"."dim")
15456 ("exp"."exp")
15457 ("gcd"."gcd")
15458 ("hom"."hom")
15459 ("inf"."inf")
15460 ("ker"."ker")
15461 ("lg"."lg")
15462 ("lim"."lim")
15463 ("liminf"."liminf")
15464 ("limsup"."limsup")
15465 ("ln"."ln")
15466 ("log"."log")
15467 ("max"."max")
15468 ("min"."min")
15469 ("Pr"."Pr")
15470 ("sec"."sec")
15471 ("sin"."sin")
15472 ("sinh"."sinh")
15473 ("sup"."sup")
15474 ("tan"."tan")
15475 ("tanh"."tanh")
15477 "Entities for TeX->HTML translation.
15478 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
15479 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
15480 In that case, \"\\ent\" will be translated to \"&other;\".
15481 The list contains HTML entities for Latin-1, Greek and other symbols.
15482 It is supplemented by a number of commonly used TeX macros with appropriate
15483 translations. There is currently no way for users to extend this.")
15485 ;;; General functions for all backends
15487 (defun org-cleaned-string-for-export (string &rest parameters)
15488 "Cleanup a buffer substring so that links can be created safely."
15489 (interactive)
15490 (let* ((re-radio (and org-target-link-regexp
15491 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
15492 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
15493 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
15494 (re-archive (concat ":" org-archive-tag ":"))
15495 rtn)
15496 (save-excursion
15497 (set-buffer (get-buffer-create " org-mode-tmp"))
15498 (erase-buffer)
15499 (insert string)
15500 (let ((org-inhibit-startup t)) (org-mode))
15501 (untabify (point-min) (point-max))
15503 ;; Get rid of archived trees
15504 (when (not (eq org-export-with-archived-trees t))
15505 (goto-char (point-min))
15506 (while (re-search-forward re-archive nil t)
15507 (if (not (org-on-heading-p))
15508 (org-end-of-subtree t)
15509 (beginning-of-line 1)
15510 (delete-region
15511 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
15512 (org-end-of-subtree t)))))
15514 ;; Find targets in comments and move them out of comments,
15515 ;; but mark them as targets that should be invisible
15516 (goto-char (point-min))
15517 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
15518 (replace-match "\\1(INVISIBLE)"))
15520 ;; Remove comments
15521 (goto-char (point-min))
15522 (while (re-search-forward "^#.*\n?" nil t)
15523 (replace-match ""))
15525 ;; Find matches for radio targets and turn them into internal links
15526 (goto-char (point-min))
15527 (when re-radio
15528 (while (re-search-forward re-radio nil t)
15529 (replace-match "\\1[[\\2]]")))
15531 ;; Find all links that contain a newline and put them into a single line
15532 (goto-char (point-min))
15533 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
15534 (replace-match "\\1 \\3")
15535 (goto-char (match-beginning 0)))
15537 ;; Convert LaTeX fragments to images
15538 (when (memq :LaTeX-fragments parameters)
15539 (org-format-latex
15540 (concat "ltxpng/" (file-name-sans-extension
15541 (file-name-nondirectory
15542 org-current-export-file)))
15543 org-current-export-dir nil "Creating LaTeX image %s"))
15544 (message "Exporting...")
15546 ;; Normalize links: Convert angle and plain links into bracket links
15547 ;; Expand link abbreviations
15548 (goto-char (point-min))
15549 (while (re-search-forward re-plain-link nil t)
15550 (replace-match
15551 (concat
15552 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
15553 t t))
15554 (goto-char (point-min))
15555 (while (re-search-forward re-angle-link nil t)
15556 (replace-match
15557 (concat
15558 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
15559 t t))
15560 (goto-char (point-min))
15561 (while (re-search-forward org-bracket-link-regexp nil t)
15562 (replace-match
15563 (concat "[[" (save-match-data
15564 (org-link-expand-abbrev (match-string 1)))
15566 (if (match-end 3)
15567 (match-string 2)
15568 (concat "[" (match-string 1) "]"))
15569 "]")
15570 t t))
15572 ;; Find multiline emphasis and put them into single line
15573 (when (memq :emph-multiline parameters)
15574 (goto-char (point-min))
15575 (while (re-search-forward org-emph-re nil t)
15576 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
15577 (goto-char (1- (match-end 0)))))
15579 (setq rtn (buffer-string)))
15580 (kill-buffer " org-mode-tmp")
15581 rtn))
15583 (defun org-solidify-link-text (s &optional alist)
15584 "Take link text and make a safe target out of it."
15585 (save-match-data
15586 (let* ((rtn
15587 (mapconcat
15588 'identity
15589 (org-split-string s "[ \t\r\n]+") "--"))
15590 (a (assoc rtn alist)))
15591 (or (cdr a) rtn))))
15593 ;; Variable holding the vector with section numbers
15594 (defvar org-section-numbers (make-vector org-level-max 0))
15596 (defun org-init-section-numbers ()
15597 "Initialize the vector for the section numbers."
15598 (let* ((level -1)
15599 (numbers (nreverse (org-split-string "" "\\.")))
15600 (depth (1- (length org-section-numbers)))
15601 (i depth) number-string)
15602 (while (>= i 0)
15603 (if (> i level)
15604 (aset org-section-numbers i 0)
15605 (setq number-string (or (car numbers) "0"))
15606 (if (string-match "\\`[A-Z]\\'" number-string)
15607 (aset org-section-numbers i
15608 (- (string-to-char number-string) ?A -1))
15609 (aset org-section-numbers i (string-to-number number-string)))
15610 (pop numbers))
15611 (setq i (1- i)))))
15613 (defun org-section-number (&optional level)
15614 "Return a string with the current section number.
15615 When LEVEL is non-nil, increase section numbers on that level."
15616 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
15617 (when level
15618 (when (> level -1)
15619 (aset org-section-numbers
15620 level (1+ (aref org-section-numbers level))))
15621 (setq idx (1+ level))
15622 (while (<= idx depth)
15623 (if (not (= idx 1))
15624 (aset org-section-numbers idx 0))
15625 (setq idx (1+ idx))))
15626 (setq idx 0)
15627 (while (<= idx depth)
15628 (setq n (aref org-section-numbers idx))
15629 (setq string (concat string (if (not (string= string "")) "." "")
15630 (int-to-string n)))
15631 (setq idx (1+ idx)))
15632 (save-match-data
15633 (if (string-match "\\`\\([@0]\\.\\)+" string)
15634 (setq string (replace-match "" t nil string)))
15635 (if (string-match "\\(\\.0\\)+\\'" string)
15636 (setq string (replace-match "" t nil string))))
15637 string))
15639 ;;; ASCII export
15641 (defvar org-last-level nil) ; dynamically scoped variable
15642 (defvar org-levels-open nil) ; dynamically scoped parameter
15643 (defvar org-ascii-current-indentation nil) ; For communication
15645 (defun org-export-as-ascii (arg)
15646 "Export the outline as a pretty ASCII file.
15647 If there is an active region, export only the region.
15648 The prefix ARG specifies how many levels of the outline should become
15649 underlined headlines. The default is 3."
15650 (interactive "P")
15651 (setq-default org-todo-line-regexp org-todo-line-regexp)
15652 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
15653 (org-infile-export-plist)))
15654 (region
15655 (buffer-substring
15656 (if (org-region-active-p) (region-beginning) (point-min))
15657 (if (org-region-active-p) (region-end) (point-max))))
15658 (custom-times org-display-custom-times)
15659 (lines (org-export-find-first-heading-line
15660 (org-skip-comments
15661 (org-split-string
15662 (org-cleaned-string-for-export region)
15663 "[\r\n]"))))
15664 (org-ascii-current-indentation '(0 . 0))
15665 (org-startup-with-deadline-check nil)
15666 (level 0) line txt
15667 (umax nil)
15668 (case-fold-search nil)
15669 (filename (concat (file-name-as-directory
15670 (org-export-directory :ascii opt-plist))
15671 (file-name-sans-extension
15672 (file-name-nondirectory buffer-file-name))
15673 ".txt"))
15674 (buffer (find-file-noselect filename))
15675 (org-levels-open (make-vector org-level-max nil))
15676 (odd org-odd-levels-only)
15677 (date (format-time-string "%Y/%m/%d" (current-time)))
15678 (time (format-time-string "%X" (org-current-time)))
15679 (author (plist-get opt-plist :author))
15680 (title (or (plist-get opt-plist :title)
15681 (file-name-sans-extension
15682 (file-name-nondirectory buffer-file-name))))
15683 (email (plist-get opt-plist :email))
15684 (language (plist-get opt-plist :language))
15685 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
15686 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
15687 (text nil)
15688 (todo nil)
15689 (lang-words nil))
15691 (setq org-last-level 1)
15692 (org-init-section-numbers)
15694 (find-file-noselect filename)
15696 (setq lang-words (or (assoc language org-export-language-setup)
15697 (assoc "en" org-export-language-setup)))
15698 (if org-export-ascii-show-new-buffer
15699 (switch-to-buffer-other-window buffer)
15700 (set-buffer buffer))
15701 (erase-buffer)
15702 (fundamental-mode)
15703 ;; create local variables for all options, to make sure all called
15704 ;; functions get the correct information
15705 (mapcar (lambda (x)
15706 (set (make-local-variable (cdr x))
15707 (plist-get opt-plist (car x))))
15708 org-export-plist-vars)
15709 (org-set-local 'org-odd-levels-only odd)
15710 (setq umax (if arg (prefix-numeric-value arg)
15711 org-export-headline-levels))
15713 ;; File header
15714 (if title (org-insert-centered title ?=))
15715 (insert "\n")
15716 (if (or author email)
15717 (insert (concat (nth 1 lang-words) ": " (or author "")
15718 (if email (concat " <" email ">") "")
15719 "\n")))
15720 (if (and date time)
15721 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
15722 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
15724 (insert "\n\n")
15726 (if org-export-with-toc
15727 (progn
15728 (insert (nth 3 lang-words) "\n"
15729 (make-string (length (nth 3 lang-words)) ?=) "\n")
15730 (mapcar '(lambda (line)
15731 (if (string-match org-todo-line-regexp
15732 line)
15733 ;; This is a headline
15734 (progn
15735 (setq level (- (match-end 1) (match-beginning 1))
15736 level (org-tr-level level)
15737 txt (match-string 3 line)
15738 todo
15739 (or (and org-export-mark-todo-in-toc
15740 (match-beginning 2)
15741 (not (equal (match-string 2 line)
15742 org-done-string)))
15743 ; TODO, not DONE
15744 (and org-export-mark-todo-in-toc
15745 (= level umax)
15746 (org-search-todo-below
15747 line lines level))))
15748 (setq txt (org-html-expand-for-ascii txt))
15750 (if (and (memq org-export-with-tags '(not-in-toc nil))
15751 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
15752 (setq txt (replace-match "" t t txt)))
15753 (if (string-match quote-re0 txt)
15754 (setq txt (replace-match "" t t txt)))
15756 (if org-export-with-section-numbers
15757 (setq txt (concat (org-section-number level)
15758 " " txt)))
15759 (if (<= level umax)
15760 (progn
15761 (insert
15762 (make-string (* (1- level) 4) ?\ )
15763 (format (if todo "%s (*)\n" "%s\n") txt))
15764 (setq org-last-level level))
15765 ))))
15766 lines)))
15768 (org-init-section-numbers)
15769 (while (setq line (pop lines))
15770 ;; Remove the quoted HTML tags.
15771 (setq line (org-html-expand-for-ascii line))
15772 ;; Remove targets
15773 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
15774 (setq line (replace-match "" t t line)))
15775 ;; Replace internal links
15776 (while (string-match org-bracket-link-regexp line)
15777 (setq line (replace-match
15778 (if (match-end 3) "[\\3]" "[\\1]")
15779 t nil line)))
15780 (when custom-times
15781 (setq line (org-translate-time line)))
15782 (cond
15783 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
15784 ;; a Headline
15785 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
15786 txt (match-string 2 line))
15787 (org-ascii-level-start level txt umax lines))
15789 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
15790 (normal-mode)
15791 (save-buffer)
15792 ;; remove display and invisible chars
15793 (let (beg end)
15794 (goto-char (point-min))
15795 (while (setq beg (next-single-property-change (point) 'display))
15796 (setq end (next-single-property-change beg 'display))
15797 (delete-region beg end)
15798 (goto-char beg)
15799 (insert "=>"))
15800 (goto-char (point-min))
15801 (while (setq beg (next-single-property-change (point) 'org-cwidth))
15802 (setq end (next-single-property-change beg 'org-cwidth))
15803 (delete-region beg end)
15804 (goto-char beg)))
15805 (goto-char (point-min))))
15807 (defun org-search-todo-below (line lines level)
15808 "Search the subtree below LINE for any TODO entries."
15809 (let ((rest (cdr (memq line lines)))
15810 (re org-todo-line-regexp)
15811 line lv todo)
15812 (catch 'exit
15813 (while (setq line (pop rest))
15814 (if (string-match re line)
15815 (progn
15816 (setq lv (- (match-end 1) (match-beginning 1))
15817 todo (and (match-beginning 2)
15818 (not (equal (match-string 2 line)
15819 org-done-string))))
15820 ; TODO, not DONE
15821 (if (<= lv level) (throw 'exit nil))
15822 (if todo (throw 'exit t))))))))
15824 (defun org-html-expand-for-ascii (line)
15825 "Handle quoted HTML for ASCII export."
15826 (if org-export-html-expand
15827 (while (string-match "@<[^<>\n]*>" line)
15828 ;; We just remove the tags for now.
15829 (setq line (replace-match "" nil nil line))))
15830 line)
15832 (defun org-insert-centered (s &optional underline)
15833 "Insert the string S centered and underline it with character UNDERLINE."
15834 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
15835 (insert (make-string ind ?\ ) s "\n")
15836 (if underline
15837 (insert (make-string ind ?\ )
15838 (make-string (string-width s) underline)
15839 "\n"))))
15841 (defun org-ascii-level-start (level title umax &optional lines)
15842 "Insert a new level in ASCII export."
15843 (let (char (n (- level umax 1)) (ind 0))
15844 (if (> level umax)
15845 (progn
15846 (insert (make-string (* 2 n) ?\ )
15847 (char-to-string (nth (% n (length org-export-ascii-bullets))
15848 org-export-ascii-bullets))
15849 " " title "\n")
15850 ;; find the indentation of the next non-empty line
15851 (catch 'stop
15852 (while lines
15853 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
15854 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
15855 (throw 'stop (setq ind (org-get-indentation (car lines)))))
15856 (pop lines)))
15857 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
15858 (if (or (not (equal (char-before) ?\n))
15859 (not (equal (char-before (1- (point))) ?\n)))
15860 (insert "\n"))
15861 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
15862 (unless org-export-with-tags
15863 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
15864 (setq title (replace-match "" t t title))))
15865 (if org-export-with-section-numbers
15866 (setq title (concat (org-section-number level) " " title)))
15867 (insert title "\n" (make-string (string-width title) char) "\n")
15868 (setq org-ascii-current-indentation '(0 . 0)))))
15870 (defun org-export-visible (type arg)
15871 "Create a copy of the visible part of the current buffer, and export it.
15872 The copy is created in a temporary buffer and removed after use.
15873 TYPE is the final key (as a string) that also select the export command in
15874 the `C-c C-e' export dispatcher.
15875 As a special case, if the you type SPC at the prompt, the temporary
15876 org-mode file will not be removed but presented to you so that you can
15877 continue to use it. The prefix arg ARG is passed through to the exporting
15878 command."
15879 (interactive
15880 (list (progn
15881 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
15882 (read-char-exclusive))
15883 current-prefix-arg))
15884 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
15885 (error "Invalid export key"))
15886 (let* ((binding (cdr (assoc type
15887 '((?a . org-export-as-ascii)
15888 (?\C-a . org-export-as-ascii)
15889 (?b . org-export-as-html-and-open)
15890 (?\C-b . org-export-as-html-and-open)
15891 (?h . org-export-as-html)
15892 (?x . org-export-as-xoxo)))))
15893 (keepp (equal type ?\ ))
15894 (file buffer-file-name)
15895 (buffer (get-buffer-create "*Org Export Visible*"))
15896 s e)
15897 (with-current-buffer buffer (erase-buffer))
15898 (save-excursion
15899 (setq s (goto-char (point-min)))
15900 (while (not (= (point) (point-max)))
15901 (goto-char (org-find-invisible))
15902 (append-to-buffer buffer s (point))
15903 (setq s (goto-char (org-find-visible))))
15904 (goto-char (point-min))
15905 (unless keepp
15906 ;; Copy all comment lines to the end, to make sure #+ settings are
15907 ;; still available for the second export step. Kind of a hack, but
15908 ;; does do the trick.
15909 (if (looking-at "#[^\r\n]*")
15910 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
15911 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
15912 (append-to-buffer buffer (1+ (match-beginning 0))
15913 (min (point-max) (1+ (match-end 0))))))
15914 (set-buffer buffer)
15915 (let ((buffer-file-name file)
15916 (org-inhibit-startup t))
15917 (org-mode)
15918 (show-all)
15919 (unless keepp (funcall binding arg))))
15920 (if (not keepp)
15921 (kill-buffer buffer)
15922 (switch-to-buffer-other-window buffer)
15923 (goto-char (point-min)))))
15925 (defun org-find-visible ()
15926 (let ((s (point)))
15927 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
15928 (get-char-property s 'invisible)))
15930 (defun org-find-invisible ()
15931 (let ((s (point)))
15932 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
15933 (not (get-char-property s 'invisible))))
15936 ;;; HTML export
15938 (defun org-get-current-options ()
15939 "Return a string with current options as keyword options.
15940 Does include HTML export options as well as TODO and CATEGORY stuff."
15941 (format
15942 "#+TITLE: %s
15943 #+AUTHOR: %s
15944 #+EMAIL: %s
15945 #+LANGUAGE: %s
15946 #+TEXT: Some descriptive text to be emitted. Several lines OK.
15947 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
15948 #+CATEGORY: %s
15949 #+SEQ_TODO: %s
15950 #+TYP_TODO: %s
15951 #+STARTUP: %s %s %s %s %s %s
15952 #+TAGS: %s
15953 #+ARCHIVE: %s
15954 #+LINK: %s
15956 (buffer-name) (user-full-name) user-mail-address org-export-default-language
15957 org-export-headline-levels
15958 org-export-with-section-numbers
15959 org-export-with-toc
15960 org-export-preserve-breaks
15961 org-export-html-expand
15962 org-export-with-fixed-width
15963 org-export-with-tables
15964 org-export-with-sub-superscripts
15965 org-export-with-emphasize
15966 org-export-with-TeX-macros
15967 org-export-with-LaTeX-fragments
15968 (file-name-nondirectory buffer-file-name)
15969 (if (equal org-todo-interpretation 'sequence)
15970 (mapconcat 'identity org-todo-keywords " ")
15971 "TODO FEEDBACK VERIFY DONE")
15972 (if (equal org-todo-interpretation 'type)
15973 (mapconcat 'identity org-todo-keywords " ")
15974 "Me Jason Marie DONE")
15975 (cdr (assoc org-startup-folded
15976 '((nil . "showall") (t . "overview") (content . "content"))))
15977 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
15978 (if org-odd-levels-only "odd" "oddeven")
15979 (if org-hide-leading-stars "hidestars" "showstars")
15980 (if org-startup-align-all-tables "align" "noalign")
15981 (if org-log-done "logging" "nologging")
15982 (or (mapconcat (lambda (x)
15983 (cond
15984 ((equal '(:startgroup) x) "{")
15985 ((equal '(:endgroup) x) "}")
15986 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
15987 (t (car x))))
15988 (or org-tag-alist (org-get-buffer-tags)) " ") "")
15989 org-archive-location
15990 "org file:~/org/%s.org"
15993 (defun org-insert-export-options-template ()
15994 "Insert into the buffer a template with information for exporting."
15995 (interactive)
15996 (if (not (bolp)) (newline))
15997 (let ((s (org-get-current-options)))
15998 (and (string-match "#\\+CATEGORY" s)
15999 (setq s (substring s 0 (match-beginning 0))))
16000 (insert s)))
16002 (defun org-toggle-fixed-width-section (arg)
16003 "Toggle the fixed-width export.
16004 If there is no active region, the QUOTE keyword at the current headline is
16005 inserted or removed. When present, it causes the text between this headline
16006 and the next to be exported as fixed-width text, and unmodified.
16007 If there is an active region, this command adds or removes a colon as the
16008 first character of this line. If the first character of a line is a colon,
16009 this line is also exported in fixed-width font."
16010 (interactive "P")
16011 (let* ((cc 0)
16012 (regionp (org-region-active-p))
16013 (beg (if regionp (region-beginning) (point)))
16014 (end (if regionp (region-end)))
16015 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16016 (re "[ \t]*\\(:\\)")
16017 off)
16018 (if regionp
16019 (save-excursion
16020 (goto-char beg)
16021 (setq cc (current-column))
16022 (beginning-of-line 1)
16023 (setq off (looking-at re))
16024 (while (> nlines 0)
16025 (setq nlines (1- nlines))
16026 (beginning-of-line 1)
16027 (cond
16028 (arg
16029 (move-to-column cc t)
16030 (insert ":\n")
16031 (forward-line -1))
16032 ((and off (looking-at re))
16033 (replace-match "" t t nil 1))
16034 ((not off) (move-to-column cc t) (insert ":")))
16035 (forward-line 1)))
16036 (save-excursion
16037 (org-back-to-heading)
16038 (if (looking-at (concat outline-regexp
16039 "\\( +\\<" org-quote-string "\\>\\)"))
16040 (replace-match "" t t nil 1)
16041 (if (looking-at outline-regexp)
16042 (progn
16043 (goto-char (match-end 0))
16044 (insert " " org-quote-string))))))))
16046 (defun org-export-as-html-and-open (arg)
16047 "Export the outline as HTML and immediately open it with a browser.
16048 If there is an active region, export only the region.
16049 The prefix ARG specifies how many levels of the outline should become
16050 headlines. The default is 3. Lower levels will become bulleted lists."
16051 (interactive "P")
16052 (org-export-as-html arg 'hidden)
16053 (org-open-file buffer-file-name))
16055 (defun org-export-as-html-batch ()
16056 "Call `org-export-as-html', may be used in batch processing as
16057 emacs --batch
16058 --load=$HOME/lib/emacs/org.el
16059 --eval \"(setq org-export-headline-levels 2)\"
16060 --visit=MyFile --funcall org-export-as-html-batch"
16061 (org-export-as-html org-export-headline-levels 'hidden))
16063 (defun org-export-as-html (arg &optional hidden ext-plist)
16064 "Export the outline as a pretty HTML file.
16065 If there is an active region, export only the region.
16066 The prefix ARG specifies how many levels of the outline should become
16067 headlines. The default is 3. Lower levels will become bulleted lists.
16068 When HIDDEN is non-nil, don't display the HTML buffer.
16069 EXT-PLIST is a property list with external parameters overriding
16070 org-mode's default settings, but still inferior to file-local settings."
16071 (interactive "P")
16072 (message "Exporting...")
16073 (setq-default org-todo-line-regexp org-todo-line-regexp)
16074 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
16075 (setq-default org-done-string org-done-string)
16076 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
16077 ext-plist
16078 (org-infile-export-plist)))
16080 (style (plist-get opt-plist :style))
16081 (link-validate (plist-get opt-plist :link-validation-function))
16082 valid
16083 (odd org-odd-levels-only)
16084 (region-p (org-region-active-p))
16085 (region
16086 (buffer-substring
16087 (if region-p (region-beginning) (point-min))
16088 (if region-p (region-end) (point-max))))
16089 ;; The following two are dynamically scoped into other
16090 ;; routines below.
16091 (org-current-export-dir (org-export-directory :html opt-plist))
16092 (org-current-export-file buffer-file-name)
16093 (all_lines
16094 (org-skip-comments (org-split-string
16095 (org-cleaned-string-for-export
16096 region :emph-multiline
16097 (if (plist-get opt-plist :LaTeX-fragments)
16098 :LaTeX-fragments))
16099 "[\r\n]")))
16100 (lines (org-export-find-first-heading-line all_lines))
16101 (level 0) (line "") (origline "") txt todo
16102 (umax nil)
16103 (filename (concat (file-name-as-directory
16104 (org-export-directory :html opt-plist))
16105 (file-name-sans-extension
16106 (file-name-nondirectory buffer-file-name))
16107 ".html"))
16108 (current-dir (file-name-directory buffer-file-name))
16109 (buffer (find-file-noselect filename))
16110 (org-levels-open (make-vector org-level-max nil))
16111 (date (format-time-string "%Y/%m/%d" (current-time)))
16112 (time (format-time-string "%X" (org-current-time)))
16113 (author (plist-get opt-plist :author))
16114 (title (or (plist-get opt-plist :title)
16115 (file-name-sans-extension
16116 (file-name-nondirectory buffer-file-name))))
16117 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
16118 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
16119 (inquote nil)
16120 (infixed nil)
16121 (in-local-list nil)
16122 (local-list-num nil)
16123 (local-list-indent nil)
16124 (llt org-plain-list-ordered-item-terminator)
16125 (email (plist-get opt-plist :email))
16126 (language (plist-get opt-plist :language))
16127 (text (plist-get opt-plist :text))
16128 (lang-words nil)
16129 (target-alist nil) tg
16130 (head-count 0) cnt
16131 (start 0)
16132 (coding-system (and (boundp 'buffer-file-coding-system)
16133 buffer-file-coding-system))
16134 (coding-system-for-write coding-system)
16135 (save-buffer-coding-system coding-system)
16136 (charset (and coding-system
16137 (fboundp 'coding-system-get)
16138 (coding-system-get coding-system 'mime-charset)))
16139 table-open type
16140 table-buffer table-orig-buffer
16141 ind start-is-num starter
16142 rpl path desc descp desc1 desc2 link
16144 (message "Exporting...")
16146 (setq org-last-level 1)
16147 (org-init-section-numbers)
16149 ;; Get the language-dependent settings
16150 (setq lang-words (or (assoc language org-export-language-setup)
16151 (assoc "en" org-export-language-setup)))
16153 ;; Switch to the output buffer
16154 (if (or hidden (not org-export-html-show-new-buffer))
16155 (set-buffer buffer)
16156 (switch-to-buffer-other-window buffer))
16157 (erase-buffer)
16158 (fundamental-mode)
16159 (let ((case-fold-search nil)
16160 (org-odd-levels-only odd))
16161 ;; create local variables for all options, to make sure all called
16162 ;; functions get the correct information
16163 (mapcar (lambda (x)
16164 (set (make-local-variable (cdr x))
16165 (plist-get opt-plist (car x))))
16166 org-export-plist-vars)
16167 (setq umax (if arg (prefix-numeric-value arg)
16168 org-export-headline-levels))
16170 ;; File header
16171 (insert (format
16172 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
16173 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
16174 <html xmlns=\"http://www.w3.org/1999/xhtml\"
16175 lang=\"%s\" xml:lang=\"%s\">
16176 <head>
16177 <title>%s</title>
16178 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
16179 <meta name=\"generator\" content=\"Org-mode\"/>
16180 <meta name=\"generated\" content=\"%s %s\"/>
16181 <meta name=\"author\" content=\"%s\"/>
16183 </head><body>
16185 language language (org-html-expand title) (or charset "iso-8859-1")
16186 date time author style))
16189 (insert (or (plist-get opt-plist :preamble) ""))
16191 (when (plist-get opt-plist :auto-preamble)
16192 (if title (insert (format org-export-html-title-format
16193 (org-html-expand title))))
16194 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
16196 (if org-export-with-toc
16197 (progn
16198 (insert (format "<h%d>%s</h%d>\n"
16199 org-export-html-toplevel-hlevel
16200 (nth 3 lang-words)
16201 org-export-html-toplevel-hlevel))
16202 (insert "<ul>\n<li>")
16203 (setq lines
16204 (mapcar '(lambda (line)
16205 (if (string-match org-todo-line-regexp line)
16206 ;; This is a headline
16207 (progn
16208 (setq level (- (match-end 1) (match-beginning 1))
16209 level (org-tr-level level)
16210 txt (save-match-data
16211 (org-html-expand
16212 (org-export-cleanup-toc-line
16213 (match-string 3 line))))
16214 todo
16215 (or (and org-export-mark-todo-in-toc
16216 (match-beginning 2)
16217 (not (equal (match-string 2 line)
16218 org-done-string)))
16219 ; TODO, not DONE
16220 (and org-export-mark-todo-in-toc
16221 (= level umax)
16222 (org-search-todo-below
16223 line lines level))))
16224 (if (and (memq org-export-with-tags '(not-in-toc nil))
16225 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
16226 (setq txt (replace-match "" t t txt)))
16227 (if (string-match quote-re0 txt)
16228 (setq txt (replace-match "" t t txt)))
16229 (if org-export-with-section-numbers
16230 (setq txt (concat (org-section-number level)
16231 " " txt)))
16232 (if (<= level umax)
16233 (progn
16234 (setq head-count (+ head-count 1))
16235 (if (> level org-last-level)
16236 (progn
16237 (setq cnt (- level org-last-level))
16238 (while (>= (setq cnt (1- cnt)) 0)
16239 (insert "\n<ul>\n<li>"))
16240 (insert "\n")))
16241 (if (< level org-last-level)
16242 (progn
16243 (setq cnt (- org-last-level level))
16244 (while (>= (setq cnt (1- cnt)) 0)
16245 (insert "</li>\n</ul>"))
16246 (insert "\n")))
16247 ;; Check for targets
16248 (while (string-match org-target-regexp line)
16249 (setq tg (match-string 1 line)
16250 line (replace-match
16251 (concat "@<span class=\"target\">" tg "@</span> ")
16252 t t line))
16253 (push (cons (org-solidify-link-text tg)
16254 (format "sec-%d" head-count))
16255 target-alist))
16256 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
16257 (setq txt (replace-match "" t t txt)))
16258 (insert
16259 (format
16260 (if todo
16261 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
16262 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
16263 head-count txt))
16265 (setq org-last-level level))
16267 line)
16268 lines))
16269 (while (> org-last-level 0)
16270 (setq org-last-level (1- org-last-level))
16271 (insert "</li>\n</ul>\n"))
16273 (setq head-count 0)
16274 (org-init-section-numbers)
16276 (while (setq line (pop lines) origline line)
16277 (catch 'nextline
16279 ;; end of quote section?
16280 (when (and inquote (string-match "^\\*+" line))
16281 (insert "</pre>\n")
16282 (setq inquote nil))
16283 ;; inside a quote section?
16284 (when inquote
16285 (insert (org-html-protect line) "\n")
16286 (throw 'nextline nil))
16288 ;; verbatim lines
16289 (when (and org-export-with-fixed-width
16290 (string-match "^[ \t]*:\\(.*\\)" line))
16291 (when (not infixed)
16292 (setq infixed t)
16293 (insert "<pre>\n"))
16294 (insert (org-html-protect (match-string 1 line)) "\n")
16295 (when (and lines
16296 (not (string-match "^[ \t]*\\(:.*\\)"
16297 (car lines))))
16298 (setq infixed nil)
16299 (insert "</pre>\n"))
16300 (throw 'nextline nil))
16303 ;; make targets to anchors
16304 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
16305 (cond
16306 ((match-end 2)
16307 (setq line (replace-match
16308 (concat "@<a name=\""
16309 (org-solidify-link-text (match-string 1 line))
16310 "\">\\nbsp@</a>")
16311 t t line)))
16312 ((and org-export-with-toc (equal (string-to-char line) ?*))
16313 (setq line (replace-match
16314 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
16315 ; (concat "@<i>" (match-string 1 line) "@</i> ")
16316 t t line)))
16318 (setq line (replace-match
16319 (concat "@<a name=\""
16320 (org-solidify-link-text (match-string 1 line))
16321 "\" class=\"target\">" (match-string 1 line) "@</a> ")
16322 t t line)))))
16324 (setq line (org-html-handle-time-stamps line))
16326 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
16327 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
16328 ;; Also handle sub_superscripts and checkboxes
16329 (setq line (org-html-expand line))
16331 ;; Format the links
16332 (setq start 0)
16333 (while (string-match org-bracket-link-analytic-regexp line start)
16334 (setq start (match-beginning 0))
16335 (setq type (if (match-end 2) (match-string 2 line) "internal"))
16336 (setq path (match-string 3 line))
16337 (setq desc1 (if (match-end 5) (match-string 5 line))
16338 desc2 (if (match-end 2) (concat type ":" path) path)
16339 descp (and desc1 (not (equal desc1 desc2)))
16340 desc (or desc1 desc2))
16341 ;; FIXME: do we need to unescape here somewhere?
16342 (cond
16343 ((equal type "internal")
16344 (setq rpl
16345 (concat
16346 "<a href=\"#"
16347 (org-solidify-link-text path target-alist)
16348 "\">" desc "</a>")))
16349 ((member type '("http" "https" "ftp" "mailto" "news"))
16350 ;; standard URL
16351 (setq link (concat type ":" path))
16352 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
16353 ((string= type "file")
16354 ;; FILE link
16355 (let* ((filename path)
16356 (abs-p (file-name-absolute-p filename))
16357 thefile file-is-image-p search)
16358 (save-match-data
16359 (if (string-match "::\\(.*\\)" filename)
16360 (setq search (match-string 1 filename)
16361 filename (replace-match "" t nil filename)))
16362 (setq valid
16363 (if (functionp link-validate)
16364 (funcall link-validate filename current-dir)
16366 (setq file-is-image-p
16367 (string-match (org-image-file-name-regexp) filename))
16368 (setq thefile (if abs-p (expand-file-name filename) filename))
16369 (when (and org-export-html-link-org-files-as-html
16370 (string-match "\\.org$" thefile))
16371 (setq thefile (concat (substring thefile 0
16372 (match-beginning 0))
16373 ".html"))
16374 (if (and search
16375 ;; make sure this is can be used as target search
16376 (not (string-match "^[0-9]*$" search))
16377 (not (string-match "^\\*" search))
16378 (not (string-match "^/.*/$" search)))
16379 (setq thefile (concat thefile "#"
16380 (org-solidify-link-text
16381 (org-link-unescape search)))))
16382 (when (string-match "^file:" desc)
16383 (setq desc (replace-match "" t t desc))
16384 (if (string-match "\\.org$" desc)
16385 (setq desc (replace-match "" t t desc))))))
16386 (setq rpl (if (and file-is-image-p
16387 (or (eq t org-export-html-inline-images)
16388 (and org-export-html-inline-images
16389 (not descp))))
16390 (concat "<img src=\"" thefile "\"/>")
16391 (concat "<a href=\"" thefile "\">" desc "</a>")))
16392 (if (not valid) (setq rpl desc))))
16393 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
16394 (setq rpl (concat "<i>&lt;" type ":"
16395 (save-match-data (org-link-unescape path))
16396 "&gt;</i>"))))
16397 (setq line (replace-match rpl t t line)
16398 start (+ start (length rpl))))
16399 ;; TODO items
16400 (if (and (string-match org-todo-line-regexp line)
16401 (match-beginning 2))
16402 (if (equal (match-string 2 line) org-done-string)
16403 (setq line (replace-match
16404 "<span class=\"done\">\\2</span>"
16405 t nil line 2))
16406 (setq line (replace-match "<span class=\"todo\">\\2</span>"
16407 t nil line 2))))
16409 (cond
16410 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
16411 ;; This is a headline
16412 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
16413 txt (match-string 2 line))
16414 (if (string-match quote-re0 txt)
16415 (setq txt (replace-match "" t t txt)))
16416 (if (<= level umax) (setq head-count (+ head-count 1)))
16417 (when in-local-list
16418 ;; Close any local lists before inserting a new header line
16419 (while local-list-num
16420 (org-close-li)
16421 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
16422 (pop local-list-num))
16423 (setq local-list-indent nil
16424 in-local-list nil))
16425 (org-html-level-start level txt umax
16426 (and org-export-with-toc (<= level umax))
16427 head-count)
16428 ;; QUOTES
16429 (when (string-match quote-re line)
16430 (insert "<pre>")
16431 (setq inquote t)))
16433 ((and org-export-with-tables
16434 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
16435 (if (not table-open)
16436 ;; New table starts
16437 (setq table-open t table-buffer nil table-orig-buffer nil))
16438 ;; Accumulate lines
16439 (setq table-buffer (cons line table-buffer)
16440 table-orig-buffer (cons origline table-orig-buffer))
16441 (when (or (not lines)
16442 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
16443 (car lines))))
16444 (setq table-open nil
16445 table-buffer (nreverse table-buffer)
16446 table-orig-buffer (nreverse table-orig-buffer))
16447 (org-close-par-maybe)
16448 (insert (org-format-table-html table-buffer table-orig-buffer))))
16450 ;; Normal lines
16451 (when (string-match
16452 (cond
16453 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
16454 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
16455 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
16456 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
16457 line)
16458 (setq ind (org-get-string-indentation line)
16459 start-is-num (match-beginning 4)
16460 starter (if (match-beginning 2)
16461 (substring (match-string 2 line) 0 -1))
16462 line (substring line (match-beginning 5)))
16463 (unless (string-match "[^ \t]" line)
16464 ;; empty line. Pretend indentation is large.
16465 (setq ind (1+ (or (car local-list-indent) 1))))
16466 (while (and in-local-list
16467 (or (and (= ind (car local-list-indent))
16468 (not starter))
16469 (< ind (car local-list-indent))))
16470 (org-close-li)
16471 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
16472 (pop local-list-num) (pop local-list-indent)
16473 (setq in-local-list local-list-indent))
16474 (cond
16475 ((and starter
16476 (or (not in-local-list)
16477 (> ind (car local-list-indent))))
16478 ;; Start new (level of ) list
16479 (org-close-par-maybe)
16480 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
16481 (push start-is-num local-list-num)
16482 (push ind local-list-indent)
16483 (setq in-local-list t))
16484 (starter
16485 ;; continue current list
16486 (org-close-li)
16487 (insert "<li>\n")))
16488 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
16489 (setq line
16490 (replace-match
16491 (if (equal (match-string 1 line) "X")
16492 "<b>[X]</b>"
16493 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
16494 t t line))))
16496 ;; Empty lines start a new paragraph. If hand-formatted lists
16497 ;; are not fully interpreted, lines starting with "-", "+", "*"
16498 ;; also start a new paragraph.
16499 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
16501 ;; Check if the line break needs to be conserved
16502 (cond
16503 ((string-match "\\\\\\\\[ \t]*$" line)
16504 (setq line (replace-match "<br/>" t t line)))
16505 (org-export-preserve-breaks
16506 (setq line (concat line "<br/>"))))
16508 (insert line "\n")))))
16510 ;; Properly close all local lists and other lists
16511 (when inquote (insert "</pre>\n"))
16512 (when in-local-list
16513 ;; Close any local lists before inserting a new header line
16514 (while local-list-num
16515 (org-close-li)
16516 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
16517 (pop local-list-num))
16518 (setq local-list-indent nil
16519 in-local-list nil))
16520 (org-html-level-start 1 nil umax
16521 (and org-export-with-toc (<= level umax))
16522 head-count)
16524 (when (plist-get opt-plist :auto-postamble)
16525 (when author
16526 (insert "<p class=\"author\"> "
16527 (nth 1 lang-words) ": " author "\n")
16528 (when email
16529 (insert "<a href=\"mailto:" email "\">&lt;"
16530 email "&gt;</a>\n"))
16531 (insert "</p>\n"))
16532 (when (and date time)
16533 (insert "<p class=\"date\"> "
16534 (nth 2 lang-words) ": "
16535 date " " time "</p>\n")))
16537 (if org-export-html-with-timestamp
16538 (insert org-export-html-html-helper-timestamp))
16539 (insert (or (plist-get opt-plist :postamble) ""))
16540 (insert "</body>\n</html>\n")
16541 (normal-mode)
16542 ;; remove empty paragraphs and lists
16543 (goto-char (point-min))
16544 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
16545 (replace-match ""))
16546 (goto-char (point-min))
16547 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
16548 (replace-match ""))
16549 (save-buffer)
16550 (goto-char (point-min))
16551 (message "Exporting... done"))))
16554 (defun org-format-table-html (lines olines)
16555 "Find out which HTML converter to use and return the HTML code."
16556 (if (string-match "^[ \t]*|" (car lines))
16557 ;; A normal org table
16558 (org-format-org-table-html lines)
16559 ;; Table made by table.el - test for spanning
16560 (let* ((hlines (delq nil (mapcar
16561 (lambda (x)
16562 (if (string-match "^[ \t]*\\+-" x) x
16563 nil))
16564 lines)))
16565 (first (car hlines))
16566 (ll (and (string-match "\\S-+" first)
16567 (match-string 0 first)))
16568 (re (concat "^[ \t]*" (regexp-quote ll)))
16569 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
16570 hlines))))
16571 (if (and (not spanning)
16572 (not org-export-prefer-native-exporter-for-tables))
16573 ;; We can use my own converter with HTML conversions
16574 (org-format-table-table-html lines)
16575 ;; Need to use the code generator in table.el, with the original text.
16576 (org-format-table-table-html-using-table-generate-source olines)))))
16578 (defun org-format-org-table-html (lines)
16579 "Format a table into HTML."
16580 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
16581 (setq lines (nreverse lines))
16582 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
16583 (setq lines (nreverse lines))
16584 (when org-export-table-remove-special-lines
16585 ;; Check if the table has a marking column. If yes remove the
16586 ;; column and the special lines
16587 (let* ((special
16588 (not
16589 (memq nil
16590 (mapcar
16591 (lambda (x)
16592 (or (string-match "^[ \t]*|-" x)
16593 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
16594 lines)))))
16595 (if special
16596 (setq lines
16597 (delq nil
16598 (mapcar
16599 (lambda (x)
16600 (if (string-match "^[ \t]*| *[!_^] *|" x)
16601 nil ; ignore this line
16602 (and (or (string-match "^[ \t]*|-+\\+" x)
16603 (string-match "^[ \t]*|[^|]*|" x))
16604 (replace-match "|" t t x))))
16605 lines))))))
16607 (let ((head (and org-export-highlight-first-table-line
16608 (delq nil (mapcar
16609 (lambda (x) (string-match "^[ \t]*|-" x))
16610 (cdr lines)))))
16611 line fields html)
16612 (setq html (concat org-export-html-table-tag "\n"))
16613 (while (setq line (pop lines))
16614 (catch 'next-line
16615 (if (string-match "^[ \t]*|-" line)
16616 (progn
16617 (setq head nil) ;; head ends here, first time around
16618 ;; ignore this line
16619 (throw 'next-line t)))
16620 ;; Break the line into fields
16621 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
16622 (setq html (concat
16623 html
16624 "<tr>"
16625 (mapconcat (lambda (x)
16626 (if head
16627 (concat "<th>" x "</th>")
16628 (concat "<td>" x "</td>")))
16629 fields "")
16630 "</tr>\n"))))
16631 (setq html (concat html "</table>\n"))
16632 html))
16634 (defun org-fake-empty-table-line (line)
16635 "Replace everything except \"|\" with spaces."
16636 (let ((i (length line))
16637 (newstr (copy-sequence line)))
16638 (while (> i 0)
16639 (setq i (1- i))
16640 (if (not (eq (aref newstr i) ?|))
16641 (aset newstr i ?\ )))
16642 newstr))
16644 (defun org-format-table-table-html (lines)
16645 "Format a table generated by table.el into HTML.
16646 This conversion does *not* use `table-generate-source' from table.el.
16647 This has the advantage that Org-mode's HTML conversions can be used.
16648 But it has the disadvantage, that no cell- or row-spanning is allowed."
16649 (let (line field-buffer
16650 (head org-export-highlight-first-table-line)
16651 fields html empty)
16652 (setq html (concat org-export-html-table-tag "\n"))
16653 (while (setq line (pop lines))
16654 (setq empty "&nbsp;")
16655 (catch 'next-line
16656 (if (string-match "^[ \t]*\\+-" line)
16657 (progn
16658 (if field-buffer
16659 (progn
16660 (setq html (concat
16661 html
16662 "<tr>"
16663 (mapconcat
16664 (lambda (x)
16665 (if (equal x "") (setq x empty))
16666 (if head
16667 (concat "<th>" x "</th>\n")
16668 (concat "<td>" x "</td>\n")))
16669 field-buffer "\n")
16670 "</tr>\n"))
16671 (setq head nil)
16672 (setq field-buffer nil)))
16673 ;; Ignore this line
16674 (throw 'next-line t)))
16675 ;; Break the line into fields and store the fields
16676 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
16677 (if field-buffer
16678 (setq field-buffer (mapcar
16679 (lambda (x)
16680 (concat x "<br/>" (pop fields)))
16681 field-buffer))
16682 (setq field-buffer fields))))
16683 (setq html (concat html "</table>\n"))
16684 html))
16686 (defun org-format-table-table-html-using-table-generate-source (lines)
16687 "Format a table into html, using `table-generate-source' from table.el.
16688 This has the advantage that cell- or row-spanning is allowed.
16689 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
16690 (require 'table)
16691 (with-current-buffer (get-buffer-create " org-tmp1 ")
16692 (erase-buffer)
16693 (insert (mapconcat 'identity lines "\n"))
16694 (goto-char (point-min))
16695 (if (not (re-search-forward "|[^+]" nil t))
16696 (error "Error processing table"))
16697 (table-recognize-table)
16698 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
16699 (table-generate-source 'html " org-tmp2 ")
16700 (set-buffer " org-tmp2 ")
16701 (buffer-substring (point-min) (point-max))))
16703 (defun org-html-handle-time-stamps (s)
16704 "Format time stamps in string S, or remove them."
16705 (catch 'exit
16706 (let (r b)
16707 (while (string-match org-maybe-keyword-time-regexp s)
16708 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
16709 ;; never export CLOCK
16710 (throw 'exit ""))
16711 (or b (setq b (substring s 0 (match-beginning 0))))
16712 (if (not org-export-with-timestamps)
16713 (setq r (concat r (substring s 0 (match-beginning 0)))
16714 s (substring s (match-end 0)))
16715 (setq r (concat
16716 r (substring s 0 (match-beginning 0))
16717 (if (match-end 1)
16718 (format "@<span class=\"timestamp-kwd\">%s @</span>"
16719 (match-string 1 s)))
16720 (format " @<span class=\"timestamp\">%s@</span>"
16721 (substring
16722 (org-translate-time (match-string 3 s)) 1 -1)))
16723 s (substring s (match-end 0)))))
16724 ;; Line break if line started and ended with time stamp stuff
16725 (if (not r)
16727 (setq r (concat r s))
16728 (unless (string-match "\\S-" (concat b s))
16729 (setq r (concat r "@<br/>")))
16730 r))))
16732 (defun org-html-protect (s)
16733 ;; convert & to &amp;, < to &lt; and > to &gt;
16734 (let ((start 0))
16735 (while (string-match "&" s start)
16736 (setq s (replace-match "&amp;" t t s)
16737 start (1+ (match-beginning 0))))
16738 (while (string-match "<" s)
16739 (setq s (replace-match "&lt;" t t s)))
16740 (while (string-match ">" s)
16741 (setq s (replace-match "&gt;" t t s))))
16744 (defun org-export-cleanup-toc-line (s)
16745 "Remove tags and time staps from lines going into the toc."
16746 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
16747 (setq s (replace-match "" t t s)))
16748 (when org-export-remove-timestamps-from-toc
16749 (while (string-match org-maybe-keyword-time-regexp s)
16750 (setq s (replace-match "" t t s))))
16753 (defun org-html-expand (string)
16754 "Prepare STRING for HTML export. Applies all active conversions.
16755 If there are links in the string, don't modify these."
16756 (let* (m s l res)
16757 (while (setq m (string-match org-bracket-link-regexp string))
16758 (setq s (substring string 0 m)
16759 l (match-string 0 string)
16760 string (substring string (match-end 0)))
16761 (push (org-html-do-expand s) res)
16762 (push l res))
16763 (push (org-html-do-expand string) res)
16764 (apply 'concat (nreverse res))))
16766 (defun org-html-do-expand (s)
16767 "Apply all active conversions to translate special ASCII to HTML."
16768 (setq s (org-html-protect s))
16769 (if org-export-html-expand
16770 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
16771 (setq s (replace-match "<\\1>" t nil s))))
16772 (if org-export-with-emphasize
16773 (setq s (org-export-html-convert-emphasize s)))
16774 (if org-export-with-sub-superscripts
16775 (setq s (org-export-html-convert-sub-super s)))
16776 (if org-export-with-TeX-macros
16777 (let ((start 0) wd ass)
16778 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
16779 (setq wd (match-string 1 s))
16780 (if (setq ass (assoc wd org-html-entities))
16781 (setq s (replace-match (or (cdr ass)
16782 (concat "&" (car ass) ";"))
16783 t t s))
16784 (setq start (+ start (length wd)))))))
16787 (defun org-create-multibrace-regexp (left right n)
16788 "Create a regular expression which will match a balanced sexp.
16789 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
16790 as single character strings.
16791 The regexp returned will match the entire expression including the
16792 delimiters. It will also define a single group which contains the
16793 match except for the outermost delimiters. The maximum depth of
16794 stacked delimiters is N. Escaping delimiters is not possible."
16795 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
16796 (or "\\|")
16797 (re nothing)
16798 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
16799 (while (> n 1)
16800 (setq n (1- n)
16801 re (concat re or next)
16802 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
16803 (concat left "\\(" re "\\)" right)))
16805 (defvar org-match-substring-regexp
16806 (concat
16807 "\\([^\\]\\)\\([_^]\\)\\("
16808 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
16809 "\\|"
16810 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
16811 "\\|"
16812 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
16813 "The regular expression matching a sub- or superscript.")
16815 (defun org-export-html-convert-sub-super (string)
16816 "Convert sub- and superscripts in STRING to HTML."
16817 (let (key c)
16818 (while (string-match org-match-substring-regexp string)
16819 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
16820 (setq c (or (match-string 8 string)
16821 (match-string 6 string)
16822 (match-string 5 string)))
16823 (setq string (replace-match
16824 (concat (match-string 1 string)
16825 "<" key ">" c "</" key ">")
16826 t t string)))
16827 (while (string-match "\\\\\\([_^]\\)" string)
16828 (setq string (replace-match (match-string 1 string) t t string))))
16829 string)
16831 (defun org-export-html-convert-emphasize (string)
16832 "Apply emphasis."
16833 (while (string-match org-emph-re string)
16834 (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)))
16835 string)
16837 (defvar org-par-open nil)
16838 (defun org-open-par ()
16839 "Insert <p>, but first close previous paragraph if any."
16840 (org-close-par-maybe)
16841 (insert "\n<p>")
16842 (setq org-par-open t))
16843 (defun org-close-par-maybe ()
16844 "Close paragraph if there is one open."
16845 (when org-par-open
16846 (insert "</p>")
16847 (setq org-par-open nil)))
16848 (defun org-close-li ()
16849 "Close <li> if necessary."
16850 (org-close-par-maybe)
16851 (insert "</li>\n"))
16852 ; (when (save-excursion
16853 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
16854 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
16855 ; (insert "</li>"))))
16857 (defun org-html-level-start (level title umax with-toc head-count)
16858 "Insert a new level in HTML export.
16859 When TITLE is nil, just close all open levels."
16860 (org-close-par-maybe)
16861 (let ((l (1+ (max level umax))))
16862 (while (<= l org-level-max)
16863 (if (aref org-levels-open (1- l))
16864 (progn
16865 (org-html-level-close l)
16866 (aset org-levels-open (1- l) nil)))
16867 (setq l (1+ l)))
16868 (when title
16869 ;; If title is nil, this means this function is called to close
16870 ;; all levels, so the rest is done only if title is given
16871 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
16872 (setq title (replace-match
16873 (if org-export-with-tags
16874 (save-match-data
16875 (concat
16876 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
16877 (mapconcat 'identity (org-split-string
16878 (match-string 1 title) ":")
16879 "&nbsp;")
16880 "</span>"))
16882 t t title)))
16883 (if (> level umax)
16884 (progn
16885 (if (aref org-levels-open (1- level))
16886 (progn
16887 (org-close-li)
16888 (insert "<li>" title "<br/>\n"))
16889 (aset org-levels-open (1- level) t)
16890 (org-close-par-maybe)
16891 (insert "<ul>\n<li>" title "<br/>\n")))
16892 (if org-export-with-section-numbers
16893 (setq title (concat (org-section-number level) " " title)))
16894 (setq level (+ level org-export-html-toplevel-hlevel -1))
16895 (if with-toc
16896 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
16897 level head-count title level))
16898 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
16899 (org-open-par)))))
16901 (defun org-html-level-close (&rest args)
16902 "Terminate one level in HTML export."
16903 (org-close-li)
16904 (insert "</ul>"))
16906 ;;; iCalendar export
16908 ;;;###autoload
16909 (defun org-export-icalendar-this-file ()
16910 "Export current file as an iCalendar file.
16911 The iCalendar file will be located in the same directory as the Org-mode
16912 file, but with extension `.ics'."
16913 (interactive)
16914 (org-export-icalendar nil buffer-file-name))
16916 ;;;###autoload
16917 (defun org-export-icalendar-all-agenda-files ()
16918 "Export all files in `org-agenda-files' to iCalendar .ics files.
16919 Each iCalendar file will be located in the same directory as the Org-mode
16920 file, but with extension `.ics'."
16921 (interactive)
16922 (apply 'org-export-icalendar nil (org-agenda-files t)))
16924 ;;;###autoload
16925 (defun org-export-icalendar-combine-agenda-files ()
16926 "Export all files in `org-agenda-files' to a single combined iCalendar file.
16927 The file is stored under the name `org-combined-agenda-icalendar-file'."
16928 (interactive)
16929 (apply 'org-export-icalendar t (org-agenda-files t)))
16931 (defun org-export-icalendar (combine &rest files)
16932 "Create iCalendar files for all elements of FILES.
16933 If COMBINE is non-nil, combine all calendar entries into a single large
16934 file and store it under the name `org-combined-agenda-icalendar-file'."
16935 (save-excursion
16936 (let* ((dir (org-export-directory
16937 :ical (list :publishing-directory
16938 org-export-publishing-directory)))
16939 file ical-file ical-buffer category started org-agenda-new-buffers)
16941 (when combine
16942 (setq ical-file
16943 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
16944 org-combined-agenda-icalendar-file
16945 (expand-file-name org-combined-agenda-icalendar-file dir))
16946 ical-buffer (org-get-agenda-file-buffer ical-file))
16947 (set-buffer ical-buffer) (erase-buffer))
16948 (while (setq file (pop files))
16949 (catch 'nextfile
16950 (org-check-agenda-file file)
16951 (set-buffer (org-get-agenda-file-buffer file))
16952 (unless combine
16953 (setq ical-file (concat (file-name-as-directory dir)
16954 (file-name-sans-extension
16955 (file-name-nondirectory buffer-file-name))
16956 ".ics"))
16957 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
16958 (with-current-buffer ical-buffer (erase-buffer)))
16959 (setq category (or org-category
16960 (file-name-sans-extension
16961 (file-name-nondirectory buffer-file-name))))
16962 (if (symbolp category) (setq category (symbol-name category)))
16963 (let ((standard-output ical-buffer))
16964 (if combine
16965 (and (not started) (setq started t)
16966 (org-start-icalendar-file org-icalendar-combined-name))
16967 (org-start-icalendar-file category))
16968 (org-print-icalendar-entries combine category)
16969 (when (or (and combine (not files)) (not combine))
16970 (org-finish-icalendar-file)
16971 (set-buffer ical-buffer)
16972 (save-buffer)
16973 (run-hooks 'org-after-save-iCalendar-file-hook)))))
16974 (org-release-buffers org-agenda-new-buffers))))
16976 (defvar org-after-save-iCalendar-file-hook nil
16977 "Hook run after an iCalendar file has been saved.
16978 The iCalendar buffer is still current when this hook is run.
16979 A good way to use this is to tell a desktop calenndar application to re-read
16980 the iCalendar file.")
16983 ;; FIXME: Strip down the links
16984 (defun org-print-icalendar-entries (&optional combine category)
16985 "Print iCalendar entries for the current Org-mode file to `standard-output'.
16986 When COMBINE is non nil, add the category to each line."
16987 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
16988 (dts (org-ical-ts-to-string
16989 (format-time-string (cdr org-time-stamp-formats) (current-time))
16990 "DTSTART"))
16991 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
16992 (save-excursion
16993 (goto-char (point-min))
16994 (while (re-search-forward org-ts-regexp nil t)
16995 (setq pos (match-beginning 0)
16996 ts (match-string 0)
16997 inc t
16998 hd (org-get-heading))
16999 (if (looking-at re2)
17000 (progn
17001 (goto-char (match-end 0))
17002 (setq ts2 (match-string 1) inc nil))
17003 (setq ts2 ts
17004 tmp (buffer-substring (max (point-min)
17005 (- pos org-ds-keyword-length))
17006 pos)
17007 deadlinep (string-match org-deadline-regexp tmp)
17008 scheduledp (string-match org-scheduled-regexp tmp)
17009 ;; donep (org-entry-is-done-p)
17011 (if (or (string-match org-tr-regexp hd)
17012 (string-match org-ts-regexp hd))
17013 (setq hd (replace-match "" t t hd)))
17014 (if deadlinep (setq hd (concat "DL: " hd)))
17015 (if scheduledp (setq hd (concat "S: " hd)))
17016 (princ (format "BEGIN:VEVENT
17019 SUMMARY:%s
17020 CATEGORIES:%s
17021 END:VEVENT\n"
17022 (org-ical-ts-to-string ts "DTSTART")
17023 (org-ical-ts-to-string ts2 "DTEND" inc)
17024 hd category)))
17025 (when org-icalendar-include-todo
17026 (goto-char (point-min))
17027 (while (re-search-forward org-todo-line-regexp nil t)
17028 (setq state (match-string 1))
17029 (unless (equal state org-done-string)
17030 (setq hd (match-string 3))
17031 (if (string-match org-priority-regexp hd)
17032 (setq pri (string-to-char (match-string 2 hd))
17033 hd (concat (substring hd 0 (match-beginning 1))
17034 (substring hd (- (match-end 1)))))
17035 (setq pri org-default-priority))
17036 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
17037 (- org-lowest-priority ?A))))))
17039 (princ (format "BEGIN:VTODO
17041 SUMMARY:%s
17042 CATEGORIES:%s
17043 SEQUENCE:1
17044 PRIORITY:%d
17045 END:VTODO\n"
17046 dts hd category pri))))))))
17048 (defun org-start-icalendar-file (name)
17049 "Start an iCalendar file by inserting the header."
17050 (let ((user user-full-name)
17051 (name (or name "unknown"))
17052 (timezone (cadr (current-time-zone))))
17053 (princ
17054 (format "BEGIN:VCALENDAR
17055 VERSION:2.0
17056 X-WR-CALNAME:%s
17057 PRODID:-//%s//Emacs with Org-mode//EN
17058 X-WR-TIMEZONE:%s
17059 CALSCALE:GREGORIAN\n" name user timezone))))
17061 (defun org-finish-icalendar-file ()
17062 "Finish an iCalendar file by inserting the END statement."
17063 (princ "END:VCALENDAR\n"))
17065 (defun org-ical-ts-to-string (s keyword &optional inc)
17066 "Take a time string S and convert it to iCalendar format.
17067 KEYWORD is added in front, to make a complete line like DTSTART....
17068 When INC is non-nil, increase the hour by two (if time string contains
17069 a time), or the day by one (if it does not contain a time)."
17070 (let ((t1 (org-parse-time-string s 'nodefault))
17071 t2 fmt have-time time)
17072 (if (and (car t1) (nth 1 t1) (nth 2 t1))
17073 (setq t2 t1 have-time t)
17074 (setq t2 (org-parse-time-string s)))
17075 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
17076 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
17077 (when inc
17078 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
17079 (setq time (encode-time s mi h d m y)))
17080 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
17081 (concat keyword (format-time-string fmt time))))
17083 ;;; XOXO export
17085 (defun org-export-as-xoxo-insert-into (buffer &rest output)
17086 (with-current-buffer buffer
17087 (apply 'insert output)))
17088 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
17090 (defun org-export-as-xoxo (&optional buffer)
17091 "Export the org buffer as XOXO.
17092 The XOXO buffer is named *xoxo-<source buffer name>*"
17093 (interactive (list (current-buffer)))
17094 ;; A quickie abstraction
17096 ;; Output everything as XOXO
17097 (with-current-buffer (get-buffer buffer)
17098 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
17099 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
17100 (org-infile-export-plist)))
17101 (filename (concat (file-name-as-directory
17102 (org-export-directory :xoxo opt-plist))
17103 (file-name-sans-extension
17104 (file-name-nondirectory buffer-file-name))
17105 ".html"))
17106 (out (find-file-noselect filename))
17107 (last-level 1)
17108 (hanging-li nil))
17109 ;; Check the output buffer is empty.
17110 (with-current-buffer out (erase-buffer))
17111 ;; Kick off the output
17112 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
17113 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
17114 (let* ((hd (match-string-no-properties 1))
17115 (level (length hd))
17116 (text (concat
17117 (match-string-no-properties 2)
17118 (save-excursion
17119 (goto-char (match-end 0))
17120 (let ((str ""))
17121 (catch 'loop
17122 (while 't
17123 (forward-line)
17124 (if (looking-at "^[ \t]\\(.*\\)")
17125 (setq str (concat str (match-string-no-properties 1)))
17126 (throw 'loop str)))))))))
17128 ;; Handle level rendering
17129 (cond
17130 ((> level last-level)
17131 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
17133 ((< level last-level)
17134 (dotimes (- (- last-level level) 1)
17135 (if hanging-li
17136 (org-export-as-xoxo-insert-into out "</li>\n"))
17137 (org-export-as-xoxo-insert-into out "</ol>\n"))
17138 (when hanging-li
17139 (org-export-as-xoxo-insert-into out "</li>\n")
17140 (setq hanging-li nil)))
17142 ((equal level last-level)
17143 (if hanging-li
17144 (org-export-as-xoxo-insert-into out "</li>\n")))
17147 (setq last-level level)
17149 ;; And output the new li
17150 (setq hanging-li 't)
17151 (if (equal ?+ (elt text 0))
17152 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
17153 (org-export-as-xoxo-insert-into out "<li>" text))))
17155 ;; Finally finish off the ol
17156 (dotimes (- last-level 1)
17157 (if hanging-li
17158 (org-export-as-xoxo-insert-into out "</li>\n"))
17159 (org-export-as-xoxo-insert-into out "</ol>\n"))
17161 ;; Finish the buffer off and clean it up.
17162 (switch-to-buffer-other-window out)
17163 (indent-region (point-min) (point-max) nil)
17164 (save-buffer)
17165 (goto-char (point-min))
17169 ;;;; Key bindings
17171 ;; - Bindings in Org-mode map are currently
17172 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
17173 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
17174 ;; e (?) useful from outline-mode
17175 ;; i k @ expendable from outline-mode
17176 ;; 0123456789 % & ()_{} " ` free
17178 ;; Make `C-c C-x' a prefix key
17179 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
17181 ;; TAB key with modifiers
17182 (define-key org-mode-map "\C-i" 'org-cycle)
17183 (define-key org-mode-map [(tab)] 'org-cycle)
17184 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
17185 (define-key org-mode-map [(meta tab)] 'org-complete)
17186 (define-key org-mode-map "\M-\C-i" 'org-complete)
17187 ;; The following line is necessary under Suse GNU/Linux
17188 (unless (featurep 'xemacs)
17189 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
17190 (define-key org-mode-map [(shift tab)] 'org-shifttab)
17192 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
17193 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17194 (define-key org-mode-map [(meta return)] 'org-meta-return)
17196 ;; Cursor keys with modifiers
17197 (define-key org-mode-map [(meta left)] 'org-metaleft)
17198 (define-key org-mode-map [(meta right)] 'org-metaright)
17199 (define-key org-mode-map [(meta up)] 'org-metaup)
17200 (define-key org-mode-map [(meta down)] 'org-metadown)
17202 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17203 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
17204 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
17205 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
17207 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
17208 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
17209 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
17210 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
17212 ;;; Extra keys for tty access.
17213 ;; We only set them when really needed because otherwise the
17214 ;; menus don't show the simple keys
17216 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17217 (not window-system))
17218 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17219 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17220 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return)
17221 (define-key org-mode-map [?\e (return)] 'org-meta-return)
17222 (define-key org-mode-map [?\e (left)] 'org-metaleft)
17223 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft)
17224 (define-key org-mode-map [?\e (right)] 'org-metaright)
17225 (define-key org-mode-map "\C-c\C-xr" 'org-metaright)
17226 (define-key org-mode-map [?\e (up)] 'org-metaup)
17227 (define-key org-mode-map "\C-c\C-xu" 'org-metaup)
17228 (define-key org-mode-map [?\e (down)] 'org-metadown)
17229 (define-key org-mode-map "\C-c\C-xd" 'org-metadown)
17230 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17231 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17232 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17233 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17234 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
17235 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
17236 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
17237 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright))
17239 ;; All the other keys
17241 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17242 (define-key org-mode-map "\C-c\C-r" 'org-reveal)
17243 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
17244 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
17245 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
17246 (define-key org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17247 (define-key org-mode-map "\C-c\C-j" 'org-goto)
17248 (define-key org-mode-map "\C-c\C-t" 'org-todo)
17249 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
17250 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
17251 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
17252 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
17253 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
17254 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
17255 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
17256 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
17257 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
17258 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
17259 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
17260 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
17261 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
17262 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
17263 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17264 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17265 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17266 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17267 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
17268 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
17269 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17270 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
17271 (define-key org-mode-map "\C-c]" 'org-remove-file)
17272 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
17273 (define-key org-mode-map "\C-c^" 'org-sort)
17274 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17275 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
17276 (define-key org-mode-map "\C-m" 'org-return)
17277 (define-key org-mode-map "\C-c?" 'org-table-current-column)
17278 (define-key org-mode-map "\C-c " 'org-table-blank-field)
17279 (define-key org-mode-map "\C-c+" 'org-table-sum)
17280 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
17281 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
17282 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
17283 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17284 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
17285 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17286 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
17287 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
17288 (define-key org-mode-map "\C-c\C-e" 'org-export)
17289 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17291 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
17292 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17293 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17294 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17296 (define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17297 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17298 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17299 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17300 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17301 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17302 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17303 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17304 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17306 (when (featurep 'xemacs)
17307 (define-key org-mode-map 'button3 'popup-mode-menu))
17309 (defsubst org-table-p () (org-at-table-p))
17311 (defun org-self-insert-command (N)
17312 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17313 If the cursor is in a table looking at whitespace, the whitespace is
17314 overwritten, and the table is not marked as requiring realignment."
17315 (interactive "p")
17316 (if (and (org-table-p)
17317 (progn
17318 ;; check if we blank the field, and if that triggers align
17319 (and org-table-auto-blank-field
17320 (member last-command
17321 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
17322 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17323 ;; got extra space, this field does not determine column width
17324 (let (org-table-may-need-update) (org-table-blank-field))
17325 ;; no extra space, this field may determine column width
17326 (org-table-blank-field)))
17328 (eq N 1)
17329 (looking-at "[^|\n]* |"))
17330 (let (org-table-may-need-update)
17331 (goto-char (1- (match-end 0)))
17332 (delete-backward-char 1)
17333 (goto-char (match-beginning 0))
17334 (self-insert-command N))
17335 (setq org-table-may-need-update t)
17336 (self-insert-command N)))
17338 (defun org-delete-backward-char (N)
17339 "Like `delete-backward-char', insert whitespace at field end in tables.
17340 When deleting backwards, in tables this function will insert whitespace in
17341 front of the next \"|\" separator, to keep the table aligned. The table will
17342 still be marked for re-alignment if the field did fill the entire column,
17343 because, in this case the deletion might narrow the column."
17344 (interactive "p")
17345 (if (and (org-table-p)
17346 (eq N 1)
17347 (string-match "|" (buffer-substring (point-at-bol) (point)))
17348 (looking-at ".*?|"))
17349 (let ((pos (point))
17350 (noalign (looking-at "[^|\n\r]* |"))
17351 (c org-table-may-need-update))
17352 (backward-delete-char N)
17353 (skip-chars-forward "^|")
17354 (insert " ")
17355 (goto-char (1- pos))
17356 ;; noalign: if there were two spaces at the end, this field
17357 ;; does not determine the width of the column.
17358 (if noalign (setq org-table-may-need-update c)))
17359 (backward-delete-char N)))
17361 (defun org-delete-char (N)
17362 "Like `delete-char', but insert whitespace at field end in tables.
17363 When deleting characters, in tables this function will insert whitespace in
17364 front of the next \"|\" separator, to keep the table aligned. The table will
17365 still be marked for re-alignment if the field did fill the entire column,
17366 because, in this case the deletion might narrow the column."
17367 (interactive "p")
17368 (if (and (org-table-p)
17369 (not (bolp))
17370 (not (= (char-after) ?|))
17371 (eq N 1))
17372 (if (looking-at ".*?|")
17373 (let ((pos (point))
17374 (noalign (looking-at "[^|\n\r]* |"))
17375 (c org-table-may-need-update))
17376 (replace-match (concat
17377 (substring (match-string 0) 1 -1)
17378 " |"))
17379 (goto-char pos)
17380 ;; noalign: if there were two spaces at the end, this field
17381 ;; does not determine the width of the column.
17382 (if noalign (setq org-table-may-need-update c)))
17383 (delete-char N))
17384 (delete-char N)))
17386 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17387 (put 'org-self-insert-command 'delete-selection t)
17388 (put 'orgtbl-self-insert-command 'delete-selection t)
17389 (put 'org-delete-char 'delete-selection 'supersede)
17390 (put 'org-delete-backward-char 'delete-selection 'supersede)
17392 ;; How to do this: Measure non-white length of current string
17393 ;; If equal to column width, we should realign.
17395 (defun org-remap (map &rest commands)
17396 "In MAP, remap the functions given in COMMANDS.
17397 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17398 (let (new old)
17399 (while commands
17400 (setq old (pop commands) new (pop commands))
17401 (if (fboundp 'command-remapping)
17402 (define-key map (vector 'remap old) new)
17403 (substitute-key-definition old new map global-map)))))
17405 (when (eq org-enable-table-editor 'optimized)
17406 ;; If the user wants maximum table support, we need to hijack
17407 ;; some standard editing functions
17408 (org-remap org-mode-map
17409 'self-insert-command 'org-self-insert-command
17410 'delete-char 'org-delete-char
17411 'delete-backward-char 'org-delete-backward-char)
17412 (define-key org-mode-map "|" 'org-force-self-insert))
17414 (defun org-shiftcursor-error ()
17415 "Throw an error because Shift-Cursor command was applied in wrong context."
17416 (error "This command is active in special context like tables, headlines or timestamps"))
17418 (defun org-shifttab (&optional arg)
17419 "Global visibility cycling or move to previous table field.
17420 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17421 on context.
17422 See the individual commands for more information."
17423 (interactive "P")
17424 (cond
17425 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17426 (t (call-interactively 'org-global-cycle))))
17428 (defun org-shiftmetaleft ()
17429 "Promote subtree or delete table column.
17430 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
17431 See the individual commands for more information."
17432 (interactive)
17433 (cond
17434 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17435 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17436 ((org-at-item-p) (call-interactively 'org-outdent-item))
17437 (t (org-shiftcursor-error))))
17439 (defun org-shiftmetaright ()
17440 "Demote subtree or insert table column.
17441 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
17442 See the individual commands for more information."
17443 (interactive)
17444 (cond
17445 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17446 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17447 ((org-at-item-p) (call-interactively 'org-indent-item))
17448 (t (org-shiftcursor-error))))
17450 (defun org-shiftmetaup (&optional arg)
17451 "Move subtree up or kill table row.
17452 Calls `org-move-subtree-up' or `org-table-kill-row' or
17453 `org-move-item-up' depending on context. See the individual commands
17454 for more information."
17455 (interactive "P")
17456 (cond
17457 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17458 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17459 ((org-at-item-p) (call-interactively 'org-move-item-up))
17460 (t (org-shiftcursor-error))))
17461 (defun org-shiftmetadown (&optional arg)
17462 "Move subtree down or insert table row.
17463 Calls `org-move-subtree-down' or `org-table-insert-row' or
17464 `org-move-item-down', depending on context. See the individual
17465 commands for more information."
17466 (interactive "P")
17467 (cond
17468 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17469 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17470 ((org-at-item-p) (call-interactively 'org-move-item-down))
17471 (t (org-shiftcursor-error))))
17473 (defun org-metaleft (&optional arg)
17474 "Promote heading or move table column to left.
17475 Calls `org-do-promote' or `org-table-move-column', depending on context.
17476 With no specific context, calls the Emacs default `backward-word'.
17477 See the individual commands for more information."
17478 (interactive "P")
17479 (cond
17480 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17481 ((or (org-on-heading-p) (org-region-active-p))
17482 (call-interactively 'org-do-promote))
17483 ((org-at-item-p) (call-interactively 'org-outdent-item))
17484 (t (call-interactively 'backward-word))))
17486 (defun org-metaright (&optional arg)
17487 "Demote subtree or move table column to right.
17488 Calls `org-do-demote' or `org-table-move-column', depending on context.
17489 With no specific context, calls the Emacs default `forward-word'.
17490 See the individual commands for more information."
17491 (interactive "P")
17492 (cond
17493 ((org-at-table-p) (call-interactively 'org-table-move-column))
17494 ((or (org-on-heading-p) (org-region-active-p))
17495 (call-interactively 'org-do-demote))
17496 ((org-at-item-p) (call-interactively 'org-indent-item))
17497 (t (call-interactively 'forward-word))))
17499 (defun org-metaup (&optional arg)
17500 "Move subtree up or move table row up.
17501 Calls `org-move-subtree-up' or `org-table-move-row' or
17502 `org-move-item-up', depending on context. See the individual commands
17503 for more information."
17504 (interactive "P")
17505 (cond
17506 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17507 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17508 ((org-at-item-p) (call-interactively 'org-move-item-up))
17509 (t (org-shiftcursor-error))))
17511 (defun org-metadown (&optional arg)
17512 "Move subtree down or move table row down.
17513 Calls `org-move-subtree-down' or `org-table-move-row' or
17514 `org-move-item-down', depending on context. See the individual
17515 commands for more information."
17516 (interactive "P")
17517 (cond
17518 ((org-at-table-p) (call-interactively 'org-table-move-row))
17519 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17520 ((org-at-item-p) (call-interactively 'org-move-item-down))
17521 (t (org-shiftcursor-error))))
17523 (defun org-shiftup (&optional arg)
17524 "Increase item in timestamp or increase priority of current headline.
17525 Calls `org-timestamp-up' or `org-priority-up', depending on context.
17526 See the individual commands for more information."
17527 (interactive "P")
17528 (cond
17529 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
17530 ((org-on-heading-p) (call-interactively 'org-priority-up))
17531 ((org-at-item-p) (call-interactively 'org-previous-item))
17532 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
17534 (defun org-shiftdown (&optional arg)
17535 "Decrease item in timestamp or decrease priority of current headline.
17536 Calls `org-timestamp-down' or `org-priority-down', depending on context.
17537 See the individual commands for more information."
17538 (interactive "P")
17539 (cond
17540 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
17541 ((org-on-heading-p) (call-interactively 'org-priority-down))
17542 (t (call-interactively 'org-next-item))))
17544 (defun org-shiftright ()
17545 "Next TODO keyword or timestamp one day later, depending on context."
17546 (interactive)
17547 (cond
17548 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17549 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
17550 (t (org-shiftcursor-error))))
17552 (defun org-shiftleft ()
17553 "Previous TODO keyword or timestamp one day earlier, depending on context."
17554 (interactive)
17555 (cond
17556 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17557 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
17558 (t (org-shiftcursor-error))))
17560 (defun org-copy-special ()
17561 "Copy region in table or copy current subtree.
17562 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17563 See the individual commands for more information."
17564 (interactive)
17565 (call-interactively
17566 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17568 (defun org-cut-special ()
17569 "Cut region in table or cut current subtree.
17570 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17571 See the individual commands for more information."
17572 (interactive)
17573 (call-interactively
17574 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17576 (defun org-paste-special (arg)
17577 "Paste rectangular region into table, or past subtree relative to level.
17578 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17579 See the individual commands for more information."
17580 (interactive "P")
17581 (if (org-at-table-p)
17582 (org-table-paste-rectangle)
17583 (org-paste-subtree arg)))
17585 (defun org-ctrl-c-ctrl-c (&optional arg)
17586 "Set tags in headline, or update according to changed information at point.
17588 This command does many different things, depending on context:
17590 - If the cursor is in a headline, prompt for tags and insert them
17591 into the current line, aligned to `org-tags-column'. When called
17592 with prefix arg, realign all tags in the current buffer.
17594 - If the cursor is in one of the special #+KEYWORD lines, this
17595 triggers scanning the buffer for these lines and updating the
17596 information.
17598 - If the cursor is inside a table, realign the table. This command
17599 works even if the automatic table editor has been turned off.
17601 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17602 the entire table.
17604 - If the cursor is inside a table created by the table.el package,
17605 activate that table.
17607 - If the current buffer is a remember buffer, close note and file it.
17608 with a prefix argument, file it without further interaction to the default
17609 location.
17611 - If the cursor is on a <<<target>>>, update radio targets and corresponding
17612 links in this buffer.
17614 - If the cursor is on a numbered item in a plain list, renumber the
17615 ordered list."
17616 (interactive "P")
17617 (let ((org-enable-table-editor t))
17618 (cond
17619 ((or org-clock-overlays
17620 org-occur-highlights
17621 org-latex-fragment-image-overlays)
17622 (org-remove-clock-overlays)
17623 (org-remove-occur-highlights)
17624 (org-remove-latex-fragment-image-overlays)
17625 (message "Temporary highlights/overlays removed from current buffer"))
17626 ((and (local-variable-p 'org-finish-function (current-buffer))
17627 (fboundp org-finish-function))
17628 (funcall org-finish-function))
17629 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17630 ((org-on-heading-p) (call-interactively 'org-set-tags))
17631 ((org-at-table.el-p)
17632 (require 'table)
17633 (beginning-of-line 1)
17634 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
17635 (call-interactively 'table-recognize-table))
17636 ((org-at-table-p)
17637 (org-table-maybe-eval-formula)
17638 (if arg
17639 (call-interactively 'org-table-recalculate)
17640 (org-table-maybe-recalculate-line))
17641 (call-interactively 'org-table-align))
17642 ((org-at-item-checkbox-p)
17643 (call-interactively 'org-toggle-checkbox))
17644 ((org-at-item-p)
17645 (call-interactively 'org-renumber-ordered-list))
17646 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
17647 (cond
17648 ((equal (match-string 1) "TBLFM")
17649 ;; Recalculate the table before this line
17650 (save-excursion
17651 (beginning-of-line 1)
17652 (skip-chars-backward " \r\n\t")
17653 (if (org-at-table-p)
17654 (org-call-with-arg 'org-table-recalculate t))))
17656 (call-interactively 'org-mode-restart))))
17657 (t (error "C-c C-c can do nothing useful at this location.")))))
17659 (defun org-mode-restart ()
17660 "Restart Org-mode, to scan again for special lines.
17661 Also updates the keyword regular expressions."
17662 (interactive)
17663 (let ((org-inhibit-startup t)) (org-mode))
17664 (message "Org-mode restarted to refresh keyword and special line setup"))
17666 (defun org-return ()
17667 "Goto next table row or insert a newline.
17668 Calls `org-table-next-row' or `newline', depending on context.
17669 See the individual commands for more information."
17670 (interactive)
17671 (cond
17672 ((org-at-table-p)
17673 (org-table-justify-field-maybe)
17674 (call-interactively 'org-table-next-row))
17675 (t (newline))))
17677 (defun org-meta-return (&optional arg)
17678 "Insert a new heading or wrap a region in a table.
17679 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17680 See the individual commands for more information."
17681 (interactive "P")
17682 (cond
17683 ((org-at-table-p)
17684 (call-interactively 'org-table-wrap-region))
17685 (t (call-interactively 'org-insert-heading))))
17687 ;;; Menu entries
17689 ;; Define the Org-mode menus
17690 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17691 '("Tbl"
17692 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
17693 ["Next Field" org-cycle (org-at-table-p)]
17694 ["Previous Field" org-shifttab (org-at-table-p)]
17695 ["Next Row" org-return (org-at-table-p)]
17696 "--"
17697 ["Blank Field" org-table-blank-field (org-at-table-p)]
17698 ["Edit Field" org-table-edit-field (org-at-table-p)]
17699 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17700 "--"
17701 ("Column"
17702 ["Move Column Left" org-metaleft (org-at-table-p)]
17703 ["Move Column Right" org-metaright (org-at-table-p)]
17704 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17705 ["Insert Column" org-shiftmetaright (org-at-table-p)]
17706 "--"
17707 ["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])
17708 ("Row"
17709 ["Move Row Up" org-metaup (org-at-table-p)]
17710 ["Move Row Down" org-metadown (org-at-table-p)]
17711 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17712 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17713 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17714 "--"
17715 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
17716 ("Rectangle"
17717 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17718 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17719 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17720 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17721 "--"
17722 ("Calculate"
17723 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17724 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17725 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
17726 "--"
17727 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17728 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17729 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17730 "--"
17731 ["Sum Column/Rectangle" org-table-sum
17732 (or (org-at-table-p) (org-region-active-p))]
17733 ["Which Column?" org-table-current-column (org-at-table-p)])
17734 ["Debug Formulas"
17735 (setq org-table-formula-debug (not org-table-formula-debug))
17736 :style toggle :selected org-table-formula-debug]
17737 "--"
17738 ["Create" org-table-create (and (not (org-at-table-p))
17739 org-enable-table-editor)]
17740 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17741 ["Import from File" org-table-import (not (org-at-table-p))]
17742 ["Export to File" org-table-export (org-at-table-p)]
17743 "--"
17744 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17746 (easy-menu-define org-org-menu org-mode-map "Org menu"
17747 '("Org"
17748 ("Show/Hide"
17749 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
17750 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
17751 ["Sparse Tree" org-occur t]
17752 ["Reveal Context" org-reveal t]
17753 ["Show All" show-all t]
17754 "--"
17755 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17756 "--"
17757 ["New Heading" org-insert-heading t]
17758 ("Navigate Headings"
17759 ["Up" outline-up-heading t]
17760 ["Next" outline-next-visible-heading t]
17761 ["Previous" outline-previous-visible-heading t]
17762 ["Next Same Level" outline-forward-same-level t]
17763 ["Previous Same Level" outline-backward-same-level t]
17764 "--"
17765 ["Jump" org-goto t])
17766 ("Edit Structure"
17767 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17768 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17769 "--"
17770 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17771 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17772 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17773 "--"
17774 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17775 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17776 ["Demote Heading" org-metaright (not (org-at-table-p))]
17777 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17778 "--"
17779 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17780 "--"
17781 ["Convert to odd levels" org-convert-to-odd-levels t]
17782 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17783 ("Archive"
17784 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17785 ["Check and Tag Children" (org-toggle-archive-tag (4))
17786 :active t :keys "C-u C-c C-x C-a"]
17787 ["Sparse trees open ARCHIVE trees"
17788 (setq org-sparse-tree-open-archived-trees
17789 (not org-sparse-tree-open-archived-trees))
17790 :style toggle :selected org-sparse-tree-open-archived-trees]
17791 ["Cycling opens ARCHIVE trees"
17792 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
17793 :style toggle :selected org-cycle-open-archived-trees]
17794 ["Agenda includes ARCHIVE trees"
17795 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
17796 :style toggle :selected (not org-agenda-skip-archived-trees)]
17797 "--"
17798 ["Move Subtree to Archive" org-archive-subtree t]
17799 ["Check and Move Children" (org-archive-subtree '(4))
17800 :active t :keys "C-u C-c $"])
17801 "--"
17802 ("TODO Lists"
17803 ["TODO/DONE/-" org-todo t]
17804 ("Select keyword"
17805 ["Next keyword" org-shiftright (org-on-heading-p)]
17806 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17807 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
17808 ["Show TODO Tree" org-show-todo-tree t]
17809 ["Global TODO list" org-todo-list t]
17810 "--"
17811 ["Set Priority" org-priority t]
17812 ["Priority Up" org-shiftup t]
17813 ["Priority Down" org-shiftdown t]
17814 "--"
17815 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
17816 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
17817 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
17818 ; (or (org-on-heading-p) (org-at-item-p))]
17819 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
17820 ; (or (org-on-heading-p) (org-at-item-p))]
17821 ; ["Update Statistics" org-update-checkbox-count t]
17823 ("Dates and Scheduling"
17824 ["Timestamp" org-time-stamp t]
17825 ["Timestamp (inactive)" org-time-stamp-inactive t]
17826 ("Change Date"
17827 ["1 Day Later" org-shiftright t]
17828 ["1 Day Earlier" org-shiftleft t]
17829 ["1 ... Later" org-shiftup t]
17830 ["1 ... Earlier" org-shiftdown t])
17831 ["Compute Time Range" org-evaluate-time-range t]
17832 ["Schedule Item" org-schedule t]
17833 ["Deadline" org-deadline t]
17834 "--"
17835 ["Custom time format" org-toggle-time-stamp-overlays
17836 :style radio :selected org-display-custom-times]
17837 "--"
17838 ["Goto Calendar" org-goto-calendar t]
17839 ["Date from Calendar" org-date-from-calendar t])
17840 ("Logging work"
17841 ["Clock in" org-clock-in t]
17842 ["Clock out" org-clock-out t]
17843 ["Clock cancel" org-clock-cancel t]
17844 ["Display times" org-clock-display t]
17845 ["Create clock table" org-clock-report t]
17846 "--"
17847 ["Record DONE time"
17848 (progn (setq org-log-done (not org-log-done))
17849 (message "Switching to %s will %s record a timestamp"
17850 org-done-string
17851 (if org-log-done "automatically" "not")))
17852 :style toggle :selected org-log-done])
17853 "--"
17854 ["Agenda Command..." org-agenda t]
17855 ("File List for Agenda")
17856 ("Special views current file"
17857 ["TODO Tree" org-show-todo-tree t]
17858 ["Check Deadlines" org-check-deadlines t]
17859 ["Timeline" org-timeline t]
17860 ["Tags Tree" org-tags-sparse-tree t])
17861 "--"
17862 ("Hyperlinks"
17863 ["Store Link (Global)" org-store-link t]
17864 ["Insert Link" org-insert-link t]
17865 ["Follow Link" org-open-at-point t]
17866 "--"
17867 ["Descriptive Links"
17868 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17869 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
17870 ["Literal Links"
17871 (progn
17872 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17873 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
17874 "--"
17875 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
17876 (save-excursion (goto-char (point-min))
17877 (re-search-forward "<[a-z]+:" nil t))])
17878 "--"
17879 ["Export/Publish..." org-export t]
17880 ("LaTeX"
17881 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
17882 :selected org-cdlatex-mode]
17883 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
17884 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
17885 ["Modify math symbol" org-cdlatex-math-modify
17886 (org-inside-LaTeX-fragment-p)]
17887 ["Export LaTeX fragments as images"
17888 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
17889 :style toggle :selected org-export-with-LaTeX-fragments])
17890 "--"
17891 ("Documentation"
17892 ["Show Version" org-version t]
17893 ["Info Documentation" org-info t])
17894 ("Customize"
17895 ["Browse Org Group" org-customize t]
17896 "--"
17897 ["Expand This Menu" org-create-customize-menu
17898 (fboundp 'customize-menu-create)])
17899 "--"
17900 ["Refresh setup" org-mode-restart t]
17903 (defun org-info (&optional node)
17904 "Read documentation for Org-mode in the info system.
17905 With optional NODE, go directly to that node."
17906 (interactive)
17907 (require 'info)
17908 (Info-goto-node (format "(org)%s" (or node ""))))
17910 (defun org-install-agenda-files-menu ()
17911 (let ((bl (buffer-list)))
17912 (save-excursion
17913 (while bl
17914 (set-buffer (pop bl))
17915 (if (org-mode-p) (setq bl nil)))
17916 (when (org-mode-p)
17917 (easy-menu-change
17918 '("Org") "File List for Agenda"
17919 (append
17920 (list
17921 ["Edit File List" (org-edit-agenda-file-list) t]
17922 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17923 ["Remove Current File from List" org-remove-file t]
17924 ["Cycle through agenda files" org-cycle-agenda-files t]
17925 "--")
17926 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17928 ;;;; Documentation
17930 (defun org-customize ()
17931 "Call the customize function with org as argument."
17932 (interactive)
17933 (customize-browse 'org))
17935 (defun org-create-customize-menu ()
17936 "Create a full customization menu for Org-mode, insert it into the menu."
17937 (interactive)
17938 (if (fboundp 'customize-menu-create)
17939 (progn
17940 (easy-menu-change
17941 '("Org") "Customize"
17942 `(["Browse Org group" org-customize t]
17943 "--"
17944 ,(customize-menu-create 'org)
17945 ["Set" Custom-set t]
17946 ["Save" Custom-save t]
17947 ["Reset to Current" Custom-reset-current t]
17948 ["Reset to Saved" Custom-reset-saved t]
17949 ["Reset to Standard Settings" Custom-reset-standard t]))
17950 (message "\"Org\"-menu now contains full customization menu"))
17951 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17953 ;;;; Miscellaneous stuff
17956 ;;; Generally useful functions
17958 (defun org-context ()
17959 "Return a list of contexts of the current cursor position.
17960 If several contexts apply, all are returned.
17961 Each context entry is a list with a symbol naming the context, and
17962 two positions indicating start and end of the context. Possible
17963 contexts are:
17965 :headline anywhere in a headline
17966 :headline-stars on the leading stars in a headline
17967 :todo-keyword on a TODO keyword (including DONE) in a headline
17968 :tags on the TAGS in a headline
17969 :priority on the priority cookie in a headline
17970 :item on the first line of a plain list item
17971 :item-bullet on the bullet/number of a plain list item
17972 :checkbox on the checkbox in a plain list item
17973 :table in an org-mode table
17974 :table-special on a special filed in a table
17975 :table-table in a table.el table
17976 :link on a hyperline
17977 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17978 :target on a <<target>>
17979 :radio-target on a <<<radio-target>>>
17980 :latex-fragment on a LaTeX fragment
17981 :latex-preview on a LaTeX fragment with overlayed preview image
17983 This function expects the position to be visible because it uses font-lock
17984 faces as a help to recognize the following contexts: :table-special, :link,
17985 and :keyword."
17986 (let* ((f (get-text-property (point) 'face))
17987 (faces (if (listp f) f (list f)))
17988 (p (point)) clist o)
17989 ;; First the large context
17990 (cond
17991 ((org-on-heading-p)
17992 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17993 (when (progn
17994 (beginning-of-line 1)
17995 (looking-at org-todo-line-tags-regexp))
17996 (push (org-point-in-group p 1 :headline-stars) clist)
17997 (push (org-point-in-group p 2 :todo-keyword) clist)
17998 (push (org-point-in-group p 4 :tags) clist))
17999 (goto-char p)
18000 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
18001 (if (looking-at "\\[#[A-Z]\\]")
18002 (push (org-point-in-group p 0 :priority) clist)))
18004 ((org-at-item-p)
18005 (push (org-point-in-group p 2 :item-bullet) clist)
18006 (push (list :item (point-at-bol)
18007 (save-excursion (org-end-of-item) (point)))
18008 clist)
18009 (and (org-at-item-checkbox-p)
18010 (push (org-point-in-group p 0 :checkbox) clist)))
18012 ((org-at-table-p)
18013 (push (list :table (org-table-begin) (org-table-end)) clist)
18014 (if (memq 'org-formula faces)
18015 (push (list :table-special
18016 (previous-single-property-change p 'face)
18017 (next-single-property-change p 'face)) clist)))
18018 ((org-at-table-p 'any)
18019 (push (list :table-table) clist)))
18020 (goto-char p)
18022 ;; Now the small context
18023 (cond
18024 ((org-at-timestamp-p)
18025 (push (org-point-in-group p 0 :timestamp) clist))
18026 ((memq 'org-link faces)
18027 (push (list :link
18028 (previous-single-property-change p 'face)
18029 (next-single-property-change p 'face)) clist))
18030 ((memq 'org-special-keyword faces)
18031 (push (list :keyword
18032 (previous-single-property-change p 'face)
18033 (next-single-property-change p 'face)) clist))
18034 ((org-on-target-p)
18035 (push (org-point-in-group p 0 :target) clist)
18036 (goto-char (1- (match-beginning 0)))
18037 (if (looking-at org-radio-target-regexp)
18038 (push (org-point-in-group p 0 :radio-target) clist))
18039 (goto-char p))
18040 ((setq o (car (delq nil
18041 (mapcar
18042 (lambda (x)
18043 (if (memq x org-latex-fragment-image-overlays) x))
18044 (org-overlays-at (point))))))
18045 (push (list :latex-fragment
18046 (org-overlay-start o) (org-overlay-end o)) clist)
18047 (push (list :latex-preview
18048 (org-overlay-start o) (org-overlay-end o)) clist))
18049 ((org-inside-LaTeX-fragment-p)
18050 ;; FIXME: positions wrong.
18051 (push (list :latex-fragment (point) (point)) clist)))
18053 (setq clist (nreverse (delq nil clist)))
18054 clist))
18056 (defun org-point-in-group (point group &optional context)
18057 "Check if POINT is in match-group GROUP.
18058 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18059 match. If the match group does ot exist or point is not inside it,
18060 return nil."
18061 (and (match-beginning group)
18062 (>= point (match-beginning group))
18063 (<= point (match-end group))
18064 (if context
18065 (list context (match-beginning group) (match-end group))
18066 t)))
18068 (defun org-move-line-down (arg)
18069 "Move the current line down. With prefix argument, move it past ARG lines."
18070 (interactive "p")
18071 (let ((col (current-column))
18072 beg end pos)
18073 (beginning-of-line 1) (setq beg (point))
18074 (beginning-of-line 2) (setq end (point))
18075 (beginning-of-line (+ 1 arg))
18076 (setq pos (move-marker (make-marker) (point)))
18077 (insert (delete-and-extract-region beg end))
18078 (goto-char pos)
18079 (move-to-column col)))
18081 (defun org-move-line-up (arg)
18082 "Move the current line up. With prefix argument, move it past ARG lines."
18083 (interactive "p")
18084 (let ((col (current-column))
18085 beg end pos)
18086 (beginning-of-line 1) (setq beg (point))
18087 (beginning-of-line 2) (setq end (point))
18088 (beginning-of-line (- arg))
18089 (setq pos (move-marker (make-marker) (point)))
18090 (insert (delete-and-extract-region beg end))
18091 (goto-char pos)
18092 (move-to-column col)))
18094 (defun org-replace-escapes (string table)
18095 ;; FIXME: document and make safer
18096 (let (e)
18097 (while (setq e (pop table))
18098 (while (string-match (car e) string)
18099 (setq string (replace-match (cdr e) t t string))))
18100 string))
18102 ;;; Paragraph filling stuff.
18103 ;; We want this to be just right, so use the full arsenal.
18105 (defun org-set-autofill-regexps ()
18106 (interactive)
18107 ;; In the paragraph separator we include headlines, because filling
18108 ;; text in a line directly attached to a headline would otherwise
18109 ;; fill the headline as well.
18110 (org-set-local 'comment-start-skip "^#+[ \t]*")
18111 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
18112 ;; The paragraph starter includes hand-formatted lists.
18113 (org-set-local 'paragraph-start
18114 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
18115 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
18116 ;; But only if the user has not turned off tables or fixed-width regions
18117 (org-set-local
18118 'auto-fill-inhibit-regexp
18119 (concat "\\*\\|#\\+"
18120 "\\|[ \t]*" org-keyword-time-regexp
18121 (if (or org-enable-table-editor org-enable-fixed-width-editor)
18122 (concat
18123 "\\|[ \t]*["
18124 (if org-enable-table-editor "|" "")
18125 (if org-enable-fixed-width-editor ":" "")
18126 "]"))))
18127 ;; We use our own fill-paragraph function, to make sure that tables
18128 ;; and fixed-width regions are not wrapped. That function will pass
18129 ;; through to `fill-paragraph' when appropriate.
18130 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
18131 ; Adaptive filling: To get full control, first make sure that
18132 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
18133 (org-set-local 'adaptive-fill-regexp "\000")
18134 (org-set-local 'adaptive-fill-function
18135 'org-adaptive-fill-function))
18137 (defun org-fill-paragraph (&optional justify)
18138 "Re-align a table, pass through to fill-paragraph if no table."
18139 (let ((table-p (org-at-table-p))
18140 (table.el-p (org-at-table.el-p)))
18141 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
18142 (table.el-p t) ; skip table.el tables
18143 (table-p (org-table-align) t) ; align org-mode tables
18144 (t nil)))) ; call paragraph-fill
18146 ;; For reference, this is the default value of adaptive-fill-regexp
18147 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
18149 (defun org-adaptive-fill-function ()
18150 "Return a fill prefix for org-mode files.
18151 In particular, this makes sure hanging paragraphs for hand-formatted lists
18152 work correctly."
18153 (cond ((looking-at "#[ \t]+")
18154 (match-string 0))
18155 ((looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
18156 (make-string (- (match-end 0) (match-beginning 0)) ?\ ))
18157 (t nil)))
18160 (defun org-image-file-name-regexp ()
18161 "Return regexp matching the file names of images."
18162 (if (fboundp 'image-file-name-regexp)
18163 (image-file-name-regexp)
18164 (let ((image-file-name-extensions
18165 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18166 "xbm" "xpm" "pbm" "pgm" "ppm")))
18167 (concat "\\."
18168 (regexp-opt (nconc (mapcar 'upcase
18169 image-file-name-extensions)
18170 image-file-name-extensions)
18172 "\\'"))))
18174 ;;;; Functions extending outline functionality
18176 ;; C-a should go to the beginning of a *visible* line, also in the
18177 ;; new outline.el. I guess this should be patched into Emacs?
18178 (defun org-beginning-of-line ()
18179 "Go to the beginning of the current line. If that is invisible, continue
18180 to a visible line beginning. This makes the function of C-a more intuitive."
18181 (interactive)
18182 (beginning-of-line 1)
18183 (if (bobp)
18185 (backward-char 1)
18186 (if (org-invisible-p)
18187 (while (and (not (bobp)) (org-invisible-p))
18188 (backward-char 1)
18189 (beginning-of-line 1))
18190 (forward-char 1))))
18192 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18194 (defun org-invisible-p ()
18195 "Check if point is at a character currently not visible."
18196 ;; Early versions of noutline don't have `outline-invisible-p'.
18197 (if (fboundp 'outline-invisible-p)
18198 (outline-invisible-p)
18199 (get-char-property (point) 'invisible)))
18201 (defun org-invisible-p2 ()
18202 "Check if point is at a character currently not visible."
18203 (save-excursion
18204 (if (and (eolp) (not (bobp))) (backward-char 1))
18205 ;; Early versions of noutline don't have `outline-invisible-p'.
18206 (if (fboundp 'outline-invisible-p)
18207 (outline-invisible-p)
18208 (get-char-property (point) 'invisible))))
18210 (defalias 'org-back-to-heading 'outline-back-to-heading)
18211 (defalias 'org-on-heading-p 'outline-on-heading-p)
18213 (defun org-on-target-p ()
18214 (let ((pos (point)))
18215 (save-excursion
18216 (skip-chars-forward "<")
18217 (and (re-search-backward "<<" nil t)
18218 (or (looking-at org-radio-target-regexp)
18219 (looking-at org-target-regexp))
18220 (<= (match-beginning 0) pos)
18221 (>= (1+ (match-end 0)) pos)))))
18223 (defun org-up-heading-all (arg)
18224 "Move to the heading line of which the present line is a subheading.
18225 This function considers both visible and invisible heading lines.
18226 With argument, move up ARG levels."
18227 (if (fboundp 'outline-up-heading-all)
18228 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18229 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18231 (defun org-goto-sibling (&optional previous)
18232 "Goto the next sibling, even if it is invisible.
18233 When PREVIOUS is set, go to the previous sibling instead. Returns t
18234 when a sibling was found. When none is found, return nil and don't
18235 move point."
18236 (let ((fun (if previous 're-search-backward 're-search-forward))
18237 (pos (point))
18238 (re (concat "^" outline-regexp))
18239 level l)
18240 (org-back-to-heading t)
18241 (setq level (funcall outline-level))
18242 (catch 'exit
18243 (or previous (forward-char 1))
18244 (while (funcall fun re nil t)
18245 (setq l (funcall outline-level))
18246 (when (< l level) (goto-char pos) (throw 'exit nil))
18247 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18248 (goto-char pos)
18249 nil)))
18251 (defun org-show-hidden-entry ()
18252 "Show an entry where even the heading is hidden."
18253 (save-excursion
18254 (org-show-entry)))
18256 (defun org-flag-heading (flag &optional entry)
18257 "Flag the current heading. FLAG non-nil means make invisible.
18258 When ENTRY is non-nil, show the entire entry."
18259 (save-excursion
18260 (org-back-to-heading t)
18261 ;; Check if we should show the entire entry
18262 (if entry
18263 (progn
18264 (org-show-entry)
18265 (save-excursion
18266 (and (outline-next-heading)
18267 (org-flag-heading nil))))
18268 (outline-flag-region (max 1 (1- (point)))
18269 (save-excursion (outline-end-of-heading) (point))
18270 flag))))
18272 (defun org-end-of-subtree (&optional invisible-OK)
18273 ;; This is an exact copy of the original function, but it uses
18274 ;; `org-back-to-heading', to make it work also in invisible
18275 ;; trees. And is uses an invisible-OK argument.
18276 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18277 (org-back-to-heading invisible-OK)
18278 (let ((first t)
18279 (level (funcall outline-level)))
18280 (while (and (not (eobp))
18281 (or first (> (funcall outline-level) level)))
18282 (setq first nil)
18283 (outline-next-heading))
18284 (if (memq (preceding-char) '(?\n ?\^M))
18285 (progn
18286 ;; Go to end of line before heading
18287 (forward-char -1)
18288 (if (memq (preceding-char) '(?\n ?\^M))
18289 ;; leave blank line before heading
18290 (forward-char -1)))))
18291 (point))
18293 (defun org-show-subtree ()
18294 "Show everything after this heading at deeper levels."
18295 (outline-flag-region
18296 (point)
18297 (save-excursion
18298 (outline-end-of-subtree) (outline-next-heading) (point))
18299 nil))
18301 (defun org-show-entry ()
18302 "Show the body directly following this heading.
18303 Show the heading too, if it is currently invisible."
18304 (interactive)
18305 (save-excursion
18306 (org-back-to-heading t)
18307 (outline-flag-region
18308 (max 1 (1- (point)))
18309 (save-excursion
18310 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
18311 (or (match-beginning 1) (point-max)))
18312 nil)))
18314 (defun org-make-options-regexp (kwds)
18315 "Make a regular expression for keyword lines."
18316 (concat
18318 "#?[ \t]*\\+\\("
18319 (mapconcat 'regexp-quote kwds "\\|")
18320 "\\):[ \t]*"
18321 "\\(.+\\)"))
18323 ;;;; Repair problems with some other packages
18325 ;; Make `bookmark-jump' show the jump location if it was hidden.
18326 (eval-after-load "bookmark"
18327 '(if (boundp 'bookmark-after-jump-hook)
18328 ;; We can use the hook
18329 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18330 ;; Hook not available, use advice
18331 (defadvice bookmark-jump (after org-make-visible activate)
18332 "Make the position visible."
18333 (org-bookmark-jump-unhide))))
18335 (defun org-bookmark-jump-unhide ()
18336 "Unhide the current position, to show the bookmark location."
18337 (and (org-mode-p)
18338 (or (org-invisible-p)
18339 (save-excursion (goto-char (max (point-min) (1- (point))))
18340 (org-invisible-p)))
18341 (org-show-context 'bookmark-jump)))
18343 ;; Make session.el ignore our circular variable
18344 (eval-after-load "session"
18345 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18347 ;;;; Experimental code
18351 ;;;; Finish up
18353 (provide 'org)
18355 (run-hooks 'org-load-hook)
18357 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18358 ;;; org.el ends here