Release 4.40
[org-mode.git] / org.el
bloba1ff47de7de5700d0b0ff75c3dd944e108e03bec
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.40
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.
49 ;; Installation
50 ;; ------------
51 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
52 ;; only need to copy the following lines to your .emacs file. The last two
53 ;; lines define *global* keys for the commands `org-store-link' and
54 ;; `org-agenda' - please choose suitable keys yourself.
56 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
57 ;; (define-key global-map "\C-cl" 'org-store-link)
58 ;; (define-key global-map "\C-ca" 'org-agenda)
60 ;; Furthermore you need to activate font-lock-mode in org-mode buffers.
61 ;; either of the following two lins will do the trick:
63 ;; (global-font-lock-mode 1) ; for all buffers
64 ;; (add-hook 'org-mode-hook 'turn-on-font-lock) ; org-mode buffers only
66 ;; If you have downloaded Org-mode from the Web, you have to take additional
67 ;; action: Byte-compile org.el and org-publish.el and put them together with
68 ;; org-install.el on your load path. Then also add to your .emacs file:
70 ;; (require 'org-install)
73 ;; Activation
74 ;; ----------
75 ;; The setup above will put all files with extension ".org" into Org-mode.
76 ;; As an alternative, make the first line of a file look like this:
78 ;; MY PROJECTS -*- mode: org; -*-
80 ;; which will select Org-mode for this buffer no matter what the file's
81 ;; name is.
83 ;; Documentation
84 ;; -------------
85 ;; The documentation of Org-mode can be found in the TeXInfo file. The
86 ;; distribution also contains a PDF version of it. At the homepage of
87 ;; Org-mode, you can read the same text online as HTML. There is also an
88 ;; excellent reference card made by Philip Rooke. This card can be found
89 ;; in the etc/ directory of Emacs 22.
91 ;; Recent changes
92 ;; --------------
93 ;; Version 4.40
94 ;; - Bug fixes.
96 ;; Version 4.39
97 ;; - Special tag ARCHIVE keeps a subtree closed and away from agenda lists.
98 ;; - LaTeX code in Org-mode files can be converted to images for HTML.
99 ;; - Bug fixes.
100 ;; - CDLaTeX-mode features can be used in Org-mode to help inserting
101 ;; LaTeX environment and math.
103 ;; Version 4.38
104 ;; - noutline.el is now required (important for XEmacs users only).
105 ;; - Dynamic blocks.
106 ;; - Archiving of all level 1 trees without open TODO items.
107 ;; - Clock reports can be inserted into the file in a special section.
108 ;; - FAQ removed from the manual, now only on the web.
109 ;; - Bug fixes.
111 ;; Version 4.37
112 ;; - Clock-feature for measuring time spent on specific items.
113 ;; - Improved emphasizing allows configuration and stacking.
115 ;; Version 4.36
116 ;; - Improved indentation of ASCII export, when headlines become items.
117 ;; - Handling of 12am and 12pm fixed. Times beyond 24:00 can be used
118 ;; and will not lead to conflicts.
119 ;; - Support for mutually exclusive TAGS with the fast tags interface.
120 ;; - Bug fixes.
122 ;; Version 4.35
123 ;; - HTML export is now valid XHTML.
124 ;; - Timeline can also show dates without entries. See new option
125 ;; `org-timeline-show-empty-dates'.
126 ;; - The bullets created by the ASCII exporter can now be configured.
127 ;; See the new option `org-export-ascii-bullets'.
128 ;; - New face `org-upcoming-deadline' (was `org-scheduled-previously').
129 ;; - New function `org-context' to allow testing for local context.
131 ;; Version 4.34
132 ;; - Bug fixes.
134 ;; Version 4.33
135 ;; - New commands to move through plain lists: S-up and S-down.
136 ;; - Bug fixes and documentation update.
138 ;; Version 4.32
139 ;; - Fast (single-key-per-tag) interface for setting TAGS.
140 ;; - The list of legal tags can be configured globally and locally.
141 ;; - Elisp and Info links (thanks to Todd Neal).
142 ;; - `org-export-publishing-directory' can be an alist, with different
143 ;; directories for different export types.
144 ;; - All context-sensitive commands use `call-interactively' to dispatch.
145 ;; - `org-confirm-shell-links' renamed to `org-confirm-shell-link-function'.
146 ;; - Bug fixes.
148 ;; Version 4.31
149 ;; - Bug fixes.
151 ;; Version 4.30
152 ;; - Modified installation: Autoloads have been collected in org-install.el.
153 ;; - Logging (org-log-done) is now a #+STARTUP option.
154 ;; - Checkboxes in plain list items, following up on Frank Ruell's idea.
155 ;; - File links inserted with C-c C-l will use relative paths if the linked
156 ;; file is in the current directory or a subdirectory of it.
157 ;; - New variable `org-link-file-path-type' to specify preference for
158 ;; relative and absolute paths.
159 ;; - New CSS classes for tags, timestamps, timestamp keywords.
160 ;; - Bug and typo fixes.
162 ;; Version 4.29
163 ;; - Inlining images in HTML export now depends on wheather the link
164 ;; contains a description or not.
165 ;; - TODO items can be scheduled from the global TODO list using C-c C-s.
166 ;; - TODO items already scheduled can be made to disappear from the global
167 ;; todo list, see `org-agenda-todo-ignore-scheduled'.
168 ;; - In Tables, formulas may also be Lisp forms.
169 ;; - Exporting the visible part of an outline with `C-c C-x v' works now
170 ;; for all available exporters.
171 ;; - Bug fixes, lots of them :-(
173 ;; Version 4.28
174 ;; - Bug fixes.
176 ;; Version 4.27
177 ;; - HTML exporter generalized to receive external options.
178 ;; As part of the process, author, email and date have been moved to the
179 ;; end of the HTML file.
180 ;; - Support for customizable file search in file links.
181 ;; - BibTeX database links as first application of the above.
182 ;; - New option `org-agenda-todo-list-sublevels' to turn off listing TODO
183 ;; entries that are sublevels of another TODO entry.
186 ;;; Code:
188 (eval-when-compile
189 (require 'cl)
190 (require 'calendar))
191 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
192 ;; the file noutline.el being loaded.
193 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
194 ;; We require noutline, which might be provided in outline.el
195 (require 'outline) (require 'noutline)
196 ;; Other stuff we need.
197 (require 'time-date)
198 (require 'easymenu)
200 ;;; Customization variables
202 (defvar org-version "4.40"
203 "The version number of the file org.el.")
204 (defun org-version ()
205 (interactive)
206 (message "Org-mode version %s" org-version))
208 ;; The following constant is for compatibility with different versions
209 ;; of outline.el.
210 (defconst org-noutline-p (featurep 'noutline)
211 "Are we using the new outline mode?")
212 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
213 (defconst org-format-transports-properties-p
214 (let ((x "a"))
215 (add-text-properties 0 1 '(test t) x)
216 (get-text-property 0 'test (format "%s" x)))
217 "Does format transport text properties?")
219 (defgroup org nil
220 "Outline-based notes management and organizer."
221 :tag "Org"
222 :group 'outlines
223 :group 'hypermedia
224 :group 'calendar)
226 (defgroup org-startup nil
227 "Options concerning startup of Org-mode."
228 :tag "Org Startup"
229 :group 'org)
231 (defcustom org-startup-folded t
232 "Non-nil means, entering Org-mode will switch to OVERVIEW.
233 This can also be configured on a per-file basis by adding one of
234 the following lines anywhere in the buffer:
236 #+STARTUP: fold
237 #+STARTUP: nofold
238 #+STARTUP: content"
239 :group 'org-startup
240 :type '(choice
241 (const :tag "nofold: show all" nil)
242 (const :tag "fold: overview" t)
243 (const :tag "content: all headlines" content)))
245 (defcustom org-startup-truncated t
246 "Non-nil means, entering Org-mode will set `truncate-lines'.
247 This is useful since some lines containing links can be very long and
248 uninteresting. Also tables look terrible when wrapped."
249 :group 'org-startup
250 :type 'boolean)
252 (defcustom org-startup-align-all-tables nil
253 "Non-nil means, align all tables when visiting a file.
254 This is useful when the column width in tables is forced with <N> cookies
255 in table fields. Such tables will look correct only after the first re-align.
256 This can also be configured on a per-file basis by adding one of
257 the following lines anywhere in the buffer:
258 #+STARTUP: align
259 #+STARTUP: noalign"
260 :group 'org-startup
261 :type 'boolean)
263 (defcustom org-startup-with-deadline-check nil
264 "Non-nil means, entering Org-mode will run the deadline check.
265 This means, if you start editing an org file, you will get an
266 immediate reminder of any due deadlines.
267 This can also be configured on a per-file basis by adding one of
268 the following lines anywhere in the buffer:
269 #+STARTUP: dlcheck
270 #+STARTUP: nodlcheck"
271 :group 'org-startup
272 :type 'boolean)
274 (defcustom org-insert-mode-line-in-empty-file nil
275 "Non-nil means insert the first line setting Org-mode in empty files.
276 When the function `org-mode' is called interactively in an empty file, this
277 normally means that the file name does not automatically trigger Org-mode.
278 To ensure that the file will always be in Org-mode in the future, a
279 line enforcing Org-mode will be inserted into the buffer, if this option
280 has been set."
281 :group 'org-startup
282 :type 'boolean)
284 (defcustom org-CUA-compatible nil
285 "Non-nil means use alternative key bindings for S-<cursor movement>.
286 Org-mode used S-<cursor movement> for changing timestamps and priorities.
287 S-<cursor movement> is also used for example by `CUA-mode' to select text.
288 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
289 alternative bindings. Setting this variable to t will replace the following
290 keys both in Org-mode and in the Org-agenda buffer.
292 S-RET -> C-S-RET
293 S-up -> M-p
294 S-down -> M-n
295 S-left -> M--
296 S-right -> M-+
298 If you do not like the alternative keys, take a look at the variable
299 `org-disputed-keys'.
301 This option is only relevant at load-time of Org-mode. Changing it requires
302 a restart of Emacs to become effective."
303 :group 'org-startup
304 :type 'boolean)
306 (defvar org-disputed-keys
307 '((S-up [(shift up)] [(meta ?p)])
308 (S-down [(shift down)] [(meta ?n)])
309 (S-left [(shift left)] [(meta ?-)])
310 (S-right [(shift right)] [(meta ?+)])
311 (S-return [(shift return)] [(control shift return)]))
312 "Keys for which Org-mode and other modes compete.
313 This is an alist, cars are symbols for lookup, 1st element is the default key,
314 second element will be used when `org-CUA-compatible' is t.")
316 (defun org-key (key)
317 "Select a key according to `org-CUA-compatible'."
318 (nth (if org-CUA-compatible 2 1)
319 (or (assq key org-disputed-keys)
320 (error "Invalid Key %s in `org-key'" key))))
322 (defcustom org-ellipsis nil
323 "The ellipsis to use in the Org-mode outline.
324 When nil, just use the standard three dots. When a string, use that instead,
325 and just in Org-mode (which will then use its own display table).
326 Changing this requires executing `M-x org-mode' in a buffer to become
327 effective."
328 :group 'org-startup
329 :type '(choice (const :tag "Default" nil)
330 (string :tag "String" :value "...#")))
332 (defvar org-display-table nil
333 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
335 (defgroup org-keywords nil
336 "Keywords in Org-mode."
337 :tag "Org Keywords"
338 :group 'org)
340 (defcustom org-deadline-string "DEADLINE:"
341 "String to mark deadline entries.
342 A deadline is this string, followed by a time stamp. Should be a word,
343 terminated by a colon. You can insert a schedule keyword and
344 a timestamp with \\[org-deadline].
345 Changes become only effective after restarting Emacs."
346 :group 'org-keywords
347 :type 'string)
349 (defcustom org-scheduled-string "SCHEDULED:"
350 "String to mark scheduled TODO entries.
351 A schedule is this string, followed by a time stamp. Should be a word,
352 terminated by a colon. You can insert a schedule keyword and
353 a timestamp with \\[org-schedule].
354 Changes become only effective after restarting Emacs."
355 :group 'org-keywords
356 :type 'string)
358 (defcustom org-closed-string "CLOSED:"
359 "String used as the prefix for timestamps logging closing a TODO entry."
360 :group 'org-keywords
361 :type 'string)
363 (defcustom org-clock-string "CLOCK:"
364 "String used as prefix for timestamps clocking work hours on an item."
365 :group 'org-keywords
366 :type 'string)
368 (defcustom org-comment-string "COMMENT"
369 "Entries starting with this keyword will never be exported.
370 An entry can be toggled between COMMENT and normal with
371 \\[org-toggle-comment].
372 Changes become only effective after restarting Emacs."
373 :group 'org-keywords
374 :type 'string)
376 (defcustom org-quote-string "QUOTE"
377 "Entries starting with this keyword will be exported in fixed-width font.
378 Quoting applies only to the text in the entry following the headline, and does
379 not extend beyond the next headline, even if that is lower level.
380 An entry can be toggled between QUOTE and normal with
381 \\[org-toggle-fixed-width-section]."
382 :group 'org-keywords
383 :type 'string)
385 (defgroup org-structure nil
386 "Options concerning the general structure of Org-mode files."
387 :tag "Org Structure"
388 :group 'org)
390 (defgroup org-cycle nil
391 "Options concerning visibility cycling in Org-mode."
392 :tag "Org Cycle"
393 :group 'org-structure)
395 (defcustom org-cycle-global-at-bob t
396 "Cycle globally if cursor is at beginning of buffer and not at a headline.
397 This makes it possible to do global cycling without having to use S-TAB or
398 C-u TAB. For this special case to work, the first line of the buffer
399 must not be a headline - it may be empty ot some other text. When used in
400 this way, `org-cycle-hook' is disables temporarily, to make sure the
401 cursor stays at the beginning of the buffer.
402 When this option is nil, don't do anything special at the beginning
403 of the buffer."
404 :group 'org-cycle
405 :type 'boolean)
407 (defcustom org-cycle-emulate-tab t
408 "Where should `org-cycle' emulate TAB.
409 nil Never
410 white Only in completely white lines
411 whitestart Only at the beginning of lines, before the first non-white char.
412 t Everywhere except in headlines
413 If TAB is used in a place where it does not emulate TAB, the current subtree
414 visibility is cycled."
415 :group 'org-cycle
416 :type '(choice (const :tag "Never" nil)
417 (const :tag "Only in completely white lines" white)
418 (const :tag "Before first char in a line" whitestart)
419 (const :tag "Everywhere except in headlines" t)
422 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
423 org-optimize-window-after-visibility-change)
424 "Hook that is run after `org-cycle' has changed the buffer visibility.
425 The function(s) in this hook must accept a single argument which indicates
426 the new state that was set by the most recent `org-cycle' command. The
427 argument is a symbol. After a global state change, it can have the values
428 `overview', `content', or `all'. After a local state change, it can have
429 the values `folded', `children', or `subtree'."
430 :group 'org-cycle
431 :type 'hook)
433 (defgroup org-edit-structure nil
434 "Options concerning structure editing in Org-mode."
435 :tag "Org Edit Structure"
436 :group 'org-structure)
438 (defcustom org-odd-levels-only nil
439 "Non-nil means, skip even levels and only use odd levels for the outline.
440 This has the effect that two stars are being added/taken away in
441 promotion/demotion commands. It also influences how levels are
442 handled by the exporters.
443 Changing it requires restart of `font-lock-mode' to become effective
444 for fontification also in regions already fontified.
445 You may also set this on a per-file basis by adding one of the following
446 lines to the buffer:
448 #+STARTUP: odd
449 #+STARTUP: oddeven"
450 :group 'org-edit-structure
451 :group 'org-font-lock
452 :type 'boolean)
454 (defcustom org-adapt-indentation t
455 "Non-nil means, adapt indentation when promoting and demoting.
456 When this is set and the *entire* text in an entry is indented, the
457 indentation is increased by one space in a demotion command, and
458 decreased by one in a promotion command. If any line in the entry
459 body starts at column 0, indentation is not changed at all."
460 :group 'org-edit-structure
461 :type 'boolean)
463 (defcustom org-insert-heading-hook nil
464 "Hook being run after inserting a new heading."
465 :group 'org-edit-structure
466 :type 'boolean)
468 (defcustom org-enable-fixed-width-editor t
469 "Non-nil means, lines starting with \":\" are treated as fixed-width.
470 This currently only means, they are never auto-wrapped.
471 When nil, such lines will be treated like ordinary lines.
472 See also the QUOTE keyword."
473 :group 'org-edit-structure
474 :type 'boolean)
476 (defgroup org-sparse-trees nil
477 "Options concerning sparse trees in Org-mode."
478 :tag "Org Sparse Trees"
479 :group 'org-structure)
481 (defcustom org-highlight-sparse-tree-matches t
482 "Non-nil means, highlight all matches that define a sparse tree.
483 The highlights will automatically disappear the next time the buffer is
484 changed by an edit command."
485 :group 'org-sparse-trees
486 :type 'boolean)
488 (defcustom org-show-hierarchy-above t
489 "Non-nil means, show full hierarchy when showing a spot in the tree.
490 Turning this off makes sparse trees more compact, but also less clear."
491 :group 'org-sparse-trees
492 :type 'boolean)
494 (defcustom org-show-following-heading t
495 "Non-nil means, show heading following match in `org-occur'.
496 When doing an `org-occur' it is useful to show the headline which
497 follows the match, even if they do not match the regexp. This makes it
498 easier to edit directly inside the sparse tree. However, if you use
499 `org-occur' mainly as an overview, the following headlines are
500 unnecessary clutter."
501 :group 'org-sparse-trees
502 :type 'boolean)
504 (defcustom org-occur-hook '(org-first-headline-recenter)
505 "Hook that is run after `org-occur' has constructed a sparse tree.
506 This can be used to recenter the window to show as much of the structure
507 as possible."
508 :group 'org-sparse-trees
509 :type 'hook)
511 (defgroup org-plain-lists nil
512 "Options concerning plain lists in Org-mode."
513 :tag "Org Plain lists"
514 :group 'org-structure)
516 (defcustom org-cycle-include-plain-lists nil
517 "Non-nil means, include plain lists into visibility cycling.
518 This means that during cycling, plain list items will *temporarily* be
519 interpreted as outline headlines with a level given by 1000+i where i is the
520 indentation of the bullet. In all other operations, plain list items are
521 not seen as headlines. For example, you cannot assign a TODO keyword to
522 such an item."
523 :group 'org-plain-lists
524 :type 'boolean)
527 (defcustom org-plain-list-ordered-item-terminator t
528 "The character that makes a line with leading number an ordered list item.
529 Valid values are ?. and ?\). To get both terminators, use t. While
530 ?. may look nicer, it creates the danger that a line with leading
531 number may be incorrectly interpreted as an item. ?\) therefore is
532 the safe choice."
533 :group 'org-plain-lists
534 :type '(choice (const :tag "dot like in \"2.\"" ?.)
535 (const :tag "paren like in \"2)\"" ?\))
536 (const :tab "both" t)))
538 (defcustom org-auto-renumber-ordered-lists t
539 "Non-nil means, automatically renumber ordered plain lists.
540 Renumbering happens when the sequence have been changed with
541 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
542 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
543 :group 'org-plain-lists
544 :type 'boolean)
546 (defgroup org-archive nil
547 "Options concerning archiving in Org-mode."
548 :tag "Org Archive"
549 :group 'org-structure)
551 (defcustom org-archive-tag "ARCHIVE"
552 "The tag that marks a subtree as archived.
553 An archived subtree does not open during visibility cycling, and does
554 not contribute to the agenda listings."
555 :group 'org-archive
556 :group 'org-keywords
557 :type 'string)
559 (defcustom org-agenda-skip-archived-trees t
560 "Non-nil means, the agenda will skip any items located in archived trees.
561 An archived tree is a tree marked with the tag ARCHIVE."
562 :group 'org-archive
563 :group 'org-agenda-display
564 :type 'boolean)
566 (defcustom org-cycle-open-archived-trees nil
567 "Non-nil means, `org-cycle' will open archived trees.
568 An archived tree is a tree marked with the tag ARCHIVE.
569 When nil, archived trees will stay folded. You can still open them with
570 normal outline commands like `show-all', but not with the cycling commands."
571 :group 'org-archive
572 :group 'org-cycle
573 :type 'boolean)
575 (defcustom org-sparse-tree-open-archived-trees nil
576 "Non-nil means sparse tree construction shows matches in archived trees.
577 When nil, matches in these trees are highlighted, but the trees are kept in
578 collapsed state."
579 :group 'org-archive
580 :group 'org-sparse-trees
581 :type 'boolean)
583 (defcustom org-archive-location "%s_archive::"
584 "The location where subtrees should be archived.
585 This string consists of two parts, separated by a double-colon.
587 The first part is a file name - when omitted, archiving happens in the same
588 file. %s will be replaced by the current file name (without directory part).
589 Archiving to a different file is useful to keep archived entries from
590 contributing to the Org-mode Agenda.
592 The part after the double colon is a headline. The archived entries will be
593 filed under that headline. When omitted, the subtrees are simply filed away
594 at the end of the file, as top-level entries.
596 Here are a few examples:
597 \"%s_archive::\"
598 If the current file is Projects.org, archive in file
599 Projects.org_archive, as top-level trees. This is the default.
601 \"::* Archived Tasks\"
602 Archive in the current file, under the top-level headline
603 \"* Archived Tasks\".
605 \"~/org/archive.org::\"
606 Archive in file ~/org/archive.org (absolute path), as top-level trees.
608 \"basement::** Finished Tasks\"
609 Archive in file ./basement (relative path), as level 3 trees
610 below the level 2 heading \"** Finished Tasks\".
612 You may set this option on a per-file basis by adding to the buffer a
613 line like
615 #+ARCHIVE: basement::** Finished Tasks"
616 :group 'org-archive
617 :type 'string)
619 (defcustom org-archive-mark-done t
620 "Non-nil means, mark entries as DONE when they are moved to the archive file."
621 :group 'org-archive
622 :type 'boolean)
624 (defcustom org-archive-stamp-time t
625 "Non-nil means, add a time stamp to entries moved to an archive file.
626 The time stamp will be added directly after the TODO state keyword in the
627 first line, so it is probably best to use this in combinations with
628 `org-archive-mark-done'."
629 :group 'org-archive
630 :type 'boolean)
632 (defgroup org-table nil
633 "Options concerning tables in Org-mode."
634 :tag "Org Table"
635 :group 'org)
637 (defcustom org-enable-table-editor 'optimized
638 "Non-nil means, lines starting with \"|\" are handled by the table editor.
639 When nil, such lines will be treated like ordinary lines.
641 When equal to the symbol `optimized', the table editor will be optimized to
642 do the following:
643 - Use automatic overwrite mode in front of whitespace in table fields.
644 This make the structure of the table stay in tact as long as the edited
645 field does not exceed the column width.
646 - Minimize the number of realigns. Normally, the table is aligned each time
647 TAB or RET are pressed to move to another field. With optimization this
648 happens only if changes to a field might have changed the column width.
649 Optimization requires replacing the functions `self-insert-command',
650 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
651 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
652 very good at guessing when a re-align will be necessary, but you can always
653 force one with \\[org-ctrl-c-ctrl-c].
655 If you would like to use the optimized version in Org-mode, but the
656 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
658 This variable can be used to turn on and off the table editor during a session,
659 but in order to toggle optimization, a restart is required.
661 See also the variable `org-table-auto-blank-field'."
662 :group 'org-table
663 :type '(choice
664 (const :tag "off" nil)
665 (const :tag "on" t)
666 (const :tag "on, optimized" optimized)))
668 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
669 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
670 In the optimized version, the table editor takes over all simple keys that
671 normally just insert a character. In tables, the characters are inserted
672 in a way to minimize disturbing the table structure (i.e. in overwrite mode
673 for empty fields). Outside tables, the correct binding of the keys is
674 restored.
676 The default for this option is t if the optimized version is also used in
677 Org-mode. See the variable `org-enable-table-editor' for details. Changing
678 this variable requires a restart of Emacs to become effective."
679 :group 'org-table
680 :type 'boolean)
682 (defgroup org-table-settings nil
683 "Settings for tables in Org-mode."
684 :tag "Org Table Settings"
685 :group 'org-table)
687 (defcustom org-table-default-size "5x2"
688 "The default size for newly created tables, Columns x Rows."
689 :group 'org-table-settings
690 :type 'string)
692 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
693 "Regular expression for recognizing numbers in table columns.
694 If a table column contains mostly numbers, it will be aligned to the
695 right. If not, it will be aligned to the left.
697 The default value of this option is a regular expression which allows
698 anything which looks remotely like a number as used in scientific
699 context. For example, all of the following will be considered a
700 number:
701 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
703 Other options offered by the customize interface are more restrictive."
704 :group 'org-table-settings
705 :type '(choice
706 (const :tag "Positive Integers"
707 "^[0-9]+$")
708 (const :tag "Integers"
709 "^[-+]?[0-9]+$")
710 (const :tag "Floating Point Numbers"
711 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
712 (const :tag "Floating Point Number or Integer"
713 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
714 (const :tag "Exponential, Floating point, Integer"
715 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
716 (const :tag "Very General Number-Like"
717 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
718 (string :tag "Regexp:")))
720 (defcustom org-table-number-fraction 0.5
721 "Fraction of numbers in a column required to make the column align right.
722 In a column all non-white fields are considered. If at least this
723 fraction of fields is matched by `org-table-number-fraction',
724 alignment to the right border applies."
725 :group 'org-table-settings
726 :type 'number)
728 (defgroup org-table-editing nil
729 "Bahavior of tables during editing in Org-mode."
730 :tag "Org Table Editing"
731 :group 'org-table)
733 (defcustom org-table-automatic-realign t
734 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
735 When nil, aligning is only done with \\[org-table-align], or after column
736 removal/insertion."
737 :group 'org-table-editing
738 :type 'boolean)
740 (defcustom org-table-limit-column-width t ;kw
741 "Non-nil means, allow to limit the width of table columns with <N> fields."
742 :group 'org-table-editing
743 :type 'boolean)
745 (defcustom org-table-auto-blank-field t
746 "Non-nil means, automatically blank table field when starting to type into it.
747 This only happens when typing immediately after a field motion
748 command (TAB, S-TAB or RET).
749 Only relevant when `org-enable-table-editor' is equal to `optimized'."
750 :group 'org-table-editing
751 :type 'boolean)
753 (defcustom org-table-tab-jumps-over-hlines t
754 "Non-nil means, tab in the last column of a table with jump over a hline.
755 If a horizontal separator line is following the current line,
756 `org-table-next-field' can either create a new row before that line, or jump
757 over the line. When this option is nil, a new line will be created before
758 this line."
759 :group 'org-table-editing
760 :type 'boolean)
762 (defcustom org-table-tab-recognizes-table.el t
763 "Non-nil means, TAB will automatically notice a table.el table.
764 When it sees such a table, it moves point into it and - if necessary -
765 calls `table-recognize-table'."
766 :group 'org-table-editing
767 :type 'boolean)
769 (defgroup org-table-calculation nil
770 "Options concerning tables in Org-mode."
771 :tag "Org Table Calculation"
772 :group 'org-table)
774 (defcustom org-table-copy-increment t
775 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
776 :group 'org-table-calculation
777 :type 'boolean)
779 (defcustom org-calc-default-modes
780 '(calc-internal-prec 12
781 calc-float-format (float 5)
782 calc-angle-mode deg
783 calc-prefer-frac nil
784 calc-symbolic-mode nil
785 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
786 calc-display-working-message t
788 "List with Calc mode settings for use in calc-eval for table formulas.
789 The list must contain alternating symbols (Calc modes variables and values).
790 Don't remove any of the default settings, just change the values. Org-mode
791 relies on the variables to be present in the list."
792 :group 'org-table-calculation
793 :type 'plist)
795 (defcustom org-table-formula-evaluate-inline t
796 "Non-nil means, TAB and RET evaluate a formula in current table field.
797 If the current field starts with an equal sign, it is assumed to be a formula
798 which should be evaluated as described in the manual and in the documentation
799 string of the command `org-table-eval-formula'. This feature requires the
800 Emacs calc package.
801 When this variable is nil, formula calculation is only available through
802 the command \\[org-table-eval-formula]."
803 :group 'org-table-calculation
804 :type 'boolean)
807 (defcustom org-table-formula-use-constants t
808 "Non-nil means, interpret constants in formulas in tables.
809 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
810 by the value given in `org-table-formula-constants', or by a value obtained
811 from the `constants.el' package."
812 :group 'org-table-calculation
813 :type 'boolean)
815 (defcustom org-table-formula-constants nil
816 "Alist with constant names and values, for use in table formulas.
817 The car of each element is a name of a constant, without the `$' before it.
818 The cdr is the value as a string. For example, if you'd like to use the
819 speed of light in a formula, you would configure
821 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
823 and then use it in an equation like `$1*$c'."
824 :group 'org-table-calculation
825 :type '(repeat
826 (cons (string :tag "name")
827 (string :tag "value"))))
829 (defcustom org-table-formula-numbers-only nil
830 "Non-nil means, calculate only with numbers in table formulas.
831 Then all input fields will be converted to a number, and the result
832 must also be a number. When nil, calc's full potential is available
833 in table calculations, including symbolics etc."
834 :group 'org-table-calculation
835 :type 'boolean)
837 (defcustom org-table-allow-automatic-line-recalculation t
838 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
839 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
840 :group 'org-table-calculation
841 :type 'boolean)
843 (defgroup org-link nil
844 "Options concerning links in Org-mode."
845 :tag "Org Link"
846 :group 'org)
848 (defcustom org-descriptive-links t
849 "Non-nil means, hide link part and only show description of bracket links.
850 Bracket links are like [[link][descritpion]]. This variable sets the initial
851 state in new org-mode buffers. The setting can then be toggled on a
852 per-buffer basis from the Org->Hyperlinks menu."
853 :group 'org-link
854 :type 'boolean)
856 (defcustom org-link-style 'bracket
857 "The style of links to be inserted with \\[org-insert-link].
858 Possible values are:
859 bracket [[link][description]]. This is recommended
860 plain Description \\n link. The old way, no longer recommended."
861 :group 'org-link
862 :type '(choice
863 (const :tag "Bracket (recommended)" bracket)
864 (const :tag "Plain (no longer recommended)" plain)))
866 (defcustom org-link-format "%s"
867 "Default format for external, URL-like linkes in the buffer.
868 This is a format string for printf, %s will be replaced by the link text.
869 The recommended value is just \"%s\", since links will be protected by
870 enclosing them in double brackets. If you prefer plain links (see variable
871 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
872 additional URL: prefix, so the format would be \"<URL:%s>\"."
873 :group 'org-link
874 :type '(choice
875 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
876 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
877 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
878 (string :tag "Other" :value "<%s>")))
880 (defcustom org-link-file-path-type 'adaptive
881 "How the path name in file links should be stored.
882 Valid values are:
884 relative relative to the current directory, i.e. the directory of the file
885 into which the link is being inserted.
886 absolute absolute path, if possible with ~ for home directory.
887 noabbrev absolute path, no abbreviation of home directory.
888 adaptive Use relative path for files in the current directory and sub-
889 directories of it. For other files, use an absolute path."
890 :group 'org-link
891 :type '(choice
892 (const relative)
893 (const absolute)
894 (const noabbrev)
895 (const adaptive)))
897 (defcustom org-activate-links '(bracket angle plain radio tag date)
898 "Types of links that should be activated in Org-mode files.
899 This is a list of symbols, each leading to the activation of a certain link
900 type. In principle, it does not hurt to turn on most link types - there may
901 be a small gain when turning off unused link types. The types are:
903 bracket The recommended [[link][description]] or [[link]] links with hiding.
904 angular Links in angular brackes that may contain whitespace like
905 <bbdb:Carsten Dominik>.
906 plain Plain links in normal text, no whitespace, like http://google.com.
907 radio Text that is matched by a radio target, see manual for details.
908 tag Tag settings in a headline (link to tag search).
909 date Time stamps (link to calendar).
910 camel CamelCase words defining text searches.
912 Changing this variable requires a restart of Emacs to become effective."
913 :group 'org-link
914 :type '(set (const :tag "Double bracket links (new style)" bracket)
915 (const :tag "Angular bracket links (old style)" angular)
916 (const :tag "plain text links" plain)
917 (const :tag "Radio target matches" radio)
918 (const :tag "Tags" tag)
919 (const :tag "Timestamps" date)
920 (const :tag "CamelCase words" camel)))
922 (defgroup org-link-store nil
923 "Options concerning storing links in Org-mode"
924 :tag "Org Store Link"
925 :group 'org-link)
927 (defcustom org-context-in-file-links t
928 "Non-nil means, file links from `org-store-link' contain context.
929 A search string will be added to the file name with :: as separator and
930 used to find the context when the link is activated by the command
931 `org-open-at-point'.
932 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
933 negates this setting for the duration of the command."
934 :group 'org-link-store
935 :type 'boolean)
937 (defcustom org-file-link-context-use-camel-case nil
938 "Non-nil means, use CamelCase to store a search context in a file link.
939 When nil, the search string simply consists of the words of the string.
940 CamelCase is deprecated, and support for it may be dropped in the future."
941 :group 'org-link-store
942 :type 'boolean)
944 (defcustom org-keep-stored-link-after-insertion nil
945 "Non-nil means, keep link in list for entire session.
947 The command `org-store-link' adds a link pointing to the current
948 location to an internal list. These links accumulate during a session.
949 The command `org-insert-link' can be used to insert links into any
950 Org-mode file (offering completion for all stored links). When this
951 option is nil, every link which has been inserted once using \\[org-insert-link]
952 will be removed from the list, to make completing the unused links
953 more efficient."
954 :group 'org-link-store
955 :type 'boolean)
957 (defcustom org-usenet-links-prefer-google nil
958 "Non-nil means, `org-store-link' will create web links to Google groups.
959 When nil, Gnus will be used for such links.
960 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
961 negates this setting for the duration of the command."
962 :group 'org-link-store
963 :type 'boolean)
965 (defgroup org-link-follow nil
966 "Options concerning following links in Org-mode"
967 :tag "Org Follow Link"
968 :group 'org-link)
970 (defcustom org-tab-follows-link nil
971 "Non-nil means, on links TAB will follow the link.
972 Needs to be set before org.el is loaded."
973 :group 'org-link-follow
974 :type 'boolean)
976 (defcustom org-return-follows-link nil
977 "Non-nil means, on links RET will follow the link.
978 Needs to be set before org.el is loaded."
979 :group 'org-link-follow
980 :type 'boolean)
982 (defcustom org-mouse-1-follows-link t
983 "Non-nil means, mouse-1 on a link will follow the link.
984 A longer mouse click will still set point. Does not wortk on XEmacs.
985 Needs to be set before org.el is loaded."
986 :group 'org-link-follow
987 :type 'boolean)
989 (defcustom org-mark-ring-length 4
990 "Number of different positions to be recorded in the ring
991 Changing this requires a restart of Emacs to work correctly."
992 :group 'org-link-follow
993 :type 'interger)
995 (defcustom org-link-frame-setup
996 '((vm . vm-visit-folder-other-frame)
997 (gnus . gnus-other-frame)
998 (file . find-file-other-window))
999 "Setup the frame configuration for following links.
1000 When following a link with Emacs, it may often be useful to display
1001 this link in another window or frame. This variable can be used to
1002 set this up for the different types of links.
1003 For VM, use any of
1004 `vm-visit-folder'
1005 `vm-visit-folder-other-frame'
1006 For Gnus, use any of
1007 `gnus'
1008 `gnus-other-frame'
1009 For FILE, use any of
1010 `find-file'
1011 `find-file-other-window'
1012 `find-file-other-frame'
1013 For the calendar, use the variable `calendar-setup'.
1014 For BBDB, it is currently only possible to display the matches in
1015 another window."
1016 :group 'org-link-follow
1017 :type '(list
1018 (cons (const vm)
1019 (choice
1020 (const vm-visit-folder)
1021 (const vm-visit-folder-other-window)
1022 (const vm-visit-folder-other-frame)))
1023 (cons (const gnus)
1024 (choice
1025 (const gnus)
1026 (const gnus-other-frame)))
1027 (cons (const file)
1028 (choice
1029 (const find-file)
1030 (const find-file-other-window)
1031 (const find-file-other-frame)))))
1033 (defcustom org-open-non-existing-files nil
1034 "Non-nil means, `org-open-file' will open non-existing file.
1035 When nil, an error will be generated."
1036 :group 'org-link-follow
1037 :type 'boolean)
1039 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1040 "Non-nil means, ask for confirmation before executing shell links.
1041 Shell links can be dangerous, just thing about a link
1043 [[shell:rm -rf ~/*][Google Search]]
1045 This link would show up in your Org-mode document as \"Google Search\"
1046 but really it would remove your entire home directory.
1047 Therefore I *definitely* advise against setting this variable to nil.
1048 Just change it to `y-or-n-p' of you want to confirm with a single key press
1049 rather than having to type \"yes\"."
1050 :group 'org-link-follow
1051 :type '(choice
1052 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1053 (const :tag "with y-or-n (faster)" y-or-n-p)
1054 (const :tag "no confirmation (dangerous)" nil)))
1056 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1057 "Non-nil means, ask for confirmation before executing elisp links.
1058 Elisp links can be dangerous, just thing about a link
1060 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1062 This link would show up in your Org-mode document as \"Google Search\"
1063 but really it would remove your entire home directory.
1064 Therefore I *definitely* advise against setting this variable to nil.
1065 Just change it to `y-or-n-p' of you want to confirm with a single key press
1066 rather than having to type \"yes\"."
1067 :group 'org-link-follow
1068 :type '(choice
1069 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1070 (const :tag "with y-or-n (faster)" y-or-n-p)
1071 (const :tag "no confirmation (dangerous)" nil)))
1073 (defconst org-file-apps-defaults-gnu
1074 '((remote . emacs)
1075 (t . mailcap))
1076 "Default file applications on a UNIX or GNU/Linux system.
1077 See `org-file-apps'.")
1079 (defconst org-file-apps-defaults-macosx
1080 '((remote . emacs)
1081 (t . "open %s")
1082 ("ps" . "gv %s")
1083 ("ps.gz" . "gv %s")
1084 ("eps" . "gv %s")
1085 ("eps.gz" . "gv %s")
1086 ("dvi" . "xdvi %s")
1087 ("fig" . "xfig %s"))
1088 "Default file applications on a MacOS X system.
1089 The system \"open\" is known as a default, but we use X11 applications
1090 for some files for which the OS does not have a good default.
1091 See `org-file-apps'.")
1093 (defconst org-file-apps-defaults-windowsnt
1094 (list
1095 '(remote . emacs)
1096 (cons t
1097 (list (if (featurep 'xemacs)
1098 'mswindows-shell-execute
1099 'w32-shell-execute)
1100 "open" 'file)))
1101 "Default file applications on a Windows NT system.
1102 The system \"open\" is used for most files.
1103 See `org-file-apps'.")
1105 (defcustom org-file-apps
1107 ("txt" . emacs)
1108 ("tex" . emacs)
1109 ("ltx" . emacs)
1110 ("org" . emacs)
1111 ("el" . emacs)
1112 ("bib" . emacs)
1114 "External applications for opening `file:path' items in a document.
1115 Org-mode uses system defaults for different file types, but
1116 you can use this variable to set the application for a given file
1117 extension. The entries in this list are cons cells where the car identifies
1118 files and the cdr the corresponding command. Possible values for the
1119 file identifier are
1120 \"ext\" A string identifying an extension
1121 `directory' Matches a directory
1122 `remote' Matches a remove file, accessible through tramp or efs.
1123 Remote files most likely should be visited through emacs
1124 because external applications cannot handle such paths.
1125 t Default for all remaining files
1127 Possible values for the command are:
1128 `emacs' The file will be visited by the current Emacs process.
1129 `default' Use the default application for this file type.
1130 string A command to be executed by a shell; %s will be replaced
1131 by the path to the file.
1132 sexp A Lisp form which will be evaluated. The file path will
1133 be available in the Lisp variable `file'.
1134 For more examples, see the system specific constants
1135 `org-file-apps-defaults-macosx'
1136 `org-file-apps-defaults-windowsnt'
1137 `org-file-apps-defaults-gnu'."
1138 :group 'org-link-follow
1139 :type '(repeat
1140 (cons (choice :value ""
1141 (string :tag "Extension")
1142 (const :tag "Default for unrecognized files" t)
1143 (const :tag "Remote file" remote)
1144 (const :tag "Links to a directory" directory))
1145 (choice :value ""
1146 (const :tag "Visit with Emacs" emacs)
1147 (const :tag "Use system default" default)
1148 (string :tag "Command")
1149 (sexp :tag "Lisp form")))))
1151 (defcustom org-mhe-search-all-folders nil
1152 "Non-nil means, that the search for the mh-message will be extended to
1153 all folders if the message cannot be found in the folder given in the link.
1154 Searching all folders is very effective with one of the search engines
1155 supported by MH-E, but will be slow with pick."
1156 :group 'org-link-follow
1157 :type 'boolean)
1159 (defgroup org-remember nil
1160 "Options concerning interaction with remember.el."
1161 :tag "Org Remember"
1162 :group 'org)
1164 (defcustom org-directory "~/org"
1165 "Directory with org files.
1166 This directory will be used as default to prompt for org files.
1167 Used by the hooks for remember.el."
1168 :group 'org-remember
1169 :type 'directory)
1171 (defcustom org-default-notes-file "~/.notes"
1172 "Default target for storing notes.
1173 Used by the hooks for remember.el. This can be a string, or nil to mean
1174 the value of `remember-data-file'."
1175 :group 'org-remember
1176 :type '(choice
1177 (const :tag "Default from remember-data-file" nil)
1178 file))
1180 (defcustom org-remember-templates nil
1181 "Templates for the creation of remember buffers.
1182 When nil, just let remember make the buffer.
1183 When not nil, this is a list of 3-element lists. In each entry, the first
1184 element is a character, a unique key to select this template.
1185 The second element is the template. The third element is optional and can
1186 specify a destination file for remember items created with this template.
1187 The default file is given by `org-default-notes-file'.
1189 The template specifies the structure of the remember buffer. It should have
1190 a first line starting with a star, to act as the org-mode headline.
1191 Furthermore, the following %-escapes will be replaced with content:
1192 %t time stamp, date only
1193 %T time stamp with date and time
1194 %u inactive time stamp, date only
1195 %U inactive time stamp with date and time
1196 %n user name
1197 %a annotation, normally the link created with org-store-link
1198 %i initial content, the region when remember is called with C-u.
1199 If %i is indented, the entire inserted text will be indented as well.
1200 %? This will be removed, and the cursor placed at this position."
1201 :group 'org-remember
1202 :type '(repeat :tag "enabled"
1203 (list :value (?a "\n" nil)
1204 (character :tag "Selection Key")
1205 (string :tag "Template")
1206 (file :tag "Destination file (optional)"))))
1208 (defcustom org-reverse-note-order nil
1209 "Non-nil means, store new notes at the beginning of a file or entry.
1210 When nil, new notes will be filed to the end of a file or entry."
1211 :group 'org-remember
1212 :type '(choice
1213 (const :tag "Reverse always" t)
1214 (const :tag "Reverse never" nil)
1215 (repeat :tag "By file name regexp"
1216 (cons regexp boolean))))
1218 (defgroup org-todo nil
1219 "Options concerning TODO items in Org-mode."
1220 :tag "Org TODO"
1221 :group 'org)
1223 (defcustom org-todo-keywords '("TODO" "DONE")
1224 "List of TODO entry keywords.
1225 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1226 considered to mean that the entry is \"done\". All the other mean that
1227 action is required, and will make the entry show up in todo lists, diaries
1228 etc.
1229 The command \\[org-todo] cycles an entry through these states, and an
1230 additional state where no keyword is present. For details about this
1231 cycling, see also the variable `org-todo-interpretation'
1232 Changes become only effective after restarting Emacs."
1233 :group 'org-todo
1234 :group 'org-keywords
1235 :type '(repeat (string :tag "Keyword")))
1237 (defcustom org-todo-interpretation 'sequence
1238 "Controls how TODO keywords are interpreted.
1239 This variable is only relevant if `org-todo-keywords' contains more than two
1240 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1242 When `sequence', \\[org-todo] will always switch to the next state in the
1243 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1244 to state when executed several times in direct succession. Otherwise, it
1245 switches directly to DONE from any state.
1246 See the manual for more information."
1247 :group 'org-todo
1248 :group 'org-keywords
1249 :type '(choice (const sequence)
1250 (const type)))
1252 (defcustom org-after-todo-state-change-hook nil
1253 "Hook which is run after the state of a TODO item was changed.
1254 The new state (a string with a TODO keyword, or nil) is available in the
1255 Lisp variable `state'."
1256 :group 'org-todo
1257 :type 'hook)
1259 (defcustom org-log-done nil
1260 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1261 When the state of an entry is changed from nothing to TODO, remove a previous
1262 closing date.
1263 This can also be configured on a per-file basis by adding one of
1264 the following lines anywhere in the buffer:
1266 #+STARTUP: logging
1267 #+STARTUP: nologging"
1268 :group 'org-todo
1269 :type 'boolean)
1271 (defgroup org-priorities nil
1272 "Priorities in Org-mode."
1273 :tag "Org Priorities"
1274 :group 'org-todo)
1276 (defcustom org-default-priority ?B
1277 "The default priority of TODO items.
1278 This is the priority an item get if no explicit priority is given."
1279 :group 'org-priorities
1280 :type 'character)
1282 (defcustom org-lowest-priority ?C
1283 "The lowest priority of TODO items. A character like ?A, ?B etc."
1284 :group 'org-priorities
1285 :type 'character)
1287 (defgroup org-time nil
1288 "Options concerning time stamps and deadlines in Org-mode."
1289 :tag "Org Time"
1290 :group 'org)
1292 (defcustom org-insert-labeled-timestamps-at-point nil
1293 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1294 When nil, these labeled time stamps are forces into the second line of an
1295 entry, just after the headline. When scheduling from the global TODO list,
1296 the time stamp will always be forced into the second line."
1297 :group 'org-time
1298 :type 'boolean)
1300 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1301 "Formats for `format-time-string' which are used for time stamps.
1302 It is not recommended to change this constant.")
1304 (defcustom org-time-stamp-rounding-minutes 0
1305 "Number of minutes to round time stamps to upon insertion.
1306 When zero, insert the time unmodified. Useful rounding numbers
1307 should be factors of 60, so for example 5, 10, 15.
1308 When this is not zero, you can still force an exact time-stamp by using
1309 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1310 :group 'org-time
1311 :type 'integer)
1313 (defcustom org-deadline-warning-days 30
1314 "No. of days before expiration during which a deadline becomes active.
1315 This variable governs the display in the org file."
1316 :group 'org-time
1317 :type 'number)
1319 (defcustom org-popup-calendar-for-date-prompt t
1320 "Non-nil means, pop up a calendar when prompting for a date.
1321 In the calendar, the date can be selected with mouse-1. However, the
1322 minibuffer will also be active, and you can simply enter the date as well.
1323 When nil, only the minibuffer will be available."
1324 :group 'org-time
1325 :type 'boolean)
1327 (defcustom org-calendar-follow-timestamp-change t
1328 "Non-nil means, make the calendar window follow timestamp changes.
1329 When a timestamp is modified and the calendar window is visible, it will be
1330 moved to the new date."
1331 :group 'org-time
1332 :type 'boolean)
1334 (defgroup org-tags nil
1335 "Options concerning tags in Org-mode."
1336 :tag "Org Tags"
1337 :group 'org)
1339 (defcustom org-tag-alist nil
1340 "List of tags allowed in Org-mode files.
1341 When this list is nil, Org-mode will base TAG input on what is already in the
1342 buffer.
1343 The value of this variable is an alist, the car may be (and should) be a
1344 character that is used to select that tag through the fast-tag-selection
1345 interface. See the manual for details."
1346 :group 'org-tags
1347 :type '(repeat
1348 (choice
1349 (cons (string :tag "Tag name")
1350 (character :tag "Access char"))
1351 (const :tag "Start radio group" (:startgroup))
1352 (const :tag "End radio group" (:endgroup)))))
1354 (defcustom org-use-fast-tag-selection 'auto
1355 "Non-nil means, use fast tag selection scheme.
1356 This is a special interface to select and deselect tags with single keys.
1357 When nil, fast selection is never used.
1358 When the symbol `auto', fast selection is used if and only if selection
1359 characters for tags have been configured, either through the variable
1360 `org-tag-alist' or through a #+TAGS line in the buffer.
1361 When t, fast selection is always used and selection keys are assigned
1362 automatically if necessary."
1363 :group 'org-tags
1364 :type '(choice
1365 (const :tag "Always" t)
1366 (const :tag "Never" nil)
1367 (const :tag "When selection characters are configured" 'auto)))
1369 (defcustom org-tags-column 48
1370 "The column to which tags should be indented in a headline.
1371 If this number is positive, it specifies the column. If it is negative,
1372 it means that the tags should be flushright to that column. For example,
1373 -79 works well for a normal 80 character screen."
1374 :group 'org-tags
1375 :type 'integer)
1377 (defcustom org-auto-align-tags t
1378 "Non-nil means, realign tags after pro/demotion of TODO state change.
1379 These operations change the length of a headline and therefore shift
1380 the tags around. With this options turned on, after each such operation
1381 the tags are again aligned to `org-tags-column'."
1382 :group 'org-tags
1383 :type 'boolean)
1385 (defcustom org-use-tag-inheritance t
1386 "Non-nil means, tags in levels apply also for sublevels.
1387 When nil, only the tags directly given in a specific line apply there.
1388 If you turn off this option, you very likely want to turn on the
1389 companion option `org-tags-match-list-sublevels'."
1390 :group 'org-tags
1391 :type 'boolean)
1393 (defcustom org-tags-match-list-sublevels nil
1394 "Non-nil means list also sublevels of headlines matching tag search.
1395 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1396 the sublevels of a headline matching a tag search often also match
1397 the same search. Listing all of them can create very long lists.
1398 Setting this variable to nil causes subtrees of a match to be skipped.
1399 This option is off by default, because inheritance in on. If you turn
1400 inheritance off, you very likely want to turn this option on.
1402 As a special case, if the tag search is restricted to TODO items, the
1403 value of this variable is ignored and sublevels are always checked, to
1404 make sure all corresponding TODO items find their way into the list."
1405 :group 'org-tags
1406 :type 'boolean)
1408 (defvar org-tags-history nil
1409 "History of minibuffer reads for tags.")
1410 (defvar org-last-tags-completion-table nil
1411 "The last used completion table for tags.")
1413 (defgroup org-agenda nil
1414 "Options concerning agenda display Org-mode."
1415 :tag "Org Agenda"
1416 :group 'org)
1418 (defvar org-category nil
1419 "Variable used by org files to set a category for agenda display.
1420 Such files should use a file variable to set it, for example
1422 -*- mode: org; org-category: \"ELisp\"
1424 or contain a special line
1426 #+CATEGORY: ELisp
1428 If the file does not specify a category, then file's base name
1429 is used instead.")
1430 (make-variable-buffer-local 'org-category)
1432 (defcustom org-agenda-files nil
1433 "The files to be used for agenda display.
1434 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1435 \\[org-remove-file]. You can also use customize to edit the list.
1437 If the value of the variable is not a list but a single file name, then
1438 the list of agenda files is actually stored and maintained in that file, one
1439 agenda file per line."
1440 :group 'org-agenda
1441 :type '(choice
1442 (repeat :tag "List of files" file)
1443 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1445 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1446 "Custom commands for the agenda.
1447 These commands will be offered on the splash screen displayed by the
1448 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1450 key The key (a single char as a string) to be associated with the command.
1451 type The command type, any of the following symbols:
1452 todo Entries with a specific TODO keyword, in all agenda files.
1453 tags Tags match in all agenda files.
1454 tags-todo Tags match in all agenda files, TODO entries only.
1455 todo-tree Sparse tree of specific TODO keyword in *current* file.
1456 tags-tree Sparse tree with all tags matches in *current* file.
1457 occur-tree Occur sparse tree for current file.
1458 match What to search for:
1459 - a single keyword for TODO keyword searches
1460 - a tags match expression for tags searches
1461 - a regular expression for occur searches"
1462 :group 'org-agenda
1463 :type '(repeat
1464 (list (string :tag "Key")
1465 (choice :tag "Type"
1466 (const :tag "Tags search in all agenda files" tags)
1467 (const :tag "Tags search of TODO entries, all agenda files" tags-todo)
1468 (const :tag "TODO keyword search in all agenda files" todo)
1469 (const :tag "Tags sparse tree in current buffer" tags-tree)
1470 (const :tag "TODO keyword tree in current buffer" todo-tree)
1471 (const :tag "Occur tree in current buffer" occur-tree))
1472 (string :tag "Match"))))
1474 (defcustom org-agenda-todo-list-sublevels t
1475 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1476 When nil, the sublevels of a TODO entry are not checked, resulting in
1477 potentially much shorter TODO lists."
1478 :group 'org-agenda
1479 :group 'org-todo
1480 :type 'boolean)
1482 (defcustom org-agenda-todo-ignore-scheduled nil
1483 "Non-nil means, don't show scheduled entries in the global todo list.
1484 The idea behind this is that by scheduling it, you have already taken care
1485 of this item."
1486 :group 'org-agenda
1487 :group 'org-todo
1488 :type 'boolean)
1490 (defcustom org-agenda-include-all-todo nil
1491 "Non-nil means, the agenda will always contain all TODO entries.
1492 When nil, date-less entries will only be shown if `org-agenda' is called
1493 with a prefix argument.
1494 When non-nil, the TODO entries will be listed at the top of the agenda, before
1495 the entries for specific days."
1496 :group 'org-agenda
1497 :type 'boolean)
1499 (defcustom org-agenda-include-diary nil
1500 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1501 :group 'org-agenda
1502 :type 'boolean)
1504 (defcustom org-calendar-to-agenda-key [?c]
1505 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1506 The command `org-calendar-goto-agenda' will be bound to this key. The
1507 default is the character `c' because then `c' can be used to switch back and
1508 forth between agenda and calendar."
1509 :group 'org-agenda
1510 :type 'sexp)
1512 (defgroup org-agenda-setup nil
1513 "Options concerning setting up the Agenda window in Org Mode."
1514 :tag "Org Agenda Window Setup"
1515 :group 'org-agenda)
1517 (defcustom org-agenda-mouse-1-follows-link nil
1518 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1519 A longer mouse click will still set point. Does not wortk on XEmacs.
1520 Needs to be set before org.el is loaded."
1521 :group 'org-agenda-setup
1522 :type 'boolean)
1524 (defcustom org-agenda-start-with-follow-mode nil
1525 "The initial value of follwo-mode in a newly created agenda window."
1526 :group 'org-agenda-setup
1527 :type 'boolean)
1529 (defcustom org-select-agenda-window t
1530 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1531 When nil, cursor will remain in the current window."
1532 :group 'org-agenda-setup
1533 :type 'boolean)
1535 (defcustom org-fit-agenda-window t
1536 "Non-nil means, change window size of agenda to fit content."
1537 :group 'org-agenda-setup
1538 :type 'boolean)
1540 (defgroup org-agenda-display nil
1541 "Options concerning what to display initially in Agenda."
1542 :tag "Org Agenda Display"
1543 :group 'org-agenda)
1545 (defcustom org-agenda-show-all-dates t
1546 "Non-nil means, `org-agenda' shows every day in the selected range.
1547 When nil, only the days which actually have entries are shown."
1548 :group 'org-agenda-display
1549 :type 'boolean)
1551 (defcustom org-agenda-start-on-weekday 1
1552 "Non-nil means, start the overview always on the specified weekday.
1553 0 denotes Sunday, 1 denotes Monday etc.
1554 When nil, always start on the current day."
1555 :group 'org-agenda-display
1556 :type '(choice (const :tag "Today" nil)
1557 (number :tag "Weekday No.")))
1559 (defcustom org-agenda-ndays 7
1560 "Number of days to include in overview display.
1561 Should be 1 or 7."
1562 :group 'org-agenda-display
1563 :type 'number)
1565 (defcustom org-agenda-use-time-grid t
1566 "Non-nil means, show a time grid in the agenda schedule.
1567 A time grid is a set of lines for specific times (like every two hours between
1568 8:00 and 20:00). The items scheduled for a day at specific times are
1569 sorted in between these lines.
1570 For details about when the grid will be shown, and what it will look like, see
1571 the variable `org-agenda-time-grid'."
1572 :group 'org-agenda-display
1573 :type 'boolean)
1575 (defcustom org-agenda-time-grid
1576 '((daily today require-timed)
1577 "----------------"
1578 (800 1000 1200 1400 1600 1800 2000))
1580 "The settings for time grid for agenda display.
1581 This is a list of three items. The first item is again a list. It contains
1582 symbols specifying conditions when the grid should be displayed:
1584 daily if the agenda shows a single day
1585 weekly if the agenda shows an entire week
1586 today show grid on current date, independent of daily/weekly display
1587 require-timed show grid only if at least on item has a time specification
1589 The second item is a string which will be places behing the grid time.
1591 The third item is a list of integers, indicating the times that should have
1592 a grid line."
1593 :group 'org-agenda-display
1594 :type
1595 '(list
1596 (set :greedy t :tag "Grid Display Options"
1597 (const :tag "Show grid in single day agenda display" daily)
1598 (const :tag "Show grid in weekly agenda display" weekly)
1599 (const :tag "Always show grid for today" today)
1600 (const :tag "Show grid only if any timed entries are present"
1601 require-timed)
1602 (const :tag "Skip grid times already present in an entry"
1603 remove-match))
1604 (string :tag "Grid String")
1605 (repeat :tag "Grid Times" (integer :tag "Time"))))
1607 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1608 "Sorting structure for the agenda items of a single day.
1609 This is a list of symbols which will be used in sequence to determine
1610 if an entry should be listed before another entry. The following
1611 symbols are recognized:
1613 time-up Put entries with time-of-day indications first, early first
1614 time-down Put entries with time-of-day indications first, late first
1615 category-keep Keep the default order of categories, corresponding to the
1616 sequence in `org-agenda-files'.
1617 category-up Sort alphabetically by category, A-Z.
1618 category-down Sort alphabetically by category, Z-A.
1619 priority-up Sort numerically by priority, high priority last.
1620 priority-down Sort numerically by priority, high priority first.
1622 The different possibilities will be tried in sequence, and testing stops
1623 if one comparison returns a \"not-equal\". For example, the default
1624 '(time-up category-keep priority-down)
1625 means: Pull out all entries having a specified time of day and sort them,
1626 in order to make a time schedule for the current day the first thing in the
1627 agenda listing for the day. Of the entries without a time indication, keep
1628 the grouped in categories, don't sort the categories, but keep them in
1629 the sequence given in `org-agenda-files'. Within each category sort by
1630 priority.
1632 Leaving out `category-keep' would mean that items will be sorted across
1633 categories by priority."
1634 :group 'org-agenda-display
1635 :type '(repeat
1636 (choice
1637 (const time-up)
1638 (const time-down)
1639 (const category-keep)
1640 (const category-up)
1641 (const category-down)
1642 (const priority-up)
1643 (const priority-down))))
1645 (defcustom org-sort-agenda-notime-is-late t
1646 "Non-nil means, items without time are considered late.
1647 This is only relevant for sorting. When t, items which have no explicit
1648 time like 15:30 will be considered as 99:01, i.e. later than any items which
1649 do have a time. When nil, the default time is before 0:00. You can use this
1650 option to decide if the schedule for today should come before or after timeless
1651 agenda entries."
1652 :group 'org-agenda-display
1653 :type 'boolean)
1656 (defgroup org-agenda-prefix nil
1657 "Options concerning the entry prefix in the Org-mode agenda display."
1658 :tag "Org Agenda Prefix"
1659 :group 'org-agenda)
1661 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1662 "Format specification for the prefix of items in the agenda buffer.
1663 This format works similar to a printf format, with the following meaning:
1665 %c the category of the item, \"Diary\" for entries from the diary, or
1666 as given by the CATEGORY keyword or derived from the file name.
1667 %T the first tag of the item.
1668 %t the time-of-day specification if one applies to the entry, in the
1669 format HH:MM
1670 %s Scheduling/Deadline information, a short string
1672 All specifiers work basically like the standard `%s' of printf, but may
1673 contain two additional characters: A question mark just after the `%' and
1674 a whitespace/punctuation character just before the final letter.
1676 If the first character after `%' is a question mark, the entire field
1677 will only be included if the corresponding value applies to the
1678 current entry. This is useful for fields which should have fixed
1679 width when present, but zero width when absent. For example,
1680 \"%?-12t\" will result in a 12 character time field if a time of the
1681 day is specified, but will completely disappear in entries which do
1682 not contain a time.
1684 If there is punctuation or whitespace character just before the final
1685 format letter, this character will be appended to the field value if
1686 the value is not empty. For example, the format \"%-12:c\" leads to
1687 \"Diary: \" if the category is \"Diary\". If the category were be
1688 empty, no additional colon would be interted.
1690 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1691 - Indent the line with two space characters
1692 - Give the category in a 12 chars wide field, padded with whitespace on
1693 the right (because of `-'). Append a colon if there is a category
1694 (because of `:').
1695 - If there is a time-of-day, put it into a 12 chars wide field. If no
1696 time, don't put in an empty field, just skip it (because of '?').
1697 - Finally, put the scheduling information and append a whitespace.
1699 As another example, if you don't want the time-of-day of entries in
1700 the prefix, you could use:
1702 (setq org-agenda-prefix-format \" %-11:c% s\")
1704 See also the variables `org-agenda-remove-times-when-in-prefix' and
1705 `org-agenda-remove-tags-when-in-prefix'."
1706 :type 'string
1707 :group 'org-agenda-prefix)
1709 (defvar org-prefix-format-compiled nil
1710 "The compiled version of the most recently used prefix format.
1711 Depending on which command was used last, this may be the compiled version
1712 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1714 (defcustom org-agenda-remove-times-when-in-prefix t
1715 "Non-nil means, remove duplicate time specifications in agenda items.
1716 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1717 time-of-day specification in a headline or diary entry is extracted and
1718 placed into the prefix. If this option is non-nil, the original specification
1719 \(a timestamp or -range, or just a plain time(range) specification like
1720 11:30-4pm) will be removed for agenda display. This makes the agenda less
1721 cluttered.
1722 The option can be t or nil. It may also be the symbol `beg', indicating
1723 that the time should only be removed what it is located at the beginning of
1724 the headline/diary entry."
1725 :group 'org-agenda-prefix
1726 :type '(choice
1727 (const :tag "Always" t)
1728 (const :tag "Never" nil)
1729 (const :tag "When at beginning of entry" beg)))
1731 (defcustom org-agenda-remove-tags-when-in-prefix nil
1732 "Non-nil means, remove the tags from the headline copy in the agenda.
1733 When this is the symbol `prefix', only remove tags when
1734 `org-agenda-prefix-format' contains a `%T' specifier."
1735 :group 'org-agenda-prefix
1736 :type '(choice
1737 (const :tag "Always" t)
1738 (const :tag "Never" nil)
1739 (const :tag "When prefix format contains %T" prefix)))
1741 (defgroup org-agenda-timeline nil
1742 "Options concerning the timeline buffer in Org Mode."
1743 :tag "Org Agenda Timeline"
1744 :group 'org-agenda)
1746 (defcustom org-timeline-prefix-format " % s"
1747 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1748 :type 'string
1749 :group 'org-agenda-timeline)
1751 (defcustom org-select-timeline-window t
1752 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1753 When nil, cursor will remain in the current window."
1754 :group 'org-agenda-timeline
1755 :type 'boolean)
1757 (defcustom org-timeline-show-empty-dates 3
1758 "Non-nil means, `org-timeline' also shows dates without an entry.
1759 When nil, only the days which actually have entries are shown.
1760 When t, all days between the first and the last date are shown.
1761 When an integer, show also empty dates, but if there is a gap of more than
1762 N days, just insert a special line indicating the size of the gap."
1763 :group 'org-agenda-timeline
1764 :type '(choice
1765 (const :tag "None" nil)
1766 (const :tag "All" t)
1767 (number :tag "at most")))
1769 (defgroup org-latex nil
1770 "Options for embedding LaTeX code into Org-mode"
1771 :tag "Org LaTeX"
1772 :group 'org)
1774 (defcustom org-format-latex-options
1775 '(:foreground "Black" :background "Transparent" :scale 1.0
1776 :matchers ("begin" "$" "$$" "\\(" "\\["))
1777 "Options for creating images from LaTeX fragments.
1778 This is a property list with the following properties:
1779 :foreground the foreground color, for example \"Black\".
1780 :background the background color, or \"Transparent\".
1781 :scale a scaling factor for the size of the images
1782 :matchers a list indicating which matchers should be used to
1783 find LaTeX fragments. Valid members of this list are:
1784 \"begin\" find environments
1785 \"$\" find math expressions surrounded by $...$
1786 \"$$\" find math expressions surrounded by $$....$$
1787 \"\\(\" find math expressions surrounded by \\(...\\)
1788 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1789 :group 'org-latex
1790 :type 'plist)
1792 (defgroup org-export nil
1793 "Options for exporting org-listings."
1794 :tag "Org Export"
1795 :group 'org)
1797 (defgroup org-export-general nil
1798 "General options for exporting Org-mode files."
1799 :tag "Org Export General"
1800 :group 'org-export)
1802 (defcustom org-export-publishing-directory "."
1803 "Path to the location where exported files should be located.
1804 This path may be relative to the directory where the Org-mode file lives.
1805 The default is to put them into the same directory as the Org-mode file.
1806 The variable may also be an alist with export types `:html', `:ascii',
1807 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1808 is relative, it is interpreted relative to the directory where the exported
1809 Org-mode files lives."
1810 :group 'org-export-general
1811 :type '(choice
1812 (directory)
1813 (repeat
1814 (cons
1815 (choice :tag "Type"
1816 (const :html) (const :ascii) (const :ical) (const :xoxo))
1817 (directory)))))
1819 (defcustom org-export-language-setup
1820 '(("en" "Author" "Date" "Table of Contents")
1821 ("da" "Ophavsmand" "Dato" "Indhold")
1822 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1823 ("es" "Autor" "Fecha" "\xccndice")
1824 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1825 ("it" "Autore" "Data" "Indice")
1826 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1827 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1828 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1829 "Terms used in export text, translated to different languages.
1830 Use the variable `org-export-default-language' to set the language,
1831 or use the +OPTION lines for a per-file setting."
1832 :group 'org-export-general
1833 :type '(repeat
1834 (list
1835 (string :tag "HTML language tag")
1836 (string :tag "Author")
1837 (string :tag "Date")
1838 (string :tag "Table of Contents"))))
1840 (defcustom org-export-default-language "en"
1841 "The default language of HTML export, as a string.
1842 This should have an association in `org-export-language-setup'."
1843 :group 'org-export-general
1844 :type 'string)
1846 (defcustom org-export-headline-levels 3
1847 "The last level which is still exported as a headline.
1848 Inferior levels will produce itemize lists when exported.
1849 Note that a numeric prefix argument to an exporter function overrides
1850 this setting.
1852 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1853 :group 'org-export-general
1854 :type 'number)
1856 (defcustom org-export-with-section-numbers t
1857 "Non-nil means, add section numbers to headlines when exporting.
1859 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1860 :group 'org-export-general
1861 :type 'boolean)
1863 (defcustom org-export-with-toc t
1864 "Non-nil means, create a table of contents in exported files.
1865 The TOC contains headlines with levels up to`org-export-headline-levels'.
1867 Headlines which contain any TODO items will be marked with \"(*)\" in
1868 ASCII export, and with red color in HTML output.
1870 In HTML output, the TOC will be clickable.
1872 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1873 :group 'org-export-general
1874 :type 'boolean)
1876 (defcustom org-export-mark-todo-in-toc nil
1877 "Non-nil means, mark TOC lines that contain any open TODO items."
1878 :group 'org-export-general
1879 :type 'boolean)
1881 (defcustom org-export-preserve-breaks nil
1882 "Non-nil means, preserve all line breaks when exporting.
1883 Normally, in HTML output paragraphs will be reformatted. In ASCII
1884 export, line breaks will always be preserved, regardless of this variable.
1886 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1887 :group 'org-export-general
1888 :type 'boolean)
1890 (defcustom org-export-with-archived-trees 'headline
1891 "Whether subtrees with the ARCHIVE tag should be exported.
1892 This can have three different values
1893 nil Do not export, pretend this tree is not present
1894 t Do export the entire tree
1895 headline Only export the headline, but skip the tree below it."
1896 :group 'org-export-general
1897 :group 'org-archive
1898 :type '(choice
1899 (const :tag "not at all" nil)
1900 (const :tag "headline only" 'headline)
1901 (const :tag "entirely" t)))
1903 (defcustom org-export-with-timestamps t
1904 "Nil means, do not export time stamps and associated keywords."
1905 :group 'org-export
1906 :type 'boolean)
1908 (defcustom org-export-with-tags t
1909 "Nil means, do not export tags, just remove them from headlines."
1910 :group 'org-export-general
1911 :type 'boolean)
1913 (defcustom org-export-with-timestamps t
1914 "Nil means, do not export timestamps and associated keywords."
1915 :group 'org-export-general
1916 :type 'boolean)
1918 (defgroup org-export-translation nil
1919 "Options for translating special ascii sequences for the export backends."
1920 :tag "Org Export Translation"
1921 :group 'org-export)
1923 (defcustom org-export-with-emphasize t
1924 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1925 If the export target supports emphasizing text, the word will be
1926 typeset in bold, italic, or underlined, respectively. Works only for
1927 single words, but you can say: I *really* *mean* *this*.
1928 Not all export backends support this.
1930 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1931 :group 'org-export-translation
1932 :type 'boolean)
1934 (defcustom org-export-with-sub-superscripts t
1935 "Non-nil means, interpret \"_\" and \"^\" for export.
1936 When this option is turned on, you can use TeX-like syntax for sub- and
1937 superscripts. Several characters after \"_\" or \"^\" will be
1938 considered as a single item - so grouping with {} is normally not
1939 needed. For example, the following things will be parsed as single
1940 sub- or superscripts.
1942 10^24 or 10^tau several digits will be considered 1 item.
1943 10^-12 or 10^-tau a leading sign with digits or a word
1944 x^2-y^3 will be read as x^2 - y^3, because items are
1945 terminated by almost any nonword/nondigit char.
1946 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1948 Still, ambiguity is possible - so when in doubt use {} to enclose the
1949 sub/superscript.
1950 Not all export backends support this, but HTML does.
1952 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1953 :group 'org-export-translation
1954 :type 'boolean)
1956 (defcustom org-export-with-TeX-macros t
1957 "Non-nil means, interpret simple TeX-like macros when exporting.
1958 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1959 No only real TeX macros will work here, but the standard HTML entities
1960 for math can be used as macro names as well. For a list of supported
1961 names in HTML export, see the constant `org-html-entities'.
1962 Not all export backends support this.
1964 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1965 :group 'org-export-translation
1966 :group 'org-latex
1967 :type 'boolean)
1969 (defcustom org-export-with-LaTeX-fragments nil
1970 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
1971 When set, the exporter will find LaTeX environments if the \\begin line is
1972 the first non-white thing on a line. It will also find the math delimiters
1973 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
1974 display math.
1976 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
1977 :group 'org-export-translation
1978 :group 'org-latex
1979 :type 'boolean)
1981 (defcustom org-export-with-fixed-width t
1982 "Non-nil means, lines starting with \":\" will be in fixed width font.
1983 This can be used to have pre-formatted text, fragments of code etc. For
1984 example:
1985 : ;; Some Lisp examples
1986 : (while (defc cnt)
1987 : (ding))
1988 will be looking just like this in also HTML. See also the QUOTE keyword.
1989 Not all export backends support this.
1991 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1992 :group 'org-export-translation
1993 :type 'boolean)
1995 (defcustom org-match-sexp-depth 3
1996 "Number of stacked braces for sub/superscript matching.
1997 This has to be set before loading org.el to be effective."
1998 :group 'org-export-translation
1999 :type 'integer)
2001 (defgroup org-export-tables nil
2002 "Options for exporting tables in Org-mode."
2003 :tag "Org Export Tables"
2004 :group 'org-export)
2006 (defcustom org-export-with-tables t
2007 "If non-nil, lines starting with \"|\" define a table.
2008 For example:
2010 | Name | Address | Birthday |
2011 |-------------+----------+-----------|
2012 | Arthur Dent | England | 29.2.2100 |
2014 Not all export backends support this.
2016 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2017 :group 'org-export-tables
2018 :type 'boolean)
2020 (defcustom org-export-highlight-first-table-line t
2021 "Non-nil means, highlight the first table line.
2022 In HTML export, this means use <th> instead of <td>.
2023 In tables created with table.el, this applies to the first table line.
2024 In Org-mode tables, all lines before the first horizontal separator
2025 line will be formatted with <th> tags."
2026 :group 'org-export-tables
2027 :type 'boolean)
2029 (defcustom org-export-table-remove-special-lines t
2030 "Remove special lines and marking characters in calculating tables.
2031 This removes the special marking character column from tables that are set
2032 up for spreadsheet calculations. It also removes the entire lines
2033 marked with `!', `_', or `^'. The lines with `$' are kept, because
2034 the values of constants may be useful to have."
2035 :group 'org-export-tables
2036 :type 'boolean)
2038 (defcustom org-export-prefer-native-exporter-for-tables nil
2039 "Non-nil means, always export tables created with table.el natively.
2040 Natively means, use the HTML code generator in table.el.
2041 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2042 the table does not use row- or column-spanning). This has the
2043 advantage, that the automatic HTML conversions for math symbols and
2044 sub/superscripts can be applied. Org-mode's HTML generator is also
2045 much faster."
2046 :group 'org-export-tables
2047 :type 'boolean)
2049 (defgroup org-export-ascii nil
2050 "Options specific for ASCII export of Org-mode files."
2051 :tag "Org Export ASCII"
2052 :group 'org-export)
2054 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2055 "Characters for underlining headings in ASCII export.
2056 In the given sequence, these characters will be used for level 1, 2, ..."
2057 :group 'org-export-ascii
2058 :type '(repeat character))
2060 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2061 "Bullet characters for headlines converted to lists in ASCII export.
2062 The first character is is used for the first lest level generated in this
2063 way, and so on. If there are more levels than characters given here,
2064 the list will be repeated.
2065 Note that plain lists will keep the same bullets as the have in the
2066 Org-mode file."
2067 :group 'org-export-ascii
2068 :type '(repeat character))
2070 (defcustom org-export-ascii-show-new-buffer t
2071 "Non-nil means, popup buffer containing the exported ASCII text.
2072 Otherwise the buffer will just be saved to a file and stay hidden."
2073 :group 'org-export-ascii
2074 :type 'boolean)
2076 (defgroup org-export-xml nil
2077 "Options specific for XML export of Org-mode files."
2078 :tag "Org Export XML"
2079 :group 'org-export)
2081 (defgroup org-export-html nil
2082 "Options specific for HTML export of Org-mode files."
2083 :tag "Org Export HTML"
2084 :group 'org-export)
2086 (defcustom org-export-html-style
2087 "<style type=\"text/css\">
2088 html {
2089 font-family: Times, serif;
2090 font-size: 12pt;
2092 .title { text-align: center; }
2093 .todo { color: red; }
2094 .done { color: green; }
2095 .timestamp { color: grey }
2096 .timestamp-kwd { color: CadetBlue }
2097 .tag { background-color:lightblue; font-weight:normal }
2098 .target { background-color: lavender; }
2099 pre {
2100 border: 1pt solid #AEBDCC;
2101 background-color: #F3F5F7;
2102 padding: 5pt;
2103 font-family: courier, monospace;
2105 table { border-collapse: collapse; }
2106 td, th {
2107 vertical-align: top;
2108 border: 1pt solid #ADB9CC;
2110 </style>"
2111 "The default style specification for exported HTML files.
2112 Since there are different ways of setting style information, this variable
2113 needs to contain the full HTML structure to provide a style, including the
2114 surrounding HTML tags. The style specifications should include definitions
2115 for new classes todo, done, title, and deadline. For example, legal values
2116 would be:
2118 <style type=\"text/css\">
2119 p { font-weight: normal; color: gray; }
2120 h1 { color: black; }
2121 .title { text-align: center; }
2122 .todo, .deadline { color: red; }
2123 .done { color: green; }
2124 </style>
2126 or, if you want to keep the style in a file,
2128 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2130 As the value of this option simply gets inserted into the HTML <head> header,
2131 you can \"misuse\" it to add arbitrary text to the header."
2132 :group 'org-export-html
2133 :type 'string)
2135 (defcustom org-export-html-link-org-files-as-html t
2136 "Non-nil means, make file links to `file.org' point to `file.html'.
2137 When org-mode is exporting an org-mode file to HTML, links to
2138 non-html files are directly put into a href tag in HTML.
2139 However, links to other Org-mode files (recognized by the
2140 extension `.org.) should become links to the corresponding html
2141 file, assuming that the linked org-mode file will also be
2142 converted to HTML.
2143 When nil, the links still point to the plain `.org' file."
2144 :group 'org-export-html
2145 :type 'boolean)
2147 (defcustom org-export-html-inline-images 'maybe
2148 "Non-nil means, inline images into exported HTML pages.
2149 This is done using an <img> tag. When nil, an anchor with href is used to
2150 link to the image. If this option is `maybe', then images in links with
2151 an empty description will be inlined, while images with a description will
2152 be linked only."
2153 :group 'org-export-html
2154 :type '(choice (const :tag "Never" nil)
2155 (const :tag "Always" t)
2156 (const :tag "When there is no description" maybe)))
2158 (defcustom org-export-html-expand t
2159 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2160 When nil, these tags will be exported as plain text and therefore
2161 not be interpreted by a browser.
2163 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2164 :group 'org-export-html
2165 :type 'boolean)
2167 (defcustom org-export-html-table-tag
2168 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2169 "The HTML tag used to start a table.
2170 This must be a <table> tag, but you may change the options like
2171 borders and spacing."
2172 :group 'org-export-html
2173 :type 'string)
2175 (defcustom org-export-html-with-timestamp nil
2176 "If non-nil, write `org-export-html-html-helper-timestamp'
2177 into the exported HTML text. Otherwise, the buffer will just be saved
2178 to a file."
2179 :group 'org-export-html
2180 :type 'boolean)
2182 (defcustom org-export-html-html-helper-timestamp
2183 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2184 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2185 :group 'org-export-html
2186 :type 'string)
2188 (defcustom org-export-html-show-new-buffer nil
2189 "Non-nil means, popup buffer containing the exported html text.
2190 Otherwise, the buffer will just be saved to a file and stay hidden."
2191 :group 'org-export-html
2192 :type 'boolean)
2194 (defgroup org-export-icalendar nil
2195 "Options specific for iCalendar export of Org-mode files."
2196 :tag "Org Export iCalendar"
2197 :group 'org-export)
2199 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2200 "The file name for the iCalendar file covering all agenda files.
2201 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2202 The file name should be absolute."
2203 :group 'org-export-icalendar
2204 :type 'file)
2206 (defcustom org-icalendar-include-todo nil
2207 "Non-nil means, export to iCalendar files should also cover TODO items."
2208 :group 'org-export-icalendar
2209 :type 'boolean)
2211 (defcustom org-icalendar-combined-name "OrgMode"
2212 "Calendar name for the combined iCalendar representing all agenda files."
2213 :group 'org-export-icalendar
2214 :type 'string)
2216 (defgroup org-font-lock nil
2217 "Font-lock settings for highlighting in Org-mode."
2218 :tag "Org Font Lock"
2219 :group 'org)
2221 (defcustom org-level-color-stars-only nil
2222 "Non-nil means fontify only the stars in each headline.
2223 When nil, the entire headline is fontified.
2224 Changing it requires restart of `font-lock-mode' to become effective
2225 also in regions already fontified."
2226 :group 'org-font-lock
2227 :type 'boolean)
2229 (defcustom org-hide-leading-stars nil
2230 "Non-nil means, hide the first N-1 stars in a headline.
2231 This works by using the face `org-hide' for these stars. This
2232 face is white for a light background, and black for a dark
2233 background. You may have to customize the face `org-hide' to
2234 make this work.
2235 Changing it requires restart of `font-lock-mode' to become effective
2236 also in regions already fontified.
2237 You may also set this on a per-file basis by adding one of the following
2238 lines to the buffer:
2240 #+STARTUP: hidestars
2241 #+STARTUP: showstars"
2242 :group 'org-font-lock
2243 :type 'boolean)
2245 (defcustom org-fontify-done-headline nil
2246 "Non-nil means, change the face of a headline if it is marked DONE.
2247 Normally, only the TODO/DONE keyword indicates the state of a headline.
2248 When this is non-nil, the headline after the keyword is set to the
2249 `org-headline-done' as an additional indication."
2250 :group 'org-font-lock
2251 :type 'boolean)
2253 (defcustom org-fontify-emphasized-text t
2254 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2255 Changing this variable requires a restart of Emacs to take effect."
2256 :group 'org-font-lock
2257 :type 'boolean)
2259 (defvar org-emph-re nil
2260 "Regular expression for matching emphasis.")
2261 (defvar org-emphasis-regexp-components) ; defined just below
2262 (defvar org-emphasis-alist) ; defined just below
2263 (defun org-set-emph-re (var val)
2264 "Set variable and compute the emphasis regular expression."
2265 (set var val)
2266 (when (and (boundp 'org-emphasis-alist)
2267 (boundp 'org-emphasis-regexp-components)
2268 org-emphasis-alist org-emphasis-regexp-components)
2269 (let* ((e org-emphasis-regexp-components)
2270 (pre (car e))
2271 (post (nth 1 e))
2272 (border (nth 2 e))
2273 (body (nth 3 e))
2274 (nl (nth 4 e))
2275 (stacked (nth 5 e))
2276 (body1 (concat body "*?"))
2277 (markers (mapconcat 'car org-emphasis-alist "")))
2278 ;; make sure special characters appear at the right position in the class
2279 (if (string-match "\\^" markers)
2280 (setq markers (concat (replace-match "" t t markers) "^")))
2281 (if (string-match "-" markers)
2282 (setq markers (concat (replace-match "" t t markers) "-")))
2283 (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2284 ;; Make the regexp
2285 (setq org-emph-re
2286 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2287 "\\("
2288 "\\([" markers "]\\)"
2289 "\\("
2290 "[^" border markers "]"
2291 body1
2292 "[^" border markers "]"
2293 "\\)"
2294 "\\3\\)"
2295 "\\([" post (if stacked markers) "]\\|$\\)")))))
2297 (defcustom org-emphasis-regexp-components
2298 '(" \t(" " \t.,?;:'\")" " \t\r\n,." "." 1 nil)
2299 "Components used to build the reqular expression for emphasis.
2300 This is a list with 6 entries. Terminology: In an emphasis string
2301 like \" *strong word* \", we call the initial space PREMATCH, the final
2302 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2303 and \"trong wor\" is the body. The different components in this variable
2304 specify what is allowed/forbidden in each part:
2306 pre Chars allowed as prematch. Beginning of line will be allowed too.
2307 post Chars allowed as postmatch. End of line will be allowed too.
2308 border The chars *forbidden* as border characters. In addition to the
2309 characters given here, all marker characters are forbidden too.
2310 body-regexp A regexp like \".\" to match a body character. Don't use
2311 non-shy groups here, and don't allow newline here.
2312 newline The maximum number of newlines allowed in an emphasis exp.
2313 stacked Non-nil means, allow stacked styles. This works only in HTML
2314 export. When this is set, all marker characters (as given in
2315 `org-emphasis-alist') will be allowed as pre/post, aiding
2316 inside-out matching.
2317 Use customize to modify this, or restart emacs after changing it."
2318 :group 'org-font-lock
2319 :set 'org-set-emph-re
2320 :type '(list
2321 (sexp :tag "Allowed chars in pre ")
2322 (sexp :tag "Allowed chars in post ")
2323 (sexp :tag "Forbidden chars in border ")
2324 (sexp :tag "Regexp for body ")
2325 (integer :tag "number of newlines allowed")
2326 (boolean :tag "Stacking allowed ")))
2328 (defcustom org-emphasis-alist
2329 '(("*" bold "<b>" "</b>")
2330 ("/" italic "<i>" "</i>")
2331 ("_" underline "<u>" "</u>")
2332 ("=" shadow "<code>" "</code>")
2333 ("+" (:strike-through t) "<del>" "</del>")
2335 "Special syntax for emphasised text.
2336 Text starting and ending with a special character will be emphasized, for
2337 example *bold*, _underlined_ and /italic/. This variable sets the marker
2338 characters, the face to bbe used by font-lock for highlighting in Org-mode
2339 emacs buffers, and the HTML tags to be used for this.
2340 Use customize to modify this, or restart emacs after changing it."
2341 :group 'org-font-lock
2342 :set 'org-set-emph-re
2343 :type '(repeat
2344 (list
2345 (string :tag "Marker character")
2346 (choice
2347 (face :tag "Font-lock-face")
2348 (plist :tag "Face property list"))
2349 (string :tag "HTML start tag")
2350 (string :tag "HTML end tag"))))
2352 (defgroup org-faces nil
2353 "Faces in Org-mode."
2354 :tag "Org Faces"
2355 :group 'org-font-lock)
2357 (defun org-compatible-face (specs)
2358 "Make a compatible face specification.
2359 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2360 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2361 to the top of the list. The `min-colors' attribute will be removed from
2362 any other entries, and any resulting duplicates will be removed entirely."
2363 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2364 (let (r e a)
2365 (while (setq e (pop specs))
2366 (cond
2367 ((memq (car e) '(t default)) (push e r))
2368 ((setq a (member '(min-colors 8) (car e)))
2369 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2370 (cdr e)))))
2371 ((setq a (assq 'min-colors (car e)))
2372 (setq e (cons (delq a (car e)) (cdr e)))
2373 (or (assoc (car e) r) (push e r)))
2374 (t (or (assoc (car e) r) (push e r)))))
2375 (nreverse r))
2376 specs))
2378 (defface org-hide
2379 '((((background light)) (:foreground "white"))
2380 (((background dark)) (:foreground "black")))
2381 "Face used to hide leading stars in headlines.
2382 The forground color of this face should be equal to the background
2383 color of the frame."
2384 :group 'org-faces)
2386 (defface org-level-1 ;; font-lock-function-name-face
2387 (org-compatible-face
2388 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2389 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2390 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2391 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2392 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2393 (t (:bold t))))
2394 "Face used for level 1 headlines."
2395 :group 'org-faces)
2397 (defface org-level-2 ;; font-lock-variable-name-face
2398 (org-compatible-face
2399 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2400 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2401 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2402 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2403 (t (:bold t))))
2404 "Face used for level 2 headlines."
2405 :group 'org-faces)
2407 (defface org-level-3 ;; font-lock-keyword-face
2408 (org-compatible-face
2409 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2410 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2411 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2412 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2413 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2414 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2415 (t (:bold t))))
2416 "Face used for level 3 headlines."
2417 :group 'org-faces)
2419 (defface org-level-4 ;; font-lock-comment-face
2420 (org-compatible-face
2421 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2422 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2423 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2424 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2425 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2426 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2427 (t (:bold t))))
2428 "Face used for level 4 headlines."
2429 :group 'org-faces)
2431 (defface org-level-5 ;; font-lock-type-face
2432 (org-compatible-face
2433 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2434 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2435 (((class color) (min-colors 8)) (:foreground "green"))))
2436 "Face used for level 5 headlines."
2437 :group 'org-faces)
2439 (defface org-level-6 ;; font-lock-constant-face
2440 (org-compatible-face
2441 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2442 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2443 (((class color) (min-colors 8)) (:foreground "magenta"))))
2444 "Face used for level 6 headlines."
2445 :group 'org-faces)
2447 (defface org-level-7 ;; font-lock-builtin-face
2448 (org-compatible-face
2449 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2450 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2451 (((class color) (min-colors 8)) (:foreground "blue"))))
2452 "Face used for level 7 headlines."
2453 :group 'org-faces)
2455 (defface org-level-8 ;; font-lock-string-face
2456 (org-compatible-face
2457 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2458 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2459 (((class color) (min-colors 8)) (:foreground "green"))))
2460 "Face used for level 8 headlines."
2461 :group 'org-faces)
2463 (defface org-special-keyword ;; font-lock-string-face
2464 (org-compatible-face
2465 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2466 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2467 (t (:italic t))))
2468 "Face used for special keywords."
2469 :group 'org-faces)
2471 (defface org-warning ;; font-lock-warning-face
2472 (org-compatible-face
2473 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2474 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2475 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2476 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2477 (t (:bold t))))
2478 "Face for deadlines and TODO keywords."
2479 :group 'org-faces)
2481 (defface org-headline-done ;; font-lock-string-face
2482 (org-compatible-face
2483 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2484 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2485 (((class color) (min-colors 8) (background light)) (:bold nil))))
2486 "Face used to indicate that a headline is DONE.
2487 This face is only used if `org-fontify-done-headline' is set."
2488 :group 'org-faces)
2490 (defface org-archived ; similar to shadow
2491 (org-compatible-face
2492 '((((class color grayscale) (min-colors 88) (background light))
2493 (:foreground "grey50"))
2494 (((class color grayscale) (min-colors 88) (background dark))
2495 (:foreground "grey70"))
2496 (((class color) (min-colors 8) (background light))
2497 (:foreground "green"))
2498 (((class color) (min-colors 8) (background dark))
2499 (:foreground "yellow"))))
2500 "Face for headline with the ARCHIVE tag."
2501 :group 'org-faces)
2503 (defface org-link
2504 '((((class color) (background light)) (:foreground "Purple" :underline t))
2505 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2506 (t (:underline t)))
2507 "Face for links."
2508 :group 'org-faces)
2510 (defface org-date
2511 '((((class color) (background light)) (:foreground "Purple" :underline t))
2512 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2513 (t (:underline t)))
2514 "Face for links."
2515 :group 'org-faces)
2517 (defface org-tag
2518 '((t (:bold t)))
2519 "Face for tags."
2520 :group 'org-faces)
2522 (defface org-todo ;; font-lock-warning-face
2523 (org-compatible-face
2524 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2525 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2526 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2527 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2528 (t (:inverse-video t :bold t))))
2529 "Face for TODO keywords."
2530 :group 'org-faces)
2532 (defface org-done ;; font-lock-type-face
2533 (org-compatible-face
2534 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2535 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2536 (((class color) (min-colors 8)) (:foreground "green"))
2537 (t (:bold t))))
2538 "Face used for DONE."
2539 :group 'org-faces)
2541 (defface org-table ;; font-lock-function-name-face
2542 (org-compatible-face
2543 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2544 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2545 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2546 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2547 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2548 (((class color) (min-colors 8) (background dark)))))
2549 "Face used for tables."
2550 :group 'org-faces)
2552 (defface org-formula
2553 (org-compatible-face
2554 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2555 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2556 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2557 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2558 (t (:bold t :italic t))))
2559 "Face for formulas."
2560 :group 'org-faces)
2562 (defface org-scheduled-today
2563 (org-compatible-face
2564 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2565 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2566 (((class color) (min-colors 8)) (:foreground "green"))
2567 (t (:bold t :italic t))))
2568 "Face for items scheduled for a certain day."
2569 :group 'org-faces)
2571 (defface org-scheduled-previously
2572 (org-compatible-face
2573 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2574 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2575 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2576 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2577 (t (:bold t))))
2578 "Face for items scheduled previously, and not yet done."
2579 :group 'org-faces)
2581 (defface org-upcoming-deadline
2582 (org-compatible-face
2583 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2584 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2585 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2586 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2587 (t (:bold t))))
2588 "Face for items scheduled previously, and not yet done."
2589 :group 'org-faces)
2591 (defface org-time-grid ;; font-lock-variable-name-face
2592 (org-compatible-face
2593 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2594 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2595 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2596 "Face used for time grids."
2597 :group 'org-faces)
2599 (defconst org-level-faces
2600 '(org-level-1 org-level-2 org-level-3 org-level-4
2601 org-level-5 org-level-6 org-level-7 org-level-8
2603 (defconst org-n-levels (length org-level-faces))
2606 ;; Variables for pre-computed regular expressions, all buffer local
2607 (defvar org-done-string nil
2608 "The last string in `org-todo-keywords', indicating an item is DONE.")
2609 (make-variable-buffer-local 'org-done-string)
2610 (defvar org-todo-regexp nil
2611 "Matches any of the TODO state keywords.")
2612 (make-variable-buffer-local 'org-todo-regexp)
2613 (defvar org-not-done-regexp nil
2614 "Matches any of the TODO state keywords except the last one.")
2615 (make-variable-buffer-local 'org-not-done-regexp)
2616 (defvar org-todo-line-regexp nil
2617 "Matches a headline and puts TODO state into group 2 if present.")
2618 (make-variable-buffer-local 'org-todo-line-regexp)
2619 (defvar org-todo-line-tags-regexp nil
2620 "Matches a headline and puts TODO state into group 2 if present.
2621 Also put tags into group 4 if tags are present.")
2622 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2623 (defvar org-nl-done-regexp nil
2624 "Matches newline followed by a headline with the DONE keyword.")
2625 (make-variable-buffer-local 'org-nl-done-regexp)
2626 (defvar org-looking-at-done-regexp nil
2627 "Matches the DONE keyword a point.")
2628 (make-variable-buffer-local 'org-looking-at-done-regexp)
2629 (defvar org-todo-kwd-priority-p nil
2630 "Do TODO items have priorities?")
2631 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2632 (defvar org-todo-kwd-max-priority nil
2633 "Maximum priority of TODO items.")
2634 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2635 (defvar org-ds-keyword-length 12
2636 "Maximum length of the Deadline and SCHEDULED keywords.")
2637 (make-variable-buffer-local 'org-ds-keyword-length)
2638 (defvar org-deadline-regexp nil
2639 "Matches the DEADLINE keyword.")
2640 (make-variable-buffer-local 'org-deadline-regexp)
2641 (defvar org-deadline-time-regexp nil
2642 "Matches the DEADLINE keyword together with a time stamp.")
2643 (make-variable-buffer-local 'org-deadline-time-regexp)
2644 (defvar org-deadline-line-regexp nil
2645 "Matches the DEADLINE keyword and the rest of the line.")
2646 (make-variable-buffer-local 'org-deadline-line-regexp)
2647 (defvar org-scheduled-regexp nil
2648 "Matches the SCHEDULED keyword.")
2649 (make-variable-buffer-local 'org-scheduled-regexp)
2650 (defvar org-scheduled-time-regexp nil
2651 "Matches the SCHEDULED keyword together with a time stamp.")
2652 (make-variable-buffer-local 'org-scheduled-time-regexp)
2653 (defvar org-closed-time-regexp nil
2654 "Matches the CLOSED keyword together with a time stamp.")
2655 (make-variable-buffer-local 'org-closed-time-regexp)
2657 (defvar org-keyword-time-regexp nil
2658 "Matches any of the 3 keywords, together with the time stamp.")
2659 (make-variable-buffer-local 'org-keyword-time-regexp)
2660 (defvar org-maybe-keyword-time-regexp nil
2661 "Matches a timestamp, possibly preceeded by a keyword.")
2662 (make-variable-buffer-local 'org-keyword-time-regexp)
2664 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2665 mouse-map t)
2666 "Properties to remove when a string without properties is wanted.")
2668 (defsubst org-match-string-no-properties (num &optional string)
2669 (if (featurep 'xemacs)
2670 (let ((s (match-string num string)))
2671 (remove-text-properties 0 (length s) org-rm-props s)
2673 (match-string-no-properties num string)))
2675 (defsubst org-no-properties (s)
2676 (remove-text-properties 0 (length s) org-rm-props s)
2679 (defun org-set-regexps-and-options ()
2680 "Precompute regular expressions for current buffer."
2681 (when (eq major-mode 'org-mode)
2682 (let ((re (org-make-options-regexp
2683 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2684 "STARTUP" "ARCHIVE" "TAGS")))
2685 (splitre "[ \t]+")
2686 kwds int key value cat arch tags)
2687 (save-excursion
2688 (save-restriction
2689 (widen)
2690 (goto-char (point-min))
2691 (while (re-search-forward re nil t)
2692 (setq key (match-string 1) value (org-match-string-no-properties 2))
2693 (cond
2694 ((equal key "CATEGORY")
2695 (if (string-match "[ \t]+$" value)
2696 (setq value (replace-match "" t t value)))
2697 (setq cat (intern value)))
2698 ((equal key "SEQ_TODO")
2699 (setq int 'sequence
2700 kwds (append kwds (org-split-string value splitre))))
2701 ((equal key "PRI_TODO")
2702 (setq int 'priority
2703 kwds (append kwds (org-split-string value splitre))))
2704 ((equal key "TYP_TODO")
2705 (setq int 'type
2706 kwds (append kwds (org-split-string value splitre))))
2707 ((equal key "TAGS")
2708 (setq tags (append tags (org-split-string value splitre))))
2709 ((equal key "STARTUP")
2710 (let ((opts (org-split-string value splitre))
2711 (set '(("fold" org-startup-folded t)
2712 ("overview" org-startup-folded t)
2713 ("nofold" org-startup-folded nil)
2714 ("showall" org-startup-folded nil)
2715 ("content" org-startup-folded content)
2716 ("hidestars" org-hide-leading-stars t)
2717 ("showstars" org-hide-leading-stars nil)
2718 ("odd" org-odd-levels-only t)
2719 ("oddeven" org-odd-levels-only nil)
2720 ("align" org-startup-align-all-tables t)
2721 ("noalign" org-startup-align-all-tables nil)
2722 ("logging" org-log-done t)
2723 ("nologging" org-log-done nil)
2724 ("dlcheck" org-startup-with-deadline-check t)
2725 ("nodlcheck" org-startup-with-deadline-check nil)))
2726 l var val)
2727 (while (setq l (assoc (pop opts) set))
2728 (setq var (nth 1 l) val (nth 2 l))
2729 (set (make-local-variable var) val))))
2730 ((equal key "ARCHIVE")
2731 (string-match " *$" value)
2732 (setq arch (replace-match "" t t value))
2733 (remove-text-properties 0 (length arch)
2734 '(face t fontified t) arch)))
2736 (and cat (set (make-local-variable 'org-category) cat))
2737 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2738 (and arch (set (make-local-variable 'org-archive-location) arch))
2739 (and int (set (make-local-variable 'org-todo-interpretation) int))
2740 (when tags
2741 (let (e tgs)
2742 (while (setq e (pop tags))
2743 (cond
2744 ((equal e "{") (push '(:startgroup) tgs))
2745 ((equal e "}") (push '(:endgroup) tgs))
2746 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2747 (push (cons (match-string 1 e)
2748 (string-to-char (match-string 2 e)))
2749 tgs))
2750 (t (push (list e) tgs))))
2751 (set (make-local-variable 'org-tag-alist) nil)
2752 (while (setq e (pop tgs))
2753 (or (and (stringp (car e))
2754 (assoc (car e) org-tag-alist))
2755 (push e org-tag-alist))))))
2757 ;; Compute the regular expressions and other local variables
2758 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2759 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2760 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2761 (length org-scheduled-string)))
2762 org-done-string
2763 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2764 org-todo-regexp
2765 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2766 "\\|") "\\)\\>")
2767 org-not-done-regexp
2768 (concat "\\<\\("
2769 (mapconcat 'regexp-quote
2770 (nreverse (cdr (reverse org-todo-keywords)))
2771 "\\|")
2772 "\\)\\>")
2773 org-todo-line-regexp
2774 (concat "^\\(\\*+\\)[ \t]*\\("
2775 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2776 "\\)? *\\(.*\\)")
2777 org-nl-done-regexp
2778 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2779 org-todo-line-tags-regexp
2780 (concat "^\\(\\*+\\)[ \t]*\\("
2781 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2782 "\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
2783 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2784 org-deadline-regexp (concat "\\<" org-deadline-string)
2785 org-deadline-time-regexp
2786 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2787 org-deadline-line-regexp
2788 (concat "\\<\\(" org-deadline-string "\\).*")
2789 org-scheduled-regexp
2790 (concat "\\<" org-scheduled-string)
2791 org-scheduled-time-regexp
2792 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2793 org-closed-time-regexp
2794 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2795 org-keyword-time-regexp
2796 (concat "\\<\\(" org-scheduled-string
2797 "\\|" org-deadline-string
2798 "\\|" org-closed-string
2799 "\\|" org-clock-string "\\)"
2800 " *[[<]\\([^]>]+\\)[]>]")
2801 org-maybe-keyword-time-regexp
2802 (concat "\\(\\<\\(" org-scheduled-string
2803 "\\|" org-deadline-string
2804 "\\|" org-closed-string
2805 "\\|" org-clock-string "\\)\\)?"
2806 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
2808 (org-set-font-lock-defaults)))
2810 ;; Tell the compiler about dynamically scoped variables,
2811 ;; and variables from other packages
2812 (defvar calc-embedded-close-formula) ; defined by the calc package
2813 (defvar calc-embedded-open-formula) ; defined by the calc package
2814 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
2815 (defvar zmacs-regions) ; XEmacs regions
2816 (defvar original-date) ; dynamically scoped in calendar
2817 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2818 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2819 (defvar org-html-entities) ; defined later in this file
2820 (defvar org-goto-start-pos) ; dynamically scoped parameter
2821 (defvar org-time-was-given) ; dynamically scoped parameter
2822 (defvar org-ts-what) ; dynamically scoped parameter
2823 (defvar org-current-export-file) ; dynamically scoped parameter
2824 (defvar org-current-export-dir) ; dynamically scoped parameter
2825 (defvar mark-active) ; Emacs only, not available in XEmacs.
2826 (defvar timecnt) ; dynamically scoped parameter
2827 (defvar levels-open) ; dynamically scoped parameter
2828 (defvar entry) ; dynamically scoped parameter
2829 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
2830 (defvar date) ; dynamically scoped parameter
2831 (defvar description) ; dynamically scoped parameter
2832 (defvar ans1) ; dynamically scoped parameter
2833 (defvar ans2) ; dynamically scoped parameter
2834 (defvar starting-day) ; local variable
2835 (defvar include-all-loc) ; local variable
2836 (defvar vm-message-pointer) ; from vm
2837 (defvar vm-folder-directory) ; from vm
2838 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2839 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2840 (defvar gnus-group-name) ; from gnus
2841 (defvar gnus-article-current) ; from gnus
2842 (defvar w3m-current-url) ; from w3m
2843 (defvar w3m-current-title) ; from w3m
2844 (defvar mh-progs) ; from MH-E
2845 (defvar mh-current-folder) ; from MH-E
2846 (defvar mh-show-folder-buffer) ; from MH-E
2847 (defvar mh-index-folder) ; from MH-E
2848 (defvar mh-searcher) ; from MH-E
2849 (defvar org-selected-point) ; dynamically scoped parameter
2850 (defvar calendar-mode-map) ; from calendar.el
2851 (defvar last-arg) ; local variable
2852 (defvar remember-save-after-remembering) ; from remember.el
2853 (defvar remember-data-file) ; from remember.el
2854 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2855 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2856 (defvar orgtbl-mode) ; defined later in this file
2857 (defvar Info-current-file) ; from info.el
2858 (defvar Info-current-node) ; from info.el
2859 (defvar texmathp-why) ; from texmathp.el
2860 (defvar org-latex-regexps)
2862 ;;; Define the mode
2864 (defvar org-mode-map
2865 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2866 (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.")
2867 (copy-keymap outline-mode-map))
2868 "Keymap for Org-mode.")
2870 (defvar org-struct-menu) ; defined later in this file
2871 (defvar org-org-menu) ; defined later in this file
2872 (defvar org-tbl-menu) ; defined later in this file
2874 ;; We use a before-change function to check if a table might need
2875 ;; an update.
2876 (defvar org-table-may-need-update t
2877 "Indicates that a table might need an update.
2878 This variable is set by `org-before-change-function'.
2879 `org-table-align' sets it back to nil.")
2880 (defvar org-mode-hook nil)
2881 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2882 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2885 ;;;###autoload
2886 (define-derived-mode org-mode outline-mode "Org"
2887 "Outline-based notes management and organizer, alias
2888 \"Carsten's outline-mode for keeping track of everything.\"
2890 Org-mode develops organizational tasks around a NOTES file which
2891 contains information about projects as plain text. Org-mode is
2892 implemented on top of outline-mode, which is ideal to keep the content
2893 of large files well structured. It supports ToDo items, deadlines and
2894 time stamps, which magically appear in the diary listing of the Emacs
2895 calendar. Tables are easily created with a built-in table editor.
2896 Plain text URL-like links connect to websites, emails (VM), Usenet
2897 messages (Gnus), BBDB entries, and any files related to the project.
2898 For printing and sharing of notes, an Org-mode file (or a part of it)
2899 can be exported as a structured ASCII or HTML file.
2901 The following commands are available:
2903 \\{org-mode-map}"
2905 ;; Get rid of Outline menus, they are not needed
2906 ;; Need to do this here because define-derived-mode sets up
2907 ;; the keymap so late.
2908 (if (featurep 'xemacs)
2909 (if org-noutline-p
2910 (progn
2911 (easy-menu-remove outline-mode-menu-heading)
2912 (easy-menu-remove outline-mode-menu-show)
2913 (easy-menu-remove outline-mode-menu-hide))
2914 (delete-menu-item '("Headings"))
2915 (delete-menu-item '("Show"))
2916 (delete-menu-item '("Hide"))
2917 (set-menubar-dirty-flag))
2918 (define-key org-mode-map [menu-bar headings] 'undefined)
2919 (define-key org-mode-map [menu-bar hide] 'undefined)
2920 (define-key org-mode-map [menu-bar show] 'undefined))
2922 (easy-menu-add org-org-menu)
2923 (easy-menu-add org-tbl-menu)
2924 (org-install-agenda-files-menu)
2925 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2926 (org-add-to-invisibility-spec '(org-cwidth))
2927 (when (featurep 'xemacs)
2928 (set (make-local-variable 'line-move-ignore-invisible) t))
2929 (setq outline-regexp "\\*+")
2930 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2931 (setq outline-level 'org-outline-level)
2932 (when (and org-ellipsis (stringp org-ellipsis))
2933 (unless org-display-table
2934 (setq org-display-table (make-display-table)))
2935 (set-display-table-slot org-display-table
2936 4 (string-to-vector org-ellipsis))
2937 (setq buffer-display-table org-display-table))
2938 (org-set-regexps-and-options)
2939 (modify-syntax-entry ?# "<")
2940 (if org-startup-truncated (setq truncate-lines t))
2941 (set (make-local-variable 'font-lock-unfontify-region-function)
2942 'org-unfontify-region)
2943 ;; Activate before-change-function
2944 (set (make-local-variable 'org-table-may-need-update) t)
2945 (org-add-hook 'before-change-functions 'org-before-change-function nil
2946 'local)
2947 ;; Check for running clock before killing a buffer
2948 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
2949 ;; Paragraphs and auto-filling
2950 (org-set-autofill-regexps)
2951 (org-update-radio-target-regexp)
2952 ;; Settings for Calc embedded mode
2953 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2954 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2955 (if (and org-insert-mode-line-in-empty-file
2956 (interactive-p)
2957 (= (point-min) (point-max)))
2958 (insert " -*- mode: org -*-\n\n"))
2960 (unless org-inhibit-startup
2961 (when org-startup-align-all-tables
2962 (let ((bmp (buffer-modified-p)))
2963 (org-table-map-tables 'org-table-align)
2964 (set-buffer-modified-p bmp)))
2965 (if org-startup-with-deadline-check
2966 (call-interactively 'org-check-deadlines)
2967 (cond
2968 ((eq org-startup-folded t)
2969 (org-cycle '(4)))
2970 ((eq org-startup-folded 'content)
2971 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2972 (org-cycle '(4)) (org-cycle '(4))))))))
2974 (defsubst org-call-with-arg (command arg)
2975 "Call COMMAND interactively, but pretend prefix are was ARG."
2976 (let ((current-prefix-arg arg)) (call-interactively command)))
2978 (defsubst org-current-line (&optional pos)
2979 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2981 (defun org-current-time ()
2982 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2983 (if (> org-time-stamp-rounding-minutes 0)
2984 (let ((r org-time-stamp-rounding-minutes)
2985 (time (decode-time)))
2986 (apply 'encode-time
2987 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2988 (nthcdr 2 time))))
2989 (current-time)))
2991 (defun org-add-props (string plist &rest props)
2992 "Add text properties to entire string, from beginning to end.
2993 PLIST may be a list of properties, PROPS are individual properties and values
2994 that will be added to PLIST. Returns the string that was modified."
2995 (add-text-properties
2996 0 (length string) (if props (append plist props) plist) string)
2997 string)
2998 (put 'org-add-props 'lisp-indent-function 2)
3001 ;;; Font-Lock stuff
3003 (defvar org-mouse-map (make-sparse-keymap))
3004 (define-key org-mouse-map
3005 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3006 (define-key org-mouse-map
3007 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3008 (when org-mouse-1-follows-link
3009 (define-key org-mouse-map [follow-link] 'mouse-face))
3010 (when org-tab-follows-link
3011 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3012 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3013 (when org-return-follows-link
3014 (define-key org-mouse-map [(return)] 'org-open-at-point)
3015 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3017 (require 'font-lock)
3019 (defconst org-non-link-chars "]\t\n\r<>")
3020 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3021 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3022 (defconst org-link-re-with-space
3023 (concat
3024 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3025 "\\([^" org-non-link-chars " ]"
3026 "[^" org-non-link-chars "]*"
3027 "[^" org-non-link-chars " ]\\)>?")
3028 "Matches a link with spaces, optional angular brackets around it.")
3030 (defconst org-link-re-with-space2
3031 (concat
3032 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3033 "\\([^" org-non-link-chars " ]"
3034 "[^]\t\n\r]*"
3035 "[^" org-non-link-chars " ]\\)>?")
3036 "Matches a link with spaces, optional angular brackets around it.")
3038 (defconst org-angle-link-re
3039 (concat
3040 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3041 "\\([^" org-non-link-chars " ]"
3042 "[^" org-non-link-chars "]*"
3043 "\\)>")
3044 "Matches link with angular brackets, spaces are allowed.")
3045 (defconst org-plain-link-re
3046 (concat
3047 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3048 "\\([^]\t\n\r<>,;() ]+\\)")
3049 "Matches plain link, without spaces.")
3051 (defconst org-bracket-link-regexp
3052 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3053 "Matches a link in double brackets.")
3055 (defconst org-bracket-link-analytic-regexp
3056 (concat
3057 "\\[\\["
3058 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3059 "\\([^]]+\\)"
3060 "\\]"
3061 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3062 "\\]"))
3063 ; 1: http:
3064 ; 2: http
3065 ; 3: path
3066 ; 4: [desc]
3067 ; 5: desc
3070 (defconst org-ts-lengths
3071 (cons (length (format-time-string (car org-time-stamp-formats)))
3072 (length (format-time-string (cdr org-time-stamp-formats))))
3073 "This holds the lengths of the two different time formats.")
3074 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3075 "Regular expression for fast time stamp matching.")
3076 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3077 "Regular expression for fast time stamp matching.")
3078 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3079 "Regular expression matching time strings for analysis.")
3080 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3081 "Regular expression matching time stamps, with groups.")
3082 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3083 "Regular expression matching a time stamp range.")
3084 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3085 org-ts-regexp "\\)?")
3086 "Regular expression matching a time stamp or time stamp range.")
3088 (defvar org-§emph-face nil)
3090 (defun org-do-emphasis-faces (limit)
3091 "Run through the buffer and add overlays to links."
3092 (if (re-search-forward org-emph-re limit t)
3093 (progn
3094 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3095 'face
3096 (nth 1 (assoc (match-string 3)
3097 org-emphasis-alist)))
3098 (add-text-properties (match-beginning 2) (match-end 2)
3099 '(font-lock-multiline t))
3100 (backward-char 1)
3101 t)))
3103 (defun org-activate-plain-links (limit)
3104 "Run through the buffer and add overlays to links."
3105 (if (re-search-forward org-plain-link-re limit t)
3106 (progn
3107 (add-text-properties (match-beginning 0) (match-end 0)
3108 (list 'mouse-face 'highlight
3109 'keymap org-mouse-map
3111 t)))
3113 (defun org-activate-angle-links (limit)
3114 "Run through the buffer and add overlays to links."
3115 (if (re-search-forward org-angle-link-re limit t)
3116 (progn
3117 (add-text-properties (match-beginning 0) (match-end 0)
3118 (list 'mouse-face 'highlight
3119 'keymap org-mouse-map
3121 t)))
3123 (defun org-activate-bracket-links (limit)
3124 "Run through the buffer and add overlays to bracketed links."
3125 (if (re-search-forward org-bracket-link-regexp limit t)
3126 (let* ((help (concat "LINK: "
3127 (org-match-string-no-properties 1)))
3128 ;; FIXME: above we should remove the escapes.
3129 ;; but that requires another match, protecting match data,
3130 ;; a lot of overhead for font-lock.
3131 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
3132 'keymap org-mouse-map 'mouse-face 'highlight
3133 'help-echo help))
3134 (vp (list 'rear-nonsticky t
3135 'keymap org-mouse-map 'mouse-face 'highlight
3136 'help-echo help)))
3137 ;; We need to remove the invisible property here. Table narrowing
3138 ;; may have made some of this invisible.
3139 (remove-text-properties (match-beginning 0) (match-end 0)
3140 '(invisible nil))
3141 (if (match-end 3)
3142 (progn
3143 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3144 (add-text-properties (match-beginning 3) (match-end 3) vp)
3145 (add-text-properties (match-end 3) (match-end 0) ip))
3146 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3147 (add-text-properties (match-beginning 1) (match-end 1) vp)
3148 (add-text-properties (match-end 1) (match-end 0) ip))
3149 t)))
3151 (defun org-activate-dates (limit)
3152 "Run through the buffer and add overlays to dates."
3153 (if (re-search-forward org-tsr-regexp limit t)
3154 (progn
3155 (add-text-properties (match-beginning 0) (match-end 0)
3156 (list 'mouse-face 'highlight
3157 'keymap org-mouse-map))
3158 t)))
3160 (defvar org-target-link-regexp nil
3161 "Regular expression matching radio targets in plain text.")
3162 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3163 "Regular expression matching a link target.")
3164 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3165 "Regular expression matching a link target.")
3167 (defun org-activate-target-links (limit)
3168 "Run through the buffer and add overlays to target matches."
3169 (when org-target-link-regexp
3170 (let ((case-fold-search t))
3171 (if (re-search-forward org-target-link-regexp limit t)
3172 (progn
3173 (add-text-properties (match-beginning 0) (match-end 0)
3174 (list 'mouse-face 'highlight
3175 'keymap org-mouse-map
3176 'help-echo "Radio target link"
3177 'org-linked-text t))
3178 t)))))
3180 (defun org-update-radio-target-regexp ()
3181 "Find all radio targets in this file and update the regular expression."
3182 (interactive)
3183 (when (memq 'radio org-activate-links)
3184 (setq org-target-link-regexp
3185 (org-make-target-link-regexp (org-all-targets 'radio)))
3186 (org-restart-font-lock)))
3188 (defun org-hide-wide-columns (limit)
3189 (let (s e)
3190 (setq s (text-property-any (point) (or limit (point-max))
3191 'org-cwidth t))
3192 (when s
3193 (setq e (next-single-property-change s 'org-cwidth))
3194 (add-text-properties s e '(invisible org-cwidth intangible t))
3195 (goto-char e)
3196 t)))
3198 (defun org-restart-font-lock ()
3199 "Restart font-lock-mode, to force refontification."
3200 (when (and (boundp 'font-lock-mode) font-lock-mode)
3201 (font-lock-mode -1)
3202 (font-lock-mode 1)))
3204 (defun org-all-targets (&optional radio)
3205 "Return a list of all targets in this file.
3206 With optional argument RADIO, only find radio targets."
3207 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3208 rtn)
3209 (save-excursion
3210 (goto-char (point-min))
3211 (while (re-search-forward re nil t)
3212 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3213 rtn)))
3215 (defun org-make-target-link-regexp (targets)
3216 "Make regular expression matching all strings in TARGETS.
3217 The regular expression finds the targets also if there is a line break
3218 between words."
3219 (and targets
3220 (concat
3221 "\\<\\("
3222 (mapconcat
3223 (lambda (x)
3224 (while (string-match " +" x)
3225 (setq x (replace-match "\\s-+" t t x)))
3227 targets
3228 "\\|")
3229 "\\)\\>")))
3231 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3232 "Matches CamelCase words, possibly with a star before it.")
3234 (defun org-activate-camels (limit)
3235 "Run through the buffer and add overlays to dates."
3236 (if (re-search-forward org-camel-regexp limit t)
3237 (progn
3238 (add-text-properties (match-beginning 0) (match-end 0)
3239 (list 'mouse-face 'highlight
3240 'keymap org-mouse-map))
3241 t)))
3243 (defun org-activate-tags (limit)
3244 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3245 (progn
3246 (add-text-properties (match-beginning 1) (match-end 1)
3247 (list 'mouse-face 'highlight
3248 'keymap org-mouse-map))
3249 t)))
3251 (defun org-font-lock-level ()
3252 (save-excursion
3253 (org-back-to-heading t)
3254 (- (match-end 0) (match-beginning 0))))
3256 (defun org-outline-level ()
3257 (save-excursion
3258 (looking-at outline-regexp)
3259 (if (match-beginning 1)
3260 (+ (org-get-string-indentation (match-string 1)) 1000)
3261 (- (match-end 0) (match-beginning 0)))))
3263 (defvar org-font-lock-keywords nil)
3265 (defun org-set-font-lock-defaults ()
3266 (let* ((em org-fontify-emphasized-text)
3267 (lk org-activate-links)
3268 (org-font-lock-extra-keywords
3269 ;; Headlines
3270 (list
3271 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3272 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3273 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3274 (1 'org-table))
3275 ;; Links
3276 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3277 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3278 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3279 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3280 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3281 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3282 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3283 (if org-table-limit-column-width
3284 '(org-hide-wide-columns (0 nil append)))
3285 ;; TODO lines
3286 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3287 '(1 'org-todo t))
3288 ;; Priorities
3289 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3290 ;; Special keywords
3291 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3292 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3293 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3294 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3295 ;; Emphasis
3296 (if em '(org-do-emphasis-faces))
3297 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3298 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3299 2 'bold prepend)
3300 ;; COMMENT
3301 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3302 "\\|" org-quote-string "\\)\\>")
3303 '(1 'org-special-keyword t))
3304 '("^#.*" (0 'font-lock-comment-face t))
3305 ;; DONE
3306 (if org-fontify-done-headline
3307 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3308 '(1 'org-done t) '(2 'org-headline-done t))
3309 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3310 '(1 'org-done t)))
3311 ;; Table stuff
3312 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3313 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3314 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3315 (if org-format-transports-properties-p
3316 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3317 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3319 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3320 ;; Now set the full font-lock-keywords
3321 (set (make-local-variable 'org-font-lock-keywords)
3322 org-font-lock-extra-keywords)
3323 (set (make-local-variable 'font-lock-defaults)
3324 '(org-font-lock-keywords t nil nil backward-paragraph))
3325 (kill-local-variable 'font-lock-keywords) nil))
3327 (defvar org-m nil)
3328 (defvar org-l nil)
3329 (defvar org-f nil)
3330 (defun org-get-level-face (n)
3331 "Get the right face for match N in font-lock matching of healdines."
3332 (setq org-l (- (match-end 2) (match-beginning 1)))
3333 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3334 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3335 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3336 (cond
3337 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3338 ((eq n 2) org-f)
3339 (t (if org-level-color-stars-only nil org-f))))
3341 (defun org-unfontify-region (beg end &optional maybe_loudly)
3342 "Remove fontification and activation overlays from links."
3343 (font-lock-default-unfontify-region beg end)
3344 (let* ((buffer-undo-list t)
3345 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3346 (inhibit-modification-hooks t)
3347 deactivate-mark buffer-file-name buffer-file-truename)
3348 (remove-text-properties beg end
3349 '(mouse-face nil keymap nil org-linked-text nil
3350 invisible nil intangible nil))))
3351 ;;; Visibility cycling
3353 (defvar org-cycle-global-status nil)
3354 (make-variable-buffer-local 'org-cycle-global-status)
3355 (defvar org-cycle-subtree-status nil)
3356 (make-variable-buffer-local 'org-cycle-subtree-status)
3358 ;;;###autoload
3359 (defun org-cycle (&optional arg)
3360 "Visibility cycling for Org-mode.
3362 - When this function is called with a prefix argument, rotate the entire
3363 buffer through 3 states (global cycling)
3364 1. OVERVIEW: Show only top-level headlines.
3365 2. CONTENTS: Show all headlines of all levels, but no body text.
3366 3. SHOW ALL: Show everything.
3368 - When point is at the beginning of a headline, rotate the subtree started
3369 by this line through 3 different states (local cycling)
3370 1. FOLDED: Only the main headline is shown.
3371 2. CHILDREN: The main headline and the direct children are shown.
3372 From this state, you can move to one of the children
3373 and zoom in further.
3374 3. SUBTREE: Show the entire subtree, including body text.
3376 - When there is a numeric prefix, go up to a heading with level ARG, do
3377 a `show-subtree' and return to the previous cursor position. If ARG
3378 is negative, go up that many levels.
3380 - When point is not at the beginning of a headline, execute
3381 `indent-relative', like TAB normally does. See the option
3382 `org-cycle-emulate-tab' for details.
3384 - Special case: if point is the the beginning of the buffer and there is
3385 no headline in line 1, this function will act as if called with prefix arg."
3386 (interactive "P")
3388 (let* ((outline-regexp
3389 (if org-cycle-include-plain-lists
3390 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
3391 outline-regexp))
3392 (bob-special (and org-cycle-global-at-bob (bobp)
3393 (not (looking-at outline-regexp))))
3394 (org-cycle-hook
3395 (if bob-special
3396 (delq 'org-optimize-window-after-visibility-change
3397 (copy-sequence org-cycle-hook))
3398 org-cycle-hook))
3399 (pos (point)))
3401 (if (or bob-special (equal arg '(4)))
3402 ;; special case: use global cycling
3403 (setq arg t))
3405 (cond
3407 ((org-at-table-p 'any)
3408 ;; Enter the table or move to the next field in the table
3409 (or (org-table-recognize-table.el)
3410 (progn
3411 (if arg (org-table-edit-field t)
3412 (org-table-justify-field-maybe)
3413 (call-interactively 'org-table-next-field)))))
3415 ((eq arg t) ;; Global cycling
3417 (cond
3418 ((and (eq last-command this-command)
3419 (eq org-cycle-global-status 'overview))
3420 ;; We just created the overview - now do table of contents
3421 ;; This can be slow in very large buffers, so indicate action
3422 (message "CONTENTS...")
3423 (org-content)
3424 (message "CONTENTS...done")
3425 (setq org-cycle-global-status 'contents)
3426 (run-hook-with-args 'org-cycle-hook 'contents))
3428 ((and (eq last-command this-command)
3429 (eq org-cycle-global-status 'contents))
3430 ;; We just showed the table of contents - now show everything
3431 (show-all)
3432 (message "SHOW ALL")
3433 (setq org-cycle-global-status 'all)
3434 (run-hook-with-args 'org-cycle-hook 'all))
3437 ;; Default action: go to overview
3438 (org-overview)
3439 (message "OVERVIEW")
3440 (setq org-cycle-global-status 'overview)
3441 (run-hook-with-args 'org-cycle-hook 'overview))))
3443 ((integerp arg)
3444 ;; Show-subtree, ARG levels up from here.
3445 (save-excursion
3446 (org-back-to-heading)
3447 (outline-up-heading (if (< arg 0) (- arg)
3448 (- (funcall outline-level) arg)))
3449 (org-show-subtree)))
3451 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3452 ;; At a heading: rotate between three different views
3453 (org-back-to-heading)
3454 (let ((goal-column 0) eoh eol eos)
3455 ;; First, some boundaries
3456 (save-excursion
3457 (org-back-to-heading)
3458 (save-excursion
3459 (beginning-of-line 2)
3460 (while (and (not (eobp)) ;; this is like `next-line'
3461 (get-char-property (1- (point)) 'invisible))
3462 (beginning-of-line 2)) (setq eol (point)))
3463 (outline-end-of-heading) (setq eoh (point))
3464 (org-end-of-subtree t) (setq eos (point))
3465 (outline-next-heading))
3466 ;; Find out what to do next and set `this-command'
3467 (cond
3468 ((and (= eos eoh)
3469 ;; Nothing is hidden behind this heading
3470 (message "EMPTY ENTRY")
3471 (setq org-cycle-subtree-status nil)))
3472 ((>= eol eos)
3473 ;; Entire subtree is hidden in one line: open it
3474 (org-show-entry)
3475 (show-children)
3476 (message "CHILDREN")
3477 (setq org-cycle-subtree-status 'children)
3478 (run-hook-with-args 'org-cycle-hook 'children))
3479 ((and (eq last-command this-command)
3480 (eq org-cycle-subtree-status 'children))
3481 ;; We just showed the children, now show everything.
3482 (org-show-subtree)
3483 (message "SUBTREE")
3484 (setq org-cycle-subtree-status 'subtree)
3485 (run-hook-with-args 'org-cycle-hook 'subtree))
3487 ;; Default action: hide the subtree.
3488 (hide-subtree)
3489 (message "FOLDED")
3490 (setq org-cycle-subtree-status 'folded)
3491 (run-hook-with-args 'org-cycle-hook 'folded)))))
3493 ;; TAB emulation
3494 (buffer-read-only (org-back-to-heading))
3496 ((org-try-cdlatex-tab))
3498 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3499 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3500 (or (and (eq org-cycle-emulate-tab 'white)
3501 (= (match-end 0) (point-at-eol)))
3502 (and (eq org-cycle-emulate-tab 'whitestart)
3503 (>= (match-end 0) pos))))
3505 (eq org-cycle-emulate-tab t))
3506 (if (and (looking-at "[ \n\r\t]")
3507 (string-match "^[ \t]*$" (buffer-substring
3508 (point-at-bol) (point))))
3509 (progn
3510 (beginning-of-line 1)
3511 (and (looking-at "[ \t]+") (replace-match ""))))
3512 (indent-relative))
3514 (t (save-excursion
3515 (org-back-to-heading)
3516 (org-cycle))))))
3518 ;;;###autoload
3519 (defun org-global-cycle (&optional arg)
3520 "Cycle the global visibility. For details see `org-cycle'."
3521 (interactive "P")
3522 (if (integerp arg)
3523 (progn
3524 (show-all)
3525 (hide-sublevels arg)
3526 (setq org-cycle-global-status 'contents))
3527 (org-cycle '(4))))
3529 (defun org-overview ()
3530 "Switch to overview mode, shoing only top-level headlines.
3531 Really, this shows all headlines with level equal or greater than the level
3532 of the first headline in the buffer. This is important, because if the
3533 first headline is not level one, then (hide-sublevels 1) gives confusing
3534 results."
3535 (interactive)
3536 (hide-sublevels (save-excursion
3537 (goto-char (point-min))
3538 (if (re-search-forward (concat "^" outline-regexp) nil t)
3539 (progn
3540 (goto-char (match-beginning 0))
3541 (funcall outline-level))
3542 1))))
3544 ;; FIXME: allow an argument to give a limiting level for this.
3545 (defun org-content ()
3546 "Show all headlines in the buffer, like a table of contents"
3547 (interactive)
3548 (save-excursion
3549 ;; Visit all headings and show their offspring
3550 (goto-char (point-max))
3551 (catch 'exit
3552 (while (and (progn (condition-case nil
3553 (outline-previous-visible-heading 1)
3554 (error (goto-char (point-min))))
3556 (looking-at outline-regexp))
3557 (show-branches)
3558 (if (bobp) (throw 'exit nil))))))
3561 (defun org-optimize-window-after-visibility-change (state)
3562 "Adjust the window after a change in outline visibility.
3563 This function is the default value of the hook `org-cycle-hook'."
3564 (when (get-buffer-window (current-buffer))
3565 (cond
3566 ((eq state 'overview) (org-first-headline-recenter 1))
3567 ((eq state 'content) nil)
3568 ((eq state 'all) nil)
3569 ((eq state 'folded) nil)
3570 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3571 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3573 (defun org-subtree-end-visible-p ()
3574 "Is the end of the current subtree visible?"
3575 (pos-visible-in-window-p
3576 (save-excursion (org-end-of-subtree t) (point))))
3578 (defun org-first-headline-recenter (&optional N)
3579 "Move cursor to the first headline and recenter the headline.
3580 Optional argument N means, put the headline into the Nth line of the window."
3581 (goto-char (point-min))
3582 (when (re-search-forward (concat "^" outline-regexp) nil t)
3583 (beginning-of-line)
3584 (recenter (prefix-numeric-value N))))
3586 (defvar org-goto-window-configuration nil)
3587 (defvar org-goto-marker nil)
3588 (defvar org-goto-map (make-sparse-keymap))
3589 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3590 (while (setq cmd (pop cmds))
3591 (substitute-key-definition cmd cmd org-goto-map global-map)))
3592 (define-key org-goto-map "\C-m" 'org-goto-ret)
3593 (define-key org-goto-map [(left)] 'org-goto-left)
3594 (define-key org-goto-map [(right)] 'org-goto-right)
3595 (define-key org-goto-map [(?q)] 'org-goto-quit)
3596 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3597 (define-key org-goto-map "\C-i" 'org-cycle)
3598 (define-key org-goto-map [(tab)] 'org-cycle)
3599 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3600 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3601 (define-key org-goto-map "n" 'outline-next-visible-heading)
3602 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3603 (define-key org-goto-map "f" 'outline-forward-same-level)
3604 (define-key org-goto-map "b" 'outline-backward-same-level)
3605 (define-key org-goto-map "u" 'outline-up-heading)
3606 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3607 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3608 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3609 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3610 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3611 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3612 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3614 (defconst org-goto-help
3615 "Select a location to jump to, press RET
3616 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3618 (defun org-goto ()
3619 "Go to a different location of the document, keeping current visibility.
3621 When you want to go to a different location in a document, the fastest way
3622 is often to fold the entire buffer and then dive into the tree. This
3623 method has the disadvantage, that the previous location will be folded,
3624 which may not be what you want.
3626 This command works around this by showing a copy of the current buffer in
3627 overview mode. You can dive into the tree in that copy, to find the
3628 location you want to reach. When pressing RET, the command returns to the
3629 original buffer in which the visibility is still unchanged. It then jumps
3630 to the new location, making it and the headline hierarchy above it visible."
3631 (interactive)
3632 (let* ((org-goto-start-pos (point))
3633 (selected-point
3634 (org-get-location (current-buffer) org-goto-help)))
3635 (if selected-point
3636 (progn
3637 (org-mark-ring-push org-goto-start-pos)
3638 (goto-char selected-point)
3639 (if (or (org-invisible-p) (org-invisible-p2))
3640 (org-show-hierarchy-above)))
3641 (error "Quit"))))
3643 (defun org-get-location (buf help)
3644 "Let the user select a location in the Org-mode buffer BUF.
3645 This function uses a recursive edit. It returns the selected position
3646 or nil."
3647 (let (org-selected-point)
3648 (save-excursion
3649 (save-window-excursion
3650 (delete-other-windows)
3651 (switch-to-buffer (get-buffer-create "*org-goto*"))
3652 (with-output-to-temp-buffer "*Help*"
3653 (princ help))
3654 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3655 (setq buffer-read-only nil)
3656 (erase-buffer)
3657 (insert-buffer-substring buf)
3658 (let ((org-startup-truncated t)
3659 (org-startup-folded t)
3660 (org-startup-align-all-tables nil)
3661 (org-startup-with-deadline-check nil))
3662 (org-mode))
3663 (setq buffer-read-only t)
3664 (if (boundp 'org-goto-start-pos)
3665 (goto-char org-goto-start-pos)
3666 (goto-char (point-min)))
3667 (org-beginning-of-line)
3668 (message "Select location and press RET")
3669 ;; now we make sure that during selection, ony very few keys work
3670 ;; and that it is impossible to switch to another window.
3671 (let ((gm (current-global-map))
3672 (overriding-local-map org-goto-map))
3673 (unwind-protect
3674 (progn
3675 (use-global-map org-goto-map)
3676 (recursive-edit))
3677 (use-global-map gm)))))
3678 (kill-buffer "*org-goto*")
3679 org-selected-point))
3681 (defun org-goto-ret (&optional arg)
3682 "Finish `org-goto' by going to the new location."
3683 (interactive "P")
3684 (setq org-selected-point (point)
3685 current-prefix-arg arg)
3686 (throw 'exit nil))
3688 (defun org-goto-left ()
3689 "Finish `org-goto' by going to the new location."
3690 (interactive)
3691 (if (org-on-heading-p)
3692 (progn
3693 (beginning-of-line 1)
3694 (setq org-selected-point (point)
3695 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3696 (throw 'exit nil))
3697 (error "Not on a heading")))
3699 (defun org-goto-right ()
3700 "Finish `org-goto' by going to the new location."
3701 (interactive)
3702 (if (org-on-heading-p)
3703 (progn
3704 (outline-end-of-subtree)
3705 (or (eobp) (forward-char 1))
3706 (setq org-selected-point (point)
3707 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3708 (throw 'exit nil))
3709 (error "Not on a heading")))
3711 (defun org-goto-quit ()
3712 "Finish `org-goto' without cursor motion."
3713 (interactive)
3714 (setq org-selected-point nil)
3715 (throw 'exit nil))
3717 ;;; Promotion, Demotion, Inserting new headlines
3719 (defvar org-ignore-region nil
3720 "To temporarily disable the active region.")
3722 (defun org-insert-heading (&optional force-heading)
3723 "Insert a new heading or item with same depth at point.
3724 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3725 If point is at the beginning of a headline, insert a sibling before the
3726 current headline. If point is in the middle of a headline, split the headline
3727 at that position and make the rest of the headline part of the sibling below
3728 the current headline."
3729 (interactive "P")
3730 (if (= (buffer-size) 0)
3731 (insert "\n* ")
3732 (when (or force-heading (not (org-insert-item)))
3733 (let* ((head (save-excursion
3734 (condition-case nil
3735 (progn
3736 (org-back-to-heading)
3737 (match-string 0))
3738 (error "*"))))
3739 pos)
3740 (cond
3741 ((and (org-on-heading-p) (bolp)
3742 (save-excursion (backward-char 1) (not (org-invisible-p))))
3743 (open-line 1))
3744 ((and (bolp) (save-excursion
3745 (backward-char 1) (not (org-invisible-p))))
3746 nil)
3747 (t (newline)))
3748 (insert head) (just-one-space)
3749 (setq pos (point))
3750 (end-of-line 1)
3751 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3752 (run-hooks 'org-insert-heading-hook)))))
3754 (defun org-insert-item (&optional checkbox)
3755 "Insert a new item at the current level.
3756 Return t when things worked, nil when we are not in an item."
3757 (when (save-excursion
3758 (condition-case nil
3759 (progn
3760 (org-beginning-of-item)
3761 (org-at-item-p)
3763 (error nil)))
3764 (let* ((bul (match-string 0))
3765 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3766 (match-end 0)))
3767 pos)
3768 (cond
3769 ((and (org-at-item-p) (<= (point) eow))
3770 ;; before the bullet
3771 (beginning-of-line 1)
3772 (open-line 1))
3773 ((<= (point) eow)
3774 (beginning-of-line 1))
3775 (t (newline)))
3776 (insert bul (if checkbox "[ ]" ""))
3777 (just-one-space)
3778 (setq pos (point))
3779 (end-of-line 1)
3780 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3781 (org-maybe-renumber-ordered-list)
3784 (defun org-insert-todo-heading (arg)
3785 "Insert a new heading with the same level and TODO state as current heading.
3786 If the heading has no TODO state, or if the state is DONE, use the first
3787 state (TODO by default). Also with prefix arg, force first state."
3788 (interactive "P")
3789 (when (not (org-insert-item 'checkbox))
3790 (org-insert-heading)
3791 (save-excursion
3792 (org-back-to-heading)
3793 (if org-noutline-p
3794 (outline-previous-heading)
3795 (outline-previous-visible-heading t))
3796 (looking-at org-todo-line-regexp))
3797 (if (or arg
3798 (not (match-beginning 2))
3799 (equal (match-string 2) org-done-string))
3800 (insert (car org-todo-keywords) " ")
3801 (insert (match-string 2) " "))))
3803 (defun org-promote-subtree ()
3804 "Promote the entire subtree.
3805 See also `org-promote'."
3806 (interactive)
3807 (save-excursion
3808 (org-map-tree 'org-promote)))
3810 (defun org-demote-subtree ()
3811 "Demote the entire subtree. See `org-demote'.
3812 See also `org-promote'."
3813 (interactive)
3814 (save-excursion
3815 (org-map-tree 'org-demote)))
3817 (defun org-do-promote ()
3818 "Promote the current heading higher up the tree.
3819 If the region is active in `transient-mark-mode', promote all headings
3820 in the region."
3821 (interactive)
3822 (save-excursion
3823 (if (org-region-active-p)
3824 (org-map-region 'org-promote (region-beginning) (region-end))
3825 (org-promote)))
3826 (org-fix-position-after-promote))
3828 (defun org-do-demote ()
3829 "Demote the current heading lower down the tree.
3830 If the region is active in `transient-mark-mode', demote all headings
3831 in the region."
3832 (interactive)
3833 (save-excursion
3834 (if (org-region-active-p)
3835 (org-map-region 'org-demote (region-beginning) (region-end))
3836 (org-demote)))
3837 (org-fix-position-after-promote))
3839 (defun org-fix-position-after-promote ()
3840 "Make sure that after pro/demotion cursor position is right."
3841 (and (equal (char-after) ?\ )
3842 (equal (char-before) ?*)
3843 (forward-char 1)))
3845 (defun org-get-legal-level (level change)
3846 "Rectify a level change under the influence of `org-odd-levels-only'
3847 LEVEL is a current level, CHANGE is by how much the level should be
3848 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3849 even level numbers will become the next higher odd number."
3850 (if org-odd-levels-only
3851 (cond ((not change) (1+ (* 2 (/ level 2))))
3852 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3853 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3854 (max 1 (+ level change))))
3856 (defun org-promote ()
3857 "Promote the current heading higher up the tree.
3858 If the region is active in `transient-mark-mode', promote all headings
3859 in the region."
3860 (org-back-to-heading t)
3861 (let* ((level (save-match-data (funcall outline-level)))
3862 (up-head (make-string (org-get-legal-level level -1) ?*))
3863 (diff (abs (- level (length up-head)))))
3864 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3865 (replace-match up-head nil t)
3866 ;; Fixup tag positioning
3867 (and org-auto-align-tags (org-set-tags nil t))
3868 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
3870 (defun org-demote ()
3871 "Demote the current heading lower down the tree.
3872 If the region is active in `transient-mark-mode', demote all headings
3873 in the region."
3874 (org-back-to-heading t)
3875 (let* ((level (save-match-data (funcall outline-level)))
3876 (down-head (make-string (org-get-legal-level level 1) ?*))
3877 (diff (abs (- level (length down-head)))))
3878 (replace-match down-head nil t)
3879 ;; Fixup tag positioning
3880 (and org-auto-align-tags (org-set-tags nil t))
3881 (if org-adapt-indentation (org-fixup-indentation diff))))
3883 (defun org-map-tree (fun)
3884 "Call FUN for every heading underneath the current one."
3885 (org-back-to-heading)
3886 (let ((level (funcall outline-level)))
3887 (save-excursion
3888 (funcall fun)
3889 (while (and (progn
3890 (outline-next-heading)
3891 (> (funcall outline-level) level))
3892 (not (eobp)))
3893 (funcall fun)))))
3895 (defun org-map-region (fun beg end)
3896 "Call FUN for every heading between BEG and END."
3897 (let ((org-ignore-region t))
3898 (save-excursion
3899 (setq end (copy-marker end))
3900 (goto-char beg)
3901 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3902 (< (point) end))
3903 (funcall fun))
3904 (while (and (progn
3905 (outline-next-heading)
3906 (< (point) end))
3907 (not (eobp)))
3908 (funcall fun)))))
3910 (defun org-fixup-indentation (diff)
3911 "Change the indentation in the current entry by DIFF
3912 However, if any line in the current entry has no indentation, or if it
3913 would end up with no indentation after the change, nothing at all is done."
3914 (save-excursion
3915 (let ((end (save-excursion (outline-next-heading)
3916 (point-marker)))
3917 (prohibit (if (> diff 0)
3918 "^\\S-"
3919 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
3920 col)
3921 (unless (save-excursion (re-search-forward prohibit end t))
3922 (while (re-search-forward "^[ \t]+" end t)
3923 (goto-char (match-end 0))
3924 (setq col (current-column))
3925 (if (< diff 0) (replace-match ""))
3926 (indent-to (+ diff col))))
3927 (move-marker end nil))))
3929 ;;; Vertical tree motion, cutting and pasting of subtrees
3931 (defun org-move-subtree-up (&optional arg)
3932 "Move the current subtree up past ARG headlines of the same level."
3933 (interactive "p")
3934 (org-move-subtree-down (- (prefix-numeric-value arg))))
3936 (defun org-move-subtree-down (&optional arg)
3937 "Move the current subtree down past ARG headlines of the same level."
3938 (interactive "p")
3939 (setq arg (prefix-numeric-value arg))
3940 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3941 'outline-get-last-sibling))
3942 (ins-point (make-marker))
3943 (cnt (abs arg))
3944 beg end txt folded)
3945 ;; Select the tree
3946 (org-back-to-heading)
3947 (setq beg (point))
3948 (save-match-data
3949 (save-excursion (outline-end-of-heading)
3950 (setq folded (org-invisible-p)))
3951 (outline-end-of-subtree))
3952 (outline-next-heading)
3953 (setq end (point))
3954 ;; Find insertion point, with error handling
3955 (goto-char beg)
3956 (while (> cnt 0)
3957 (or (and (funcall movfunc) (looking-at outline-regexp))
3958 (progn (goto-char beg)
3959 (error "Cannot move past superior level or buffer limit")))
3960 (setq cnt (1- cnt)))
3961 (if (> arg 0)
3962 ;; Moving forward - still need to move over subtree
3963 (progn (outline-end-of-subtree)
3964 (outline-next-heading)
3965 (if (not (or (looking-at (concat "^" outline-regexp))
3966 (bolp)))
3967 (newline))))
3968 (move-marker ins-point (point))
3969 (setq txt (buffer-substring beg end))
3970 (delete-region beg end)
3971 (insert txt)
3972 (goto-char ins-point)
3973 (if folded (hide-subtree))
3974 (move-marker ins-point nil)))
3976 (defvar org-subtree-clip ""
3977 "Clipboard for cut and paste of subtrees.
3978 This is actually only a copy of the kill, because we use the normal kill
3979 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3981 (defvar org-subtree-clip-folded nil
3982 "Was the last copied subtree folded?
3983 This is used to fold the tree back after pasting.")
3985 (defun org-cut-subtree ()
3986 "Cut the current subtree into the clipboard.
3987 This is a short-hand for marking the subtree and then cutting it."
3988 (interactive)
3989 (org-copy-subtree 'cut))
3991 (defun org-copy-subtree (&optional cut)
3992 "Cut the current subtree into the clipboard.
3993 This is a short-hand for marking the subtree and then copying it.
3994 If CUT is non nil, actually cut the subtree."
3995 (interactive)
3996 (let (beg end folded)
3997 (org-back-to-heading)
3998 (setq beg (point))
3999 (save-match-data
4000 (save-excursion (outline-end-of-heading)
4001 (setq folded (org-invisible-p)))
4002 (outline-end-of-subtree))
4003 (if (equal (char-after) ?\n) (forward-char 1))
4004 (setq end (point))
4005 (goto-char beg)
4006 (when (> end beg)
4007 (setq org-subtree-clip-folded folded)
4008 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4009 (setq org-subtree-clip (current-kill 0))
4010 (message "%s: Subtree with %d characters"
4011 (if cut "Cut" "Copied")
4012 (length org-subtree-clip)))))
4014 (defun org-paste-subtree (&optional level tree)
4015 "Paste the clipboard as a subtree, with modification of headline level.
4016 The entire subtree is promoted or demoted in order to match a new headline
4017 level. By default, the new level is derived from the visible headings
4018 before and after the insertion point, and taken to be the inferior headline
4019 level of the two. So if the previous visible heading is level 3 and the
4020 next is level 4 (or vice versa), level 4 will be used for insertion.
4021 This makes sure that the subtree remains an independent subtree and does
4022 not swallow low level entries.
4024 You can also force a different level, either by using a numeric prefix
4025 argument, or by inserting the heading marker by hand. For example, if the
4026 cursor is after \"*****\", then the tree will be shifted to level 5.
4028 If you want to insert the tree as is, just use \\[yank].
4030 If optional TREE is given, use this text instead of the kill ring."
4031 (interactive "P")
4032 (unless (org-kill-is-subtree-p tree)
4033 (error
4034 (substitute-command-keys
4035 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4036 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4037 (^re (concat "^\\(" outline-regexp "\\)"))
4038 (re (concat "\\(" outline-regexp "\\)"))
4039 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4041 (old-level (if (string-match ^re txt)
4042 (- (match-end 0) (match-beginning 0))
4043 -1))
4044 (force-level (cond (level (prefix-numeric-value level))
4045 ((string-match
4046 ^re_ (buffer-substring (point-at-bol) (point)))
4047 (- (match-end 0) (match-beginning 0)))
4048 (t nil)))
4049 (previous-level (save-excursion
4050 (condition-case nil
4051 (progn
4052 (outline-previous-visible-heading 1)
4053 (if (looking-at re)
4054 (- (match-end 0) (match-beginning 0))
4056 (error 1))))
4057 (next-level (save-excursion
4058 (condition-case nil
4059 (progn
4060 (outline-next-visible-heading 1)
4061 (if (looking-at re)
4062 (- (match-end 0) (match-beginning 0))
4064 (error 1))))
4065 (new-level (or force-level (max previous-level next-level)))
4066 (shift (if (or (= old-level -1)
4067 (= new-level -1)
4068 (= old-level new-level))
4070 (- new-level old-level)))
4071 (shift1 shift)
4072 (delta (if (> shift 0) -1 1))
4073 (func (if (> shift 0) 'org-demote 'org-promote))
4074 (org-odd-levels-only nil)
4075 beg end)
4076 ;; Remove the forces level indicator
4077 (if force-level
4078 (delete-region (point-at-bol) (point)))
4079 ;; Make sure we start at the beginning of an empty line
4080 (if (not (bolp)) (insert "\n"))
4081 (if (not (looking-at "[ \t]*$"))
4082 (progn (insert "\n") (backward-char 1)))
4083 ;; Paste
4084 (setq beg (point))
4085 (if (string-match "[ \t\r\n]+\\'" txt)
4086 (setq txt (replace-match "\n" t t txt)))
4087 (insert txt)
4088 (setq end (point))
4089 (if (looking-at "[ \t\r\n]+")
4090 (replace-match "\n"))
4091 (goto-char beg)
4092 ;; Shift if necessary
4093 (if (= shift 0)
4094 (message "Pasted at level %d, without shift" new-level)
4095 (save-restriction
4096 (narrow-to-region beg end)
4097 (while (not (= shift 0))
4098 (org-map-region func (point-min) (point-max))
4099 (setq shift (+ delta shift)))
4100 (goto-char (point-min))
4101 (message "Pasted at level %d, with shift by %d levels"
4102 new-level shift1)))
4103 (if (and kill-ring
4104 (eq org-subtree-clip (current-kill 0))
4105 org-subtree-clip-folded)
4106 ;; The tree was folded before it was killed/copied
4107 (hide-subtree))))
4109 (defun org-kill-is-subtree-p (&optional txt)
4110 "Check if the current kill is an outline subtree, or a set of trees.
4111 Returns nil if kill does not start with a headline, or if the first
4112 headline level is not the largest headline level in the tree.
4113 So this will actually accept several entries of equal levels as well,
4114 which is OK for `org-paste-subtree'.
4115 If optional TXT is given, check this string instead of the current kill."
4116 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4117 (start-level (and kill
4118 (string-match (concat "\\`" outline-regexp) kill)
4119 (- (match-end 0) (match-beginning 0))))
4120 (re (concat "^" outline-regexp))
4121 (start 1))
4122 (if (not start-level)
4123 nil ;; does not even start with a heading
4124 (catch 'exit
4125 (while (setq start (string-match re kill (1+ start)))
4126 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4127 (throw 'exit nil)))
4128 t))))
4130 (defun org-narrow-to-subtree ()
4131 "Narrow buffer to the current subtree."
4132 (interactive)
4133 (save-excursion
4134 (narrow-to-region
4135 (progn (org-back-to-heading) (point))
4136 (progn (org-end-of-subtree t) (point)))))
4138 ;;; Plain list items
4140 (defun org-at-item-p ()
4141 "Is point in a line starting a hand-formatted item?"
4142 (let ((llt org-plain-list-ordered-item-terminator))
4143 (save-excursion
4144 (goto-char (point-at-bol))
4145 (looking-at
4146 (cond
4147 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4148 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4149 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4150 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4152 (defun org-at-item-checkbox-p ()
4153 "Is point at a line starting a plain-list item with a checklet?"
4154 (and (org-at-item-p)
4155 (save-excursion
4156 (goto-char (match-end 0))
4157 (skip-chars-forward " \t")
4158 (looking-at "\\[[ X]\\]"))))
4160 (defun org-toggle-checkbox ()
4161 "Toggle the checkbox in the current line."
4162 (interactive)
4163 (save-excursion
4164 (if (org-at-item-checkbox-p)
4165 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))))
4167 (defun org-get-indentation (&optional line)
4168 "Get the indentation of the current line, interpreting tabs.
4169 When LINE is given, assume it represents a line and compute its indentation."
4170 (if line
4171 (if (string-match "^ *" (org-remove-tabs line))
4172 (match-end 0))
4173 (save-excursion
4174 (beginning-of-line 1)
4175 (skip-chars-forward " \t")
4176 (current-column))))
4178 (defun org-remove-tabs (s &optional width)
4179 "Replace tabulators in S with spaces.
4180 Assumes that s is a single line, starting in column 0."
4181 (setq width (or width tab-width))
4182 (while (string-match "\t" s)
4183 (setq s (replace-match
4184 (make-string
4185 (- (* width (/ (+ (match-beginning 0) width) width))
4186 (match-beginning 0)) ?\ )
4187 t t s)))
4190 ;; FIXME: document properly.
4191 (defun org-fix-indentation (line ind)
4192 "If the current indenation is smaller than ind1, leave it alone.
4193 If it is larger than ind, reduce it by ind."
4194 (let* ((l (org-remove-tabs line))
4195 (i (org-get-indentation l))
4196 (i1 (car ind)) (i2 (cdr ind)))
4197 (if (>= i i2) (setq l (substring line i2)))
4198 (if (> i1 0)
4199 (concat (make-string i1 ?\ ) l)
4200 l)))
4202 (defun org-beginning-of-item ()
4203 "Go to the beginning of the current hand-formatted item.
4204 If the cursor is not in an item, throw an error."
4205 (interactive)
4206 (let ((pos (point))
4207 (limit (save-excursion (org-back-to-heading)
4208 (beginning-of-line 2) (point)))
4209 ind ind1)
4210 (if (org-at-item-p)
4211 (beginning-of-line 1)
4212 (beginning-of-line 1)
4213 (skip-chars-forward " \t")
4214 (setq ind (current-column))
4215 (if (catch 'exit
4216 (while t
4217 (beginning-of-line 0)
4218 (if (< (point) limit) (throw 'exit nil))
4219 (unless (looking-at " \t]*$")
4220 (skip-chars-forward " \t")
4221 (setq ind1 (current-column))
4222 (if (< ind1 ind)
4223 (throw 'exit (org-at-item-p))))))
4225 (goto-char pos)
4226 (error "Not in an item")))))
4228 (defun org-end-of-item ()
4229 "Go to the end of the current hand-formatted item.
4230 If the cursor is not in an item, throw an error."
4231 (interactive)
4232 (let ((pos (point))
4233 (limit (save-excursion (outline-next-heading) (point)))
4234 (ind (save-excursion
4235 (org-beginning-of-item)
4236 (skip-chars-forward " \t")
4237 (current-column)))
4238 ind1)
4239 (if (catch 'exit
4240 (while t
4241 (beginning-of-line 2)
4242 (if (>= (point) limit) (throw 'exit t))
4243 (unless (looking-at "[ \t]*$")
4244 (skip-chars-forward " \t")
4245 (setq ind1 (current-column))
4246 (if (<= ind1 ind) (throw 'exit t)))))
4247 (beginning-of-line 1)
4248 (goto-char pos)
4249 (error "Not in an item"))))
4251 (defun org-next-item ()
4252 "Move to the beginning of the next item in the current plain list.
4253 Error if not at a plain list, or if this is the last item in the list."
4254 (interactive)
4255 (let (ind ind1 (pos (point)))
4256 (org-beginning-of-item)
4257 (setq ind (org-get-indentation))
4258 (org-end-of-item)
4259 (setq ind1 (org-get-indentation))
4260 (unless (and (org-at-item-p) (= ind ind1))
4261 (goto-char pos)
4262 (error "On last item"))))
4264 (defun org-previous-item ()
4265 "Move to the beginning of the previous item in the current plain list.
4266 Error if not at a plain list, or if this is the last item in the list."
4267 (interactive)
4268 (let (beg ind (pos (point)))
4269 (org-beginning-of-item)
4270 (setq beg (point))
4271 (setq ind (org-get-indentation))
4272 (goto-char beg)
4273 (catch 'exit
4274 (while t
4275 (beginning-of-line 0)
4276 (if (looking-at "[ \t]*$")
4278 (if (<= (org-get-indentation) ind)
4279 (throw 'exit t)))))
4280 (condition-case nil
4281 (org-beginning-of-item)
4282 (error (goto-char pos)
4283 (error "On first item")))))
4285 (defun org-move-item-down ()
4286 "Move the plain list item at point down, i.e. swap with following item.
4287 Subitems (items with larger indentation) are considered part of the item,
4288 so this really moves item trees."
4289 (interactive)
4290 (let (beg end ind ind1 (pos (point)) txt)
4291 (org-beginning-of-item)
4292 (setq beg (point))
4293 (setq ind (org-get-indentation))
4294 (org-end-of-item)
4295 (setq end (point))
4296 (setq ind1 (org-get-indentation))
4297 (if (and (org-at-item-p) (= ind ind1))
4298 (progn
4299 (org-end-of-item)
4300 (setq txt (buffer-substring beg end))
4301 (save-excursion
4302 (delete-region beg end))
4303 (setq pos (point))
4304 (insert txt)
4305 (goto-char pos)
4306 (org-maybe-renumber-ordered-list))
4307 (goto-char pos)
4308 (error "Cannot move this item further down"))))
4310 (defun org-move-item-up (arg)
4311 "Move the plain list item at point up, i.e. swap with previous item.
4312 Subitems (items with larger indentation) are considered part of the item,
4313 so this really moves item trees."
4314 (interactive "p")
4315 (let (beg end ind ind1 (pos (point)) txt)
4316 (org-beginning-of-item)
4317 (setq beg (point))
4318 (setq ind (org-get-indentation))
4319 (org-end-of-item)
4320 (setq end (point))
4321 (goto-char beg)
4322 (catch 'exit
4323 (while t
4324 (beginning-of-line 0)
4325 (if (looking-at "[ \t]*$")
4327 (if (<= (setq ind1 (org-get-indentation)) ind)
4328 (throw 'exit t)))))
4329 (condition-case nil
4330 (org-beginning-of-item)
4331 (error (goto-char beg)
4332 (error "Cannot move this item further up")))
4333 (setq ind1 (org-get-indentation))
4334 (if (and (org-at-item-p) (= ind ind1))
4335 (progn
4336 (setq txt (buffer-substring beg end))
4337 (save-excursion
4338 (delete-region beg end))
4339 (setq pos (point))
4340 (insert txt)
4341 (goto-char pos)
4342 (org-maybe-renumber-ordered-list))
4343 (goto-char pos)
4344 (error "Cannot move this item further up"))))
4346 (defun org-maybe-renumber-ordered-list ()
4347 "Renumber the ordered list at point if setup allows it.
4348 This tests the user option `org-auto-renumber-ordered-lists' before
4349 doing the renumbering."
4350 (and org-auto-renumber-ordered-lists
4351 (org-at-item-p)
4352 (match-beginning 3)
4353 (org-renumber-ordered-list 1)))
4355 (defun org-get-string-indentation (s)
4356 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4357 (let ((n -1) (i 0) (w tab-width) c)
4358 (catch 'exit
4359 (while (< (setq n (1+ n)) (length s))
4360 (setq c (aref s n))
4361 (cond ((= c ?\ ) (setq i (1+ i)))
4362 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4363 (t (throw 'exit t)))))
4366 (defun org-renumber-ordered-list (arg)
4367 "Renumber an ordered plain list.
4368 Cursor needs to be in the first line of an item, the line that starts
4369 with something like \"1.\" or \"2)\"."
4370 (interactive "p")
4371 (unless (and (org-at-item-p)
4372 (match-beginning 3))
4373 (error "This is not an ordered list"))
4374 (let ((line (org-current-line))
4375 (col (current-column))
4376 (ind (org-get-string-indentation
4377 (buffer-substring (point-at-bol) (match-beginning 3))))
4378 ;; (term (substring (match-string 3) -1))
4379 ind1 (n (1- arg)))
4380 ;; find where this list begins
4381 (catch 'exit
4382 (while t
4383 (catch 'next
4384 (beginning-of-line 0)
4385 (if (looking-at "[ \t]*$") (throw 'next t))
4386 (skip-chars-forward " \t") (setq ind1 (current-column))
4387 (if (or (< ind1 ind)
4388 (and (= ind1 ind)
4389 (not (org-at-item-p))))
4390 (throw 'exit t)))))
4391 ;; Walk forward and replace these numbers
4392 (catch 'exit
4393 (while t
4394 (catch 'next
4395 (beginning-of-line 2)
4396 (if (eobp) (throw 'exit nil))
4397 (if (looking-at "[ \t]*$") (throw 'next nil))
4398 (skip-chars-forward " \t") (setq ind1 (current-column))
4399 (if (> ind1 ind) (throw 'next t))
4400 (if (< ind1 ind) (throw 'exit t))
4401 (if (not (org-at-item-p)) (throw 'exit nil))
4402 (if (not (match-beginning 3))
4403 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4404 (delete-region (match-beginning 3) (1- (match-end 3)))
4405 (goto-char (match-beginning 3))
4406 (insert (format "%d" (setq n (1+ n)))))))
4407 (goto-line line)
4408 (move-to-column col)))
4410 (defvar org-last-indent-begin-marker (make-marker))
4411 (defvar org-last-indent-end-marker (make-marker))
4413 (defun org-outdent-item (arg)
4414 "Outdent a local list item."
4415 (interactive "p")
4416 (org-indent-item (- arg)))
4418 (defun org-indent-item (arg)
4419 "Indent a local list item."
4420 (interactive "p")
4421 (unless (org-at-item-p)
4422 (error "Not on an item"))
4423 (save-excursion
4424 (let (beg end ind ind1)
4425 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4426 (setq beg org-last-indent-begin-marker
4427 end org-last-indent-end-marker)
4428 (org-beginning-of-item)
4429 (setq beg (move-marker org-last-indent-begin-marker (point)))
4430 (org-end-of-item)
4431 (setq end (move-marker org-last-indent-end-marker (point))))
4432 (goto-char beg)
4433 (skip-chars-forward " \t") (setq ind (current-column))
4434 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4435 (while (< (point) end)
4436 (beginning-of-line 1)
4437 (skip-chars-forward " \t") (setq ind1 (current-column))
4438 (delete-region (point-at-bol) (point))
4439 (indent-to-column (+ ind1 arg))
4440 (beginning-of-line 2)))))
4442 ;;; Archiving
4444 (defun org-archive-subtree (&optional find-done)
4445 "Move the current subtree to the archive.
4446 The archive can be a certain top-level heading in the current file, or in
4447 a different file. The tree will be moved to that location, the subtree
4448 heading be marked DONE, and the current time will be added.
4450 When called with prefix argument FIND-DONE, find whole trees without any
4451 open TODO items and archive them (after getting confirmation from the user).
4452 If the cursor is not at a headline when this comand is called, try all level
4453 1 trees. If the cursor is on a headline, only try the direct children of
4454 this heading. "
4455 (interactive "P")
4456 (if find-done
4457 (org-archive-all-done)
4458 ;; Save all relevant TODO keyword-relatex variables
4460 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4461 (tr-org-todo-keywords org-todo-keywords)
4462 (tr-org-todo-interpretation org-todo-interpretation)
4463 (tr-org-done-string org-done-string)
4464 (tr-org-todo-regexp org-todo-regexp)
4465 (tr-org-todo-line-regexp org-todo-line-regexp)
4466 (this-buffer (current-buffer))
4467 file heading buffer level newfile-p)
4468 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4469 (progn
4470 (setq file (format (match-string 1 org-archive-location)
4471 (file-name-nondirectory buffer-file-name))
4472 heading (match-string 2 org-archive-location)))
4473 (error "Invalid `org-archive-location'"))
4474 (if (> (length file) 0)
4475 (setq newfile-p (not (file-exists-p file))
4476 buffer (find-file-noselect file))
4477 (setq buffer (current-buffer)))
4478 (unless buffer
4479 (error "Cannot access file \"%s\"" file))
4480 (if (and (> (length heading) 0)
4481 (string-match "^\\*+" heading))
4482 (setq level (match-end 0))
4483 (setq heading nil level 0))
4484 (save-excursion
4485 ;; We first only copy, in case something goes wrong
4486 ;; we need to protect this-command, to avoid kill-region sets it,
4487 ;; which would lead to duplication of subtrees
4488 (let (this-command) (org-copy-subtree))
4489 (set-buffer buffer)
4490 ;; Enforce org-mode for the archive buffer
4491 (if (not (eq major-mode 'org-mode))
4492 ;; Force the mode for future visits.
4493 (let ((org-insert-mode-line-in-empty-file t))
4494 (call-interactively 'org-mode)))
4495 (when newfile-p
4496 (goto-char (point-max))
4497 (insert (format "\nArchived entries from file %s\n\n"
4498 (buffer-file-name this-buffer))))
4499 ;; Force the TODO keywords of the original buffer
4500 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4501 (org-todo-keywords tr-org-todo-keywords)
4502 (org-todo-interpretation tr-org-todo-interpretation)
4503 (org-done-string tr-org-done-string)
4504 (org-todo-regexp tr-org-todo-regexp)
4505 (org-todo-line-regexp tr-org-todo-line-regexp))
4506 (goto-char (point-min))
4507 (if heading
4508 (progn
4509 (if (re-search-forward
4510 (concat "\\(^\\|\r\\)"
4511 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4512 nil t)
4513 (goto-char (match-end 0))
4514 ;; Heading not found, just insert it at the end
4515 (goto-char (point-max))
4516 (or (bolp) (insert "\n"))
4517 (insert "\n" heading "\n")
4518 (end-of-line 0))
4519 ;; Make the subtree visible
4520 (show-subtree)
4521 (org-end-of-subtree t)
4522 (skip-chars-backward " \t\r\n]")
4523 (and (looking-at "[ \t\r\n]*")
4524 (replace-match "\n\n")))
4525 ;; No specific heading, just go to end of file.
4526 (goto-char (point-max)) (insert "\n"))
4527 ;; Paste
4528 (org-paste-subtree (1+ level))
4529 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4530 (if org-archive-mark-done
4531 (org-todo (length org-todo-keywords)))
4532 ;; Move cursor to right after the TODO keyword
4533 (when org-archive-stamp-time
4534 (beginning-of-line 1)
4535 (looking-at org-todo-line-regexp)
4536 (goto-char (or (match-end 2) (match-beginning 3)))
4537 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4538 (org-current-time))
4539 ")"))
4540 ;; Save the buffer, if it is not the same buffer.
4541 (if (not (eq this-buffer buffer)) (save-buffer))))
4542 ;; Here we are back in the original buffer. Everything seems to have
4543 ;; worked. So now cut the tree and finish up.
4544 (let (this-command) (org-cut-subtree))
4545 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4546 (message "Subtree archived %s"
4547 (if (eq this-buffer buffer)
4548 (concat "under heading: " heading)
4549 (concat "in file: " (abbreviate-file-name file)))))))
4551 (defun org-archive-all-done (&optional tag)
4552 "Archive sublevels of the current tree without open TODO items.
4553 If the cursor is not on a headline, try all level 1 trees. If
4554 it is on a headline, try all direct children.
4555 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4556 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4557 (rea (concat ".*:" org-archive-tag ":"))
4558 (begm (make-marker))
4559 (endm (make-marker))
4560 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4561 "Move subtree to archive (no open TODO items)? "))
4562 beg end (cntarch 0))
4563 (if (org-on-heading-p)
4564 (progn
4565 (setq re1 (concat "^" (regexp-quote
4566 (make-string
4567 (1+ (- (match-end 0) (match-beginning 0)))
4568 ?*))
4569 " "))
4570 (move-marker begm (point))
4571 (move-marker endm (org-end-of-subtree)))
4572 (setq re1 "^* ")
4573 (move-marker begm (point-min))
4574 (move-marker endm (point-max)))
4575 (save-excursion
4576 (goto-char begm)
4577 (while (re-search-forward re1 endm t)
4578 beg (match-beginning 0)
4579 end (save-excursion (org-end-of-subtree t) (point)))
4580 (goto-char beg)
4581 (if (re-search-forward re end t)
4582 (goto-char end)
4583 (goto-char beg)
4584 (if (and (or (not tag) (not (looking-at rea)))
4585 (y-or-n-p question))
4586 (progn
4587 (if tag
4588 (org-toggle-tag org-archive-tag 'on)
4589 (org-archive-subtree))
4590 (setq cntarch (1+ cntarch)))
4591 (goto-char end))))
4592 (message "%d trees archived" cntarch)))
4595 (defun org-cycle-hide-archived-subtrees (state)
4596 "Re-hide all archived subtrees after a visibility state change."
4597 (when (and (not org-cycle-open-archived-trees)
4598 (not (memq state '(overview folded))))
4599 (save-excursion
4600 (let* ((globalp (memq state '(contents all)))
4601 (beg (if globalp (point-min) (point)))
4602 (end (if globalp (point-max) (org-end-of-subtree))))
4603 (org-hide-archived-subtrees beg end)))))
4605 (defun org-hide-archived-subtrees (beg end)
4606 "Re-hide all archived subtrees after a visibility state change."
4607 (save-excursion
4608 (let* ((re (concat ":" org-archive-tag ":")))
4609 (goto-char beg)
4610 (while (re-search-forward re end t)
4611 (and (org-on-heading-p) (hide-subtree))
4612 (org-end-of-subtree)))))
4614 (defun org-toggle-tag (tag &optional onoff)
4615 "Toggle the tag TAG for the current line.
4616 If ONOFF is `on' or `off', don't toggle but set to this state."
4617 (unless (org-on-heading-p) (error "Not on headling"))
4618 (let (res current)
4619 (save-excursion
4620 (beginning-of-line)
4621 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
4622 (point-at-eol) t)
4623 (progn
4624 (setq current (match-string 1))
4625 (replace-match ""))
4626 (setq current ""))
4627 (setq current (nreverse (org-split-string current ":")))
4628 (cond
4629 ((eq onoff 'on)
4630 (setq res t)
4631 (or (member tag current) (push tag current)))
4632 ((eq onoff 'off)
4633 (or (not (member tag current)) (setq current (delete tag current))))
4634 (t (if (member tag current)
4635 (setq current (delete tag current))
4636 (setq res t)
4637 (push tag current))))
4638 (end-of-line 1)
4639 (when current
4640 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
4641 (org-set-tags nil t))
4642 res))
4644 (defun org-toggle-archive-tag (&optional arg)
4645 "Toggle the archive tag for the current headline.
4646 With prefix ARG, check all children of current headline and offer tagging
4647 the children that do not contain any open TODO items."
4648 (interactive "P")
4649 (if arg
4650 (org-archive-all-done 'tag)
4651 (let (set)
4652 (save-excursion
4653 (org-back-to-heading t)
4654 (setq set (org-toggle-tag org-archive-tag))
4655 (when set (hide-subtree)))
4656 (and set (beginning-of-line 1))
4657 (message "Subtree %s" (if set "archived" "unarchived")))))
4659 (defun org-prepare-agenda-buffers (files)
4660 "Create buffers for all agenda files, protect archived trees and comments."
4661 (let ((pa '(:org-archived t))
4662 (pc '(:org-comment t))
4663 (pall '(:org-archived t :org-comment t))
4664 (rea (concat ":" org-archive-tag ":"))
4665 file re)
4666 (save-excursion
4667 (while (setq file (pop files))
4668 (org-check-agenda-file file)
4669 (set-buffer (org-get-agenda-file-buffer file))
4670 (widen)
4671 (save-excursion
4672 (remove-text-properties (point-min) (point-max) pall)
4673 (when org-agenda-skip-archived-trees
4674 (goto-char (point-min))
4675 (while (re-search-forward rea nil t)
4676 (if (org-on-heading-p)
4677 (add-text-properties (point-at-bol) (org-end-of-subtree) pa))))
4678 (goto-char (point-min))
4679 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
4680 (while (re-search-forward re nil t)
4681 (add-text-properties
4682 (match-beginning 0) (org-end-of-subtree) pc)))))))
4684 (defun org-agenda-skip ()
4685 "Throw to `:skip' in places that should be skipped."
4686 (let ((p (point-at-bol)))
4687 (and org-agenda-skip-archived-trees
4688 (get-text-property p :org-archived)
4689 (org-end-of-subtree)
4690 (throw :skip t))
4691 (and (get-text-property p :org-comment)
4692 (org-end-of-subtree)
4693 (throw :skip t))
4694 (if (equal (char-after p) ?#) (throw :skip t))))
4696 (defun org-agenda-toggle-archive-tag ()
4697 "Toggle the archive tag for the current entry."
4698 (interactive)
4699 (org-agenda-check-no-diary)
4700 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
4701 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
4702 (org-agenda-error)))
4703 (buffer (marker-buffer hdmarker))
4704 (pos (marker-position hdmarker))
4705 (buffer-read-only nil)
4706 newhead)
4707 (with-current-buffer buffer
4708 (widen)
4709 (goto-char pos)
4710 (org-show-hidden-entry)
4711 (save-excursion
4712 (and (outline-next-heading)
4713 (org-flag-heading nil))) ; show the next heading
4714 (call-interactively 'org-toggle-archive-tag)
4715 (end-of-line 1)
4716 (setq newhead (org-get-heading)))
4717 (org-agenda-change-all-lines newhead hdmarker)
4718 (beginning-of-line 1)))
4720 ;;; Dynamic blocks
4722 (defun org-find-dblock (name)
4723 "Find the first dynamic block with name NAME in the buffer.
4724 If not found, stay at current position and return nil."
4725 (let (pos)
4726 (save-excursion
4727 (goto-char (point-min))
4728 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
4729 nil t)
4730 (match-beginning 0))))
4731 (if pos (goto-char pos))
4732 pos))
4734 (defconst org-dblock-start-re
4735 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)[ \t]+\\(.*\\)"
4736 "Matches the startline of a dynamic block, with parameters.")
4738 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
4739 "Matches the end of a dyhamic block.")
4741 (defun org-create-dblock (plist)
4742 "Create a dynamic block section, with parameters taken from PLIST.
4743 PLIST must containe a :name entry which is used as name of the block."
4744 (unless (bolp) (newline))
4745 (let ((name (plist-get plist :name)))
4746 (insert "#+BEGIN: " name)
4747 (while plist
4748 (if (eq (car plist) :name)
4749 (setq plist (cddr plist))
4750 (insert " " (prin1-to-string (pop plist)))))
4751 (insert "\n\n#+END:\n")
4752 (beginning-of-line -2)))
4754 (defun org-prepare-dblock ()
4755 "Prepare dynamic block for refresh.
4756 This empties the block, puts the cursor at the insert position and returns
4757 the property list including an extra property :name with the block name."
4758 (unless (looking-at org-dblock-start-re)
4759 (error "Not at a dynamic block"))
4760 (let* ((begdel (1+ (match-end 0)))
4761 (name (match-string 1))
4762 (params (append (list :name name)
4763 (read (concat "(" (match-string 2) ")")))))
4764 (unless (re-search-forward org-dblock-end-re nil t)
4765 (error "Dynamic block not terminated"))
4766 (delete-region begdel (match-beginning 0))
4767 (goto-char begdel)
4768 (open-line 1)
4769 params))
4771 (defun org-map-dblocks (&optional command)
4772 "Apply COMMAND to all dynamic blocks in the current buffer.
4773 If COMMAND is not given, use `org-update-dblock'."
4774 (let ((cmd (or command 'org-update-dblock))
4775 pos)
4776 (save-excursion
4777 (goto-char (point-min))
4778 (while (re-search-forward org-dblock-start-re nil t)
4779 (goto-char (setq pos (match-beginning 0)))
4780 (condition-case nil
4781 (funcall cmd)
4782 (error (message "Error during update of dynamic block")))
4783 (goto-char pos)
4784 (unless (re-search-forward org-dblock-end-re nil t)
4785 (error "Dynamic block not terminated"))))))
4787 (defun org-dblock-update (&optional arg)
4788 "User command for updating dynamic blocks.
4789 Update the dynamic block at point. With prefix ARG, update all dynamic
4790 blocks in the buffer."
4791 (interactive "P")
4792 (if arg
4793 (org-update-all-dblocks)
4794 (or (looking-at org-dblock-start-re)
4795 (org-beginning-of-dblock))
4796 (org-update-dblock)))
4798 (defun org-update-dblock ()
4799 "Update the dynamic block at point
4800 This means to empty the block, parse for parameters and then call
4801 the correct writing function."
4802 (let* ((pos (point))
4803 (params (org-prepare-dblock))
4804 (name (plist-get params :name))
4805 (cmd (intern (concat "org-dblock-write:" name))))
4806 (funcall cmd params)
4807 (goto-char pos)))
4809 (defun org-beginning-of-dblock ()
4810 "Find the beginning of the dynamic block at point.
4811 Error if there is no scuh block at point."
4812 (let ((pos (point))
4813 beg)
4814 (end-of-line 1)
4815 (if (and (re-search-backward org-dblock-start-re nil t)
4816 (setq beg (match-beginning 0))
4817 (re-search-forward org-dblock-end-re nil t)
4818 (> (match-end 0) pos))
4819 (goto-char beg)
4820 (goto-char pos)
4821 (error "Not in a dynamic block"))))
4823 (defun org-update-all-dblocks ()
4824 "Update all dynamic blocks in the buffer.
4825 This function can be used in a hook."
4826 (when (eq major-mode 'org-mode)
4827 (org-map-dblocks 'org-update-dblock)))
4830 ;;; Completion
4832 (defun org-complete (&optional arg)
4833 "Perform completion on word at point.
4834 At the beginning of a headline, this completes TODO keywords as given in
4835 `org-todo-keywords'.
4836 If the current word is preceded by a backslash, completes the TeX symbols
4837 that are supported for HTML support.
4838 If the current word is preceded by \"#+\", completes special words for
4839 setting file options.
4840 At all other locations, this simply calls `ispell-complete-word'."
4841 (interactive "P")
4842 (catch 'exit
4843 (let* ((end (point))
4844 (beg1 (save-excursion
4845 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4846 (skip-chars-backward "a-zA-Z_@0-9")
4847 (point)))
4848 (beg (save-excursion
4849 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4850 (skip-chars-backward "a-zA-Z0-9_:$")
4851 (point)))
4852 (confirm (lambda (x) (stringp (car x))))
4853 (camel (equal (char-before beg) ?*))
4854 (tag (equal (char-before beg1) ?:))
4855 (texp (equal (char-before beg) ?\\))
4856 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
4857 beg)
4858 "#+"))
4859 (completion-ignore-case opt)
4860 (type nil)
4861 (tbl nil)
4862 (table (cond
4863 (opt
4864 (setq type :opt)
4865 (mapcar (lambda (x)
4866 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
4867 (cons (match-string 2 x) (match-string 1 x)))
4868 (org-split-string (org-get-current-options) "\n")))
4869 (texp
4870 (setq type :tex)
4871 org-html-entities)
4872 ((string-match "\\`\\*+[ \t]*\\'"
4873 (buffer-substring (point-at-bol) beg))
4874 (setq type :todo)
4875 (mapcar 'list org-todo-keywords))
4876 (camel
4877 (setq type :camel)
4878 (save-excursion
4879 (goto-char (point-min))
4880 (while (re-search-forward org-todo-line-regexp nil t)
4881 (push (list
4882 (if org-file-link-context-use-camel-case
4883 (org-make-org-heading-camel (match-string 3) t)
4884 (org-make-org-heading-search-string
4885 (match-string 3) t)))
4886 tbl)))
4887 tbl)
4888 (tag (setq type :tag beg beg1)
4889 (or org-tag-alist (org-get-buffer-tags)))
4890 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
4891 (pattern (buffer-substring-no-properties beg end))
4892 (completion (try-completion pattern table confirm)))
4893 (cond ((eq completion t)
4894 (if (equal type :opt)
4895 (insert (substring (cdr (assoc (upcase pattern) table))
4896 (length pattern)))))
4897 ((null completion)
4898 (message "Can't find completion for \"%s\"" pattern)
4899 (ding))
4900 ((not (string= pattern completion))
4901 (delete-region beg end)
4902 (if (string-match " +$" completion)
4903 (setq completion (replace-match "" t t completion)))
4904 (insert completion)
4905 (if (get-buffer-window "*Completions*")
4906 (delete-window (get-buffer-window "*Completions*")))
4907 (if (assoc completion table)
4908 (if (eq type :todo) (insert " ")
4909 (if (eq type :tag) (insert ":"))))
4910 (if (and (equal type :opt) (assoc completion table))
4911 (message "%s" (substitute-command-keys
4912 "Press \\[org-complete] again to insert example settings"))))
4914 (message "Making completion list...")
4915 (let ((list (sort (all-completions pattern table confirm)
4916 'string<)))
4917 (with-output-to-temp-buffer "*Completions*"
4918 (condition-case nil
4919 ;; Protection needed for XEmacs and emacs 21
4920 (display-completion-list list pattern)
4921 (error (display-completion-list list)))))
4922 (message "Making completion list...%s" "done"))))))
4924 ;;; Comments, TODO and DEADLINE
4926 (defun org-toggle-comment ()
4927 "Change the COMMENT state of an entry."
4928 (interactive)
4929 (save-excursion
4930 (org-back-to-heading)
4931 (if (looking-at (concat outline-regexp
4932 "\\( +\\<" org-comment-string "\\>\\)"))
4933 (replace-match "" t t nil 1)
4934 (if (looking-at outline-regexp)
4935 (progn
4936 (goto-char (match-end 0))
4937 (insert " " org-comment-string))))))
4939 (defvar org-last-todo-state-is-todo nil
4940 "This is non-nil when the last TODO state change led to a TODO state.
4941 If the last change removed the TODO tag or switched to DONE, then
4942 this is nil.")
4944 (defun org-todo (&optional arg)
4945 "Change the TODO state of an item.
4946 The state of an item is given by a keyword at the start of the heading,
4947 like
4948 *** TODO Write paper
4949 *** DONE Call mom
4951 The different keywords are specified in the variable `org-todo-keywords'.
4952 By default the available states are \"TODO\" and \"DONE\".
4953 So for this example: when the item starts with TODO, it is changed to DONE.
4954 When it starts with DONE, the DONE is removed. And when neither TODO nor
4955 DONE are present, add TODO at the beginning of the heading.
4957 With prefix arg, use completion to determine the new state. With numeric
4958 prefix arg, switch to that state."
4959 (interactive "P")
4960 (save-excursion
4961 (org-back-to-heading)
4962 (if (looking-at outline-regexp) (goto-char (match-end 0)))
4963 (or (looking-at (concat " +" org-todo-regexp " *"))
4964 (looking-at " *"))
4965 (let* ((this (match-string 1))
4966 (completion-ignore-case t)
4967 (member (member this org-todo-keywords))
4968 (tail (cdr member))
4969 (state (cond
4970 ((equal arg '(4))
4971 ;; Read a state with completion
4972 (completing-read "State: " (mapcar (lambda(x) (list x))
4973 org-todo-keywords)
4974 nil t))
4975 ((eq arg 'right)
4976 (if this
4977 (if tail (car tail) nil)
4978 (car org-todo-keywords)))
4979 ((eq arg 'left)
4980 (if (equal member org-todo-keywords)
4982 (if this
4983 (nth (- (length org-todo-keywords) (length tail) 2)
4984 org-todo-keywords)
4985 org-done-string)))
4986 (arg
4987 ;; user requests a specific state
4988 (nth (1- (prefix-numeric-value arg))
4989 org-todo-keywords))
4990 ((null member) (car org-todo-keywords))
4991 ((null tail) nil) ;; -> first entry
4992 ((eq org-todo-interpretation 'sequence)
4993 (car tail))
4994 ((memq org-todo-interpretation '(type priority))
4995 (if (eq this-command last-command)
4996 (car tail)
4997 (if (> (length tail) 0) org-done-string nil)))
4998 (t nil)))
4999 (next (if state (concat " " state " ") " ")))
5000 (replace-match next t t)
5001 (setq org-last-todo-state-is-todo
5002 (not (equal state org-done-string)))
5003 (when org-log-done
5004 (if (equal state org-done-string)
5005 (org-add-planning-info 'closed (current-time) 'scheduled)
5006 (if (not this)
5007 (org-add-planning-info nil nil 'closed))))
5008 ;; Fixup tag positioning
5009 (and org-auto-align-tags (org-set-tags nil t))
5010 (run-hooks 'org-after-todo-state-change-hook)))
5011 ;; Fixup cursor location if close to the keyword
5012 (if (and (outline-on-heading-p)
5013 (not (bolp))
5014 (save-excursion (beginning-of-line 1)
5015 (looking-at org-todo-line-regexp))
5016 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5017 (progn
5018 (goto-char (or (match-end 2) (match-end 1)))
5019 (just-one-space))))
5021 (defun org-log-done (&optional undone)
5022 "Add a time stamp logging that a TODO entry has been closed.
5023 When UNDONE is non-nil, remove such a time stamp again."
5024 (interactive)
5025 (let (beg end col)
5026 (save-excursion
5027 (org-back-to-heading t)
5028 (setq beg (point))
5029 (looking-at (concat outline-regexp " *"))
5030 (goto-char (match-end 0))
5031 (setq col (current-column))
5032 (outline-next-heading)
5033 (setq end (point))
5034 (goto-char beg)
5035 (when (re-search-forward (concat
5036 "[\r\n]\\([ \t]*"
5037 (regexp-quote org-closed-string)
5038 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
5039 (delete-region (match-beginning 1) (match-end 1)))
5040 (unless undone
5041 (org-back-to-heading t)
5042 (skip-chars-forward "^\n\r")
5043 (goto-char (min (1+ (point)) (point-max)))
5044 (when (not (member (char-before) '(?\r ?\n)))
5045 (insert "\n"))
5046 (indent-to col)
5047 (insert org-closed-string " "
5048 (format-time-string
5049 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5050 (org-current-time))
5051 "\n")))))
5053 (defun org-show-todo-tree (arg)
5054 "Make a compact tree which shows all headlines marked with TODO.
5055 The tree will show the lines where the regexp matches, and all higher
5056 headlines above the match.
5057 With \\[universal-argument] prefix, also show the DONE entries.
5058 With a numeric prefix N, construct a sparse tree for the Nth element
5059 of `org-todo-keywords'."
5060 (interactive "P")
5061 (let ((case-fold-search nil)
5062 (kwd-re
5063 (cond ((null arg) org-not-done-regexp)
5064 ((equal arg '(4)) org-todo-regexp)
5065 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5066 (regexp-quote (nth (1- (prefix-numeric-value arg))
5067 org-todo-keywords)))
5068 (t (error "Invalid prefix argument: %s" arg)))))
5069 (message "%d TODO entries found"
5070 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5072 (defun org-deadline ()
5073 "Insert the DEADLINE: string to make a deadline.
5074 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5075 to modify it to the correct date."
5076 (interactive)
5077 (org-add-planning-info 'deadline nil 'closed))
5079 (defun org-schedule ()
5080 "Insert the SCHEDULED: string to schedule a TODO item.
5081 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5082 to modify it to the correct date."
5083 (interactive)
5084 (org-add-planning-info 'scheduled nil 'closed))
5086 (defun org-add-planning-info (what &optional time &rest remove)
5087 "Insert new timestamp with keyword in the line directly after the headline.
5088 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5089 If non is given, the user is prompted for a date.
5090 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5091 be removed."
5092 (interactive)
5093 (when what (setq time (or time (org-read-date nil 'to-time))))
5094 (when (and org-insert-labeled-timestamps-at-point
5095 (member what '(scheduled deadline)))
5096 (insert
5097 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
5099 (format-time-string (car org-time-stamp-formats) time))
5100 (setq what nil))
5101 (save-excursion
5102 (let (col list elt (buffer-invisibility-spec nil) ts)
5103 (org-back-to-heading t)
5104 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5105 (goto-char (match-end 1))
5106 (setq col (current-column))
5107 (goto-char (1+ (match-end 0)))
5108 (if (and (not (looking-at outline-regexp))
5109 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5110 "[^\r\n]*"))
5111 (not (equal (match-string 1) org-clock-string)))
5112 (narrow-to-region (match-beginning 0) (match-end 0))
5113 (insert "\n")
5114 (backward-char 1)
5115 (narrow-to-region (point) (point))
5116 (indent-to-column col))
5117 ;; Check if we have to remove something.
5118 (setq list (cons what remove))
5119 (while list
5120 (setq elt (pop list))
5121 (goto-char (point-min))
5122 (when (or (and (eq elt 'scheduled)
5123 (re-search-forward org-scheduled-time-regexp nil t))
5124 (and (eq elt 'deadline)
5125 (re-search-forward org-deadline-time-regexp nil t))
5126 (and (eq elt 'closed)
5127 (re-search-forward org-closed-time-regexp nil t)))
5128 (replace-match "")
5129 (if (looking-at " +") (replace-match ""))))
5130 (goto-char (point-max))
5131 (when what
5132 (insert
5133 (if (not (equal (char-before) ?\ )) " " "")
5134 (cond ((eq what 'scheduled) org-scheduled-string)
5135 ((eq what 'deadline) org-deadline-string)
5136 ((eq what 'closed) org-closed-string))
5137 " ")
5138 (insert
5139 (setq ts
5140 (format-time-string
5141 (if (eq what 'closed)
5142 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5143 (car org-time-stamp-formats))
5144 time))))
5145 (goto-char (point-min))
5146 (widen)
5147 (if (looking-at "[ \t]+\r?\n")
5148 (replace-match ""))
5149 ts)))
5151 (defun org-occur (regexp &optional callback)
5152 "Make a compact tree which shows all matches of REGEXP.
5153 The tree will show the lines where the regexp matches, and all higher
5154 headlines above the match. It will also show the heading after the match,
5155 to make sure editing the matching entry is easy.
5156 If CALLBACK is non-nil, it is a function which is called to confirm
5157 that the match should indeed be shown."
5158 (interactive "sRegexp: ")
5159 (org-remove-occur-highlights nil nil t)
5160 (setq regexp (org-check-occur-regexp regexp))
5161 (let ((cnt 0))
5162 (save-excursion
5163 (goto-char (point-min))
5164 (org-overview)
5165 (while (re-search-forward regexp nil t)
5166 (when (or (not callback)
5167 (save-match-data (funcall callback)))
5168 (setq cnt (1+ cnt))
5169 (org-highlight-new-match (match-beginning 0) (match-end 0))
5170 (org-show-hierarchy-above))))
5171 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5172 nil 'local)
5173 (unless org-sparse-tree-open-archived-trees
5174 (org-hide-archived-subtrees (point-min) (point-max)))
5175 (run-hooks 'org-occur-hook)
5176 (if (interactive-p)
5177 (message "%d match(es) for regexp %s" cnt regexp))
5178 cnt))
5180 (defun org-show-hierarchy-above ()
5181 "Make sure point and the headings hierarchy above is visible."
5182 (catch 'exit
5183 (if (org-on-heading-p t)
5184 (org-flag-heading nil) ; only show the heading
5185 (and (or (org-invisible-p) (org-invisible-p2))
5186 (org-show-hidden-entry))) ; show entire entry
5187 (save-excursion
5188 (and org-show-following-heading
5189 (outline-next-heading)
5190 (org-flag-heading nil))) ; show the next heading
5191 (when org-show-hierarchy-above
5192 (save-excursion ; show all higher headings
5193 (while (and (condition-case nil
5194 (progn (org-up-heading-all 1) t)
5195 (error nil))
5196 (not (bobp)))
5197 (org-flag-heading nil))))))
5199 ;; Overlay compatibility functions
5200 (defun org-make-overlay (beg end &optional buffer)
5201 (if (featurep 'xemacs)
5202 (make-extent beg end buffer)
5203 (make-overlay beg end buffer)))
5204 (defun org-delete-overlay (ovl)
5205 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5206 (defun org-detatch-overlay (ovl)
5207 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5208 (defun org-move-overlay (ovl beg end &optional buffer)
5209 (if (featurep 'xemacs)
5210 (set-extent-endpoints ovl beg end buffer)
5211 (move-overlay ovl beg end buffer)))
5212 (defun org-overlay-put (ovl prop value)
5213 (if (featurep 'xemacs)
5214 (set-extent-property ovl prop value)
5215 (overlay-put ovl prop value)))
5216 (defun org-overlays-at (pos)
5217 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5218 (defun org-overlay-start (o)
5219 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5220 (defun org-overlay-end (o)
5221 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5223 (defvar org-occur-highlights nil)
5224 (make-variable-buffer-local 'org-occur-highlights)
5225 (defun org-highlight-new-match (beg end)
5226 "Highlight from BEG to END and mark the highlight is an occur headline."
5227 (let ((ov (org-make-overlay beg end)))
5228 (org-overlay-put ov 'face 'secondary-selection)
5229 (push ov org-occur-highlights)))
5231 (defvar org-inhibit-highlight-removal nil)
5232 (defun org-remove-occur-highlights (&optional beg end noremove)
5233 "Remove the occur highlights from the buffer.
5234 BEG and END are ignored. If NOREMOVE is nil, remove this function
5235 from the `before-change-functions' in the current buffer."
5236 (interactive)
5237 (unless org-inhibit-highlight-removal
5238 (mapc 'org-delete-overlay org-occur-highlights)
5239 (setq org-occur-highlights nil)
5240 (unless noremove
5241 (remove-hook 'before-change-functions
5242 'org-remove-occur-highlights 'local))))
5244 ;;; Priorities
5246 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5247 "Regular expression matching the priority indicator.")
5249 (defvar org-remove-priority-next-time nil)
5251 (defun org-priority-up ()
5252 "Increase the priority of the current item."
5253 (interactive)
5254 (org-priority 'up))
5256 (defun org-priority-down ()
5257 "Decrease the priority of the current item."
5258 (interactive)
5259 (org-priority 'down))
5261 (defun org-priority (&optional action)
5262 "Change the priority of an item by ARG.
5263 ACTION can be set, up, or down."
5264 (interactive)
5265 (setq action (or action 'set))
5266 (let (current new news have remove)
5267 (save-excursion
5268 (org-back-to-heading)
5269 (if (looking-at org-priority-regexp)
5270 (setq current (string-to-char (match-string 2))
5271 have t)
5272 (setq current org-default-priority))
5273 (cond
5274 ((eq action 'set)
5275 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5276 (setq new (read-char-exclusive))
5277 (cond ((equal new ?\ ) (setq remove t))
5278 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5279 (error "Priority must be between `%c' and `%c'"
5280 ?A org-lowest-priority))))
5281 ((eq action 'up)
5282 (setq new (1- current)))
5283 ((eq action 'down)
5284 (setq new (1+ current)))
5285 (t (error "Invalid action")))
5286 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5287 (setq news (format "%c" new))
5288 (if have
5289 (if remove
5290 (replace-match "" t t nil 1)
5291 (replace-match news t t nil 2))
5292 (if remove
5293 (error "No priority cookie found in line")
5294 (looking-at org-todo-line-regexp)
5295 (if (match-end 2)
5296 (progn
5297 (goto-char (match-end 2))
5298 (insert " [#" news "]"))
5299 (goto-char (match-beginning 3))
5300 (insert "[#" news "] ")))))
5301 (if remove
5302 (message "Priority removed")
5303 (message "Priority of current item set to %s" news))))
5306 (defun org-get-priority (s)
5307 "Find priority cookie and return priority."
5308 (save-match-data
5309 (if (not (string-match org-priority-regexp s))
5310 (* 1000 (- org-lowest-priority org-default-priority))
5311 (* 1000 (- org-lowest-priority
5312 (string-to-char (match-string 2 s)))))))
5314 ;;; Timestamps
5316 (defvar org-last-changed-timestamp nil)
5318 (defun org-time-stamp (arg)
5319 "Prompt for a date/time and insert a time stamp.
5320 If the user specifies a time like HH:MM, or if this command is called
5321 with a prefix argument, the time stamp will contain date and time.
5322 Otherwise, only the date will be included. All parts of a date not
5323 specified by the user will be filled in from the current date/time.
5324 So if you press just return without typing anything, the time stamp
5325 will represent the current date/time. If there is already a timestamp
5326 at the cursor, it will be modified."
5327 (interactive "P")
5328 (let ((fmt (if arg (cdr org-time-stamp-formats)
5329 (car org-time-stamp-formats)))
5330 (org-time-was-given nil)
5331 time)
5332 (cond
5333 ((and (org-at-timestamp-p)
5334 (eq last-command 'org-time-stamp)
5335 (eq this-command 'org-time-stamp))
5336 (insert "--")
5337 (setq time (let ((this-command this-command))
5338 (org-read-date arg 'totime)))
5339 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5340 (insert (format-time-string fmt time)))
5341 ((org-at-timestamp-p)
5342 (setq time (let ((this-command this-command))
5343 (org-read-date arg 'totime)))
5344 (and (org-at-timestamp-p) (replace-match
5345 (setq org-last-changed-timestamp
5346 (format-time-string fmt time))
5347 t t))
5348 (message "Timestamp updated"))
5350 (setq time (let ((this-command this-command))
5351 (org-read-date arg 'totime)))
5352 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5353 (insert (format-time-string fmt time))))))
5355 (defun org-time-stamp-inactive (&optional arg)
5356 "Insert an inactive time stamp.
5357 An inactive time stamp is enclosed in square brackets instead of angle
5358 brackets. It is inactive in the sense that it does not trigger agenda entries,
5359 does not link to the calendar and cannot be changed with the S-cursor keys.
5360 So these are more for recording a certain time/date."
5361 (interactive "P")
5362 (let ((fmt (if arg (cdr org-time-stamp-formats)
5363 (car org-time-stamp-formats)))
5364 (org-time-was-given nil)
5365 time)
5366 (setq time (org-read-date arg 'totime))
5367 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5368 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
5369 (insert (format-time-string fmt time))))
5371 (defvar org-date-ovl (org-make-overlay 1 1))
5372 (org-overlay-put org-date-ovl 'face 'org-warning)
5373 (org-detatch-overlay org-date-ovl)
5375 (defun org-read-date (&optional with-time to-time)
5376 "Read a date and make things smooth for the user.
5377 The prompt will suggest to enter an ISO date, but you can also enter anything
5378 which will at least partially be understood by `parse-time-string'.
5379 Unrecognized parts of the date will default to the current day, month, year,
5380 hour and minute. For example,
5381 3-2-5 --> 2003-02-05
5382 feb 15 --> currentyear-02-15
5383 sep 12 9 --> 2009-09-12
5384 12:45 --> today 12:45
5385 22 sept 0:34 --> currentyear-09-22 0:34
5386 12 --> currentyear-currentmonth-12
5387 Fri --> nearest Friday (today or later)
5388 etc.
5389 The function understands only English month and weekday abbreviations,
5390 but this can be configured with the variables `parse-time-months' and
5391 `parse-time-weekdays'.
5393 While prompting, a calendar is popped up - you can also select the
5394 date with the mouse (button 1). The calendar shows a period of three
5395 months. To scroll it to other months, use the keys `>' and `<'.
5396 If you don't like the calendar, turn it off with
5397 \(setq org-popup-calendar-for-date-prompt nil)
5399 With optional argument TO-TIME, the date will immediately be converted
5400 to an internal time.
5401 With an optional argument WITH-TIME, the prompt will suggest to also
5402 insert a time. Note that when WITH-TIME is not set, you can still
5403 enter a time, and this function will inform the calling routine about
5404 this change. The calling routine may then choose to change the format
5405 used to insert the time stamp into the buffer to include the time."
5406 (require 'parse-time)
5407 (let* ((org-time-stamp-rounding-minutes
5408 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5409 (ct (org-current-time))
5410 (default-time
5411 ;; Default time is either today, or, when entering a range,
5412 ;; the range start.
5413 (if (save-excursion
5414 (re-search-backward
5415 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5416 (- (point) 20) t))
5417 (apply
5418 'encode-time
5419 (mapcar (lambda(x) (or x 0))
5420 (parse-time-string (match-string 1))))
5421 ct))
5422 (calendar-move-hook nil)
5423 (view-diary-entries-initially nil)
5424 (view-calendar-holidays-initially nil)
5425 (timestr (format-time-string
5426 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5427 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5428 ans ans1 ans2
5429 second minute hour day month year tl wday wday1)
5431 (if org-popup-calendar-for-date-prompt
5432 (save-excursion
5433 (save-window-excursion
5434 (calendar)
5435 (calendar-forward-day (- (time-to-days default-time)
5436 (calendar-absolute-from-gregorian
5437 (calendar-current-date))))
5438 (org-eval-in-calendar nil)
5439 (let* ((old-map (current-local-map))
5440 (map (copy-keymap calendar-mode-map))
5441 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5442 (define-key map (kbd "RET") 'org-calendar-select)
5443 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5444 'org-calendar-select-mouse)
5445 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5446 'org-calendar-select-mouse)
5447 (define-key minibuffer-local-map [(meta shift left)]
5448 (lambda () (interactive)
5449 (org-eval-in-calendar '(calendar-backward-month 1))))
5450 (define-key minibuffer-local-map [(meta shift right)]
5451 (lambda () (interactive)
5452 (org-eval-in-calendar '(calendar-forward-month 1))))
5453 (define-key minibuffer-local-map [(shift up)]
5454 (lambda () (interactive)
5455 (org-eval-in-calendar '(calendar-backward-week 1))))
5456 (define-key minibuffer-local-map [(shift down)]
5457 (lambda () (interactive)
5458 (org-eval-in-calendar '(calendar-forward-week 1))))
5459 (define-key minibuffer-local-map [(shift left)]
5460 (lambda () (interactive)
5461 (org-eval-in-calendar '(calendar-backward-day 1))))
5462 (define-key minibuffer-local-map [(shift right)]
5463 (lambda () (interactive)
5464 (org-eval-in-calendar '(calendar-forward-day 1))))
5465 (define-key minibuffer-local-map ">"
5466 (lambda () (interactive)
5467 (org-eval-in-calendar '(scroll-calendar-left 1))))
5468 (define-key minibuffer-local-map "<"
5469 (lambda () (interactive)
5470 (org-eval-in-calendar '(scroll-calendar-right 1))))
5471 (unwind-protect
5472 (progn
5473 (use-local-map map)
5474 (setq ans (read-string prompt "" nil nil))
5475 (if (not (string-match "\\S-" ans)) (setq ans nil))
5476 (setq ans (or ans1 ans ans2)))
5477 (use-local-map old-map)))))
5478 ;; Naked prompt only
5479 (setq ans (read-string prompt "" nil timestr)))
5480 (org-detatch-overlay org-date-ovl)
5482 (if (string-match
5483 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5484 (progn
5485 (setq year (if (match-end 2)
5486 (string-to-number (match-string 2 ans))
5487 (string-to-number (format-time-string "%Y")))
5488 month (string-to-number (match-string 3 ans))
5489 day (string-to-number (match-string 4 ans)))
5490 (if (< year 100) (setq year (+ 2000 year)))
5491 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5492 t nil ans))))
5493 (setq tl (parse-time-string ans)
5494 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5495 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5496 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5497 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5498 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5499 second (or (nth 0 tl) 0)
5500 wday (nth 6 tl))
5501 (when (and wday (not (nth 3 tl)))
5502 ;; Weekday was given, but no day, so pick that day in the week
5503 ;; on or after the derived date.
5504 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5505 (unless (equal wday wday1)
5506 (setq day (+ day (% (- wday wday1 -7) 7)))))
5507 (if (and (boundp 'org-time-was-given)
5508 (nth 2 tl))
5509 (setq org-time-was-given t))
5510 (if (< year 100) (setq year (+ 2000 year)))
5511 (if to-time
5512 (encode-time second minute hour day month year)
5513 (if (or (nth 1 tl) (nth 2 tl))
5514 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5515 (format "%04d-%02d-%02d" year month day)))))
5517 (defun org-eval-in-calendar (form)
5518 "Eval FORM in the calendar window and return to current window.
5519 Also, store the cursor date in variable ans2."
5520 (let ((sw (selected-window)))
5521 (select-window (get-buffer-window "*Calendar*"))
5522 (eval form)
5523 (when (calendar-cursor-to-date)
5524 (let* ((date (calendar-cursor-to-date))
5525 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5526 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5527 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5528 (select-window sw)))
5530 (defun org-calendar-select ()
5531 "Return to `org-read-date' with the date currently selected.
5532 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5533 (interactive)
5534 (when (calendar-cursor-to-date)
5535 (let* ((date (calendar-cursor-to-date))
5536 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5537 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5538 (if (active-minibuffer-window) (exit-minibuffer))))
5540 (defun org-calendar-select-mouse (ev)
5541 "Return to `org-read-date' with the date currently selected.
5542 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5543 (interactive "e")
5544 (mouse-set-point ev)
5545 (when (calendar-cursor-to-date)
5546 (let* ((date (calendar-cursor-to-date))
5547 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5548 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5549 (if (active-minibuffer-window) (exit-minibuffer))))
5551 (defun org-check-deadlines (ndays)
5552 "Check if there are any deadlines due or past due.
5553 A deadline is considered due if it happens within `org-deadline-warning-days'
5554 days from today's date. If the deadline appears in an entry marked DONE,
5555 it is not shown. The prefix arg NDAYS can be used to test that many
5556 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
5557 (interactive "P")
5558 (let* ((org-warn-days
5559 (cond
5560 ((equal ndays '(4)) 100000)
5561 (ndays (prefix-numeric-value ndays))
5562 (t org-deadline-warning-days)))
5563 (case-fold-search nil)
5564 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5565 (callback
5566 (lambda ()
5567 (and (let ((d1 (time-to-days (current-time)))
5568 (d2 (time-to-days
5569 (org-time-string-to-time (match-string 1)))))
5570 (< (- d2 d1) org-warn-days))
5571 (not (org-entry-is-done-p))))))
5572 (message "%d deadlines past-due or due within %d days"
5573 (org-occur regexp callback)
5574 org-warn-days)))
5576 (defun org-evaluate-time-range (&optional to-buffer)
5577 "Evaluate a time range by computing the difference between start and end.
5578 Normally the result is just printed in the echo area, but with prefix arg
5579 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5580 If the time range is actually in a table, the result is inserted into the
5581 next column.
5582 For time difference computation, a year is assumed to be exactly 365
5583 days in order to avoid rounding problems."
5584 (interactive "P")
5585 (save-excursion
5586 (unless (org-at-date-range-p)
5587 (goto-char (point-at-bol))
5588 (re-search-forward org-tr-regexp (point-at-eol) t))
5589 (if (not (org-at-date-range-p))
5590 (error "Not at a time-stamp range, and none found in current line")))
5591 (let* ((ts1 (match-string 1))
5592 (ts2 (match-string 2))
5593 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5594 (match-end (match-end 0))
5595 (time1 (org-time-string-to-time ts1))
5596 (time2 (org-time-string-to-time ts2))
5597 (t1 (time-to-seconds time1))
5598 (t2 (time-to-seconds time2))
5599 (diff (abs (- t2 t1)))
5600 (negative (< (- t2 t1) 0))
5601 ;; (ys (floor (* 365 24 60 60)))
5602 (ds (* 24 60 60))
5603 (hs (* 60 60))
5604 (fy "%dy %dd %02d:%02d")
5605 (fy1 "%dy %dd")
5606 (fd "%dd %02d:%02d")
5607 (fd1 "%dd")
5608 (fh "%02d:%02d")
5609 y d h m align)
5610 (if havetime
5611 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5613 d (floor (/ diff ds)) diff (mod diff ds)
5614 h (floor (/ diff hs)) diff (mod diff hs)
5615 m (floor (/ diff 60)))
5616 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5618 d (floor (+ (/ diff ds) 0.5))
5619 h 0 m 0))
5620 (if (not to-buffer)
5621 (message (org-make-tdiff-string y d h m))
5622 (when (org-at-table-p)
5623 (goto-char match-end)
5624 (setq align t)
5625 (and (looking-at " *|") (goto-char (match-end 0))))
5626 (if (looking-at
5627 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5628 (replace-match ""))
5629 (if negative (insert " -"))
5630 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5631 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5632 (insert " " (format fh h m))))
5633 (if align (org-table-align))
5634 (message "Time difference inserted"))))
5636 (defun org-make-tdiff-string (y d h m)
5637 (let ((fmt "")
5638 (l nil))
5639 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5640 l (push y l)))
5641 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5642 l (push d l)))
5643 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5644 l (push h l)))
5645 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5646 l (push m l)))
5647 (apply 'format fmt (nreverse l))))
5649 (defun org-time-string-to-time (s)
5650 (apply 'encode-time (org-parse-time-string s)))
5652 (defun org-parse-time-string (s &optional nodefault)
5653 "Parse the standard Org-mode time string.
5654 This should be a lot faster than the normal `parse-time-string'.
5655 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5656 hour and minute fields will be nil if not given."
5657 (if (string-match org-ts-regexp1 s)
5658 (list 0
5659 (if (or (match-beginning 8) (not nodefault))
5660 (string-to-number (or (match-string 8 s) "0")))
5661 (if (or (match-beginning 7) (not nodefault))
5662 (string-to-number (or (match-string 7 s) "0")))
5663 (string-to-number (match-string 4 s))
5664 (string-to-number (match-string 3 s))
5665 (string-to-number (match-string 2 s))
5666 nil nil nil)
5667 (make-list 9 0)))
5669 (defun org-timestamp-up (&optional arg)
5670 "Increase the date item at the cursor by one.
5671 If the cursor is on the year, change the year. If it is on the month or
5672 the day, change that.
5673 With prefix ARG, change by that many units."
5674 (interactive "p")
5675 (org-timestamp-change (prefix-numeric-value arg)))
5677 (defun org-timestamp-down (&optional arg)
5678 "Decrease the date item at the cursor by one.
5679 If the cursor is on the year, change the year. If it is on the month or
5680 the day, change that.
5681 With prefix ARG, change by that many units."
5682 (interactive "p")
5683 (org-timestamp-change (- (prefix-numeric-value arg))))
5685 (defun org-timestamp-up-day (&optional arg)
5686 "Increase the date in the time stamp by one day.
5687 With prefix ARG, change that many days."
5688 (interactive "p")
5689 (if (and (not (org-at-timestamp-p))
5690 (org-on-heading-p))
5691 (org-todo 'up)
5692 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5694 (defun org-timestamp-down-day (&optional arg)
5695 "Decrease the date in the time stamp by one day.
5696 With prefix ARG, change that many days."
5697 (interactive "p")
5698 (if (and (not (org-at-timestamp-p))
5699 (org-on-heading-p))
5700 (org-todo 'down)
5701 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5703 (defsubst org-pos-in-match-range (pos n)
5704 (and (match-beginning n)
5705 (<= (match-beginning n) pos)
5706 (>= (match-end n) pos)))
5708 (defun org-at-timestamp-p ()
5709 "Determine if the cursor is in or at a timestamp."
5710 (interactive)
5711 (let* ((tsr org-ts-regexp2)
5712 (pos (point))
5713 (ans (or (looking-at tsr)
5714 (save-excursion
5715 (skip-chars-backward "^<\n\r\t")
5716 (if (> (point) 1) (backward-char 1))
5717 (and (looking-at tsr)
5718 (> (- (match-end 0) pos) -1))))))
5719 (and (boundp 'org-ts-what)
5720 (setq org-ts-what
5721 (cond
5722 ((org-pos-in-match-range pos 2) 'year)
5723 ((org-pos-in-match-range pos 3) 'month)
5724 ((org-pos-in-match-range pos 7) 'hour)
5725 ((org-pos-in-match-range pos 8) 'minute)
5726 ((or (org-pos-in-match-range pos 4)
5727 (org-pos-in-match-range pos 5)) 'day)
5728 (t 'day))))
5729 ans))
5731 (defun org-timestamp-change (n &optional what)
5732 "Change the date in the time stamp at point.
5733 The date will be changed by N times WHAT. WHAT can be `day', `month',
5734 `year', `minute', `second'. If WHAT is not given, the cursor position
5735 in the timestamp determines what will be changed."
5736 (let ((fmt (car org-time-stamp-formats))
5737 org-ts-what
5738 (pos (point))
5739 ts time time0)
5740 (if (not (org-at-timestamp-p))
5741 (error "Not at a timestamp"))
5742 (setq org-ts-what (or what org-ts-what))
5743 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5744 (- (match-end 0) (match-beginning 0))))
5746 (cdr org-time-stamp-formats)
5747 (car org-time-stamp-formats)))
5748 (setq ts (match-string 0))
5749 (replace-match "")
5750 (setq time0 (org-parse-time-string ts))
5751 (setq time
5752 (apply 'encode-time
5753 (append
5754 (list (or (car time0) 0))
5755 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5756 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5757 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5758 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5759 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5760 (nthcdr 6 time0))))
5761 (if (eq what 'calendar)
5762 (let ((cal-date
5763 (save-excursion
5764 (save-match-data
5765 (set-buffer "*Calendar*")
5766 (calendar-cursor-to-date)))))
5767 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5768 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5769 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5770 (setcar time0 (or (car time0) 0))
5771 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5772 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5773 (setq time (apply 'encode-time time0))))
5774 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5775 (goto-char pos)
5776 ;; Try to recenter the calendar window, if any
5777 (if (and org-calendar-follow-timestamp-change
5778 (get-buffer-window "*Calendar*" t)
5779 (memq org-ts-what '(day month year)))
5780 (org-recenter-calendar (time-to-days time)))))
5782 (defun org-recenter-calendar (date)
5783 "If the calendar is visible, recenter it to DATE."
5784 (let* ((win (selected-window))
5785 (cwin (get-buffer-window "*Calendar*" t))
5786 (calendar-move-hook nil))
5787 (when cwin
5788 (select-window cwin)
5789 (calendar-goto-date (if (listp date) date
5790 (calendar-gregorian-from-absolute date)))
5791 (select-window win))))
5793 (defun org-goto-calendar (&optional arg)
5794 "Go to the Emacs calendar at the current date.
5795 If there is a time stamp in the current line, go to that date.
5796 A prefix ARG can be used to force the current date."
5797 (interactive "P")
5798 (let ((tsr org-ts-regexp) diff
5799 (calendar-move-hook nil)
5800 (view-calendar-holidays-initially nil)
5801 (view-diary-entries-initially nil))
5802 (if (or (org-at-timestamp-p)
5803 (save-excursion
5804 (beginning-of-line 1)
5805 (looking-at (concat ".*" tsr))))
5806 (let ((d1 (time-to-days (current-time)))
5807 (d2 (time-to-days
5808 (org-time-string-to-time (match-string 1)))))
5809 (setq diff (- d2 d1))))
5810 (calendar)
5811 (calendar-goto-today)
5812 (if (and diff (not arg)) (calendar-forward-day diff))))
5814 (defun org-date-from-calendar ()
5815 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5816 If there is already a time stamp at the cursor position, update it."
5817 (interactive)
5818 (org-timestamp-change 0 'calendar))
5820 ;;; The clock for measuring work time.
5822 (defvar org-clock-marker (make-marker)
5823 "Marker recording the last clock-in.")
5825 (defun org-clock-in ()
5826 "Start the clock on the current item.
5827 If necessary, clock-out of the currently active clock."
5828 (interactive)
5829 (org-clock-out t)
5830 (let (ts)
5831 (save-excursion
5832 (org-back-to-heading t)
5833 (beginning-of-line 2)
5834 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5835 (not (equal (match-string 1) org-clock-string)))
5836 (beginning-of-line 1))
5837 (insert "\n") (backward-char 1)
5838 (indent-relative)
5839 (insert org-clock-string " "
5840 (setq ts (concat "[" (format-time-string
5841 (substring
5842 (cdr org-time-stamp-formats) 1 -1)
5843 (current-time))
5844 "]")))
5845 (move-marker org-clock-marker (point))
5846 (message "Clock started at %s" ts))))
5848 (defun org-clock-out (&optional fail-quietly)
5849 "Stop the currently running clock.
5850 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
5851 (interactive)
5852 (catch 'exit
5853 (if (not (marker-buffer org-clock-marker))
5854 (if fail-quietly (throw 'exit t) (error "No active clock")))
5855 (let (ts te s h m)
5856 (save-excursion
5857 (set-buffer (marker-buffer org-clock-marker))
5858 (goto-char org-clock-marker)
5859 (beginning-of-line 1)
5860 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5861 (equal (match-string 1) org-clock-string))
5862 (setq ts (match-string 2))
5863 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
5864 (goto-char org-clock-marker)
5865 (setq te (concat "[" (format-time-string
5866 (substring
5867 (cdr org-time-stamp-formats) 1 -1)
5868 (current-time))
5869 "]"))
5870 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
5871 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
5872 h (floor (/ s 3600))
5873 s (- s (* 3600 h))
5874 m (floor (/ s 60))
5875 s (- s (* 60 s)))
5876 (insert "--" te " => " (format "%2d:%02d" h m))
5877 (move-marker org-clock-marker nil)
5878 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
5880 (defun org-clock-cancel ()
5881 "Cancel the running clock be removing the start timestamp."
5882 (interactive)
5883 (if (not (marker-buffer org-clock-marker))
5884 (error "No active clock"))
5885 (save-excursion
5886 (set-buffer (marker-buffer org-clock-marker))
5887 (goto-char org-clock-marker)
5888 (delete-region (1- (point-at-bol)) (point-at-eol)))
5889 (message "Clock canceled"))
5891 (defvar org-clock-file-total-minutes nil
5892 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
5893 (make-variable-buffer-local 'org-clock-file-total-minutes)
5895 (defun org-clock-sum ()
5896 "Sum the times for each subtree.
5897 Puts the resulting times in minutes as a text property on each headline."
5898 (interactive)
5899 (let* ((bmp (buffer-modified-p))
5900 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
5901 org-clock-string
5902 ".*=>[ \t]*\\([0-9]+\\):\\([0-9]+\\)[ \t]*$"))
5903 (lmax 30)
5904 (ltimes (make-vector lmax 0))
5905 (t1 0)
5906 (level 0)
5907 time)
5908 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
5909 (save-excursion
5910 (goto-char (point-max))
5911 (while (re-search-backward re nil t)
5912 (if (match-end 2)
5913 ;; A time
5914 (setq t1 (+ t1 (* 60 (string-to-number (match-string 2)))
5915 (string-to-number (match-string 3))))
5916 ;; A headline
5917 (setq level (- (match-end 1) (match-beginning 1)))
5918 (when (or (> t1 0) (> (aref ltimes level) 0))
5919 (loop for l from 0 to level do
5920 (aset ltimes l (+ (aref ltimes l) t1)))
5921 (setq t1 0 time (aref ltimes level))
5922 (loop for l from level to (1- lmax) do
5923 (aset ltimes l 0))
5924 (goto-char (match-beginning 0))
5925 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
5926 (setq org-clock-file-total-minutes (aref ltimes 0)))
5927 (set-buffer-modified-p bmp)))
5929 (defun org-clock-display (&optional total-only)
5930 "Show subtree times in the entire buffer.
5931 If TOTAL-ONLY is non-nil, only show the total time for the entire file
5932 in the echo area."
5933 (interactive)
5934 (org-remove-clock-overlays)
5935 (let (time h m p)
5936 (org-clock-sum)
5937 (unless total-only
5938 (save-excursion
5939 (goto-char (point-min))
5940 (while (setq p (next-single-property-change (point) :org-clock-minutes))
5941 (goto-char p)
5942 (when (setq time (get-text-property p :org-clock-minutes))
5943 (org-put-clock-overlay time (funcall outline-level))))
5944 (setq h (/ org-clock-file-total-minutes 60)
5945 m (- org-clock-file-total-minutes (* 60 h)))
5946 ;; Arrange to remove the overlays upon next change.
5947 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
5948 nil 'local)))
5949 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
5951 (defvar org-clock-overlays nil)
5952 (make-variable-buffer-local 'org-clock-overlays)
5954 (defun org-put-clock-overlay (time &optional level)
5955 "Put an overlays on the current line, displaying TIME.
5956 If LEVEL is given, prefix time with a corresponding number of stars.
5957 This creates a new overlay and stores it in `org-clock-overlays', so that it
5958 will be easy to remove."
5959 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
5960 (l (if level (org-get-legal-level level 0) 0))
5961 (off 0)
5962 ov tx)
5963 (move-to-column c)
5964 (unless (eolp) (skip-chars-backward "^ \t"))
5965 (skip-chars-backward " \t")
5966 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
5967 tx (concat (buffer-substring (1- (point)) (point))
5968 (make-string (+ off (max 0 (- c (current-column)))) ?.)
5969 (org-add-props (format "%s %2d:%02d%s"
5970 (make-string l ?*) h m
5971 (make-string (- 10 l) ?\ ))
5972 '(face secondary-selection))
5973 ""))
5974 (org-overlay-put ov 'display tx)
5975 (push ov org-clock-overlays)))
5977 (defun org-remove-clock-overlays (&optional beg end noremove)
5978 "Remove the occur highlights from the buffer.
5979 BEG and END are ignored. If NOREMOVE is nil, remove this function
5980 from the `before-change-functions' in the current buffer."
5981 (interactive)
5982 (unless org-inhibit-highlight-removal
5983 (mapc 'org-delete-overlay org-clock-overlays)
5984 (setq org-clock-overlays nil)
5985 (unless noremove
5986 (remove-hook 'before-change-functions
5987 'org-remove-clock-overlays 'local))))
5989 (defun org-clock-out-if-current ()
5990 "Clock out if the current entry contains the running clock.
5991 This is used to stop the clock after a TODO entry is marked DONE."
5992 (when (and (equal state org-done-string)
5993 (equal (marker-buffer org-clock-marker) (current-buffer))
5994 (< (point) org-clock-marker)
5995 (> (save-excursion (outline-next-heading) (point))
5996 org-clock-marker))
5997 (org-clock-out)))
5999 (add-hook 'org-after-todo-state-change-hook
6000 'org-clock-out-if-current)
6002 (defun org-check-running-clock ()
6003 "Check if the current buffer contains the running clock.
6004 If yes, offer to stop it and to save the buffer with the changes."
6005 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6006 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6007 (buffer-name))))
6008 (org-clock-out)
6009 (when (y-or-n-p "Save changed buffer?")
6010 (save-buffer))))
6012 (defun org-clock-report ()
6013 "Create a table containing a report about clocked time.
6014 If the buffer contains lines
6015 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6017 #+END: clocktable
6018 then the table will be inserted between these lines, replacing whatever
6019 is was there before. If these lines are not in the buffer, the table
6020 is inserted at point, surrounded by the special lines.
6021 The BEGIN line can contain parameters. Allowed are:
6022 :maxlevel The maximum level to be included in the table. Default is 3.
6023 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6024 (interactive)
6025 (org-remove-clock-overlays)
6026 (unless (org-find-dblock "clocktable")
6027 (org-create-dblock (list :name "clocktable"
6028 :maxlevel 2 :emphasize nil)))
6029 (org-update-dblock))
6031 (defun org-dblock-write:clocktable (params)
6032 "Write the standard clocktable."
6033 (let ((hlchars '((1 . "*") (2 . ?/)))
6034 (emph nil)
6035 (ins (make-marker))
6036 ipos time h m p level hlc hdl maxlevel)
6037 (setq maxlevel (or (plist-get params :maxlevel) 3)
6038 emph (plist-get params :emphasize))
6039 (move-marker ins (point))
6040 (setq ipos (point))
6041 (insert-before-markers "Clock summary at ["
6042 (substring
6043 (format-time-string (cdr org-time-stamp-formats))
6044 1 -1)
6045 "]\n|L|Headline|Time|\n")
6046 (org-clock-sum)
6047 (setq h (/ org-clock-file-total-minutes 60)
6048 m (- org-clock-file-total-minutes (* 60 h)))
6049 (insert-before-markers "|-\n|0|" "*Total file time*| "
6050 (format "*%d:%02d*" h m)
6051 "|\n")
6052 (goto-char (point-min))
6053 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6054 (goto-char p)
6055 (when (setq time (get-text-property p :org-clock-minutes))
6056 (beginning-of-line 1)
6057 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6058 (setq level (- (match-end 1) (match-beginning 1)))
6059 (<= level maxlevel))
6060 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6061 hdl (match-string 2)
6062 h (/ time 60)
6063 m (- time (* 60 h)))
6064 (save-excursion
6065 (goto-char ins)
6066 (if (= level 1) (insert-before-markers "|-\n"))
6067 (insert-before-markers
6068 "| " (int-to-string level) "|" hlc hdl hlc " |"
6069 (make-string (1- level) ?|)
6071 (format "%d:%02d" h m)
6073 " |\n")))))
6074 (goto-char ins)
6075 (backward-delete-char 1)
6076 (goto-char ipos)
6077 (skip-chars-forward "^|")
6078 (org-table-align)))
6080 (defun org-collect-clock-time-entries ()
6081 "Return an internal list with clocking information.
6082 This list has one entry for each CLOCK interval.
6083 FIXME: describe the elements."
6084 (interactive)
6085 (let ((re (concat "^[ \t]*" org-clock-string
6086 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6087 rtn beg end next cont level title total closedp leafp
6088 clockpos titlepos h m donep)
6089 (save-excursion
6090 (org-clock-sum)
6091 (goto-char (point-min))
6092 (while (re-search-forward re nil t)
6093 (setq clockpos (match-beginning 0)
6094 beg (match-string 1) end (match-string 2)
6095 cont (match-end 0))
6096 (setq beg (apply 'encode-time (org-parse-time-string beg))
6097 end (apply 'encode-time (org-parse-time-string end)))
6098 (org-back-to-heading t)
6099 (setq donep (org-entry-is-done-p))
6100 (setq titlepos (point)
6101 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6102 h (/ total 60) m (- total (* 60 h))
6103 total (cons h m))
6104 (looking-at "\\(\\*+\\) +\\(.*\\)")
6105 (setq level (- (match-end 1) (match-beginning 1))
6106 title (org-match-string-no-properties 2))
6107 (save-excursion (outline-next-heading) (setq next (point)))
6108 (setq closedp (re-search-forward org-closed-time-regexp next t))
6109 (goto-char next)
6110 (setq leafp (and (looking-at "^\\*+ ")
6111 (<= (- (match-end 0) (point)) level)))
6112 (push (list beg end clockpos closedp donep
6113 total title titlepos level leafp)
6114 rtn)
6115 (goto-char cont)))
6116 (nreverse rtn)))
6118 ;;; Agenda, and Diary Integration
6120 ;;; Define the mode
6122 (defvar org-agenda-mode-map (make-sparse-keymap)
6123 "Keymap for `org-agenda-mode'.")
6125 (defvar org-agenda-menu) ; defined later in this file.
6126 (defvar org-agenda-follow-mode nil)
6127 (defvar org-agenda-show-log nil)
6128 (defvar org-agenda-buffer-name "*Org Agenda*")
6129 (defvar org-agenda-redo-command nil)
6130 (defvar org-agenda-mode-hook nil)
6131 (defvar org-agenda-type nil)
6132 (defvar org-agenda-force-single-file nil)
6134 (defun org-agenda-mode ()
6135 "Mode for time-sorted view on action items in Org-mode files.
6137 The following commands are available:
6139 \\{org-agenda-mode-map}"
6140 (interactive)
6141 (kill-all-local-variables)
6142 (setq major-mode 'org-agenda-mode)
6143 (setq mode-name "Org-Agenda")
6144 (use-local-map org-agenda-mode-map)
6145 (easy-menu-add org-agenda-menu)
6146 (if org-startup-truncated (setq truncate-lines t))
6147 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6148 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6149 (unless org-agenda-keep-modes
6150 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6151 org-agenda-show-log nil))
6152 (easy-menu-change
6153 '("Agenda") "Agenda Files"
6154 (append
6155 (list
6156 (vector
6157 (if (get 'org-agenda-files 'org-restrict)
6158 "Restricted to single file"
6159 "Edit File List")
6160 '(org-edit-agenda-file-list)
6161 (not (get 'org-agenda-files 'org-restrict)))
6162 "--")
6163 (mapcar 'org-file-menu-entry (org-agenda-files))))
6164 (org-agenda-set-mode-name)
6165 (apply
6166 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6167 (list 'org-agenda-mode-hook)))
6169 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6170 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6171 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6172 (define-key org-agenda-mode-map " " 'org-agenda-show)
6173 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6174 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6175 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6176 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6177 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6178 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6179 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6180 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6181 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6182 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6183 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6184 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6185 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6187 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6188 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6189 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6190 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6191 (while l (define-key org-agenda-mode-map
6192 (int-to-string (pop l)) 'digit-argument)))
6194 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6195 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6196 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6197 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6198 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6199 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6200 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6201 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6202 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6203 (define-key org-agenda-mode-map "n" 'next-line)
6204 (define-key org-agenda-mode-map "p" 'previous-line)
6205 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6206 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6207 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6208 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6209 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6210 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6211 (eval-after-load "calendar"
6212 '(define-key calendar-mode-map org-calendar-to-agenda-key
6213 'org-calendar-goto-agenda))
6214 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6215 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6216 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6217 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
6218 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6219 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6220 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6221 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6222 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6223 (define-key org-agenda-mode-map "O" 'org-clock-out)
6224 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6225 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6226 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6227 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6228 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6229 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6230 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6231 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6232 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6233 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6234 "Local keymap for agenda entries from Org-mode.")
6236 (define-key org-agenda-keymap
6237 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6238 (define-key org-agenda-keymap
6239 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6240 (when org-agenda-mouse-1-follows-link
6241 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6242 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6243 '("Agenda"
6244 ("Agenda Files")
6245 "--"
6246 ["Show" org-agenda-show t]
6247 ["Go To (other window)" org-agenda-goto t]
6248 ["Go To (one window)" org-agenda-switch-to t]
6249 ["Follow Mode" org-agenda-follow-mode
6250 :style toggle :selected org-agenda-follow-mode :active t]
6251 "--"
6252 ["Cycle TODO" org-agenda-todo t]
6253 ("Tags"
6254 ["Show all Tags" org-agenda-show-tags t]
6255 ["Set Tags" org-agenda-set-tags t])
6256 ("Schedule"
6257 ["Schedule" org-agenda-schedule t]
6258 ["Set Deadline" org-agenda-deadline t]
6259 "--"
6260 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6261 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6262 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6263 ("Priority"
6264 ["Set Priority" org-agenda-priority t]
6265 ["Increase Priority" org-agenda-priority-up t]
6266 ["Decrease Priority" org-agenda-priority-down t]
6267 ["Show Priority" org-agenda-show-priority t])
6268 "--"
6269 ;; ["New agenda command" org-agenda t]
6270 ["Rebuild buffer" org-agenda-redo t]
6271 "--"
6272 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6273 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6274 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6275 "--"
6276 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6277 :style radio :selected (equal org-agenda-ndays 1)]
6278 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6279 :style radio :selected (equal org-agenda-ndays 7)]
6280 "--"
6281 ["Show Logbook entries" org-agenda-log-mode
6282 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6283 ["Include Diary" org-agenda-toggle-diary
6284 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6285 ["Use Time Grid" org-agenda-toggle-time-grid
6286 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6287 "--"
6288 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6289 ("Calendar Commands"
6290 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6291 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6292 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6293 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6294 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6295 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6296 "--"
6297 ["Quit" org-agenda-quit t]
6298 ["Exit and Release Buffers" org-agenda-exit t]
6301 ;;;###autoload
6302 (defun org-agenda (arg)
6303 "Dispatch agenda commands to collect entries to the agenda buffer.
6304 Prompts for a character to select a command. Any prefix arg will be passed
6305 on to the selected command. The default selections are:
6307 a Call `org-agenda' to display the agenda for the current day or week.
6308 t Call `org-todo-list' to display the global todo list.
6309 T Call `org-todo-list' to display the global todo list, select only
6310 entries with a specific TODO keyword (the user gets a prompt).
6311 m Call `org-tags-view' to display headlines with tags matching
6312 a condition (the user is prompted for the condition).
6313 M Like `m', but select only TODO entries, no ordinary headlines.
6315 More commands can be added by configuring the variable
6316 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
6317 searches can be pre-defined in this way.
6319 If the current buffer is in Org-mode and visiting a file, you can also
6320 first press `1' to indicate that the agenda should be temporarily (until the
6321 next use of \\[org-agenda]) restricted to the current file."
6322 (interactive "P")
6323 (catch 'exit
6324 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
6325 (bfn buffer-file-name)
6326 (custom org-agenda-custom-commands)
6327 c entry key type string)
6328 (put 'org-agenda-files 'org-restrict nil)
6329 (save-window-excursion
6330 (delete-other-windows)
6331 (switch-to-buffer-other-window " *Agenda Commands*")
6332 (erase-buffer)
6333 (insert
6334 "Press key for an agenda command:
6335 --------------------------------
6336 a Agenda for current week or day
6337 t List of all TODO entries T Entries with special TODO kwd
6338 m Match a TAGS query M Like m, but only TODO entries
6339 C Configure your own agenda commands")
6340 (while (setq entry (pop custom))
6341 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
6342 (insert (format "\n%-4s%-14s: %s"
6344 (cond
6345 ((eq type 'tags) "Tags query")
6346 ((eq type 'todo) "TODO keyword")
6347 ((eq type 'tags-tree) "Tags tree")
6348 ((eq type 'todo-tree) "TODO kwd tree")
6349 ((eq type 'occur-tree) "Occur tree")
6350 (t "???"))
6351 (org-add-props string nil 'face 'org-warning))))
6352 (goto-char (point-min))
6353 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
6354 (message "Press key for agenda command%s"
6355 (if restrict-ok ", or [1] to restrict to current file" ""))
6356 (setq c (read-char-exclusive))
6357 (message "")
6358 (when (equal c ?1)
6359 (if restrict-ok
6360 (put 'org-agenda-files 'org-restrict (list bfn))
6361 (error "Cannot restrict agenda to current buffer"))
6362 (message "Press key for agenda command%s"
6363 (if restrict-ok " (restricted to current file)" ""))
6364 (setq c (read-char-exclusive))
6365 (message "")))
6366 (require 'calendar) ; FIXME: can we avoid this for some commands?
6367 ;; For example the todo list should not need it (but does...)
6368 (cond
6369 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
6370 ((equal c ?a) (call-interactively 'org-agenda-list))
6371 ((equal c ?t) (call-interactively 'org-todo-list))
6372 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
6373 ((equal c ?m) (call-interactively 'org-tags-view))
6374 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
6375 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
6376 (setq type (nth 1 entry) string (nth 2 entry))
6377 (cond
6378 ((eq type 'tags)
6379 (org-tags-view current-prefix-arg string))
6380 ((eq type 'tags-todo)
6381 (org-tags-view '(4) string))
6382 ((eq type 'todo)
6383 (org-todo-list string))
6384 ((eq type 'tags-tree)
6385 (org-check-for-org-mode)
6386 (org-tags-sparse-tree current-prefix-arg string))
6387 ((eq type 'todo-tree)
6388 (org-check-for-org-mode)
6389 (org-occur (concat "^" outline-regexp "[ \t]*"
6390 (regexp-quote string) "\\>")))
6391 ((eq type 'occur-tree)
6392 (org-check-for-org-mode)
6393 (org-occur string))
6394 (t (error "Invalid custom agenda command type %s" type))))
6395 (t (error "Invalid key"))))))
6397 (defun org-check-for-org-mode ()
6398 "Make sure current buffer is in org-mode. Error if not."
6399 (or (eq major-mode 'org-mode)
6400 (error "Cannot execute org-mode agenda command on buffer in %s."
6401 major-mode)))
6403 (defun org-fit-agenda-window ()
6404 "Fit the window to the buffer size."
6405 (and org-fit-agenda-window
6406 (fboundp 'fit-window-to-buffer)
6407 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
6408 (/ (frame-height) 2))))
6410 (defun org-agenda-files (&optional unrestricted)
6411 "Get the list of agenda files.
6412 Optional UNRESTRICTED means return the full list even if a restriction
6413 is currently in place."
6414 (cond
6415 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
6416 ((stringp org-agenda-files) (org-read-agenda-file-list))
6417 ((listp org-agenda-files) org-agenda-files)
6418 (t (error "Invalid value of `org-agenda-files'"))))
6420 (defvar org-window-configuration)
6422 (defun org-edit-agenda-file-list ()
6423 "Edit the list of agenda files.
6424 Depending on setup, this either uses customize to edit the variable
6425 `org-agenda-files', or it visits the file that is holding the list. In the
6426 latter case, the buffer is set up in a way that saving it automatically kills
6427 the buffer and restores the previous window configuration."
6428 (interactive)
6429 (if (stringp org-agenda-files)
6430 (let ((cw (current-window-configuration)))
6431 (find-file org-agenda-files)
6432 (set (make-local-variable 'org-window-configuration) cw)
6433 (org-add-hook 'after-save-hook
6434 (lambda ()
6435 (set-window-configuration
6436 (prog1 org-window-configuration
6437 (kill-buffer (current-buffer))))
6438 (org-install-agenda-files-menu)
6439 (message "New agenda file list installed"))
6440 nil 'local)
6441 (message (substitute-command-keys
6442 "Edit list and finish with \\[save-buffer]")))
6443 (customize-variable 'org-agenda-files)))
6445 (defun org-store-new-agenda-file-list (list)
6446 "Set new value for the agenda file list and save it correcly."
6447 (if (stringp org-agenda-files)
6448 (let ((f org-agenda-files) b)
6449 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
6450 (with-temp-file f
6451 (insert (mapconcat 'identity list "\n") "\n")))
6452 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
6453 (setq org-agenda-files list)
6454 (customize-save-variable 'org-agenda-files org-agenda-files))))
6456 (defun org-read-agenda-file-list ()
6457 "Read the list of agenda files from a file."
6458 (when (stringp org-agenda-files)
6459 (with-temp-buffer
6460 (insert-file-contents org-agenda-files)
6461 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
6463 (defvar org-agenda-markers nil
6464 "List of all currently active markers created by `org-agenda'.")
6465 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
6466 "Creation time of the last agenda marker.")
6468 (defun org-agenda-new-marker (&optional pos)
6469 "Return a new agenda marker.
6470 Org-mode keeps a list of these markers and resets them when they are
6471 no longer in use."
6472 (let ((m (copy-marker (or pos (point)))))
6473 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
6474 (push m org-agenda-markers)
6477 (defun org-agenda-maybe-reset-markers (&optional force)
6478 "Reset markers created by `org-agenda'. But only if they are old enough."
6479 (if (or force
6480 (> (- (time-to-seconds (current-time))
6481 org-agenda-last-marker-time)
6483 (while org-agenda-markers
6484 (move-marker (pop org-agenda-markers) nil))))
6486 (defvar org-agenda-new-buffers nil
6487 "Buffers created to visit agenda files.")
6489 (defun org-get-agenda-file-buffer (file)
6490 "Get a buffer visiting FILE. If the buffer needs to be created, add
6491 it to the list of buffers which might be released later."
6492 (let ((buf (find-buffer-visiting file)))
6493 (if buf
6494 buf ; just return it
6495 ;; Make a new buffer and remember it
6496 (setq buf (find-file-noselect file))
6497 (if buf (push buf org-agenda-new-buffers))
6498 buf)))
6500 (defun org-release-buffers (blist)
6501 "Release all buffers in list, asking the user for confirmation when needed.
6502 When a buffer is unmodified, it is just killed. When modified, it is saved
6503 \(if the user agrees) and then killed."
6504 (let (buf file)
6505 (while (setq buf (pop blist))
6506 (setq file (buffer-file-name buf))
6507 (when (and (buffer-modified-p buf)
6508 file
6509 (y-or-n-p (format "Save file %s? " file)))
6510 (with-current-buffer buf (save-buffer)))
6511 (kill-buffer buf))))
6513 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
6515 (defun org-timeline (&optional include-all keep-modes)
6516 "Show a time-sorted view of the entries in the current org file.
6517 Only entries with a time stamp of today or later will be listed. With
6518 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
6519 under the current date.
6520 If the buffer contains an active region, only check the region for
6521 dates."
6522 (interactive "P")
6523 (require 'calendar)
6524 (org-agenda-maybe-reset-markers 'force)
6525 (org-compile-prefix-format org-timeline-prefix-format)
6526 (let* ((dopast t)
6527 (dotodo include-all)
6528 (doclosed org-agenda-show-log)
6529 (org-agenda-keep-modes keep-modes)
6530 (entry buffer-file-name)
6531 (org-agenda-files (list buffer-file-name))
6532 (date (calendar-current-date))
6533 (win (selected-window))
6534 (pos1 (point))
6535 (beg (if (org-region-active-p) (region-beginning) (point-min)))
6536 (end (if (org-region-active-p) (region-end) (point-max)))
6537 (day-numbers (org-get-all-dates beg end 'no-ranges
6538 t doclosed ; always include today
6539 org-timeline-show-empty-dates))
6540 (today (time-to-days (current-time)))
6541 (org-respect-restriction t)
6542 (past t)
6543 args
6544 s e rtn d emptyp)
6545 (org-prepare-agenda-buffers org-agenda-files)
6546 (setq org-agenda-redo-command
6547 (list 'progn
6548 (list 'switch-to-buffer-other-window (current-buffer))
6549 (list 'org-timeline (list 'quote include-all) t)))
6550 (if (not dopast)
6551 ;; Remove past dates from the list of dates.
6552 (setq day-numbers (delq nil (mapcar (lambda(x)
6553 (if (>= x today) x nil))
6554 day-numbers))))
6555 (switch-to-buffer-other-window
6556 (get-buffer-create org-agenda-buffer-name))
6557 (setq buffer-read-only nil)
6558 (erase-buffer)
6559 (org-agenda-mode) (setq buffer-read-only nil)
6560 (set (make-local-variable 'org-agenda-type) 'timeline)
6561 (if doclosed (push :closed args))
6562 (push :timestamp args)
6563 (if dotodo (push :todo args))
6564 (while (setq d (pop day-numbers))
6565 (if (and (listp d) (eq (car d) :omitted))
6566 (progn
6567 (setq s (point))
6568 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
6569 (put-text-property s (1- (point)) 'face 'org-level-3))
6570 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
6571 (if (and (>= d today)
6572 dopast
6573 past)
6574 (progn
6575 (setq past nil)
6576 (insert (make-string 79 ?-) "\n")))
6577 (setq date (calendar-gregorian-from-absolute d))
6578 (setq s (point))
6579 (setq rtn (and (not emptyp)
6580 (apply 'org-agenda-get-day-entries
6581 entry date args)))
6582 (if (or rtn (equal d today) org-timeline-show-empty-dates)
6583 (progn
6584 (insert (calendar-day-name date) " "
6585 (number-to-string (extract-calendar-day date)) " "
6586 (calendar-month-name (extract-calendar-month date)) " "
6587 (number-to-string (extract-calendar-year date)) "\n")
6588 (put-text-property s (1- (point)) 'face
6589 'org-level-3)
6590 (if (equal d today)
6591 (put-text-property s (1- (point)) 'org-today t))
6592 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
6593 (put-text-property s (1- (point)) 'day d)))))
6594 (goto-char (point-min))
6595 (setq buffer-read-only t)
6596 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6597 (point-min)))
6598 (when (not org-select-timeline-window)
6599 (select-window win)
6600 (goto-char pos1))))
6602 ;;;###autoload
6603 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
6604 "Produce a weekly view from all files in variable `org-agenda-files'.
6605 The view will be for the current week, but from the overview buffer you
6606 will be able to go to other weeks.
6607 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
6608 also be shown, under the current date.
6609 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
6610 on the days are also shown. See the variable `org-log-done' for how
6611 to turn on logging.
6612 START-DAY defaults to TODAY, or to the most recent match for the weekday
6613 given in `org-agenda-start-on-weekday'.
6614 NDAYS defaults to `org-agenda-ndays'."
6615 (interactive "P")
6616 (org-agenda-maybe-reset-markers 'force)
6617 (org-compile-prefix-format org-agenda-prefix-format)
6618 (require 'calendar)
6619 (let* ((org-agenda-start-on-weekday
6620 (if (or (equal ndays 1)
6621 (and (null ndays) (equal 1 org-agenda-ndays)))
6622 nil org-agenda-start-on-weekday))
6623 (org-agenda-keep-modes keep-modes)
6624 (thefiles (org-agenda-files))
6625 (files thefiles)
6626 (win (selected-window))
6627 (today (time-to-days (current-time)))
6628 (sd (or start-day today))
6629 (start (if (or (null org-agenda-start-on-weekday)
6630 (< org-agenda-ndays 7))
6632 (let* ((nt (calendar-day-of-week
6633 (calendar-gregorian-from-absolute sd)))
6634 (n1 org-agenda-start-on-weekday)
6635 (d (- nt n1)))
6636 (- sd (+ (if (< d 0) 7 0) d)))))
6637 (day-numbers (list start))
6638 (inhibit-redisplay t)
6639 s e rtn rtnall file date d start-pos end-pos todayp nd)
6640 (org-prepare-agenda-buffers files)
6641 (setq org-agenda-redo-command
6642 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
6643 ;; Make the list of days
6644 (setq ndays (or ndays org-agenda-ndays)
6645 nd ndays)
6646 (while (> ndays 1)
6647 (push (1+ (car day-numbers)) day-numbers)
6648 (setq ndays (1- ndays)))
6649 (setq day-numbers (nreverse day-numbers))
6650 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6651 (progn
6652 (delete-other-windows)
6653 (switch-to-buffer-other-window
6654 (get-buffer-create org-agenda-buffer-name))))
6655 (setq buffer-read-only nil)
6656 (erase-buffer)
6657 (org-agenda-mode) (setq buffer-read-only nil)
6658 (set (make-local-variable 'org-agenda-type) 'agenda)
6659 (set (make-local-variable 'starting-day) (car day-numbers))
6660 (set (make-local-variable 'include-all-loc) include-all)
6661 (when (and (or include-all org-agenda-include-all-todo)
6662 (member today day-numbers))
6663 (setq files thefiles
6664 rtnall nil)
6665 (while (setq file (pop files))
6666 (catch 'nextfile
6667 (org-check-agenda-file file)
6668 (setq date (calendar-gregorian-from-absolute today)
6669 rtn (org-agenda-get-day-entries
6670 file date :todo))
6671 (setq rtnall (append rtnall rtn))))
6672 (when rtnall
6673 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
6674 (add-text-properties (point-min) (1- (point))
6675 (list 'face 'org-level-3))
6676 (insert (org-finalize-agenda-entries rtnall) "\n")))
6677 (while (setq d (pop day-numbers))
6678 (setq date (calendar-gregorian-from-absolute d)
6679 s (point))
6680 (if (or (setq todayp (= d today))
6681 (and (not start-pos) (= d sd)))
6682 (setq start-pos (point))
6683 (if (and start-pos (not end-pos))
6684 (setq end-pos (point))))
6685 (setq files thefiles
6686 rtnall nil)
6687 (while (setq file (pop files))
6688 (catch 'nextfile
6689 (org-check-agenda-file file)
6690 (if org-agenda-show-log
6691 (setq rtn (org-agenda-get-day-entries
6692 file date
6693 :deadline :scheduled :timestamp :closed))
6694 (setq rtn (org-agenda-get-day-entries
6695 file date
6696 :deadline :scheduled :timestamp)))
6697 (setq rtnall (append rtnall rtn))))
6698 (if org-agenda-include-diary
6699 (progn
6700 (require 'diary-lib)
6701 (setq rtn (org-get-entries-from-diary date))
6702 (setq rtnall (append rtnall rtn))))
6703 (if (or rtnall org-agenda-show-all-dates)
6704 (progn
6705 (insert (format "%-9s %2d %s %4d\n"
6706 (calendar-day-name date)
6707 (extract-calendar-day date)
6708 (calendar-month-name (extract-calendar-month date))
6709 (extract-calendar-year date)))
6710 (put-text-property s (1- (point)) 'face
6711 'org-level-3)
6712 (if rtnall (insert
6713 (org-finalize-agenda-entries
6714 (org-agenda-add-time-grid-maybe
6715 rtnall nd todayp))
6716 "\n"))
6717 (put-text-property s (1- (point)) 'day d))))
6718 (goto-char (point-min))
6719 (setq buffer-read-only t)
6720 (org-fit-agenda-window)
6721 (unless (and (pos-visible-in-window-p (point-min))
6722 (pos-visible-in-window-p (point-max)))
6723 (goto-char (1- (point-max)))
6724 (recenter -1)
6725 (if (not (pos-visible-in-window-p (or start-pos 1)))
6726 (progn
6727 (goto-char (or start-pos 1))
6728 (recenter 1))))
6729 (goto-char (or start-pos 1))
6730 (if (not org-select-agenda-window) (select-window win))
6731 (message "")))
6733 (defvar org-select-this-todo-keyword nil)
6735 ;;;###autoload
6736 (defun org-todo-list (arg &optional keep-modes)
6737 "Show all TODO entries from all agenda file in a single list.
6738 The prefix arg can be used to select a specific TODO keyword and limit
6739 the list to these. When using \\[universal-argument], you will be prompted
6740 for a keyword. A numeric prefix directly selects the Nth keyword in
6741 `org-todo-keywords'."
6742 (interactive "P")
6743 (org-agenda-maybe-reset-markers 'force)
6744 (org-compile-prefix-format org-agenda-prefix-format)
6745 (let* ((org-agenda-keep-modes keep-modes)
6746 (today (time-to-days (current-time)))
6747 (date (calendar-gregorian-from-absolute today))
6748 (win (selected-window))
6749 (kwds org-todo-keywords)
6750 (completion-ignore-case t)
6751 (org-select-this-todo-keyword
6752 (if (stringp arg) arg
6753 (and arg (integerp arg) (> arg 0)
6754 (nth (1- arg) org-todo-keywords))))
6755 rtn rtnall files file pos)
6756 (when (equal arg '(4))
6757 (setq org-select-this-todo-keyword
6758 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
6759 nil t)))
6760 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
6761 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6762 (progn
6763 (delete-other-windows)
6764 (switch-to-buffer-other-window
6765 (get-buffer-create org-agenda-buffer-name))))
6766 (setq buffer-read-only nil)
6767 (erase-buffer)
6768 (org-agenda-mode) (setq buffer-read-only nil)
6769 (set (make-local-variable 'org-agenda-type) 'todo)
6770 (set (make-local-variable 'last-arg) arg)
6771 (set (make-local-variable 'org-todo-keywords) kwds)
6772 (set (make-local-variable 'org-agenda-redo-command)
6773 '(org-todo-list (or current-prefix-arg last-arg) t))
6774 (setq files (org-agenda-files)
6775 rtnall nil)
6776 (org-prepare-agenda-buffers files)
6777 (while (setq file (pop files))
6778 (catch 'nextfile
6779 (org-check-agenda-file file)
6780 (setq rtn (org-agenda-get-day-entries file date :todo))
6781 (setq rtnall (append rtnall rtn))))
6782 (insert "Global list of TODO items of type: ")
6783 (add-text-properties (point-min) (1- (point))
6784 (list 'face 'org-level-3))
6785 (setq pos (point))
6786 (insert (or org-select-this-todo-keyword "ALL") "\n")
6787 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6788 (setq pos (point))
6789 (insert
6790 "Available with `N r': (0)ALL "
6791 (let ((n 0))
6792 (mapconcat (lambda (x)
6793 (format "(%d)%s" (setq n (1+ n)) x))
6794 org-todo-keywords " "))
6795 "\n")
6796 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
6797 (when rtnall
6798 (insert (org-finalize-agenda-entries rtnall) "\n"))
6799 (goto-char (point-min))
6800 (setq buffer-read-only t)
6801 (org-fit-agenda-window)
6802 (if (not org-select-agenda-window) (select-window win))))
6804 (defun org-check-agenda-file (file)
6805 "Make sure FILE exists. If not, ask user what to do."
6806 (when (not (file-exists-p file))
6807 (message "non-existent file %s. [R]emove from list or [A]bort?"
6808 (abbreviate-file-name file))
6809 (let ((r (downcase (read-char-exclusive))))
6810 (cond
6811 ((equal r ?r)
6812 (org-remove-file file)
6813 (throw 'nextfile t))
6814 (t (error "Abort"))))))
6816 (defun org-agenda-check-type (error &rest types)
6817 "Check if agenda buffer is of allowed type.
6818 If ERROR is non-nil, throw an error, otherwise just return nil."
6819 (if (memq org-agenda-type types)
6821 (if error
6822 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
6823 nil)))
6825 (defun org-agenda-quit ()
6826 "Exit agenda by removing the window or the buffer."
6827 (interactive)
6828 (let ((buf (current-buffer)))
6829 (if (not (one-window-p)) (delete-window))
6830 (kill-buffer buf)
6831 (org-agenda-maybe-reset-markers 'force)))
6833 (defun org-agenda-exit ()
6834 "Exit agenda by removing the window or the buffer.
6835 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
6836 Org-mode buffers visited directly by the user will not be touched."
6837 (interactive)
6838 (org-release-buffers org-agenda-new-buffers)
6839 (setq org-agenda-new-buffers nil)
6840 (org-agenda-quit))
6842 (defun org-agenda-redo ()
6843 "Rebuild Agenda.
6844 When this is the global TODO list, a prefix argument will be interpreted."
6845 (interactive)
6846 (message "Rebuilding agenda buffer...")
6847 (eval org-agenda-redo-command)
6848 (message "Rebuilding agenda buffer...done"))
6850 (defun org-agenda-goto-today ()
6851 "Go to today."
6852 (interactive)
6853 (org-agenda-check-type t 'timeline 'agenda)
6854 (if (boundp 'starting-day)
6855 (let ((cmd (car org-agenda-redo-command))
6856 (iall (nth 1 org-agenda-redo-command))
6857 (nday (nth 3 org-agenda-redo-command))
6858 (keep (nth 4 org-agenda-redo-command)))
6859 (eval (list cmd iall nil nday keep)))
6860 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6861 (point-min)))))
6863 (defun org-agenda-later (arg)
6864 "Go forward in time by `org-agenda-ndays' days.
6865 With prefix ARG, go forward that many times `org-agenda-ndays'."
6866 (interactive "p")
6867 (org-agenda-check-type t 'agenda)
6868 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6869 (+ starting-day (* arg org-agenda-ndays)) nil t))
6871 (defun org-agenda-earlier (arg)
6872 "Go back in time by `org-agenda-ndays' days.
6873 With prefix ARG, go back that many times `org-agenda-ndays'."
6874 (interactive "p")
6875 (org-agenda-check-type t 'agenda)
6876 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6877 (- starting-day (* arg org-agenda-ndays)) nil t))
6879 (defun org-agenda-week-view ()
6880 "Switch to weekly view for agenda."
6881 (interactive)
6882 (org-agenda-check-type t 'agenda)
6883 (setq org-agenda-ndays 7)
6884 (org-agenda-list include-all-loc
6885 (or (get-text-property (point) 'day)
6886 starting-day)
6887 nil t)
6888 (org-agenda-set-mode-name)
6889 (message "Switched to week view"))
6891 (defun org-agenda-day-view ()
6892 "Switch to daily view for agenda."
6893 (interactive)
6894 (org-agenda-check-type t 'agenda)
6895 (setq org-agenda-ndays 1)
6896 (org-agenda-list include-all-loc
6897 (or (get-text-property (point) 'day)
6898 starting-day)
6899 nil t)
6900 (org-agenda-set-mode-name)
6901 (message "Switched to day view"))
6903 (defun org-agenda-next-date-line (&optional arg)
6904 "Jump to the next line indicating a date in agenda buffer."
6905 (interactive "p")
6906 (org-agenda-check-type t 'agenda 'timeline)
6907 (beginning-of-line 1)
6908 (if (looking-at "^\\S-") (forward-char 1))
6909 (if (not (re-search-forward "^\\S-" nil t arg))
6910 (progn
6911 (backward-char 1)
6912 (error "No next date after this line in this buffer")))
6913 (goto-char (match-beginning 0)))
6915 (defun org-agenda-previous-date-line (&optional arg)
6916 "Jump to the previous line indicating a date in agenda buffer."
6917 (interactive "p")
6918 (org-agenda-check-type t 'agenda 'timeline)
6919 (beginning-of-line 1)
6920 (if (not (re-search-backward "^\\S-" nil t arg))
6921 (error "No previous date before this line in this buffer")))
6923 ;; Initialize the highlight
6924 (defvar org-hl (org-make-overlay 1 1))
6925 (org-overlay-put org-hl 'face 'highlight)
6927 (defun org-highlight (begin end &optional buffer)
6928 "Highlight a region with overlay."
6929 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
6930 org-hl begin end (or buffer (current-buffer))))
6932 (defun org-unhighlight ()
6933 "Detach overlay INDEX."
6934 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
6937 (defun org-agenda-follow-mode ()
6938 "Toggle follow mode in an agenda buffer."
6939 (interactive)
6940 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
6941 (org-agenda-set-mode-name)
6942 (message "Follow mode is %s"
6943 (if org-agenda-follow-mode "on" "off")))
6945 (defun org-agenda-log-mode ()
6946 "Toggle log mode in an agenda buffer."
6947 (interactive)
6948 (org-agenda-check-type t 'agenda 'timeline)
6949 (setq org-agenda-show-log (not org-agenda-show-log))
6950 (org-agenda-set-mode-name)
6951 (org-agenda-redo)
6952 (message "Log mode is %s"
6953 (if org-agenda-show-log "on" "off")))
6955 (defun org-agenda-toggle-diary ()
6956 "Toggle diary inclusion in an agenda buffer."
6957 (interactive)
6958 (org-agenda-check-type t 'agenda)
6959 (setq org-agenda-include-diary (not org-agenda-include-diary))
6960 (org-agenda-redo)
6961 (org-agenda-set-mode-name)
6962 (message "Diary inclusion turned %s"
6963 (if org-agenda-include-diary "on" "off")))
6965 (defun org-agenda-toggle-time-grid ()
6966 "Toggle time grid in an agenda buffer."
6967 (interactive)
6968 (org-agenda-check-type t 'agenda)
6969 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
6970 (org-agenda-redo)
6971 (org-agenda-set-mode-name)
6972 (message "Time-grid turned %s"
6973 (if org-agenda-use-time-grid "on" "off")))
6975 (defun org-agenda-set-mode-name ()
6976 "Set the mode name to indicate all the small mode settings."
6977 (setq mode-name
6978 (concat "Org-Agenda"
6979 (if (equal org-agenda-ndays 1) " Day" "")
6980 (if (equal org-agenda-ndays 7) " Week" "")
6981 (if org-agenda-follow-mode " Follow" "")
6982 (if org-agenda-include-diary " Diary" "")
6983 (if org-agenda-use-time-grid " Grid" "")
6984 (if org-agenda-show-log " Log" "")))
6985 (force-mode-line-update))
6987 (defun org-agenda-post-command-hook ()
6988 (and (eolp) (not (bolp)) (backward-char 1))
6989 (if (and org-agenda-follow-mode
6990 (get-text-property (point) 'org-marker))
6991 (org-agenda-show)))
6993 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
6995 (defun org-get-entries-from-diary (date)
6996 "Get the (Emacs Calendar) diary entries for DATE."
6997 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
6998 (diary-display-hook '(fancy-diary-display))
6999 (list-diary-entries-hook
7000 (cons 'org-diary-default-entry list-diary-entries-hook))
7001 (diary-file-name-prefix-function nil) ; turn this feature off
7002 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7003 entries
7004 (org-disable-agenda-to-diary t))
7005 (save-excursion
7006 (save-window-excursion
7007 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7008 (if (not (get-buffer fancy-diary-buffer))
7009 (setq entries nil)
7010 (with-current-buffer fancy-diary-buffer
7011 (setq buffer-read-only nil)
7012 (if (= (point-max) 1)
7013 ;; No entries
7014 (setq entries nil)
7015 ;; Omit the date and other unnecessary stuff
7016 (org-agenda-cleanup-fancy-diary)
7017 ;; Add prefix to each line and extend the text properties
7018 (if (= (point-max) 1)
7019 (setq entries nil)
7020 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7021 (set-buffer-modified-p nil)
7022 (kill-buffer fancy-diary-buffer)))
7023 (when entries
7024 (setq entries (org-split-string entries "\n"))
7025 (setq entries
7026 (mapcar
7027 (lambda (x)
7028 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7029 ;; Extend the text properties to the beginning of the line
7030 (org-add-props x (text-properties-at (1- (length x)) x)))
7031 entries)))))
7033 (defun org-agenda-cleanup-fancy-diary ()
7034 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7035 This gets rid of the date, the underline under the date, and
7036 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7037 date. It also removes lines that contain only whitespace."
7038 (goto-char (point-min))
7039 (if (looking-at ".*?:[ \t]*")
7040 (progn
7041 (replace-match "")
7042 (re-search-forward "\n=+$" nil t)
7043 (replace-match "")
7044 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7045 (re-search-forward "\n=+$" nil t)
7046 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7047 (goto-char (point-min))
7048 (while (re-search-forward "^ +\n" nil t)
7049 (replace-match ""))
7050 (goto-char (point-min))
7051 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7052 (replace-match "")))
7054 ;; Make sure entries from the diary have the right text properties.
7055 (eval-after-load "diary-lib"
7056 '(if (boundp 'diary-modify-entry-list-string-function)
7057 ;; We can rely on the hook, nothing to do
7059 ;; Hook not avaiable, must use advice to make this work
7060 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7061 "Make the position visible."
7062 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7063 (stringp string)
7064 buffer-file-name)
7065 (setq string (org-modify-diary-entry-string string))))))
7067 (defun org-modify-diary-entry-string (string)
7068 "Add text properties to string, allowing org-mode to act on it."
7069 (org-add-props string nil
7070 'mouse-face 'highlight
7071 'keymap org-agenda-keymap
7072 'help-echo (format "mouse-2 or RET jump to diary file %s"
7073 (abbreviate-file-name buffer-file-name))
7074 'org-agenda-diary-link t
7075 'org-marker (org-agenda-new-marker (point-at-bol))))
7077 (defun org-diary-default-entry ()
7078 "Add a dummy entry to the diary.
7079 Needed to avoid empty dates which mess up holiday display."
7080 ;; Catch the error if dealing with the new add-to-diary-alist
7081 (when org-disable-agenda-to-diary
7082 (condition-case nil
7083 (add-to-diary-list original-date "Org-mode dummy" "")
7084 (error
7085 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7087 (defun org-cycle-agenda-files ()
7088 "Cycle through the files in `org-agenda-files'.
7089 If the current buffer visits an agenda file, find the next one in the list.
7090 If the current buffer does not, find the first agenda file."
7091 (interactive)
7092 (let* ((fs (org-agenda-files t))
7093 (files (append fs (list (car fs))))
7094 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7095 file)
7096 (unless files (error "No agenda files"))
7097 (catch 'exit
7098 (while (setq file (pop files))
7099 (if (equal (file-truename file) tcf)
7100 (when (car files)
7101 (find-file (car files))
7102 (throw 'exit t))))
7103 (find-file (car fs)))))
7105 (defun org-agenda-file-to-end ()
7106 "Move/add the current file to the end of the agenda file list.
7107 If the file is not present in the list, it is appended to the list. If it is
7108 present, it is moved there."
7109 (interactive)
7110 (org-agenda-file-to-front 'to-end))
7112 (defun org-agenda-file-to-front (&optional to-end)
7113 "Move/add the current file to the top of the agenda file list.
7114 If the file is not present in the list, it is added to the front. If it is
7115 present, it is moved there. With optional argument TO-END, add/move to the
7116 end of the list."
7117 (interactive "P")
7118 (let ((file-alist (mapcar (lambda (x)
7119 (cons (file-truename x) x))
7120 (org-agenda-files t)))
7121 (ctf (file-truename buffer-file-name))
7122 x had)
7123 (setq x (assoc ctf file-alist) had x)
7125 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7126 (if to-end
7127 (setq file-alist (append (delq x file-alist) (list x)))
7128 (setq file-alist (cons x (delq x file-alist))))
7129 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7130 (org-install-agenda-files-menu)
7131 (message "File %s to %s of agenda file list"
7132 (if had "moved" "added") (if to-end "end" "front"))))
7134 (defun org-remove-file (&optional file)
7135 "Remove current file from the list of files in variable `org-agenda-files'.
7136 These are the files which are being checked for agenda entries.
7137 Optional argument FILE means, use this file instead of the current."
7138 (interactive)
7139 (let* ((file (or file buffer-file-name))
7140 (true-file (file-truename file))
7141 (afile (abbreviate-file-name file))
7142 (files (delq nil (mapcar
7143 (lambda (x)
7144 (if (equal true-file
7145 (file-truename x))
7146 nil x))
7147 (org-agenda-files t)))))
7148 (if (not (= (length files) (length (org-agenda-files t))))
7149 (progn
7150 (org-store-new-agenda-file-list files)
7151 (org-install-agenda-files-menu)
7152 (message "Removed file: %s" afile))
7153 (message "File was not in list: %s" afile))))
7155 (defun org-file-menu-entry (file)
7156 (vector file (list 'find-file file) t))
7158 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7159 "Return a list of all relevant day numbers from BEG to END buffer positions.
7160 If NO-RANGES is non-nil, include only the start and end dates of a range,
7161 not every single day in the range. If FORCE-TODAY is non-nil, make
7162 sure that TODAY is included in the list. If INACTIVE is non-nil, also
7163 inactive time stamps (those in square brackets) are included.
7164 When EMPTY is non-nil, also include days without any entries."
7165 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
7166 dates dates1 date day day1 day2 ts1 ts2)
7167 (if force-today
7168 (setq dates (list (time-to-days (current-time)))))
7169 (save-excursion
7170 (goto-char beg)
7171 (while (re-search-forward re end t)
7172 (setq day (time-to-days (org-time-string-to-time
7173 (substring (match-string 1) 0 10))))
7174 (or (memq day dates) (push day dates)))
7175 (unless no-ranges
7176 (goto-char beg)
7177 (while (re-search-forward org-tr-regexp end t)
7178 (setq ts1 (substring (match-string 1) 0 10)
7179 ts2 (substring (match-string 2) 0 10)
7180 day1 (time-to-days (org-time-string-to-time ts1))
7181 day2 (time-to-days (org-time-string-to-time ts2)))
7182 (while (< (setq day1 (1+ day1)) day2)
7183 (or (memq day1 dates) (push day1 dates)))))
7184 (setq dates (sort dates '<))
7185 (when empty
7186 (while (setq day (pop dates))
7187 (setq day2 (car dates))
7188 (push day dates1)
7189 (when (and day2 empty)
7190 (if (or (eq empty t)
7191 (and (numberp empty) (<= (- day2 day) empty)))
7192 (while (< (setq day (1+ day)) day2)
7193 (push (list day) dates1))
7194 (push (cons :omitted (- day2 day)) dates1))))
7195 (setq dates (nreverse dates1)))
7196 dates)))
7198 ;;;###autoload
7199 (defun org-diary (&rest args)
7200 "Return diary information from org-files.
7201 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
7202 It accesses org files and extracts information from those files to be
7203 listed in the diary. The function accepts arguments specifying what
7204 items should be listed. The following arguments are allowed:
7206 :timestamp List the headlines of items containing a date stamp or
7207 date range matching the selected date. Deadlines will
7208 also be listed, on the expiration day.
7210 :deadline List any deadlines past due, or due within
7211 `org-deadline-warning-days'. The listing occurs only
7212 in the diary for *today*, not at any other date. If
7213 an entry is marked DONE, it is no longer listed.
7215 :scheduled List all items which are scheduled for the given date.
7216 The diary for *today* also contains items which were
7217 scheduled earlier and are not yet marked DONE.
7219 :todo List all TODO items from the org-file. This may be a
7220 long list - so this is not turned on by default.
7221 Like deadlines, these entries only show up in the
7222 diary for *today*, not at any other date.
7224 The call in the diary file should look like this:
7226 &%%(org-diary) ~/path/to/some/orgfile.org
7228 Use a separate line for each org file to check. Or, if you omit the file name,
7229 all files listed in `org-agenda-files' will be checked automatically:
7231 &%%(org-diary)
7233 If you don't give any arguments (as in the example above), the default
7234 arguments (:deadline :scheduled :timestamp) are used. So the example above may
7235 also be written as
7237 &%%(org-diary :deadline :timestamp :scheduled)
7239 The function expects the lisp variables `entry' and `date' to be provided
7240 by the caller, because this is how the calendar works. Don't use this
7241 function from a program - use `org-agenda-get-day-entries' instead."
7242 (org-agenda-maybe-reset-markers)
7243 (org-compile-prefix-format org-agenda-prefix-format)
7244 (setq args (or args '(:deadline :scheduled :timestamp)))
7245 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
7246 (list entry)
7247 (org-agenda-files t)))
7248 file rtn results)
7249 ;; If this is called during org-agenda, don't return any entries to
7250 ;; the calendar. Org Agenda will list these entries itself.
7251 (if org-disable-agenda-to-diary (setq files nil))
7252 (while (setq file (pop files))
7253 (setq rtn (apply 'org-agenda-get-day-entries file date args))
7254 (setq results (append results rtn)))
7255 (if results
7256 (concat (org-finalize-agenda-entries results) "\n"))))
7257 (defvar org-category-table nil)
7258 (defun org-get-category-table ()
7259 "Get the table of categories and positions in current buffer."
7260 (let (tbl)
7261 (save-excursion
7262 (goto-char (point-min))
7263 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
7264 (push (cons (point) (org-trim (match-string 2))) tbl)))
7265 tbl))
7266 (defun org-get-category (&optional pos)
7267 "Get the category applying to position POS."
7268 (if (not org-category-table)
7269 (cond
7270 ((null org-category)
7271 (setq org-category
7272 (if buffer-file-name
7273 (file-name-sans-extension
7274 (file-name-nondirectory buffer-file-name))
7275 "???")))
7276 ((symbolp org-category) (symbol-name org-category))
7277 (t org-category))
7278 (let ((tbl org-category-table)
7279 (pos (or pos (point))))
7280 (while (and tbl (> (caar tbl) pos))
7281 (pop tbl))
7282 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
7283 org-category-table))))))
7285 (defun org-agenda-get-day-entries (file date &rest args)
7286 "Does the work for `org-diary' and `org-agenda'.
7287 FILE is the path to a file to be checked for entries. DATE is date like
7288 the one returned by `calendar-current-date'. ARGS are symbols indicating
7289 which kind of entries should be extracted. For details about these, see
7290 the documentation of `org-diary'."
7291 (setq args (or args '(:deadline :scheduled :timestamp)))
7292 (let* ((org-startup-with-deadline-check nil)
7293 (org-startup-folded nil)
7294 (org-startup-align-all-tables nil)
7295 (buffer (if (file-exists-p file)
7296 (org-get-agenda-file-buffer file)
7297 (error "No such file %s" file)))
7298 arg results rtn)
7299 (if (not buffer)
7300 ;; If file does not exist, make sure an error message ends up in diary
7301 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7302 (with-current-buffer buffer
7303 (unless (eq major-mode 'org-mode)
7304 (error "Agenda file %s is not in `org-mode'" file))
7305 (setq org-category-table (org-get-category-table))
7306 (let ((case-fold-search nil))
7307 (save-excursion
7308 (save-restriction
7309 (if org-respect-restriction
7310 (if (org-region-active-p)
7311 ;; Respect a region to restrict search
7312 (narrow-to-region (region-beginning) (region-end)))
7313 ;; If we work for the calendar or many files,
7314 ;; get rid of any restriction
7315 (widen))
7316 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
7317 (while (setq arg (pop args))
7318 (cond
7319 ((and (eq arg :todo)
7320 (equal date (calendar-current-date)))
7321 (setq rtn (org-agenda-get-todos))
7322 (setq results (append results rtn)))
7323 ((eq arg :timestamp)
7324 (setq rtn (org-agenda-get-blocks))
7325 (setq results (append results rtn))
7326 (setq rtn (org-agenda-get-timestamps))
7327 (setq results (append results rtn)))
7328 ((eq arg :scheduled)
7329 (setq rtn (org-agenda-get-scheduled))
7330 (setq results (append results rtn)))
7331 ((eq arg :closed)
7332 (setq rtn (org-agenda-get-closed))
7333 (setq results (append results rtn)))
7334 ((and (eq arg :deadline)
7335 (equal date (calendar-current-date)))
7336 (setq rtn (org-agenda-get-deadlines))
7337 (setq results (append results rtn))))))))
7338 results))))
7340 (defun org-entry-is-done-p ()
7341 "Is the current entry marked DONE?"
7342 (save-excursion
7343 (and (re-search-backward "[\r\n]\\*" nil t)
7344 (looking-at org-nl-done-regexp))))
7346 (defun org-at-date-range-p ()
7347 "Is the cursor inside a date range?"
7348 (interactive)
7349 (save-excursion
7350 (catch 'exit
7351 (let ((pos (point)))
7352 (skip-chars-backward "^<\r\n")
7353 (skip-chars-backward "<")
7354 (and (looking-at org-tr-regexp)
7355 (>= (match-end 0) pos)
7356 (throw 'exit t))
7357 (skip-chars-backward "^<\r\n")
7358 (skip-chars-backward "<")
7359 (and (looking-at org-tr-regexp)
7360 (>= (match-end 0) pos)
7361 (throw 'exit t)))
7362 nil)))
7364 (defun org-agenda-get-todos ()
7365 "Return the TODO information for agenda display."
7366 (let* ((props (list 'face nil
7367 'done-face 'org-done
7368 'org-not-done-regexp org-not-done-regexp
7369 'mouse-face 'highlight
7370 'keymap org-agenda-keymap
7371 'help-echo
7372 (format "mouse-2 or RET jump to org file %s"
7373 (abbreviate-file-name buffer-file-name))))
7374 (regexp (concat "[\n\r]\\*+ *\\("
7375 (if org-select-this-todo-keyword
7376 (concat "\\<\\(" org-select-this-todo-keyword
7377 "\\)\\>")
7378 org-not-done-regexp)
7379 "[^\n\r]*\\)"))
7380 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
7381 marker priority category tags
7382 ee txt)
7383 (goto-char (point-min))
7384 (while (re-search-forward regexp nil t)
7385 (catch :skip
7386 (and org-agenda-todo-ignore-scheduled
7387 (looking-at sched-re)
7388 (throw :skip nil))
7389 (org-agenda-skip)
7390 (goto-char (match-beginning 1))
7391 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
7392 category (org-get-category)
7393 tags (org-get-tags-at (point))
7394 txt (org-format-agenda-item "" (match-string 1) category tags)
7395 priority
7396 (+ (org-get-priority txt)
7397 (if org-todo-kwd-priority-p
7398 (- org-todo-kwd-max-priority -2
7399 (length
7400 (member (match-string 2) org-todo-keywords)))
7401 1)))
7402 (org-add-props txt props
7403 'org-marker marker 'org-hd-marker marker
7404 'priority priority 'category category)
7405 (push txt ee)
7406 (if org-agenda-todo-list-sublevels
7407 (goto-char (match-end 1))
7408 (org-end-of-subtree 'invisible))))
7409 (nreverse ee)))
7411 (defconst org-agenda-no-heading-message
7412 "No heading for this item in buffer or region.")
7414 (defun org-agenda-get-timestamps ()
7415 "Return the date stamp information for agenda display."
7416 (let* ((props (list 'face nil
7417 'org-not-done-regexp org-not-done-regexp
7418 'mouse-face 'highlight
7419 'keymap org-agenda-keymap
7420 'help-echo
7421 (format "mouse-2 or RET jump to org file %s"
7422 (abbreviate-file-name buffer-file-name))))
7423 (regexp (regexp-quote
7424 (substring
7425 (format-time-string
7426 (car org-time-stamp-formats)
7427 (apply 'encode-time ; DATE bound by calendar
7428 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7429 0 11)))
7430 marker hdmarker deadlinep scheduledp donep tmp priority category
7431 ee txt timestr tags)
7432 (goto-char (point-min))
7433 (while (re-search-forward regexp nil t)
7434 (catch :skip
7435 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
7436 (org-agenda-skip)
7437 (setq marker (org-agenda-new-marker (match-beginning 0))
7438 category (org-get-category (match-beginning 0))
7439 tmp (buffer-substring (max (point-min)
7440 (- (match-beginning 0)
7441 org-ds-keyword-length))
7442 (match-beginning 0))
7443 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7444 deadlinep (string-match org-deadline-regexp tmp)
7445 scheduledp (string-match org-scheduled-regexp tmp)
7446 donep (org-entry-is-done-p))
7447 (if (string-match ">" timestr)
7448 ;; substring should only run to end of time stamp
7449 (setq timestr (substring timestr 0 (match-end 0))))
7450 (save-excursion
7451 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7452 (progn
7453 (goto-char (match-end 1))
7454 (setq hdmarker (org-agenda-new-marker)
7455 tags (org-get-tags-at))
7456 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7457 (setq txt (org-format-agenda-item
7458 (format "%s%s"
7459 (if deadlinep "Deadline: " "")
7460 (if scheduledp "Scheduled: " ""))
7461 (match-string 1) category tags timestr)))
7462 (setq txt org-agenda-no-heading-message))
7463 (setq priority (org-get-priority txt))
7464 (org-add-props txt props
7465 'org-marker marker 'org-hd-marker hdmarker)
7466 (if deadlinep
7467 (org-add-props txt nil
7468 'face (if donep 'org-done 'org-warning)
7469 'undone-face 'org-warning 'done-face 'org-done
7470 'category category 'priority (+ 100 priority))
7471 (if scheduledp
7472 (org-add-props txt nil
7473 'face 'org-scheduled-today
7474 'undone-face 'org-scheduled-today 'done-face 'org-done
7475 'category category 'priority (+ 99 priority))
7476 (org-add-props txt nil 'priority priority 'category category)))
7477 (push txt ee))
7478 (outline-next-heading)))
7479 (nreverse ee)))
7481 (defun org-agenda-get-closed ()
7482 "Return the logged TODO entries for agenda display."
7483 (let* ((props (list 'mouse-face 'highlight
7484 'org-not-done-regexp org-not-done-regexp
7485 'keymap org-agenda-keymap
7486 'help-echo
7487 (format "mouse-2 or RET jump to org file %s"
7488 (abbreviate-file-name buffer-file-name))))
7489 (regexp (concat
7490 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
7491 (regexp-quote
7492 (substring
7493 (format-time-string
7494 (car org-time-stamp-formats)
7495 (apply 'encode-time ; DATE bound by calendar
7496 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7497 1 11))))
7498 marker hdmarker priority category tags closedp
7499 ee txt timestr)
7500 (goto-char (point-min))
7501 (while (re-search-forward regexp nil t)
7502 (catch :skip
7503 (org-agenda-skip)
7504 (setq marker (org-agenda-new-marker (match-beginning 0))
7505 closedp (equal (match-string 1) org-closed-string)
7506 category (org-get-category (match-beginning 0))
7507 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7508 ;; donep (org-entry-is-done-p)
7510 (if (string-match "\\]" timestr)
7511 ;; substring should only run to end of time stamp
7512 (setq timestr (substring timestr 0 (match-end 0))))
7513 (save-excursion
7514 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7515 (progn
7516 (goto-char (match-end 1))
7517 (setq hdmarker (org-agenda-new-marker)
7518 tags (org-get-tags-at))
7519 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7520 (setq txt (org-format-agenda-item
7521 (if closedp "Closed: " "Clocked: ")
7522 (match-string 1) category tags timestr)))
7523 (setq txt org-agenda-no-heading-message))
7524 (setq priority 100000)
7525 (org-add-props txt props
7526 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
7527 'priority priority 'category category
7528 'undone-face 'org-warning 'done-face 'org-done)
7529 (push txt ee))
7530 (outline-next-heading)))
7531 (nreverse ee)))
7533 (defun org-agenda-get-deadlines ()
7534 "Return the deadline information for agenda display."
7535 (let* ((wdays org-deadline-warning-days)
7536 (props (list 'mouse-face 'highlight
7537 'org-not-done-regexp org-not-done-regexp
7538 'keymap org-agenda-keymap
7539 'help-echo
7540 (format "mouse-2 or RET jump to org file %s"
7541 (abbreviate-file-name buffer-file-name))))
7542 (regexp org-deadline-time-regexp)
7543 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7544 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7545 d2 diff pos pos1 category tags
7546 ee txt head face)
7547 (goto-char (point-min))
7548 (while (re-search-forward regexp nil t)
7549 (catch :skip
7550 (org-agenda-skip)
7551 (setq pos (1- (match-beginning 1))
7552 d2 (time-to-days
7553 (org-time-string-to-time (match-string 1)))
7554 diff (- d2 d1))
7555 ;; When to show a deadline in the calendar:
7556 ;; If the expiration is within wdays warning time.
7557 ;; Past-due deadlines are only shown on the current date
7558 (if (and (< diff wdays) todayp (not (= diff 0)))
7559 (save-excursion
7560 (setq category (org-get-category))
7561 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7562 (progn
7563 (goto-char (match-end 0))
7564 (setq pos1 (match-end 1))
7565 (setq tags (org-get-tags-at pos1))
7566 (setq head (buffer-substring-no-properties
7567 (point)
7568 (progn (skip-chars-forward "^\r\n")
7569 (point))))
7570 (if (string-match org-looking-at-done-regexp head)
7571 (setq txt nil)
7572 (setq txt (org-format-agenda-item
7573 (format "In %3d d.: " diff) head category tags))))
7574 (setq txt org-agenda-no-heading-message))
7575 (when txt
7576 (setq face (cond ((<= diff 0) 'org-warning)
7577 ((<= diff 5) 'org-upcoming-deadline)
7578 (t nil)))
7579 (org-add-props txt props
7580 'org-marker (org-agenda-new-marker pos)
7581 'org-hd-marker (org-agenda-new-marker pos1)
7582 'priority (+ (- 10 diff) (org-get-priority txt))
7583 'category category
7584 'face face 'undone-face face 'done-face 'org-done)
7585 (push txt ee))))))
7586 ee))
7588 (defun org-agenda-get-scheduled ()
7589 "Return the scheduled information for agenda display."
7590 (let* ((props (list 'face 'org-scheduled-previously
7591 'org-not-done-regexp org-not-done-regexp
7592 'undone-face 'org-scheduled-previously
7593 'done-face 'org-done
7594 'mouse-face 'highlight
7595 'keymap org-agenda-keymap
7596 'help-echo
7597 (format "mouse-2 or RET jump to org file %s"
7598 (abbreviate-file-name buffer-file-name))))
7599 (regexp org-scheduled-time-regexp)
7600 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7601 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7602 d2 diff pos pos1 category tags
7603 ee txt head)
7604 (goto-char (point-min))
7605 (while (re-search-forward regexp nil t)
7606 (catch :skip
7607 (org-agenda-skip)
7608 (setq pos (1- (match-beginning 1))
7609 d2 (time-to-days
7610 (org-time-string-to-time (match-string 1)))
7611 diff (- d2 d1))
7612 ;; When to show a scheduled item in the calendar:
7613 ;; If it is on or past the date.
7614 (if (and (< diff 0) todayp)
7615 (save-excursion
7616 (setq category (org-get-category))
7617 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7618 (progn
7619 (goto-char (match-end 0))
7620 (setq pos1 (match-end 1))
7621 (setq tags (org-get-tags-at))
7622 (setq head (buffer-substring-no-properties
7623 (point)
7624 (progn (skip-chars-forward "^\r\n") (point))))
7625 (if (string-match org-looking-at-done-regexp head)
7626 (setq txt nil)
7627 (setq txt (org-format-agenda-item
7628 (format "Sched.%2dx: " (- 1 diff)) head
7629 category tags))))
7630 (setq txt org-agenda-no-heading-message))
7631 (when txt
7632 (org-add-props txt props
7633 'org-marker (org-agenda-new-marker pos)
7634 'org-hd-marker (org-agenda-new-marker pos1)
7635 'priority (+ (- 5 diff) (org-get-priority txt))
7636 'category category)
7637 (push txt ee))))))
7638 ee))
7640 (defun org-agenda-get-blocks ()
7641 "Return the date-range information for agenda display."
7642 (let* ((props (list 'face nil
7643 'org-not-done-regexp org-not-done-regexp
7644 'mouse-face 'highlight
7645 'keymap org-agenda-keymap
7646 'help-echo
7647 (format "mouse-2 or RET jump to org file %s"
7648 (abbreviate-file-name buffer-file-name))))
7649 (regexp org-tr-regexp)
7650 (d0 (calendar-absolute-from-gregorian date))
7651 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
7652 (goto-char (point-min))
7653 (while (re-search-forward regexp nil t)
7654 (catch :skip
7655 (org-agenda-skip)
7656 (setq timestr (match-string 0)
7657 s1 (match-string 1)
7658 s2 (match-string 2)
7659 d1 (time-to-days (org-time-string-to-time s1))
7660 d2 (time-to-days (org-time-string-to-time s2)))
7661 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
7662 ;; Only allow days between the limits, because the normal
7663 ;; date stamps will catch the limits.
7664 (save-excursion
7665 (setq marker (org-agenda-new-marker (point)))
7666 (setq category (org-get-category))
7667 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7668 (progn
7669 (setq hdmarker (org-agenda-new-marker (match-end 1)))
7670 (goto-char (match-end 1))
7671 (setq tags (org-get-tags-at))
7672 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7673 (setq txt (org-format-agenda-item
7674 (format (if (= d1 d2) "" "(%d/%d): ")
7675 (1+ (- d0 d1)) (1+ (- d2 d1)))
7676 (match-string 1) category tags
7677 (if (= d0 d1) timestr))))
7678 (setq txt org-agenda-no-heading-message))
7679 (org-add-props txt props
7680 'org-marker marker 'org-hd-marker hdmarker
7681 'priority (org-get-priority txt) 'category category)
7682 (push txt ee)))
7683 (outline-next-heading)))
7684 ;; Sort the entries by expiration date.
7685 (nreverse ee)))
7687 (defconst org-plain-time-of-day-regexp
7688 (concat
7689 "\\(\\<[012]?[0-9]"
7690 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7691 "\\(--?"
7692 "\\(\\<[012]?[0-9]"
7693 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7694 "\\)?")
7695 "Regular expression to match a plain time or time range.
7696 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
7697 groups carry important information:
7698 0 the full match
7699 1 the first time, range or not
7700 8 the second time, if it is a range.")
7702 (defconst org-stamp-time-of-day-regexp
7703 (concat
7704 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
7705 "\\([012][0-9]:[0-5][0-9]\\)>"
7706 "\\(--?"
7707 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
7708 "Regular expression to match a timestamp time or time range.
7709 After a match, the following groups carry important information:
7710 0 the full match
7711 1 date plus weekday, for backreferencing to make sure both times on same day
7712 2 the first time, range or not
7713 4 the second time, if it is a range.")
7715 (defvar org-prefix-has-time nil
7716 "A flag, set by `org-compile-prefix-format'.
7717 The flag is set if the currently compiled format contains a `%t'.")
7718 (defvar org-prefix-has-tag nil
7719 "A flag, set by `org-compile-prefix-format'.
7720 The flag is set if the currently compiled format contains a `%T'.")
7722 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
7723 "Format TXT to be inserted into the agenda buffer.
7724 In particular, it adds the prefix and corresponding text properties. EXTRA
7725 must be a string and replaces the `%s' specifier in the prefix format.
7726 CATEGORY (string, symbol or nil) may be used to overrule the default
7727 category taken from local variable or file name. It will replace the `%c'
7728 specifier in the format. DOTIME, when non-nil, indicates that a
7729 time-of-day should be extracted from TXT for sorting of this entry, and for
7730 the `%t' specifier in the format. When DOTIME is a string, this string is
7731 searched for a time before TXT is. NOPREFIX is a flag and indicates that
7732 only the correctly processes TXT should be returned - this is used by
7733 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
7734 (save-match-data
7735 ;; Diary entries sometimes have extra whitespace at the beginning
7736 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
7737 (let* ((category (or category
7738 org-category
7739 (if buffer-file-name
7740 (file-name-sans-extension
7741 (file-name-nondirectory buffer-file-name))
7742 "")))
7743 (tag (if tags (nth (1- (length tags)) tags) ""))
7744 time ;; needed for the eval of the prefix format
7745 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
7746 (time-of-day (and dotime (org-get-time-of-day ts)))
7747 stamp plain s0 s1 s2 rtn)
7748 (when (and dotime time-of-day org-prefix-has-time)
7749 ;; Extract starting and ending time and move them to prefix
7750 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
7751 (setq plain (string-match org-plain-time-of-day-regexp ts)))
7752 (setq s0 (match-string 0 ts)
7753 s1 (match-string (if plain 1 2) ts)
7754 s2 (match-string (if plain 8 4) ts))
7756 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
7757 ;; them, we might want to remove them there to avoid duplication.
7758 ;; The user can turn this off with a variable.
7759 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
7760 (string-match (concat (regexp-quote s0) " *") txt)
7761 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
7762 (= (match-beginning 0) 0)
7764 (setq txt (replace-match "" nil nil txt))))
7765 ;; Normalize the time(s) to 24 hour
7766 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
7767 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
7769 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
7770 ;; Tags are in the string
7771 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
7772 (and org-agenda-remove-tags-when-in-prefix
7773 org-prefix-has-tag))
7774 (setq txt (replace-match "" t t txt))
7775 (setq txt (replace-match
7776 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
7777 (match-string 2 txt))
7778 t t txt))))
7780 ;; Create the final string
7781 (if noprefix
7782 (setq rtn txt)
7783 ;; Prepare the variables needed in the eval of the compiled format
7784 (setq time (cond (s2 (concat s1 "-" s2))
7785 (s1 (concat s1 "......"))
7786 (t ""))
7787 extra (or extra "")
7788 category (if (symbolp category) (symbol-name category) category))
7789 ;; Evaluate the compiled format
7790 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
7792 ;; And finally add the text properties
7793 (org-add-props rtn nil
7794 'category (downcase category) 'tags tags
7795 'prefix-length (- (length rtn) (length txt))
7796 'time-of-day time-of-day
7797 'dotime dotime))))
7799 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
7800 (catch 'exit
7801 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
7802 ((and todayp (member 'today (car org-agenda-time-grid))))
7803 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
7804 ((member 'weekly (car org-agenda-time-grid)))
7805 (t (throw 'exit list)))
7806 (let* ((have (delq nil (mapcar
7807 (lambda (x) (get-text-property 1 'time-of-day x))
7808 list)))
7809 (string (nth 1 org-agenda-time-grid))
7810 (gridtimes (nth 2 org-agenda-time-grid))
7811 (req (car org-agenda-time-grid))
7812 (remove (member 'remove-match req))
7813 new time)
7814 (if (and (member 'require-timed req) (not have))
7815 ;; don't show empty grid
7816 (throw 'exit list))
7817 (while (setq time (pop gridtimes))
7818 (unless (and remove (member time have))
7819 (setq time (int-to-string time))
7820 (push (org-format-agenda-item
7821 nil string "" nil
7822 (concat (substring time 0 -2) ":" (substring time -2)))
7823 new)
7824 (put-text-property
7825 1 (length (car new)) 'face 'org-time-grid (car new))))
7826 (if (member 'time-up org-agenda-sorting-strategy)
7827 (append new list)
7828 (append list new)))))
7830 (defun org-compile-prefix-format (format)
7831 "Compile the prefix format into a Lisp form that can be evaluated.
7832 The resulting form is returned and stored in the variable
7833 `org-prefix-format-compiled'."
7834 (setq org-prefix-has-time nil org-prefix-has-tag nil)
7835 (let ((start 0) varform vars var (s format)e c f opt)
7836 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
7837 s start)
7838 (setq var (cdr (assoc (match-string 4 s)
7839 '(("c" . category) ("t" . time) ("s" . extra)
7840 ("T" . tag))))
7841 c (or (match-string 3 s) "")
7842 opt (match-beginning 1)
7843 start (1+ (match-beginning 0)))
7844 (if (equal var 'time) (setq org-prefix-has-time t))
7845 (if (equal var 'tag) (setq org-prefix-has-tag t))
7846 (setq f (concat "%" (match-string 2 s) "s"))
7847 (if opt
7848 (setq varform
7849 `(if (equal "" ,var)
7851 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
7852 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
7853 (setq s (replace-match "%s" t nil s))
7854 (push varform vars))
7855 (setq vars (nreverse vars))
7856 (setq org-prefix-format-compiled `(format ,s ,@vars))))
7858 (defun org-get-time-of-day (s &optional string mod24)
7859 "Check string S for a time of day.
7860 If found, return it as a military time number between 0 and 2400.
7861 If not found, return nil.
7862 The optional STRING argument forces conversion into a 5 character wide string
7863 HH:MM."
7864 (save-match-data
7865 (when
7867 (string-match
7868 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
7869 (string-match
7870 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
7871 (let* ((h (string-to-number (match-string 1 s)))
7872 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
7873 (ampm (if (match-end 4) (downcase (match-string 4 s))))
7874 (am-p (equal ampm "am"))
7875 (h1 (cond ((not ampm) h)
7876 ((= h 12) (if am-p 0 12))
7877 (t (+ h (if am-p 0 12)))))
7878 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
7879 (mod h1 24) h1))
7880 (t0 (+ (* 100 h2) m))
7881 (t1 (concat (if (>= h1 24) "+" " ")
7882 (if (< t0 100) "0" "")
7883 (if (< t0 10) "0" "")
7884 (int-to-string t0))))
7885 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
7887 (defun org-finalize-agenda-entries (list)
7888 "Sort and concatenate the agenda items."
7889 (setq list (mapcar 'org-agenda-highlight-todo list))
7890 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
7892 (defun org-agenda-highlight-todo (x)
7893 (let (re pl)
7894 (if (eq x 'line)
7895 (save-excursion
7896 (beginning-of-line 1)
7897 (setq re (get-text-property (point) 'org-not-done-regexp))
7898 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
7899 (and (looking-at (concat "[ \t]*" re))
7900 (add-text-properties (match-beginning 0) (match-end 0)
7901 '(face org-todo))))
7902 (setq re (get-text-property 0 'org-not-done-regexp x)
7903 pl (get-text-property 0 'prefix-length x))
7904 (and re (equal (string-match re x pl) pl)
7905 (add-text-properties (match-beginning 0) (match-end 0)
7906 '(face org-todo) x))
7907 x)))
7909 (defsubst org-cmp-priority (a b)
7910 "Compare the priorities of string A and B."
7911 (let ((pa (or (get-text-property 1 'priority a) 0))
7912 (pb (or (get-text-property 1 'priority b) 0)))
7913 (cond ((> pa pb) +1)
7914 ((< pa pb) -1)
7915 (t nil))))
7917 (defsubst org-cmp-category (a b)
7918 "Compare the string values of categories of strings A and B."
7919 (let ((ca (or (get-text-property 1 'category a) ""))
7920 (cb (or (get-text-property 1 'category b) "")))
7921 (cond ((string-lessp ca cb) -1)
7922 ((string-lessp cb ca) +1)
7923 (t nil))))
7925 (defsubst org-cmp-time (a b)
7926 "Compare the time-of-day values of strings A and B."
7927 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
7928 (ta (or (get-text-property 1 'time-of-day a) def))
7929 (tb (or (get-text-property 1 'time-of-day b) def)))
7930 (cond ((< ta tb) -1)
7931 ((< tb ta) +1)
7932 (t nil))))
7934 (defun org-entries-lessp (a b)
7935 "Predicate for sorting agenda entries."
7936 ;; The following variables will be used when the form is evaluated.
7937 (let* ((time-up (org-cmp-time a b))
7938 (time-down (if time-up (- time-up) nil))
7939 (priority-up (org-cmp-priority a b))
7940 (priority-down (if priority-up (- priority-up) nil))
7941 (category-up (org-cmp-category a b))
7942 (category-down (if category-up (- category-up) nil))
7943 (category-keep (if category-up +1 nil)))
7944 (cdr (assoc
7945 (eval (cons 'or org-agenda-sorting-strategy))
7946 '((-1 . t) (1 . nil) (nil . nil))))))
7948 (defun org-agenda-show-priority ()
7949 "Show the priority of the current item.
7950 This priority is composed of the main priority given with the [#A] cookies,
7951 and by additional input from the age of a schedules or deadline entry."
7952 (interactive)
7953 (let* ((pri (get-text-property (point-at-bol) 'priority)))
7954 (message "Priority is %d" (if pri pri -1000))))
7956 (defun org-agenda-show-tags ()
7957 "Show the tags applicable to the current item."
7958 (interactive)
7959 (let* ((tags (get-text-property (point-at-bol) 'tags)))
7960 (if tags
7961 (message "Tags are :%s:"
7962 (org-no-properties (mapconcat 'identity tags ":")))
7963 (message "No tags associated with this line"))))
7965 (defun org-agenda-goto (&optional highlight)
7966 "Go to the Org-mode file which contains the item at point."
7967 (interactive)
7968 (let* ((marker (or (get-text-property (point) 'org-marker)
7969 (org-agenda-error)))
7970 (buffer (marker-buffer marker))
7971 (pos (marker-position marker)))
7972 (switch-to-buffer-other-window buffer)
7973 (widen)
7974 (goto-char pos)
7975 (when (eq major-mode 'org-mode)
7976 (org-show-hidden-entry)
7977 (save-excursion
7978 (and (outline-next-heading)
7979 (org-flag-heading nil)))) ; show the next heading
7980 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
7982 (defun org-agenda-switch-to ()
7983 "Go to the Org-mode file which contains the item at point."
7984 (interactive)
7985 (let* ((marker (or (get-text-property (point) 'org-marker)
7986 (org-agenda-error)))
7987 (buffer (marker-buffer marker))
7988 (pos (marker-position marker)))
7989 (switch-to-buffer buffer)
7990 (delete-other-windows)
7991 (widen)
7992 (goto-char pos)
7993 (when (eq major-mode 'org-mode)
7994 (org-show-hidden-entry)
7995 (save-excursion
7996 (and (outline-next-heading)
7997 (org-flag-heading nil)))))) ; show the next heading
7999 (defun org-agenda-goto-mouse (ev)
8000 "Go to the Org-mode file which contains the item at the mouse click."
8001 (interactive "e")
8002 (mouse-set-point ev)
8003 (org-agenda-goto))
8005 (defun org-agenda-show ()
8006 "Display the Org-mode file which contains the item at point."
8007 (interactive)
8008 (let ((win (selected-window)))
8009 (org-agenda-goto t)
8010 (select-window win)))
8012 (defun org-agenda-recenter (arg)
8013 "Display the Org-mode file which contains the item at point and recenter."
8014 (interactive "P")
8015 (let ((win (selected-window)))
8016 (org-agenda-goto t)
8017 (recenter arg)
8018 (select-window win)))
8020 (defun org-agenda-show-mouse (ev)
8021 "Display the Org-mode file which contains the item at the mouse click."
8022 (interactive "e")
8023 (mouse-set-point ev)
8024 (org-agenda-show))
8026 (defun org-agenda-check-no-diary ()
8027 "Check if the entry is a diary link and abort if yes."
8028 (if (get-text-property (point) 'org-agenda-diary-link)
8029 (org-agenda-error)))
8031 (defun org-agenda-error ()
8032 (error "Command not allowed in this line"))
8034 (defvar org-last-heading-marker (make-marker)
8035 "Marker pointing to the headline that last changed its TODO state
8036 by a remote command from the agenda.")
8038 (defun org-agenda-todo (&optional arg)
8039 "Cycle TODO state of line at point, also in Org-mode file.
8040 This changes the line at point, all other lines in the agenda referring to
8041 the same tree node, and the headline of the tree node in the Org-mode file."
8042 (interactive "P")
8043 (org-agenda-check-no-diary)
8044 (let* ((col (current-column))
8045 (marker (or (get-text-property (point) 'org-marker)
8046 (org-agenda-error)))
8047 (buffer (marker-buffer marker))
8048 (pos (marker-position marker))
8049 (hdmarker (get-text-property (point) 'org-hd-marker))
8050 (buffer-read-only nil)
8051 newhead)
8052 (with-current-buffer buffer
8053 (widen)
8054 (goto-char pos)
8055 (org-show-hidden-entry)
8056 (save-excursion
8057 (and (outline-next-heading)
8058 (org-flag-heading nil))) ; show the next heading
8059 (org-todo arg)
8060 (and (bolp) (forward-char 1))
8061 (setq newhead (org-get-heading))
8062 (save-excursion
8063 (org-back-to-heading)
8064 (move-marker org-last-heading-marker (point))))
8065 (beginning-of-line 1)
8066 (save-excursion
8067 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8068 (move-to-column col)))
8070 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8071 "Change all lines in the agenda buffer which match HDMARKER.
8072 The new content of the line will be NEWHEAD (as modified by
8073 `org-format-agenda-item'). HDMARKER is checked with
8074 `equal' against all `org-hd-marker' text properties in the file.
8075 If FIXFACE is non-nil, the face of each item is modified acording to
8076 the new TODO state."
8077 (let* (props m pl undone-face done-face finish new dotime cat tags)
8078 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
8079 (save-excursion
8080 (goto-char (point-max))
8081 (beginning-of-line 1)
8082 (while (not finish)
8083 (setq finish (bobp))
8084 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8085 (equal m hdmarker))
8086 (setq props (text-properties-at (point))
8087 dotime (get-text-property (point) 'dotime)
8088 cat (get-text-property (point) 'category)
8089 tags (get-text-property (point) 'tags)
8090 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
8091 pl (get-text-property (point) 'prefix-length)
8092 undone-face (get-text-property (point) 'undone-face)
8093 done-face (get-text-property (point) 'done-face))
8094 (move-to-column pl)
8095 (if (looking-at ".*")
8096 (progn
8097 (replace-match new t t)
8098 (beginning-of-line 1)
8099 (add-text-properties (point-at-bol) (point-at-eol) props)
8100 (when fixface
8101 (add-text-properties
8102 (point-at-bol) (point-at-eol)
8103 (list 'face
8104 (if org-last-todo-state-is-todo
8105 undone-face done-face)))
8106 (org-agenda-highlight-todo 'line))
8107 (beginning-of-line 1))
8108 (error "Line update did not work")))
8109 (beginning-of-line 0)))))
8111 (defun org-agenda-priority-up ()
8112 "Increase the priority of line at point, also in Org-mode file."
8113 (interactive)
8114 (org-agenda-priority 'up))
8116 (defun org-agenda-priority-down ()
8117 "Decrease the priority of line at point, also in Org-mode file."
8118 (interactive)
8119 (org-agenda-priority 'down))
8121 (defun org-agenda-priority (&optional force-direction)
8122 "Set the priority of line at point, also in Org-mode file.
8123 This changes the line at point, all other lines in the agenda referring to
8124 the same tree node, and the headline of the tree node in the Org-mode file."
8125 (interactive)
8126 (org-agenda-check-no-diary)
8127 (let* ((marker (or (get-text-property (point) 'org-marker)
8128 (org-agenda-error)))
8129 (buffer (marker-buffer marker))
8130 (pos (marker-position marker))
8131 (hdmarker (get-text-property (point) 'org-hd-marker))
8132 (buffer-read-only nil)
8133 newhead)
8134 (with-current-buffer buffer
8135 (widen)
8136 (goto-char pos)
8137 (org-show-hidden-entry)
8138 (save-excursion
8139 (and (outline-next-heading)
8140 (org-flag-heading nil))) ; show the next heading
8141 (funcall 'org-priority force-direction)
8142 (end-of-line 1)
8143 (setq newhead (org-get-heading)))
8144 (org-agenda-change-all-lines newhead hdmarker)
8145 (beginning-of-line 1)))
8147 (defun org-get-tags-at (&optional pos)
8148 "Get a list of all headline tags applicable at POS.
8149 POS defaults to point. If tags are inherited, the list contains
8150 the targets in the same sequence as the headlines appear, i.e.
8151 the tags of the current headline come last."
8152 (interactive)
8153 (let (tags)
8154 (save-excursion
8155 (goto-char (or pos (point)))
8156 (save-match-data
8157 (org-back-to-heading t)
8158 (condition-case nil
8159 (while t
8160 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
8161 (setq tags (append (org-split-string
8162 (org-match-string-no-properties 1) ":")
8163 tags)))
8164 (or org-use-tag-inheritance (error ""))
8165 (org-up-heading-all 1))
8166 (error nil))))
8167 (message "%s" tags)
8168 tags))
8170 (defun org-agenda-set-tags ()
8171 "Set tags for the current headline."
8172 (interactive)
8173 (org-agenda-check-no-diary)
8174 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
8175 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
8176 (org-agenda-error)))
8177 (buffer (marker-buffer hdmarker))
8178 (pos (marker-position hdmarker))
8179 (buffer-read-only nil)
8180 newhead)
8181 (with-current-buffer buffer
8182 (widen)
8183 (goto-char pos)
8184 (org-show-hidden-entry)
8185 (save-excursion
8186 (and (outline-next-heading)
8187 (org-flag-heading nil))) ; show the next heading
8188 (call-interactively 'org-set-tags)
8189 (end-of-line 1)
8190 (setq newhead (org-get-heading)))
8191 (org-agenda-change-all-lines newhead hdmarker)
8192 (beginning-of-line 1)))
8194 (defun org-agenda-date-later (arg &optional what)
8195 "Change the date of this item to one day later."
8196 (interactive "p")
8197 (org-agenda-check-type t 'agenda 'timeline)
8198 (org-agenda-check-no-diary)
8199 (let* ((marker (or (get-text-property (point) 'org-marker)
8200 (org-agenda-error)))
8201 (buffer (marker-buffer marker))
8202 (pos (marker-position marker)))
8203 (with-current-buffer buffer
8204 (widen)
8205 (goto-char pos)
8206 (if (not (org-at-timestamp-p))
8207 (error "Cannot find time stamp"))
8208 (org-timestamp-change arg (or what 'day))
8209 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8211 (defun org-agenda-date-earlier (arg &optional what)
8212 "Change the date of this item to one day earlier."
8213 (interactive "p")
8214 (org-agenda-date-later (- arg) what))
8216 (defun org-agenda-date-prompt (arg)
8217 "Change the date of this item. Date is prompted for, with default today.
8218 The prefix ARG is passed to the `org-time-stamp' command and can therefore
8219 be used to request time specification in the time stamp."
8220 (interactive "P")
8221 (org-agenda-check-type t 'agenda 'timeline)
8222 (org-agenda-check-no-diary)
8223 (let* ((marker (or (get-text-property (point) 'org-marker)
8224 (org-agenda-error)))
8225 (buffer (marker-buffer marker))
8226 (pos (marker-position marker)))
8227 (with-current-buffer buffer
8228 (widen)
8229 (goto-char pos)
8230 (if (not (org-at-timestamp-p))
8231 (error "Cannot find time stamp"))
8232 (org-time-stamp arg)
8233 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8235 (defun org-agenda-schedule (arg)
8236 "Schedule the item at point."
8237 (interactive "P")
8238 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8239 (org-agenda-check-no-diary)
8240 (let* ((marker (or (get-text-property (point) 'org-marker)
8241 (org-agenda-error)))
8242 (buffer (marker-buffer marker))
8243 (pos (marker-position marker))
8244 (org-insert-labeled-timestamps-at-point nil)
8246 (with-current-buffer buffer
8247 (widen)
8248 (goto-char pos)
8249 (setq ts (org-schedule))
8250 (message "Item scheduled for %s" ts))))
8252 (defun org-agenda-deadline (arg)
8253 "Schedule the item at point."
8254 (interactive "P")
8255 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8256 (org-agenda-check-no-diary)
8257 (let* ((marker (or (get-text-property (point) 'org-marker)
8258 (org-agenda-error)))
8259 (buffer (marker-buffer marker))
8260 (pos (marker-position marker))
8261 (org-insert-labeled-timestamps-at-point nil)
8263 (with-current-buffer buffer
8264 (widen)
8265 (goto-char pos)
8266 (setq ts (org-deadline))
8267 (message "Deadline for this item set to %s" ts))))
8269 (defun org-get-heading ()
8270 "Return the heading of the current entry, without the stars."
8271 (save-excursion
8272 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
8273 (if (and (re-search-backward "[\r\n]\\*" nil t)
8274 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
8275 (match-string 1)
8276 "")))
8278 (defun org-agenda-clock-in (&optional arg)
8279 "Start the clock on the currently selected item."
8280 (interactive "P")
8281 (org-agenda-check-no-diary)
8282 (let* ((marker (or (get-text-property (point) 'org-marker)
8283 (org-agenda-error)))
8284 (pos (marker-position marker)))
8285 (with-current-buffer (marker-buffer marker)
8286 (widen)
8287 (goto-char pos)
8288 (org-clock-in))))
8290 (defun org-agenda-diary-entry ()
8291 "Make a diary entry, like the `i' command from the calendar.
8292 All the standard commands work: block, weekly etc."
8293 (interactive)
8294 (org-agenda-check-type t 'agenda 'timeline)
8295 (require 'diary-lib)
8296 (let* ((char (progn
8297 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
8298 (read-char-exclusive)))
8299 (cmd (cdr (assoc char
8300 '((?d . insert-diary-entry)
8301 (?w . insert-weekly-diary-entry)
8302 (?m . insert-monthly-diary-entry)
8303 (?y . insert-yearly-diary-entry)
8304 (?a . insert-anniversary-diary-entry)
8305 (?b . insert-block-diary-entry)
8306 (?c . insert-cyclic-diary-entry)))))
8307 (oldf (symbol-function 'calendar-cursor-to-date))
8308 (point (point))
8309 (mark (or (mark t) (point))))
8310 (unless cmd
8311 (error "No command associated with <%c>" char))
8312 (unless (and (get-text-property point 'day)
8313 (or (not (equal ?b char))
8314 (get-text-property mark 'day)))
8315 (error "Don't know which date to use for diary entry"))
8316 ;; We implement this by hacking the `calendar-cursor-to-date' function
8317 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
8318 (let ((calendar-mark-ring
8319 (list (calendar-gregorian-from-absolute
8320 (or (get-text-property mark 'day)
8321 (get-text-property point 'day))))))
8322 (unwind-protect
8323 (progn
8324 (fset 'calendar-cursor-to-date
8325 (lambda (&optional error)
8326 (calendar-gregorian-from-absolute
8327 (get-text-property point 'day))))
8328 (call-interactively cmd))
8329 (fset 'calendar-cursor-to-date oldf)))))
8332 (defun org-agenda-execute-calendar-command (cmd)
8333 "Execute a calendar command from the agenda, with the date associated to
8334 the cursor position."
8335 (org-agenda-check-type t 'agenda 'timeline)
8336 (require 'diary-lib)
8337 (unless (get-text-property (point) 'day)
8338 (error "Don't know which date to use for calendar command"))
8339 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
8340 (point (point))
8341 (date (calendar-gregorian-from-absolute
8342 (get-text-property point 'day)))
8343 (displayed-day (extract-calendar-day date))
8344 (displayed-month (extract-calendar-month date))
8345 (displayed-year (extract-calendar-year date)))
8346 (unwind-protect
8347 (progn
8348 (fset 'calendar-cursor-to-date
8349 (lambda (&optional error)
8350 (calendar-gregorian-from-absolute
8351 (get-text-property point 'day))))
8352 (call-interactively cmd))
8353 (fset 'calendar-cursor-to-date oldf))))
8355 (defun org-agenda-phases-of-moon ()
8356 "Display the phases of the moon for the 3 months around the cursor date."
8357 (interactive)
8358 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
8360 (defun org-agenda-holidays ()
8361 "Display the holidays for the 3 months around the cursor date."
8362 (interactive)
8363 (org-agenda-execute-calendar-command 'list-calendar-holidays))
8365 (defun org-agenda-sunrise-sunset (arg)
8366 "Display sunrise and sunset for the cursor date.
8367 Latitude and longitude can be specified with the variables
8368 `calendar-latitude' and `calendar-longitude'. When called with prefix
8369 argument, latitude and longitude will be prompted for."
8370 (interactive "P")
8371 (let ((calendar-longitude (if arg nil calendar-longitude))
8372 (calendar-latitude (if arg nil calendar-latitude))
8373 (calendar-location-name
8374 (if arg "the given coordinates" calendar-location-name)))
8375 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
8377 (defun org-agenda-goto-calendar ()
8378 "Open the Emacs calendar with the date at the cursor."
8379 (interactive)
8380 (org-agenda-check-type t 'agenda 'timeline)
8381 (let* ((day (or (get-text-property (point) 'day)
8382 (error "Don't know which date to open in calendar")))
8383 (date (calendar-gregorian-from-absolute day))
8384 (calendar-move-hook nil)
8385 (view-calendar-holidays-initially nil)
8386 (view-diary-entries-initially nil))
8387 (calendar)
8388 (calendar-goto-date date)))
8390 (defun org-calendar-goto-agenda ()
8391 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
8392 This is a command that has to be installed in `calendar-mode-map'."
8393 (interactive)
8394 (org-agenda-list nil (calendar-absolute-from-gregorian
8395 (calendar-cursor-to-date))
8396 nil t))
8398 (defun org-agenda-convert-date ()
8399 (interactive)
8400 (org-agenda-check-type t 'agenda 'timeline)
8401 (let ((day (get-text-property (point) 'day))
8402 date s)
8403 (unless day
8404 (error "Don't know which date to convert"))
8405 (setq date (calendar-gregorian-from-absolute day))
8406 (setq s (concat
8407 "Gregorian: " (calendar-date-string date) "\n"
8408 "ISO: " (calendar-iso-date-string date) "\n"
8409 "Day of Yr: " (calendar-day-of-year-string date) "\n"
8410 "Julian: " (calendar-julian-date-string date) "\n"
8411 "Astron. JD: " (calendar-astro-date-string date)
8412 " (Julian date number at noon UTC)\n"
8413 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
8414 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
8415 "French: " (calendar-french-date-string date) "\n"
8416 "Mayan: " (calendar-mayan-date-string date) "\n"
8417 "Coptic: " (calendar-coptic-date-string date) "\n"
8418 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
8419 "Persian: " (calendar-persian-date-string date) "\n"
8420 "Chinese: " (calendar-chinese-date-string date) "\n"))
8421 (with-output-to-temp-buffer "*Dates*"
8422 (princ s))
8423 (if (fboundp 'fit-window-to-buffer)
8424 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
8426 ;;; Tags
8428 (defun org-scan-tags (action matcher &optional todo-only)
8429 "Scan headline tags with inheritance and produce output ACTION.
8430 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8431 evaluated, testing if a given set of tags qualifies a headline for
8432 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8433 are included in the output."
8434 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8435 (mapconcat 'regexp-quote
8436 (nreverse (cdr (reverse org-todo-keywords)))
8437 "\\|")
8438 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
8439 (props (list 'face nil
8440 'done-face 'org-done
8441 'undone-face nil
8442 'mouse-face 'highlight
8443 'keymap org-agenda-keymap
8444 'help-echo
8445 (format "mouse-2 or RET jump to org file %s"
8446 (abbreviate-file-name buffer-file-name))))
8447 lspos
8448 tags tags-list tags-alist (llast 0) rtn level category i txt
8449 todo marker)
8450 (save-excursion
8451 (goto-char (point-min))
8452 (when (eq action 'sparse-tree) (org-overview))
8453 (while (re-search-forward re nil t)
8454 (catch :skip
8455 (and (eq action 'agenda) (org-agenda-skip))
8456 (setq todo (if (match-end 1) (match-string 2))
8457 tags (if (match-end 4) (match-string 4)))
8458 (goto-char (setq lspos (1+ (match-beginning 0))))
8459 (setq level (funcall outline-level)
8460 category (org-get-category))
8461 (setq i llast llast level)
8462 ;; remove tag lists from same and sublevels
8463 (while (>= i level)
8464 (when (setq entry (assoc i tags-alist))
8465 (setq tags-alist (delete entry tags-alist)))
8466 (setq i (1- i)))
8467 ;; add the nex tags
8468 (when tags
8469 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8470 tags-alist
8471 (cons (cons level tags) tags-alist)))
8472 ;; compile tags for current headline
8473 (setq tags-list
8474 (if org-use-tag-inheritance
8475 (apply 'append (mapcar 'cdr tags-alist))
8476 tags))
8477 (when (and (or (not todo-only) todo)
8478 (eval matcher)
8479 (or (not org-agenda-skip-archived-trees)
8480 (not (member org-archive-tag tags-list))))
8481 ;; list this headline
8482 (if (eq action 'sparse-tree)
8483 (progn
8484 (org-show-hierarchy-above))
8485 (setq txt (org-format-agenda-item
8487 (concat
8488 (if org-tags-match-list-sublevels
8489 (make-string (1- level) ?.) "")
8490 (org-get-heading))
8491 category tags-list))
8492 (goto-char lspos)
8493 (setq marker (org-agenda-new-marker))
8494 (org-add-props txt props
8495 'org-marker marker 'org-hd-marker marker 'category category)
8496 (push txt rtn))
8497 ;; if we are to skip sublevels, jump to end of subtree
8498 (point)
8499 (or org-tags-match-list-sublevels (org-end-of-subtree))))))
8500 (when (and (eq action 'sparse-tree)
8501 (not org-sparse-tree-open-archived-trees))
8502 (org-hide-archived-subtrees (point-min) (point-max)))
8503 (nreverse rtn)))
8505 (defun org-tags-sparse-tree (&optional arg match)
8506 "Create a sparse tree according to tags search string MATCH.
8507 MATCH can contain positive and negative selection of tags, like
8508 \"+WORK+URGENT-WITHBOSS\"."
8509 (interactive "P")
8510 (let ((org-show-following-heading nil)
8511 (org-show-hierarchy-above nil))
8512 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
8514 (defun org-make-tags-matcher (match)
8515 "Create the TAGS matcher form for the tags-selecting string MATCH."
8516 (unless match
8517 ;; Get a new match request, with completion
8518 (setq org-last-tags-completion-table
8519 (or (org-get-buffer-tags)
8520 org-last-tags-completion-table))
8521 (setq match (completing-read
8522 "Tags: " 'org-tags-completion-function nil nil nil
8523 'org-tags-history)))
8524 ;; parse the string and create a lisp form
8525 (let ((match0 match) minus tag mm matcher orterms term orlist)
8526 (setq orterms (org-split-string match "|"))
8527 (while (setq term (pop orterms))
8528 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
8529 (setq minus (and (match-end 1)
8530 (equal (match-string 1 term) "-"))
8531 tag (match-string 2 term)
8532 term (substring term (match-end 0))
8533 mm (list 'member (downcase tag) 'tags-list)
8534 mm (if minus (list 'not mm) mm))
8535 (push mm matcher))
8536 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
8537 orlist)
8538 (setq matcher nil))
8539 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8540 ;; Return the string and lisp forms of the matcher
8541 (cons match0 matcher)))
8543 ;;;###autoload
8544 (defun org-tags-view (&optional todo-only match keep-modes)
8545 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
8546 The prefix arg TODO-ONLY limits the search to TODO entries."
8547 (interactive "P")
8548 (org-agenda-maybe-reset-markers 'force)
8549 (org-compile-prefix-format org-agenda-prefix-format)
8550 (let* ((org-agenda-keep-modes keep-modes)
8551 (org-tags-match-list-sublevels
8552 (if todo-only t org-tags-match-list-sublevels))
8553 (win (selected-window))
8554 (completion-ignore-case t)
8555 rtn rtnall files file pos matcher
8556 buffer)
8557 (setq matcher (org-make-tags-matcher match)
8558 match (car matcher) matcher (cdr matcher))
8559 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
8560 (progn
8561 (delete-other-windows)
8562 (switch-to-buffer-other-window
8563 (get-buffer-create org-agenda-buffer-name))))
8564 (setq buffer-read-only nil)
8565 (erase-buffer)
8566 (org-agenda-mode) (setq buffer-read-only nil)
8567 (set (make-local-variable 'org-agenda-type) 'tags)
8568 (set (make-local-variable 'org-agenda-redo-command)
8569 (list 'org-tags-view (list 'quote todo-only)
8570 (list 'if 'current-prefix-arg nil match) t))
8571 (setq files (org-agenda-files)
8572 rtnall nil)
8573 (org-prepare-agenda-buffers files)
8574 (while (setq file (pop files))
8575 (catch 'nextfile
8576 (org-check-agenda-file file)
8577 (setq buffer (if (file-exists-p file)
8578 (org-get-agenda-file-buffer file)
8579 (error "No such file %s" file)))
8580 (if (not buffer)
8581 ;; If file does not exist, merror message to agenda
8582 (setq rtn (list
8583 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8584 rtnall (append rtnall rtn))
8585 (with-current-buffer buffer
8586 (unless (eq major-mode 'org-mode)
8587 (error "Agenda file %s is not in `org-mode'" file))
8588 (setq org-category-table (org-get-category-table))
8589 (save-excursion
8590 (save-restriction
8591 (if org-respect-restriction
8592 (if (org-region-active-p)
8593 ;; Respect a region to restrict search
8594 (narrow-to-region (region-beginning) (region-end)))
8595 ;; If we work for the calendar or many files,
8596 ;; get rid of any restriction
8597 (widen))
8598 (setq rtn (org-scan-tags 'agenda matcher todo-only))
8599 (setq rtnall (append rtnall rtn))))))))
8600 (insert "Headlines with TAGS match: ")
8601 (add-text-properties (point-min) (1- (point))
8602 (list 'face 'org-level-3))
8603 (setq pos (point))
8604 (insert match "\n")
8605 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
8606 (setq pos (point))
8607 (insert "Press `C-u r' to search again with new search string\n")
8608 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
8609 (when rtnall
8610 (insert (mapconcat 'identity rtnall "\n")))
8611 (goto-char (point-min))
8612 (setq buffer-read-only t)
8613 (org-fit-agenda-window)
8614 (if (not org-select-agenda-window) (select-window win))))
8616 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8617 (defun org-set-tags (&optional arg just-align)
8618 "Set the tags for the current headline.
8619 With prefix ARG, realign all tags in headings in the current buffer."
8620 (interactive "P")
8621 (let* ((re (concat "^" outline-regexp))
8622 (col (current-column))
8623 (current (org-get-tags))
8624 table current-tags inherited-tags ; computed below when needed
8625 tags hd empty invis)
8626 (if arg
8627 (save-excursion
8628 (goto-char (point-min))
8629 (while (re-search-forward re nil t)
8630 (org-set-tags nil t))
8631 (message "All tags realigned to column %d" org-tags-column))
8632 (if just-align
8633 (setq tags current)
8634 (setq table (or org-tag-alist (org-get-buffer-tags))
8635 org-last-tags-completion-table table
8636 current-tags (org-split-string current ":")
8637 inherited-tags (nreverse
8638 (nthcdr (length current-tags)
8639 (nreverse (org-get-tags-at))))
8640 tags
8641 (if (or (eq t org-use-fast-tag-selection)
8642 (and org-use-fast-tag-selection
8643 (delq nil (mapcar 'cdr table))))
8644 (org-fast-tag-selection current-tags inherited-tags table)
8645 (let ((org-add-colon-after-tag-completion t))
8646 (completing-read "Tags: " 'org-tags-completion-function
8647 nil nil current 'org-tags-history))))
8648 (while (string-match "[-+&]+" tags)
8649 (setq tags (replace-match ":" t t tags))))
8651 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
8652 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8653 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8654 (if (equal current "")
8655 (progn
8656 (end-of-line 1)
8657 (or empty (insert-before-markers " ")))
8658 (beginning-of-line 1)
8659 (setq invis (org-invisible-p))
8660 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
8661 (setq hd (match-string 1))
8662 (delete-region (match-beginning 0) (match-end 0))
8663 (insert-before-markers (org-trim hd) (if empty "" " ")))
8664 (if (equal tags "")
8665 (save-excursion
8666 (beginning-of-line 1)
8667 (and (re-search-forward "[ \t]+$" (point-at-eol) t)
8668 (replace-match "")))
8669 (move-to-column (max (current-column)
8670 (if (> org-tags-column 0)
8671 org-tags-column
8672 (- (- org-tags-column) (length tags))))
8674 (insert-before-markers tags)
8675 (if (and (not invis) (org-invisible-p))
8676 (outline-flag-region (point-at-bol) (point) nil)))
8677 (move-to-column col))))
8679 (defun org-tags-completion-function (string predicate &optional flag)
8680 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8681 (confirm (lambda (x) (stringp (car x)))))
8682 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8683 (setq s1 (match-string 1 string)
8684 s2 (match-string 2 string))
8685 (setq s1 "" s2 string))
8686 (cond
8687 ((eq flag nil)
8688 ;; try completion
8689 (setq rtn (try-completion s2 ctable confirm))
8690 (if (stringp rtn)
8691 (concat s1 s2 (substring rtn (length s2))
8692 (if (and org-add-colon-after-tag-completion
8693 (assoc rtn ctable))
8694 ":" "")))
8696 ((eq flag t)
8697 ;; all-completions
8698 (all-completions s2 ctable confirm)
8700 ((eq flag 'lambda)
8701 ;; exact match?
8702 (assoc s2 ctable)))
8705 (defun org-fast-tag-insert (kwd tags face &optional end)
8706 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
8707 (insert (format "%-12s" (concat kwd ":"))
8708 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
8709 (or end "")))
8711 (defun org-fast-tag-selection (current inherited table)
8712 "Fast tag selection with single keys.
8713 CURRENT is the current list of tags in the headline, INHERITED is the
8714 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
8715 possibly with grouping information.
8716 If the keys are nil, a-z are automatically assigned.
8717 Returns the new tags string, or nil to not change the current settings."
8718 (let* ((maxlen (apply 'max (mapcar
8719 (lambda (x)
8720 (if (stringp (car x)) (string-width (car x)) 0))
8721 table)))
8722 (fwidth (+ maxlen 3 1 3))
8723 (ncol (/ (- (window-width) 4) fwidth))
8724 (i-face 'org-done)
8725 (c-face 'org-tag)
8726 tg cnt e c char c1 c2 ntable tbl rtn
8727 groups ingroup)
8728 (save-window-excursion
8729 (delete-other-windows)
8730 (split-window-vertically)
8731 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
8732 (erase-buffer)
8733 (org-fast-tag-insert "Inherited" inherited i-face "\n")
8734 (org-fast-tag-insert "Current" current c-face "\n\n")
8735 (setq tbl table char ?a cnt 0)
8736 (while (setq e (pop tbl))
8737 (cond
8738 ((equal e '(:startgroup))
8739 (push '() groups) (setq ingroup t)
8740 (when (not (= cnt 0))
8741 (setq cnt 0)
8742 (insert "\n"))
8743 (insert "{ "))
8744 ((equal e '(:endgroup))
8745 (setq ingroup nil cnt 0)
8746 (insert "}\n"))
8748 (setq tg (car e) c2 nil)
8749 (if (cdr e)
8750 (setq c (cdr e))
8751 ;; automatically assign a character.
8752 (setq c1 (string-to-char
8753 (downcase (substring
8754 tg (if (= (string-to-char tg) ?@) 1 0)))))
8755 (if (or (rassoc c1 ntable) (rassoc c1 table))
8756 (while (or (rassoc char ntable) (rassoc char table))
8757 (setq char (1+ char)))
8758 (setq c2 c1))
8759 (setq c (or c2 char)))
8760 (if ingroup (push tg (car groups)))
8761 (setq tg (org-add-props tg nil 'face
8762 (cond
8763 ((member tg current) c-face)
8764 ((member tg inherited) i-face)
8765 (t nil))))
8766 (if (and (= cnt 0) (not ingroup)) (insert " "))
8767 (insert "[" c "] " tg (make-string
8768 (- fwidth 4 (length tg)) ?\ ))
8769 (push (cons tg c) ntable)
8770 (when (= (setq cnt (1+ cnt)) ncol)
8771 (insert "\n")
8772 (if ingroup (insert " "))
8773 (setq cnt 0)))))
8774 (setq ntable (nreverse ntable))
8775 (insert "\n")
8776 (goto-char (point-min))
8777 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
8778 (setq rtn
8779 (catch 'exit
8780 (while t
8781 (message "[key]:Toggle SPC: clear current RET accept%s"
8782 (if groups " [!] ignore goups" ""))
8783 (setq c (read-char-exclusive))
8784 (cond
8785 ((= c ?\r) (throw 'exit t))
8786 ((= c ?!)
8787 (setq groups nil)
8788 (goto-char (point-min))
8789 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
8790 ((or (= c ?\C-g)
8791 (and (= c ?q) (not (rassoc c ntable))))
8792 (setq quit-flag t))
8793 ((= c ?\ ) (setq current nil))
8794 ((setq e (rassoc c ntable) tg (car e))
8795 (if (member tg current)
8796 (setq current (delete tg current))
8797 (loop for g in groups do
8798 (if (member tg g)
8799 (mapcar (lambda (x)
8800 (setq current (delete x current)))
8801 g)))
8802 (setq current (cons tg current)))))
8803 ;; Create a sorted list
8804 (setq current
8805 (sort current
8806 (lambda (a b)
8807 (assoc b (cdr (memq (assoc a ntable) ntable))))))
8808 (goto-char (point-min))
8809 (beginning-of-line 2)
8810 (delete-region (point) (point-at-eol))
8811 (org-fast-tag-insert "Current" current c-face)
8812 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
8813 (setq tg (match-string 1))
8814 (add-text-properties (match-beginning 1) (match-end 1)
8815 (list 'face
8816 (cond
8817 ((member tg current) c-face)
8818 ((member tg inherited) i-face)
8819 (t nil)))))
8820 (goto-char (point-min)))))
8821 (if rtn
8822 (mapconcat 'identity current ":")
8823 nil))))
8825 (defun org-get-tags ()
8826 "Get the TAGS string in the current headline."
8827 (unless (org-on-heading-p)
8828 (error "Not on a heading"))
8829 (save-excursion
8830 (beginning-of-line 1)
8831 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
8832 (org-match-string-no-properties 1)
8833 "")))
8835 (defun org-get-buffer-tags ()
8836 "Get a table of all tags used in the buffer, for completion."
8837 (let (tags)
8838 (save-excursion
8839 (goto-char (point-min))
8840 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
8841 (mapc (lambda (x) (add-to-list 'tags x))
8842 (org-split-string (org-match-string-no-properties 1) ":"))))
8843 (mapcar 'list tags)))
8845 ;;; Link Stuff
8847 (defvar org-create-file-search-functions nil
8848 "List of functions to construct the right search string for a file link.
8849 These functions are called in turn with point at the location to
8850 which the link should point.
8852 A function in the hook should first test if it would like to
8853 handle this file type, for example by checking the major-mode or
8854 the file extension. If it decides not to handle this file, it
8855 should just return nil to give other functions a chance. If it
8856 does handle the file, it must return the search string to be used
8857 when following the link. The search string will be part of the
8858 file link, given after a double colon, and `org-open-at-point'
8859 will automatically search for it. If special measures must be
8860 taken to make the search successful, another function should be
8861 added to the companion hook `org-execute-file-search-functions',
8862 which see.
8864 A function in this hook may also use `setq' to set the variable
8865 `description' to provide a suggestion for the descriptive text to
8866 be used for this link when it gets inserted into an Org-mode
8867 buffer with \\[org-insert-link].")
8869 (defvar org-execute-file-search-functions nil
8870 "List of functions to execute a file search triggered by a link.
8872 Functions added to this hook must accept a single argument, the
8873 search string that was part of the file link, the part after the
8874 double colon. The function must first check if it would like to
8875 handle this search, for example by checking the major-mode or the
8876 file extension. If it decides not to handle this search, it
8877 should just return nil to give other functions a chance. If it
8878 does handle the search, it must return a non-nil value to keep
8879 other functions from trying.
8881 Each function can access the current prefix argument through the
8882 variable `current-prefix-argument'. Note that a single prefix is
8883 used to force opening a link in Emacs, so it may be good to only
8884 use a numeric or double prefix to guide the search function.
8886 In case this is needed, a function in this hook can also restore
8887 the window configuration before `org-open-at-point' was called using:
8889 (set-window-configuration org-window-config-before-follow-link)")
8891 (defun org-find-file-at-mouse (ev)
8892 "Open file link or URL at mouse."
8893 (interactive "e")
8894 (mouse-set-point ev)
8895 (org-open-at-point 'in-emacs))
8897 (defun org-open-at-mouse (ev)
8898 "Open file link or URL at mouse."
8899 (interactive "e")
8900 (mouse-set-point ev)
8901 (org-open-at-point))
8903 (defvar org-window-config-before-follow-link nil
8904 "The window configuration before following a link.
8905 This is saved in case the need arises to restore it.")
8907 (defun org-open-at-point (&optional in-emacs)
8908 "Open link at or after point.
8909 If there is no link at point, this function will search forward up to
8910 the end of the current subtree.
8911 Normally, files will be opened by an appropriate application. If the
8912 optional argument IN-EMACS is non-nil, Emacs will visit the file."
8913 (interactive "P")
8914 (setq org-window-config-before-follow-link (current-window-configuration))
8915 (org-remove-occur-highlights nil nil t)
8916 (if (org-at-timestamp-p)
8917 (org-agenda-list nil (time-to-days (org-time-string-to-time
8918 (substring (match-string 1) 0 10)))
8920 (let (type path link line search (pos (point)))
8921 (catch 'match
8922 (save-excursion
8923 (skip-chars-forward "^]\n\r")
8924 (when (and (re-search-backward "\\[\\[" nil t)
8925 (looking-at org-bracket-link-regexp)
8926 (<= (match-beginning 0) pos)
8927 (>= (match-end 0) pos))
8928 (setq link (org-link-unescape (org-match-string-no-properties 1)))
8929 (while (string-match " *\n *" link)
8930 (setq link (replace-match " " t t link)))
8931 (if (string-match org-link-re-with-space2 link)
8932 (setq type (match-string 1 link)
8933 path (match-string 2 link))
8934 (setq type "thisfile"
8935 path link))
8936 (throw 'match t)))
8938 (when (get-text-property (point) 'org-linked-text)
8939 (setq type "thisfile"
8940 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8941 (1+ (point)) (point))
8942 path (buffer-substring
8943 (previous-single-property-change pos 'org-linked-text)
8944 (next-single-property-change pos 'org-linked-text)))
8945 (throw 'match t))
8947 (save-excursion
8948 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
8949 (if (equal (char-before) ?<) (backward-char 1))
8950 (when (or (looking-at org-angle-link-re)
8951 (looking-at org-plain-link-re)
8952 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
8953 (re-search-forward org-plain-link-re (point-at-eol) t))
8954 (<= (match-beginning 0) pos)
8955 (>= (match-end 0) pos)))
8956 (setq type (match-string 1)
8957 path (match-string 2))
8958 (throw 'match t)))
8959 (save-excursion
8960 (skip-chars-backward "^ \t\n\r")
8961 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
8962 (setq type "tags"
8963 path (match-string 1))
8964 (while (string-match ":" path)
8965 (setq path (replace-match "+" t t path)))
8966 (throw 'match t)))
8967 (save-excursion
8968 (skip-chars-backward "a-zA-Z_")
8969 (when (and (memq 'camel org-activate-links)
8970 (looking-at org-camel-regexp))
8971 (setq type "camel" path (match-string 0))
8972 (if (equal (char-before) ?*)
8973 (setq path (concat "*" path))))
8974 (throw 'match t)))
8975 (unless path
8976 (error "No link found"))
8977 ;; Remove any trailing spaces in path
8978 (if (string-match " +\\'" path)
8979 (setq path (replace-match "" t t path)))
8981 (cond
8983 ((member type '("http" "https" "ftp" "mailto" "news"))
8984 (browse-url (concat type ":" path)))
8986 ((string= type "tags")
8987 (org-tags-view in-emacs path))
8988 ((or (string= type "camel")
8989 (string= type "thisfile"))
8990 (org-mark-ring-push)
8991 (org-link-search
8992 path
8993 (cond ((equal in-emacs '(4)) 'occur)
8994 ((equal in-emacs '(16)) 'org-occur)
8995 (t nil))))
8997 ((string= type "file")
8998 (if (string-match "::\\([0-9]+\\)\\'" path)
8999 (setq line (string-to-number (match-string 1 path))
9000 path (substring path 0 (match-beginning 0)))
9001 (if (string-match "::\\(.+\\)\\'" path)
9002 (setq search (match-string 1 path)
9003 path (substring path 0 (match-beginning 0)))))
9004 (org-open-file path in-emacs line search))
9006 ((string= type "news")
9007 (org-follow-gnus-link path))
9009 ((string= type "bbdb")
9010 (org-follow-bbdb-link path))
9012 ((string= type "info")
9013 (org-follow-info-link path))
9015 ((string= type "gnus")
9016 (let (group article)
9017 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9018 (error "Error in Gnus link"))
9019 (setq group (match-string 1 path)
9020 article (match-string 3 path))
9021 (org-follow-gnus-link group article)))
9023 ((string= type "vm")
9024 (let (folder article)
9025 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9026 (error "Error in VM link"))
9027 (setq folder (match-string 1 path)
9028 article (match-string 3 path))
9029 ;; in-emacs is the prefix arg, will be interpreted as read-only
9030 (org-follow-vm-link folder article in-emacs)))
9032 ((string= type "wl")
9033 (let (folder article)
9034 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9035 (error "Error in Wanderlust link"))
9036 (setq folder (match-string 1 path)
9037 article (match-string 3 path))
9038 (org-follow-wl-link folder article)))
9040 ((string= type "mhe")
9041 (let (folder article)
9042 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9043 (error "Error in MHE link"))
9044 (setq folder (match-string 1 path)
9045 article (match-string 3 path))
9046 (org-follow-mhe-link folder article)))
9048 ((string= type "rmail")
9049 (let (folder article)
9050 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9051 (error "Error in RMAIL link"))
9052 (setq folder (match-string 1 path)
9053 article (match-string 3 path))
9054 (org-follow-rmail-link folder article)))
9056 ((string= type "shell")
9057 (let ((cmd path))
9058 (while (string-match "@{" cmd)
9059 (setq cmd (replace-match "<" t t cmd)))
9060 (while (string-match "@}" cmd)
9061 (setq cmd (replace-match ">" t t cmd)))
9062 (if (or (not org-confirm-shell-link-function)
9063 (funcall org-confirm-shell-link-function
9064 (format "Execute \"%s\" in shell? "
9065 (org-add-props cmd nil
9066 'face 'org-warning))))
9067 (progn
9068 (message "Executing %s" cmd)
9069 (shell-command cmd))
9070 (error "Abort"))))
9072 ((string= type "elisp")
9073 (let ((cmd path))
9074 (if (or (not org-confirm-elisp-link-function)
9075 (funcall org-confirm-elisp-link-function
9076 (format "Execute \"%s\" as elisp? "
9077 (org-add-props cmd nil
9078 'face 'org-warning))))
9079 (message "%s => %s" cmd (eval (read cmd)))
9080 (error "Abort"))))
9083 (browse-url-at-point))))))
9085 (defun org-link-search (s &optional type)
9086 "Search for a link search option.
9087 When S is a CamelCaseWord, search for a target, or for a sentence containing
9088 the words. If S is surrounded by forward slashes, it is interpreted as a
9089 regular expression. In org-mode files, this will create an `org-occur'
9090 sparse tree. In ordinary files, `occur' will be used to list matches.
9091 If the current buffer is in `dired-mode', grep will be used to search
9092 in all files."
9093 (let ((case-fold-search t)
9094 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9095 (pos (point))
9096 (pre "") (post "")
9097 words re0 re1 re2 re3 re4 re5 re2a reall camel)
9098 (cond
9099 ;; First check if there are any special
9100 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9101 ;; Now try the builtin stuff
9102 ((save-excursion
9103 (goto-char (point-min))
9104 (and
9105 (re-search-forward
9106 (concat "<<" (regexp-quote s0) ">>") nil t)
9107 (setq pos (match-beginning 0))))
9108 ;; There is an exact target for this
9109 (goto-char pos))
9110 ((string-match "^/\\(.*\\)/$" s)
9111 ;; A regular expression
9112 (cond
9113 ((eq major-mode 'org-mode)
9114 (org-occur (match-string 1 s)))
9115 ;;((eq major-mode 'dired-mode)
9116 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9117 (t (org-do-occur (match-string 1 s)))))
9118 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
9120 ;; A camel or a normal search string
9121 (when (equal (string-to-char s) ?*)
9122 ;; Anchor on headlines, post may include tags.
9123 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9124 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9125 s (substring s 1)))
9126 (remove-text-properties
9127 0 (length s)
9128 '(face nil mouse-face nil keymap nil fontified nil) s)
9129 ;; Make a series of regular expressions to find a match
9130 (setq words
9131 (if camel
9132 (org-camel-to-words s)
9133 (org-split-string s "[ \n\r\t]+"))
9134 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9135 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9136 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9137 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9138 re1 (concat pre re2 post)
9139 re3 (concat pre re4 post)
9140 re5 (concat pre ".*" re4)
9141 re2 (concat pre re2)
9142 re2a (concat pre re2a)
9143 re4 (concat pre re4)
9144 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9145 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9146 re5 "\\)"
9148 (cond
9149 ((eq type 'org-occur) (org-occur reall))
9150 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9151 (t (goto-char (point-min))
9152 (if (or (org-search-not-link re0 nil t)
9153 (org-search-not-link re1 nil t)
9154 (org-search-not-link re2 nil t)
9155 (org-search-not-link re2a nil t)
9156 (org-search-not-link re3 nil t)
9157 (org-search-not-link re4 nil t)
9158 (org-search-not-link re5 nil t)
9160 (goto-char (match-beginning 1))
9161 (goto-char pos)
9162 (error "No match")))))
9164 ;; Normal string-search
9165 (goto-char (point-min))
9166 (if (search-forward s nil t)
9167 (goto-char (match-beginning 0))
9168 (error "No match"))))
9169 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
9171 (defun org-search-not-link (&rest args)
9172 "Execute `re-search-forward', but only accept matches that are not a link."
9173 (catch 'exit
9174 (let (p1)
9175 (while (apply 're-search-forward args)
9176 (setq p1 (point))
9177 (if (not (save-match-data
9178 (and (re-search-backward "\\[\\[" nil t)
9179 (looking-at org-bracket-link-regexp)
9180 (<= (match-beginning 0) p1)
9181 (>= (match-end 0) p1))))
9182 (progn (goto-char (match-end 0))
9183 (throw 'exit (point)))
9184 (goto-char (match-end 0)))))))
9186 (defun org-do-occur (regexp &optional cleanup)
9187 "Call the Emacs command `occur'.
9188 If CLEANUP is non-nil, remove the printout of the regular expression
9189 in the *Occur* buffer. This is useful if the regex is long and not useful
9190 to read."
9191 (occur regexp)
9192 (when cleanup
9193 (let ((cwin (selected-window)) win beg end)
9194 (when (setq win (get-buffer-window "*Occur*"))
9195 (select-window win))
9196 (goto-char (point-min))
9197 (when (re-search-forward "match[a-z]+" nil t)
9198 (setq beg (match-end 0))
9199 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9200 (setq end (1- (match-beginning 0)))))
9201 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9202 (goto-char (point-min))
9203 (select-window cwin))))
9205 (defvar org-mark-ring nil
9206 "Mark ring for positions before jumps in Org-mode.")
9207 (defvar org-mark-ring-last-goto nil
9208 "Last position in the mark ring used to go back.")
9209 ;; Fill and close the ring
9210 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9211 (loop for i from 1 to org-mark-ring-length do
9212 (push (make-marker) org-mark-ring))
9213 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9214 org-mark-ring)
9216 (defun org-mark-ring-push (&optional pos buffer)
9217 "Put the current position or POS into the mark ring and rotate it."
9218 (interactive)
9219 (setq pos (or pos (point)))
9220 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9221 (move-marker (car org-mark-ring)
9222 (or pos (point))
9223 (or buffer (current-buffer)))
9224 (message
9225 (substitute-command-keys
9226 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9228 (defun org-mark-ring-goto (&optional n)
9229 "Jump to the previous position in the mark ring.
9230 With prefix arg N, jump back that many stored positions. When
9231 called several times in succession, walk through the entire ring.
9232 Org-mode commands jumping to a different position in the current file,
9233 or to another Org-mode file, automatically push the old position
9234 onto the ring."
9235 (interactive "p")
9236 (let (p m)
9237 (if (eq last-command this-command)
9238 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9239 (setq p org-mark-ring))
9240 (setq org-mark-ring-last-goto p)
9241 (setq m (car p))
9242 (switch-to-buffer (marker-buffer m))
9243 (goto-char m)
9244 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
9246 (defun org-camel-to-words (s)
9247 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
9248 (let ((case-fold-search nil)
9249 words)
9250 (while (string-match "[a-z][A-Z]" s)
9251 (push (substring s 0 (1+ (match-beginning 0))) words)
9252 (setq s (substring s (1+ (match-beginning 0)))))
9253 (nreverse (cons s words))))
9255 (defun org-remove-angle-brackets (s)
9256 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9257 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9259 (defun org-add-angle-brackets (s)
9260 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9261 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9264 (defun org-follow-bbdb-link (name)
9265 "Follow a BBDB link to NAME."
9266 (require 'bbdb)
9267 (let ((inhibit-redisplay t)
9268 (bbdb-electric-p nil))
9269 (catch 'exit
9270 ;; Exact match on name
9271 (bbdb-name (concat "\\`" name "\\'") nil)
9272 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9273 ;; Exact match on name
9274 (bbdb-company (concat "\\`" name "\\'") nil)
9275 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9276 ;; Partial match on name
9277 (bbdb-name name nil)
9278 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9279 ;; Partial match on company
9280 (bbdb-company name nil)
9281 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9282 ;; General match including network address and notes
9283 (bbdb name nil)
9284 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9285 (delete-window (get-buffer-window "*BBDB*"))
9286 (error "No matching BBDB record")))))
9289 (defun org-follow-info-link (name)
9290 "Follow an info file & node link to NAME."
9291 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9292 (string-match "\\(.*\\)" name))
9293 (progn
9294 (require 'info)
9295 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9296 (Info-find-node (match-string 1 name) (match-string 2 name))
9297 (Info-find-node (match-string 1 name) "Top")))
9298 (message (concat "Could not open: " name))))
9300 (defun org-follow-gnus-link (&optional group article)
9301 "Follow a Gnus link to GROUP and ARTICLE."
9302 (require 'gnus)
9303 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9304 (if group (gnus-fetch-group group))
9305 (if article
9306 (or (gnus-summary-goto-article article nil 'force)
9307 (if (fboundp 'gnus-summary-insert-cached-articles)
9308 (progn
9309 (gnus-summary-insert-cached-articles)
9310 (gnus-summary-goto-article article nil 'force))
9311 (message "Message could not be found.")))))
9313 (defun org-follow-vm-link (&optional folder article readonly)
9314 "Follow a VM link to FOLDER and ARTICLE."
9315 (require 'vm)
9316 (setq article (org-add-angle-brackets article))
9317 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9318 ;; ange-ftp or efs or tramp access
9319 (let ((user (or (match-string 1 folder) (user-login-name)))
9320 (host (match-string 2 folder))
9321 (file (match-string 3 folder)))
9322 (cond
9323 ((featurep 'tramp)
9324 ;; use tramp to access the file
9325 (if (featurep 'xemacs)
9326 (setq folder (format "[%s@%s]%s" user host file))
9327 (setq folder (format "/%s@%s:%s" user host file))))
9329 ;; use ange-ftp or efs
9330 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9331 (setq folder (format "/%s@%s:%s" user host file))))))
9332 (when folder
9333 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9334 (sit-for 0.1)
9335 (when article
9336 (vm-select-folder-buffer)
9337 (widen)
9338 (let ((case-fold-search t))
9339 (goto-char (point-min))
9340 (if (not (re-search-forward
9341 (concat "^" "message-id: *" (regexp-quote article))))
9342 (error "Could not find the specified message in this folder"))
9343 (vm-isearch-update)
9344 (vm-isearch-narrow)
9345 (vm-beginning-of-message)
9346 (vm-summarize)))))
9348 (defun org-follow-wl-link (folder article)
9349 "Follow a Wanderlust link to FOLDER and ARTICLE."
9350 (setq article (org-add-angle-brackets article))
9351 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
9352 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
9353 (wl-summary-redisplay))
9355 (defun org-follow-rmail-link (folder article)
9356 "Follow an RMAIL link to FOLDER and ARTICLE."
9357 (setq article (org-add-angle-brackets article))
9358 (let (message-number)
9359 (save-excursion
9360 (save-window-excursion
9361 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9362 (setq message-number
9363 (save-restriction
9364 (widen)
9365 (goto-char (point-max))
9366 (if (re-search-backward
9367 (concat "^Message-ID:\\s-+" (regexp-quote
9368 (or article "")))
9369 nil t)
9370 (rmail-what-message))))))
9371 (if message-number
9372 (progn
9373 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9374 (rmail-show-message message-number)
9375 message-number)
9376 (error "Message not found"))))
9378 ;; mh-e integration based on planner-mode
9379 (defun org-mhe-get-message-real-folder ()
9380 "Return the name of the current message real folder, so if you use
9381 sequences, it will now work."
9382 (save-excursion
9383 (let* ((folder
9384 (if (equal major-mode 'mh-folder-mode)
9385 mh-current-folder
9386 ;; Refer to the show buffer
9387 mh-show-folder-buffer))
9388 (end-index
9389 (if (boundp 'mh-index-folder)
9390 (min (length mh-index-folder) (length folder))))
9392 ;; a simple test on mh-index-data does not work, because
9393 ;; mh-index-data is always nil in a show buffer.
9394 (if (and (boundp 'mh-index-folder)
9395 (string= mh-index-folder (substring folder 0 end-index)))
9396 (if (equal major-mode 'mh-show-mode)
9397 (save-window-excursion
9398 (when (buffer-live-p (get-buffer folder))
9399 (progn
9400 (pop-to-buffer folder)
9401 (org-mhe-get-message-folder-from-index)
9404 (org-mhe-get-message-folder-from-index)
9406 folder
9410 (defun org-mhe-get-message-folder-from-index ()
9411 "Returns the name of the message folder in a index folder buffer."
9412 (save-excursion
9413 (mh-index-previous-folder)
9414 (re-search-forward "^\\(+.*\\)$" nil t)
9415 (message (match-string 1))))
9417 (defun org-mhe-get-message-folder ()
9418 "Return the name of the current message folder. Be careful if you
9419 use sequences."
9420 (save-excursion
9421 (if (equal major-mode 'mh-folder-mode)
9422 mh-current-folder
9423 ;; Refer to the show buffer
9424 mh-show-folder-buffer)))
9426 (defun org-mhe-get-message-num ()
9427 "Return the number of the current message. Be careful if you
9428 use sequences."
9429 (save-excursion
9430 (if (equal major-mode 'mh-folder-mode)
9431 (mh-get-msg-num nil)
9432 ;; Refer to the show buffer
9433 (mh-show-buffer-message-number))))
9435 (defun org-mhe-get-header (header)
9436 "Return a header of the message in folder mode. This will create a
9437 show buffer for the corresponding message. If you have a more clever
9438 idea..."
9439 (let* ((folder (org-mhe-get-message-folder))
9440 (num (org-mhe-get-message-num))
9441 (buffer (get-buffer-create (concat "show-" folder)))
9442 (header-field))
9443 (with-current-buffer buffer
9444 (mh-display-msg num folder)
9445 (if (equal major-mode 'mh-folder-mode)
9446 (mh-header-display)
9447 (mh-show-header-display))
9448 (set-buffer buffer)
9449 (setq header-field (mh-get-header-field header))
9450 (if (equal major-mode 'mh-folder-mode)
9451 (mh-show)
9452 (mh-show-show))
9453 header-field)))
9455 (defun org-follow-mhe-link (folder article)
9456 "Follow an MHE link to FOLDER and ARTICLE.
9457 If ARTICLE is nil FOLDER is shown. If the configuration variable
9458 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9459 ARTICLE is searched in all folders. Indexed searches (swish++,
9460 namazu, and others supported by MH-E) will always search in all
9461 folders."
9462 (require 'mh-e)
9463 (require 'mh-search)
9464 (require 'mh-utils)
9465 (mh-find-path)
9466 (if (not article)
9467 (mh-visit-folder (mh-normalize-folder-name folder))
9468 (setq article (org-add-angle-brackets article))
9469 (mh-search-choose)
9470 (if (equal mh-searcher 'pick)
9471 (progn
9472 (mh-search folder (list "--message-id" article))
9473 (when (and org-mhe-search-all-folders
9474 (not (org-mhe-get-message-real-folder)))
9475 (kill-this-buffer)
9476 (mh-search "+" (list "--message-id" article))))
9477 (mh-search "+" article))
9478 (if (org-mhe-get-message-real-folder)
9479 (mh-show-msg 1)
9480 (kill-this-buffer)
9481 (error "Message not found"))))
9483 ;; BibTeX links
9485 ;; Use the custom search meachnism to construct and use search strings for
9486 ;; file links to BibTeX database entries.
9488 (defun org-create-file-search-in-bibtex ()
9489 "Create the search string and description for a BibTeX database entry."
9490 (when (eq major-mode 'bibtex-mode)
9491 ;; yes, we want to construct this search string.
9492 ;; Make a good description for this entry, using names, year and the title
9493 ;; Put it into the `description' variable which is dynamically scoped.
9494 (let ((bibtex-autokey-names 1)
9495 (bibtex-autokey-names-stretch 1)
9496 (bibtex-autokey-name-case-convert-function 'identity)
9497 (bibtex-autokey-name-separator " & ")
9498 (bibtex-autokey-additional-names " et al.")
9499 (bibtex-autokey-year-length 4)
9500 (bibtex-autokey-name-year-separator " ")
9501 (bibtex-autokey-titlewords 3)
9502 (bibtex-autokey-titleword-separator " ")
9503 (bibtex-autokey-titleword-case-convert-function 'identity)
9504 (bibtex-autokey-titleword-length 'infty)
9505 (bibtex-autokey-year-title-separator ": "))
9506 (setq description (bibtex-generate-autokey)))
9507 ;; Now parse the entry, get the key and return it.
9508 (save-excursion
9509 (bibtex-beginning-of-entry)
9510 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9512 (defun org-execute-file-search-in-bibtex (s)
9513 "Find the link search string S as a key for a database entry."
9514 (when (eq major-mode 'bibtex-mode)
9515 ;; Yes, we want to do the search in this file.
9516 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9517 (goto-char (point-min))
9518 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9519 (regexp-quote s) "[ \t\n]*,") nil t)
9520 (goto-char (match-beginning 0)))
9521 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9522 ;; Use double prefix to indicate that any web link should be browsed
9523 (let ((b (current-buffer)) (p (point)))
9524 ;; Restore the window configuration because we just use the web link
9525 (set-window-configuration org-window-config-before-follow-link)
9526 (save-excursion (set-buffer b) (goto-char p)
9527 (bibtex-url)))
9528 (recenter 0)) ; Move entry start to beginning of window
9529 ;; return t to indicate that the search is done.
9532 ;; Finally add the functions to the right hooks.
9533 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9534 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9536 ;; end of Bibtex link setup
9538 (defun org-upgrade-old-links (&optional query-description)
9539 "Transfer old <...> style links to new [[...]] style links.
9540 With arg query-description, ask at each match for a description text to use
9541 for this link."
9542 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
9543 (save-excursion
9544 (goto-char (point-min))
9545 (let ((re (concat "\\([^[]\\)<\\("
9546 "\\(" (mapconcat 'identity org-link-types "\\|")
9547 "\\):"
9548 "[^" org-non-link-chars "]+\\)>"))
9549 l1 l2 (cnt 0))
9550 (while (re-search-forward re nil t)
9551 (setq cnt (1+ cnt)
9552 l1 (org-match-string-no-properties 2)
9553 l2 (save-match-data (org-link-escape l1)))
9554 (when query-description (setq l1 (read-string "Desc: " l1)))
9555 (if (equal l1 l2)
9556 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
9557 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
9558 (message "%d matches have beed treated" cnt))))
9560 (defun org-open-file (path &optional in-emacs line search)
9561 "Open the file at PATH.
9562 First, this expands any special file name abbreviations. Then the
9563 configuration variable `org-file-apps' is checked if it contains an
9564 entry for this file type, and if yes, the corresponding command is launched.
9565 If no application is found, Emacs simply visits the file.
9566 With optional argument IN-EMACS, Emacs will visit the file.
9567 Optional LINE specifies a line to go to, optional SEARCH a string to
9568 search for. If LINE or SEARCH is given, the file will always be
9569 opened in Emacs.
9570 If the file does not exist, an error is thrown."
9571 (setq in-emacs (or in-emacs line search))
9572 (let* ((file (if (equal path "")
9573 buffer-file-name
9574 path))
9575 (apps (append org-file-apps (org-default-apps)))
9576 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9577 (dirp (if remp nil (file-directory-p file)))
9578 (dfile (downcase file))
9579 (old-buffer (current-buffer))
9580 (old-pos (point))
9581 (old-mode major-mode)
9582 ext cmd)
9583 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9584 (setq ext (match-string 1 dfile))
9585 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9586 (setq ext (match-string 1 dfile))))
9587 (if in-emacs
9588 (setq cmd 'emacs)
9589 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9590 (and dirp (cdr (assoc 'directory apps)))
9591 (cdr (assoc ext apps))
9592 (cdr (assoc t apps)))))
9593 (when (eq cmd 'mailcap)
9594 (require 'mailcap)
9595 (mailcap-parse-mailcaps)
9596 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9597 (command (mailcap-mime-info mime-type)))
9598 (if (stringp command)
9599 (setq cmd command)
9600 (setq cmd 'emacs))))
9601 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
9602 (not (file-exists-p file))
9603 (not org-open-non-existing-files))
9604 (error "No such file: %s" file))
9605 (cond
9606 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9607 ;; Normalize use of quote, this can vary.
9608 (if (string-match "['\"]%s['\"]" cmd)
9609 (setq cmd (replace-match "'%s'" t t cmd)))
9610 (setq cmd (format cmd file))
9611 (save-window-excursion
9612 (shell-command (concat cmd " &"))))
9613 ((or (stringp cmd)
9614 (eq cmd 'emacs))
9615 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
9616 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
9617 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9618 (if line (goto-line line)
9619 (if search (org-link-search search))))
9620 ((consp cmd)
9621 (eval cmd))
9622 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9623 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
9624 (or (not (equal old-buffer (current-buffer)))
9625 (not (equal old-pos (point))))
9626 (org-mark-ring-push old-pos old-buffer))))
9628 (defun org-default-apps ()
9629 "Return the default applications for this operating system."
9630 (cond
9631 ((eq system-type 'darwin)
9632 org-file-apps-defaults-macosx)
9633 ((eq system-type 'windows-nt)
9634 org-file-apps-defaults-windowsnt)
9635 (t org-file-apps-defaults-gnu)))
9637 (defun org-expand-file-name (path)
9638 "Replace special path abbreviations and expand the file name."
9639 (expand-file-name path))
9641 (defun org-file-remote-p (file)
9642 "Test whether FILE specifies a location on a remote system.
9643 Return non-nil if the location is indeed remote.
9645 For example, the filename \"/user@host:/foo\" specifies a location
9646 on the system \"/user@host:\"."
9647 (cond ((fboundp 'file-remote-p)
9648 (file-remote-p file))
9649 ((fboundp 'tramp-handle-file-remote-p)
9650 (tramp-handle-file-remote-p file))
9651 ((and (boundp 'ange-ftp-name-format)
9652 (string-match ange-ftp-name-format file))
9654 (t nil)))
9656 (defvar org-insert-link-history nil
9657 "Minibuffer history for links inserted with `org-insert-link'.")
9659 (defvar org-stored-links nil
9660 "Contains the links stored with `org-store-link'.")
9662 ;;;###autoload
9663 (defun org-store-link (arg)
9664 "\\<org-mode-map>Store an org-link to the current location.
9665 This link can later be inserted into an org-buffer with
9666 \\[org-insert-link].
9667 For some link types, a prefix arg is interpreted:
9668 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9669 For file links, arg negates `org-context-in-file-links'."
9670 (interactive "P")
9671 (let (link cpltxt desc description search txt (pos (point)))
9672 (cond
9674 ((eq major-mode 'bbdb-mode)
9675 (setq cpltxt (concat
9676 "bbdb:"
9677 (or (bbdb-record-name (bbdb-current-record))
9678 (bbdb-record-company (bbdb-current-record))))
9679 link (org-make-link cpltxt)))
9681 ((eq major-mode 'Info-mode)
9682 (setq link (org-make-link "info:"
9683 (file-name-nondirectory Info-current-file)
9684 ":" Info-current-node))
9685 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9686 ":" Info-current-node)))
9688 ((eq major-mode 'calendar-mode)
9689 (let ((cd (calendar-cursor-to-date)))
9690 (setq link
9691 (format-time-string
9692 (car org-time-stamp-formats)
9693 (apply 'encode-time
9694 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9695 nil nil nil))))))
9697 ((or (eq major-mode 'vm-summary-mode)
9698 (eq major-mode 'vm-presentation-mode))
9699 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9700 (vm-follow-summary-cursor)
9701 (save-excursion
9702 (vm-select-folder-buffer)
9703 (let* ((message (car vm-message-pointer))
9704 (folder buffer-file-name)
9705 (subject (vm-su-subject message))
9706 (author (vm-su-full-name message))
9707 (message-id (vm-su-message-id message)))
9708 (setq message-id (org-remove-angle-brackets message-id))
9709 (setq folder (abbreviate-file-name folder))
9710 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9711 folder)
9712 (setq folder (replace-match "" t t folder)))
9713 (setq cpltxt (concat author " on: " subject))
9714 (setq link (org-make-link "vm:" folder "#" message-id)))))
9716 ((eq major-mode 'wl-summary-mode)
9717 (let* ((msgnum (wl-summary-message-number))
9718 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9719 msgnum 'message-id))
9720 (wl-message-entity (elmo-msgdb-overview-get-entity
9721 msgnum (wl-summary-buffer-msgdb)))
9722 (author (wl-summary-line-from)) ; FIXME: correct?
9723 (subject "???")) ; FIXME:
9724 (setq message-id (org-remove-angle-brackets message-id))
9725 (setq cpltxt (concat author " on: " subject))
9726 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9727 "#" message-id))))
9729 ((or (equal major-mode 'mh-folder-mode)
9730 (equal major-mode 'mh-show-mode))
9731 (let ((from-header (org-mhe-get-header "From:"))
9732 (to-header (org-mhe-get-header "To:"))
9733 (subject (org-mhe-get-header "Subject:")))
9734 (setq cpltxt (concat from-header " on: " subject))
9735 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9736 (org-remove-angle-brackets
9737 (org-mhe-get-header "Message-Id:"))))))
9739 ((eq major-mode 'rmail-mode)
9740 (save-excursion
9741 (save-restriction
9742 (rmail-narrow-to-non-pruned-header)
9743 (let ((folder buffer-file-name)
9744 (message-id (mail-fetch-field "message-id"))
9745 (author (mail-fetch-field "from"))
9746 (subject (mail-fetch-field "subject")))
9747 (setq message-id (org-remove-angle-brackets message-id))
9748 (setq cpltxt (concat author " on: " subject))
9749 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9751 ((eq major-mode 'gnus-group-mode)
9752 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9753 (gnus-group-group-name)) ; version
9754 ((fboundp 'gnus-group-name)
9755 (gnus-group-name))
9756 (t "???"))))
9757 (setq cpltxt (concat
9758 (if (org-xor arg org-usenet-links-prefer-google)
9759 "http://groups.google.com/groups?group="
9760 "gnus:")
9761 group)
9762 link (org-make-link cpltxt))))
9764 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9765 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9766 (gnus-summary-beginning-of-article)
9767 (let* ((group (car gnus-article-current))
9768 (article (cdr gnus-article-current))
9769 (header (gnus-summary-article-header article))
9770 (author (mail-header-from header))
9771 (message-id (mail-header-id header))
9772 (date (mail-header-date header))
9773 (subject (gnus-summary-subject-string)))
9774 (setq cpltxt (concat author " on: " subject))
9775 (if (org-xor arg org-usenet-links-prefer-google)
9776 (setq link
9777 (concat
9778 cpltxt "\n "
9779 (format "http://groups.google.com/groups?as_umsgid=%s"
9780 (org-fixup-message-id-for-http message-id))))
9781 (setq link (org-make-link "gnus:" group
9782 "#" (number-to-string article))))))
9784 ((eq major-mode 'w3-mode)
9785 (setq cpltxt (url-view-url t)
9786 link (org-make-link cpltxt)))
9787 ((eq major-mode 'w3m-mode)
9788 (setq cpltxt (or w3m-current-title w3m-current-url)
9789 link (org-make-link w3m-current-url)))
9791 ((setq search (run-hook-with-args-until-success
9792 'org-create-file-search-functions))
9793 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9794 "::" search))
9795 (setq cpltxt (or description link)))
9797 ((eq major-mode 'image-mode)
9798 (setq cpltxt (concat "file:"
9799 (abbreviate-file-name buffer-file-name))
9800 link (org-make-link cpltxt)))
9802 ((eq major-mode 'org-mode)
9803 ;; Just link to current headline
9804 (setq cpltxt (concat "file:"
9805 (abbreviate-file-name buffer-file-name)))
9806 ;; Add a context search string
9807 (when (org-xor org-context-in-file-links arg)
9808 ;; Check if we are on a target
9809 (if (save-excursion
9810 (skip-chars-forward "^>\n\r")
9811 (and (re-search-backward "<<" nil t)
9812 (looking-at "<<\\(.*?\\)>>")
9813 (<= (match-beginning 0) pos)
9814 (>= (match-end 0) pos)))
9815 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9816 (setq txt (cond
9817 ((org-on-heading-p) nil)
9818 ((org-region-active-p)
9819 (buffer-substring (region-beginning) (region-end)))
9820 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9821 (when (or (null txt) (string-match "\\S-" txt))
9822 (setq cpltxt
9823 (concat cpltxt "::"
9824 (if org-file-link-context-use-camel-case
9825 (org-make-org-heading-camel txt)
9826 (org-make-org-heading-search-string txt)))
9827 desc "NONE"))))
9828 (if (string-match "::\\'" cpltxt)
9829 (setq cpltxt (substring cpltxt 0 -2)))
9830 (setq link (org-make-link cpltxt)))
9832 (buffer-file-name
9833 ;; Just link to this file here.
9834 (setq cpltxt (concat "file:"
9835 (abbreviate-file-name buffer-file-name)))
9836 ;; Add a context string
9837 (when (org-xor org-context-in-file-links arg)
9838 (setq txt (if (org-region-active-p)
9839 (buffer-substring (region-beginning) (region-end))
9840 (buffer-substring (point-at-bol) (point-at-eol))))
9841 ;; Only use search option if there is some text.
9842 (when (string-match "\\S-" txt)
9843 (setq cpltxt
9844 (concat cpltxt "::"
9845 (if org-file-link-context-use-camel-case
9846 (org-make-org-heading-camel txt)
9847 (org-make-org-heading-search-string txt)))
9848 desc "NONE")))
9849 (setq link (org-make-link cpltxt)))
9851 ((interactive-p)
9852 (error "Cannot link to a buffer which is not visiting a file"))
9854 (t (setq link nil)))
9856 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9857 (setq link (or link cpltxt)
9858 desc (or desc cpltxt))
9859 (if (equal desc "NONE") (setq desc nil))
9861 (if (and (interactive-p) link)
9862 (progn
9863 (setq org-stored-links
9864 (cons (list cpltxt link desc) org-stored-links))
9865 (message "Stored: %s" (or cpltxt link)))
9866 (org-make-link-string link desc))))
9868 (defun org-make-org-heading-search-string (&optional string heading)
9869 "Make search string for STRING or current headline."
9870 (interactive)
9871 (let ((s (or string (org-get-heading))))
9872 (unless (and string (not heading))
9873 ;; We are using a headline, clean up garbage in there.
9874 (if (string-match org-todo-regexp s)
9875 (setq s (replace-match "" t t s)))
9876 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9877 (setq s (replace-match "" t t s)))
9878 (setq s (org-trim s))
9879 (if (string-match (concat "^\\(" org-quote-string "\\|"
9880 org-comment-string "\\)") s)
9881 (setq s (replace-match "" t t s)))
9882 (while (string-match org-ts-regexp s)
9883 (setq s (replace-match "" t t s))))
9884 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
9885 (setq s (replace-match " " t t s)))
9886 (or string (setq s (concat "*" s))) ; Add * for headlines
9887 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9889 (defun org-make-org-heading-camel (&optional string heading)
9890 "Make a CamelCase string for STRING or the current headline."
9891 (interactive)
9892 (let ((s (or string (org-get-heading))))
9893 (unless (and string (not heading))
9894 ;; We are using a headline, clean up garbage in there.
9895 (if (string-match org-todo-regexp s)
9896 (setq s (replace-match "" t t s)))
9897 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9898 (setq s (replace-match "" t t s)))
9899 (setq s (org-trim s))
9900 (if (string-match (concat "^\\(" org-quote-string "\\|"
9901 org-comment-string "\\)") s)
9902 (setq s (replace-match "" t t s)))
9903 (while (string-match org-ts-regexp s)
9904 (setq s (replace-match "" t t s))))
9905 (while (string-match "[^a-zA-Z_ \t]+" s)
9906 (setq s (replace-match " " t t s)))
9907 (or string (setq s (concat "*" s))) ; Add * for headlines
9908 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
9910 (defun org-make-link (&rest strings)
9911 "Concatenate STRINGS, format resulting string with `org-link-format'."
9912 (format org-link-format (apply 'concat strings)))
9914 (defun org-make-link-string (link &optional description)
9915 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9916 (if (eq org-link-style 'plain)
9917 (if (equal description link)
9918 link
9919 (concat description "\n" link))
9920 (when (stringp description)
9921 ;; Remove brackets from the description, they are fatal.
9922 (while (string-match "\\[\\|\\]" description)
9923 (setq description (replace-match "" t t description))))
9924 (when (equal (org-link-escape link) description)
9925 ;; No description needed, it is identical
9926 (setq description nil))
9927 (when (and (not description)
9928 (not (equal link (org-link-escape link))))
9929 (setq description link))
9930 (concat "[[" (org-link-escape link) "]"
9931 (if description (concat "[" description "]") "")
9932 "]")))
9934 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9935 "Association list of escapes for some characters problematic in links.")
9937 (defun org-link-escape (text)
9938 "Escape charaters in TEXT that are problematic for links."
9939 (when text
9940 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9941 org-link-escape-chars "\\|")))
9942 (while (string-match re text)
9943 (setq text
9944 (replace-match
9945 (cdr (assoc (match-string 0 text) org-link-escape-chars))
9946 t t text)))
9947 text)))
9949 (defun org-link-unescape (text)
9950 "Reverse the action of `org-link-escape'."
9951 (when text
9952 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
9953 org-link-escape-chars "\\|")))
9954 (while (string-match re text)
9955 (setq text
9956 (replace-match
9957 (car (rassoc (match-string 0 text) org-link-escape-chars))
9958 t t text)))
9959 text)))
9961 (defun org-xor (a b)
9962 "Exclusive or."
9963 (if a (not b) b))
9965 (defun org-get-header (header)
9966 "Find a header field in the current buffer."
9967 (save-excursion
9968 (goto-char (point-min))
9969 (let ((case-fold-search t) s)
9970 (cond
9971 ((eq header 'from)
9972 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
9973 (setq s (match-string 1)))
9974 (while (string-match "\"" s)
9975 (setq s (replace-match "" t t s)))
9976 (if (string-match "[<(].*" s)
9977 (setq s (replace-match "" t t s))))
9978 ((eq header 'message-id)
9979 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
9980 (setq s (match-string 1))))
9981 ((eq header 'subject)
9982 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
9983 (setq s (match-string 1)))))
9984 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
9985 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
9986 s)))
9989 (defun org-fixup-message-id-for-http (s)
9990 "Replace special characters in a message id, so it can be used in an http query."
9991 (while (string-match "<" s)
9992 (setq s (replace-match "%3C" t t s)))
9993 (while (string-match ">" s)
9994 (setq s (replace-match "%3E" t t s)))
9995 (while (string-match "@" s)
9996 (setq s (replace-match "%40" t t s)))
9999 (defun org-insert-link (&optional complete-file)
10000 "Insert a link. At the prompt, enter the link.
10002 Completion can be used to select a link previously stored with
10003 `org-store-link'. When the empty string is entered (i.e. if you just
10004 press RET at the prompt), the link defaults to the most recently
10005 stored link. As SPC triggers completion in the minibuffer, you need to
10006 use M-SPC or C-q SPC to force the insertion of a space character.
10008 You will also be prompted for a description, and if one is given, it will
10009 be displayed in the buffer instead of the link.
10011 If there is already a link at point, this command will allow you to edit link
10012 and description parts.
10014 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10015 selected using completion. The path to the file will be relative to
10016 the current directory if the file is in the current directory or a
10017 subdirectory. Otherwise, the link will be the absolute path as
10018 completed in the minibuffer (i.e. normally ~/path/to/file).
10020 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10021 is in the current directory or below.
10022 With three \\[universal-argument] prefixes, negate the meaning of
10023 `org-keep-stored-link-after-insertion'."
10024 (interactive "P")
10025 (let (link desc entry remove file (pos (point)))
10026 (cond
10027 ((save-excursion
10028 (skip-chars-forward "^]\n\r")
10029 (and (re-search-backward "\\[\\[" nil t)
10030 (looking-at org-bracket-link-regexp)
10031 (<= (match-beginning 0) pos)
10032 (>= (match-end 0) pos)))
10033 ;; We do have a link at point, and we are going to edit it.
10034 (setq remove (list (match-beginning 0) (match-end 0)))
10035 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10036 (setq link (read-string "Link: "
10037 (org-link-unescape
10038 (org-match-string-no-properties 1)))))
10039 ((equal complete-file '(4))
10040 ;; Completing read for file names.
10041 (setq file (read-file-name "File: "))
10042 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10043 (pwd1 (file-name-as-directory (abbreviate-file-name
10044 (expand-file-name ".")))))
10045 (cond
10046 ((equal complete-file '(16))
10047 (setq link (org-make-link
10048 "file:"
10049 (abbreviate-file-name (expand-file-name file)))))
10050 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10051 (setq link (org-make-link "file:" (match-string 1 file))))
10052 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10053 (expand-file-name file))
10054 (setq link (org-make-link
10055 "file:" (match-string 1 (expand-file-name file)))))
10056 (t (setq link (org-make-link "file:" file))))))
10058 ;; Read link, with completion for stored links.
10059 (setq link (org-completing-read
10060 "Link: " org-stored-links nil nil nil
10061 org-insert-link-history
10062 (or (car (car org-stored-links)))))
10063 (setq entry (assoc link org-stored-links))
10064 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10065 (not org-keep-stored-link-after-insertion))
10066 (setq org-stored-links (delq (assoc link org-stored-links)
10067 org-stored-links)))
10068 (setq link (if entry (nth 1 entry) link)
10069 desc (or desc (nth 2 entry)))))
10071 (if (string-match org-plain-link-re link)
10072 ;; URL-like link, normalize the use of angular brackets.
10073 (setq link (org-make-link (org-remove-angle-brackets link))))
10075 ;; Check if we are linking to the current file with a search option
10076 ;; If yes, simplify the link by using only the search option.
10077 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
10078 (let* ((path (match-string 1 link))
10079 (case-fold-search nil)
10080 (search (match-string 2 link)))
10081 (save-match-data
10082 (if (equal (file-truename buffer-file-name) (file-truename path))
10083 ;; We are linking to this same file, with a search option
10084 (setq link search)))))
10086 ;; Check if we can/should use a relative path. If yes, simplify the link
10087 (when (string-match "\\<file:\\(.*\\)" link)
10088 (let* ((path (match-string 1 link))
10089 (case-fold-search nil))
10090 (cond
10091 ((eq org-link-file-path-type 'absolute)
10092 (setq path (abbreviate-file-name (expand-file-name path))))
10093 ((eq org-link-file-path-type 'noabbrev)
10094 (setq path (expand-file-name path)))
10095 ((eq org-link-file-path-type 'relative)
10096 (setq path (file-relative-name path)))
10098 (save-match-data
10099 (if (string-match (concat "^" (regexp-quote
10100 (file-name-as-directory
10101 (expand-file-name "."))))
10102 (expand-file-name path))
10103 ;; We are linking a file with relative path name.
10104 (setq path (substring (expand-file-name path)
10105 (match-end 0)))))))
10106 (setq link (concat "file:" path))))
10108 (setq desc (read-string "Description: " desc))
10109 (unless (string-match "\\S-" desc) (setq desc nil))
10110 (if remove (apply 'delete-region remove))
10111 (insert (org-make-link-string link desc))))
10113 (defun org-completing-read (&rest args)
10114 (let ((minibuffer-local-completion-map
10115 (copy-keymap minibuffer-local-completion-map)))
10116 (define-key minibuffer-local-completion-map " " 'self-insert-command)
10117 (apply 'completing-read args)))
10119 ;;; Hooks for remember.el
10121 (defvar org-finish-function nil)
10123 ;;;###autoload
10124 (defun org-remember-annotation ()
10125 "Return a link to the current location as an annotation for remember.el.
10126 If you are using Org-mode files as target for data storage with
10127 remember.el, then the annotations should include a link compatible with the
10128 conventions in Org-mode. This function returns such a link."
10129 (org-store-link nil))
10131 (defconst org-remember-help
10132 "Select a destination location for the note.
10133 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10134 RET at beg-of-buf -> Append to file as level 2 headline
10135 RET on headline -> Store as sublevel entry to current headline
10136 <left>/<right> -> before/after current headline, same headings level")
10138 ;;;###autoload
10139 (defun org-remember-apply-template ()
10140 "Initialize *remember* buffer with template, invoke `org-mode'.
10141 This function should be placed into `remember-mode-hook' and in fact requires
10142 to be run from that hook to fucntion properly."
10143 (if org-remember-templates
10145 (let* ((entry (if (= (length org-remember-templates) 1)
10146 (cdar org-remember-templates)
10147 (message "Select template: %s"
10148 (mapconcat
10149 (lambda (x) (char-to-string (car x)))
10150 org-remember-templates " "))
10151 (cdr (assoc (read-char-exclusive) org-remember-templates))))
10152 (tpl (car entry))
10153 (file (if (consp (cdr entry)) (nth 1 entry)))
10154 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10155 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10156 (v-u (concat "[" (substring v-t 1 -1) "]"))
10157 (v-U (concat "[" (substring v-T 1 -1) "]"))
10158 (v-a annotation) ; defined in `remember-mode'
10159 (v-i initial) ; defined in `remember-mode'
10160 (v-n user-full-name)
10162 (unless tpl (setq tpl "") (message "No template") (ding))
10163 (insert tpl) (goto-char (point-min))
10164 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
10165 (when (and initial (equal (match-string 0) "%i"))
10166 (save-match-data
10167 (let* ((lead (buffer-substring
10168 (point-at-bol) (match-beginning 0))))
10169 (setq v-i (mapconcat 'identity
10170 (org-split-string initial "\n")
10171 (concat "\n" lead))))))
10172 (replace-match
10173 (or (eval (intern (concat "v-" (match-string 1)))) "")
10174 t t))
10175 (let ((org-startup-folded nil)
10176 (org-startup-with-deadline-check nil))
10177 (org-mode))
10178 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10179 (set (make-local-variable 'org-default-notes-file) file))
10180 (goto-char (point-min))
10181 (if (re-search-forward "%\\?" nil t) (replace-match "")))
10182 (let ((org-startup-folded nil)
10183 (org-startup-with-deadline-check nil))
10184 (org-mode)))
10185 (set (make-local-variable 'org-finish-function) 'remember-buffer))
10187 ;;;###autoload
10188 (defun org-remember-handler ()
10189 "Store stuff from remember.el into an org file.
10190 First prompts for an org file. If the user just presses return, the value
10191 of `org-default-notes-file' is used.
10192 Then the command offers the headings tree of the selected file in order to
10193 file the text at a specific location.
10194 You can either immediately press RET to get the note appended to the
10195 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10196 find a better place. Then press RET or <left> or <right> in insert the note.
10198 Key Cursor position Note gets inserted
10199 -----------------------------------------------------------------------------
10200 RET buffer-start as level 2 heading at end of file
10201 RET on headline as sublevel of the heading at cursor
10202 RET no heading at cursor position, level taken from context.
10203 Or use prefix arg to specify level manually.
10204 <left> on headline as same level, before current heading
10205 <right> on headline as same level, after current heading
10207 So the fastest way to store the note is to press RET RET to append it to
10208 the default file. This way your current train of thought is not
10209 interrupted, in accordance with the principles of remember.el. But with
10210 little extra effort, you can push it directly to the correct location.
10212 Before being stored away, the function ensures that the text has a
10213 headline, i.e. a first line that starts with a \"*\". If not, a headline
10214 is constructed from the current date and some additional data.
10216 If the variable `org-adapt-indentation' is non-nil, the entire text is
10217 also indented so that it starts in the same column as the headline
10218 \(i.e. after the stars).
10220 See also the variable `org-reverse-note-order'."
10221 (catch 'quit
10222 (let* ((txt (buffer-substring (point-min) (point-max)))
10223 (fastp current-prefix-arg)
10224 (file (if fastp org-default-notes-file (org-get-org-file)))
10225 (visiting (find-buffer-visiting file))
10226 (org-startup-with-deadline-check nil)
10227 (org-startup-folded nil)
10228 (org-startup-align-all-tables nil)
10229 spos level indent reversed)
10230 ;; Modify text so that it becomes a nice subtree which can be inserted
10231 ;; into an org tree.
10232 (let* ((lines (split-string txt "\n"))
10233 first)
10234 ;; remove empty lines at the beginning
10235 (while (and lines (string-match "^[ \t]*\n" (car lines)))
10236 (setq lines (cdr lines)))
10237 (setq first (car lines) lines (cdr lines))
10238 (if (string-match "^\\*+" first)
10239 ;; Is already a headline
10240 (setq indent nil)
10241 ;; We need to add a headline: Use time and first buffer line
10242 (setq lines (cons first lines)
10243 first (concat "* " (current-time-string)
10244 " (" (remember-buffer-desc) ")")
10245 indent " "))
10246 (if (and org-adapt-indentation indent)
10247 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10248 (setq txt (concat first "\n"
10249 (mapconcat 'identity lines "\n"))))
10250 ;; Find the file
10251 (if (not visiting)
10252 (find-file-noselect file))
10253 (with-current-buffer (get-file-buffer file)
10254 (save-excursion (and (goto-char (point-min))
10255 (not (re-search-forward "^\\* " nil t))
10256 (insert "\n* Notes\n")))
10257 (setq reversed (org-notes-order-reversed-p))
10258 (save-excursion
10259 (save-restriction
10260 (widen)
10261 ;; Ask the User for a location
10262 (setq spos (if fastp 1 (org-get-location
10263 (current-buffer)
10264 org-remember-help)))
10265 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10266 ; not handle this note
10267 (goto-char spos)
10268 (cond ((bobp)
10269 ;; Put it at the start or end, as level 2
10270 (save-restriction
10271 (widen)
10272 (goto-char (if reversed (point-min) (point-max)))
10273 (if (not (bolp)) (newline))
10274 (org-paste-subtree 2 txt)))
10275 ((and (org-on-heading-p nil) (not current-prefix-arg))
10276 ;; Put it below this entry, at the beg/end of the subtree
10277 (org-back-to-heading)
10278 (setq level (funcall outline-level))
10279 (if reversed
10280 (outline-end-of-heading)
10281 (outline-end-of-subtree))
10282 (if (not (bolp)) (newline))
10283 (beginning-of-line 1)
10284 (org-paste-subtree (1+ level) txt))
10286 ;; Put it right there, with automatic level determined by
10287 ;; org-paste-subtree or from prefix arg
10288 (org-paste-subtree current-prefix-arg txt)))
10289 (when remember-save-after-remembering
10290 (save-buffer)
10291 (if (not visiting) (kill-buffer (current-buffer)))))))))
10292 t) ;; return t to indicate that we took care of this note.
10294 (defun org-get-org-file ()
10295 "Read a filename, with default directory `org-directory'."
10296 (let ((default (or org-default-notes-file remember-data-file)))
10297 (read-file-name (format "File name [%s]: " default)
10298 (file-name-as-directory org-directory)
10299 default)))
10301 (defun org-notes-order-reversed-p ()
10302 "Check if the current file should receive notes in reversed order."
10303 (cond
10304 ((not org-reverse-note-order) nil)
10305 ((eq t org-reverse-note-order) t)
10306 ((not (listp org-reverse-note-order)) nil)
10307 (t (catch 'exit
10308 (let ((all org-reverse-note-order)
10309 entry)
10310 (while (setq entry (pop all))
10311 (if (string-match (car entry) buffer-file-name)
10312 (throw 'exit (cdr entry))))
10313 nil)))))
10315 ;;; Tables
10317 ;; Watch out: Here we are talking about two different kind of tables.
10318 ;; Most of the code is for the tables created with the Org-mode table editor.
10319 ;; Sometimes, we talk about tables created and edited with the table.el
10320 ;; Emacs package. We call the former org-type tables, and the latter
10321 ;; table.el-type tables.
10324 (defun org-before-change-function (beg end)
10325 "Every change indicates that a table might need an update."
10326 (setq org-table-may-need-update t))
10328 (defconst org-table-line-regexp "^[ \t]*|"
10329 "Detects an org-type table line.")
10330 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
10331 "Detects an org-type table line.")
10332 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
10333 "Detects a table line marked for automatic recalculation.")
10334 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
10335 "Detects a table line marked for automatic recalculation.")
10336 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
10337 "Detects a table line marked for automatic recalculation.")
10338 (defconst org-table-hline-regexp "^[ \t]*|-"
10339 "Detects an org-type table hline.")
10340 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
10341 "Detects a table-type table hline.")
10342 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
10343 "Detects an org-type or table-type table.")
10344 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
10345 "Searching from within a table (any type) this finds the first line
10346 outside the table.")
10347 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
10348 "Searching from within a table (any type) this finds the first line
10349 outside the table.")
10351 (defun org-table-create-with-table.el ()
10352 "Use the table.el package to insert a new table.
10353 If there is already a table at point, convert between Org-mode tables
10354 and table.el tables."
10355 (interactive)
10356 (require 'table)
10357 (cond
10358 ((org-at-table.el-p)
10359 (if (y-or-n-p "Convert table to Org-mode table? ")
10360 (org-table-convert)))
10361 ((org-at-table-p)
10362 (if (y-or-n-p "Convert table to table.el table? ")
10363 (org-table-convert)))
10364 (t (call-interactively 'table-insert))))
10366 (defun org-table-create-or-convert-from-region (arg)
10367 "Convert region to table, or create an empty table.
10368 If there is an active region, convert it to a table. If there is no such
10369 region, create an empty table."
10370 (interactive "P")
10371 (if (org-region-active-p)
10372 (org-table-convert-region (region-beginning) (region-end) arg)
10373 (org-table-create arg)))
10375 (defun org-table-create (&optional size)
10376 "Query for a size and insert a table skeleton.
10377 SIZE is a string Columns x Rows like for example \"3x2\"."
10378 (interactive "P")
10379 (unless size
10380 (setq size (read-string
10381 (concat "Table size Columns x Rows [e.g. "
10382 org-table-default-size "]: ")
10383 "" nil org-table-default-size)))
10385 (let* ((pos (point))
10386 (indent (make-string (current-column) ?\ ))
10387 (split (org-split-string size " *x *"))
10388 (rows (string-to-number (nth 1 split)))
10389 (columns (string-to-number (car split)))
10390 (line (concat (apply 'concat indent "|" (make-list columns " |"))
10391 "\n")))
10392 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
10393 (point-at-bol) (point)))
10394 (beginning-of-line 1)
10395 (newline))
10396 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
10397 (dotimes (i rows) (insert line))
10398 (goto-char pos)
10399 (if (> rows 1)
10400 ;; Insert a hline after the first row.
10401 (progn
10402 (end-of-line 1)
10403 (insert "\n|-")
10404 (goto-char pos)))
10405 (org-table-align)))
10407 (defun org-table-convert-region (beg0 end0 &optional nspace)
10408 "Convert region to a table.
10409 The region goes from BEG0 to END0, but these borders will be moved
10410 slightly, to make sure a beginning of line in the first line is included.
10411 When NSPACE is non-nil, it indicates the minimum number of spaces that
10412 separate columns (default: just one space)."
10413 (interactive "rP")
10414 (let* ((beg (min beg0 end0))
10415 (end (max beg0 end0))
10416 (tabsep t)
10418 (goto-char beg)
10419 (beginning-of-line 1)
10420 (setq beg (move-marker (make-marker) (point)))
10421 (goto-char end)
10422 (if (bolp) (backward-char 1) (end-of-line 1))
10423 (setq end (move-marker (make-marker) (point)))
10424 ;; Lets see if this is tab-separated material. If every nonempty line
10425 ;; contains a tab, we will assume that it is tab-separated material
10426 (if nspace
10427 (setq tabsep nil)
10428 (goto-char beg)
10429 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
10430 (if nspace (setq tabsep nil))
10431 (if tabsep
10432 (setq re "^\\|\t")
10433 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
10434 (max 1 (prefix-numeric-value nspace)))))
10435 (goto-char beg)
10436 (while (re-search-forward re end t)
10437 (replace-match "|" t t))
10438 (goto-char beg)
10439 (insert " ")
10440 (org-table-align)))
10442 (defun org-table-import (file arg)
10443 "Import FILE as a table.
10444 The file is assumed to be tab-separated. Such files can be produced by most
10445 spreadsheet and database applications. If no tabs (at least one per line)
10446 are found, lines will be split on whitespace into fields."
10447 (interactive "f\nP")
10448 (or (bolp) (newline))
10449 (let ((beg (point))
10450 (pm (point-max)))
10451 (insert-file-contents file)
10452 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
10454 (defun org-table-export ()
10455 "Export table as a tab-separated file.
10456 Such a file can be imported into a spreadsheet program like Excel."
10457 (interactive)
10458 (let* ((beg (org-table-begin))
10459 (end (org-table-end))
10460 (table (buffer-substring beg end))
10461 (file (read-file-name "Export table to: "))
10462 buf)
10463 (unless (or (not (file-exists-p file))
10464 (y-or-n-p (format "Overwrite file %s? " file)))
10465 (error "Abort"))
10466 (with-current-buffer (find-file-noselect file)
10467 (setq buf (current-buffer))
10468 (erase-buffer)
10469 (fundamental-mode)
10470 (insert table)
10471 (goto-char (point-min))
10472 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
10473 (replace-match "" t t)
10474 (end-of-line 1))
10475 (goto-char (point-min))
10476 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
10477 (replace-match "" t t)
10478 (goto-char (min (1+ (point)) (point-max))))
10479 (goto-char (point-min))
10480 (while (re-search-forward "^-[-+]*$" nil t)
10481 (replace-match "")
10482 (if (looking-at "\n")
10483 (delete-char 1)))
10484 (goto-char (point-min))
10485 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
10486 (replace-match "\t" t t))
10487 (save-buffer))
10488 (kill-buffer buf)))
10490 (defvar org-table-aligned-begin-marker (make-marker)
10491 "Marker at the beginning of the table last aligned.
10492 Used to check if cursor still is in that table, to minimize realignment.")
10493 (defvar org-table-aligned-end-marker (make-marker)
10494 "Marker at the end of the table last aligned.
10495 Used to check if cursor still is in that table, to minimize realignment.")
10496 (defvar org-table-last-alignment nil
10497 "List of flags for flushright alignment, from the last re-alignment.
10498 This is being used to correctly align a single field after TAB or RET.")
10499 (defvar org-table-last-column-widths nil
10500 "List of max width of fields in each column.
10501 This is being used to correctly align a single field after TAB or RET.")
10503 (defvar org-last-recalc-line nil)
10504 (defconst org-narrow-column-arrow "=>"
10505 "Used as display property in narrowed table columns.")
10507 (defun org-table-align ()
10508 "Align the table at point by aligning all vertical bars."
10509 (interactive)
10510 (let* (
10511 ;; Limits of table
10512 (beg (org-table-begin))
10513 (end (org-table-end))
10514 ;; Current cursor position
10515 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10516 (colpos (org-table-current-column))
10517 (winstart (window-start))
10518 lines (new "") lengths l typenums ty fields maxfields i
10519 column
10520 (indent "") cnt frac
10521 rfmt hfmt
10522 (spaces '(1 . 1))
10523 (sp1 (car spaces))
10524 (sp2 (cdr spaces))
10525 (rfmt1 (concat
10526 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
10527 (hfmt1 (concat
10528 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
10529 emptystrings links narrow fmax f1 len c e)
10530 (untabify beg end)
10531 (remove-text-properties beg end '(org-cwidth t display t))
10532 ;; Check if we have links
10533 (goto-char beg)
10534 (setq links (re-search-forward org-bracket-link-regexp end t))
10535 ;; Make sure the link properties are right
10536 (when links (goto-char beg) (while (org-activate-bracket-links end)))
10537 ;; Check if we are narrowing any columns
10538 (goto-char beg)
10539 (setq narrow (and org-format-transports-properties-p
10540 (re-search-forward "<[0-9]+>" end t)))
10541 ;; Get the rows
10542 (setq lines (org-split-string
10543 (buffer-substring beg end) "\n"))
10544 ;; Store the indentation of the first line
10545 (if (string-match "^ *" (car lines))
10546 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
10547 ;; Mark the hlines by setting the corresponding element to nil
10548 ;; At the same time, we remove trailing space.
10549 (setq lines (mapcar (lambda (l)
10550 (if (string-match "^ *|-" l)
10552 (if (string-match "[ \t]+$" l)
10553 (substring l 0 (match-beginning 0))
10554 l)))
10555 lines))
10556 ;; Get the data fields by splitting the lines.
10557 (setq fields (mapcar
10558 (lambda (l)
10559 (org-split-string l " *| *"))
10560 (delq nil (copy-sequence lines))))
10561 ;; How many fields in the longest line?
10562 (condition-case nil
10563 (setq maxfields (apply 'max (mapcar 'length fields)))
10564 (error
10565 (kill-region beg end)
10566 (org-table-create org-table-default-size)
10567 (error "Empty table - created default table")))
10568 ;; A list of empty string to fill any short rows on output
10569 (setq emptystrings (make-list maxfields ""))
10570 ;; Check for special formatting.
10571 (setq i -1)
10572 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
10573 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
10574 ;; Check if there is an explicit width specified
10575 (when (and org-table-limit-column-width narrow)
10576 (setq c column fmax nil)
10577 (while c
10578 (setq e (pop c))
10579 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
10580 (setq fmax (string-to-number (match-string 1 e)) c nil)))
10581 ;; Find fields that are wider than fmax, and shorten them
10582 (when fmax
10583 (loop for xx in column do
10584 (when (and (stringp xx)
10585 (> (org-string-width xx) fmax))
10586 (org-add-props xx nil
10587 'help-echo
10588 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
10589 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
10590 (unless (> f1 1)
10591 (error "Cannot narrow field starting with wide link \"%s\""
10592 (match-string 0 xx)))
10593 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
10594 (add-text-properties (- f1 2) f1
10595 (list 'display org-narrow-column-arrow)
10596 xx)))))
10597 ;; Get the maximum width for each column
10598 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
10599 ;; Get the fraction of numbers, to decide about alignment of the column
10600 (setq cnt 0 frac 0.0)
10601 (loop for x in column do
10602 (if (equal x "")
10604 (setq frac ( / (+ (* frac cnt)
10605 (if (string-match org-table-number-regexp x) 1 0))
10606 (setq cnt (1+ cnt))))))
10607 (push (>= frac org-table-number-fraction) typenums))
10608 (setq lengths (nreverse lengths) typenums (nreverse typenums))
10610 ;; Store the alignment of this table, for later editing of single fields
10611 (setq org-table-last-alignment typenums
10612 org-table-last-column-widths lengths)
10614 ;; With invisible characters, `format' does not get the field width right
10615 ;; So we need to make these fields wide by hand.
10616 (when links
10617 (loop for i from 0 upto (1- maxfields) do
10618 (setq len (nth i lengths))
10619 (loop for j from 0 upto (1- (length fields)) do
10620 (setq c (nthcdr i (car (nthcdr j fields))))
10621 (if (and (stringp (car c))
10622 (string-match org-bracket-link-regexp (car c))
10623 (< (org-string-width (car c)) len))
10624 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
10626 ;; Compute the formats needed for output of the table
10627 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
10628 (while (setq l (pop lengths))
10629 (setq ty (if (pop typenums) "" "-")) ; number types flushright
10630 (setq rfmt (concat rfmt (format rfmt1 ty l))
10631 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
10632 (setq rfmt (concat rfmt "\n")
10633 hfmt (concat (substring hfmt 0 -1) "|\n"))
10635 (setq new (mapconcat
10636 (lambda (l)
10637 (if l (apply 'format rfmt
10638 (append (pop fields) emptystrings))
10639 hfmt))
10640 lines ""))
10641 ;; Replace the old one
10642 (delete-region beg end)
10643 (move-marker end nil)
10644 (move-marker org-table-aligned-begin-marker (point))
10645 (insert new)
10646 (move-marker org-table-aligned-end-marker (point))
10647 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
10648 (goto-char org-table-aligned-begin-marker)
10649 (while (org-hide-wide-columns org-table-aligned-end-marker)))
10650 ;; Try to move to the old location (approximately)
10651 (goto-line linepos)
10652 (set-window-start (selected-window) winstart 'noforce)
10653 (org-table-goto-column colpos)
10654 (setq org-table-may-need-update nil)
10657 (defun org-string-width (s)
10658 "Compute width of string, ignoring invisible characters.
10659 This ignores character with invisibility property `org-link', and also
10660 characters with property `org-cwidth', because these will become invisible
10661 upon the next fontification round."
10662 (let (b)
10663 (when (or (eq t buffer-invisibility-spec)
10664 (assq 'org-link buffer-invisibility-spec))
10665 (while (setq b (text-property-any 0 (length s)
10666 'invisible 'org-link s))
10667 (setq s (concat (substring s 0 b)
10668 (substring s (or (next-single-property-change
10669 b 'invisible s) (length s)))))))
10670 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
10671 (setq s (concat (substring s 0 b)
10672 (substring s (or (next-single-property-change
10673 b 'org-cwidth s) (length s))))))
10674 (string-width s)))
10676 (defun org-table-begin (&optional table-type)
10677 "Find the beginning of the table and return its position.
10678 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
10679 (save-excursion
10680 (if (not (re-search-backward
10681 (if table-type org-table-any-border-regexp
10682 org-table-border-regexp)
10683 nil t))
10684 (progn (goto-char (point-min)) (point))
10685 (goto-char (match-beginning 0))
10686 (beginning-of-line 2)
10687 (point))))
10689 (defun org-table-end (&optional table-type)
10690 "Find the end of the table and return its position.
10691 With argument TABLE-TYPE, go to the end of a table.el-type table."
10692 (save-excursion
10693 (if (not (re-search-forward
10694 (if table-type org-table-any-border-regexp
10695 org-table-border-regexp)
10696 nil t))
10697 (goto-char (point-max))
10698 (goto-char (match-beginning 0)))
10699 (point-marker)))
10701 (defun org-table-justify-field-maybe (&optional new)
10702 "Justify the current field, text to left, number to right.
10703 Optional argument NEW may specify text to replace the current field content."
10704 (cond
10705 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
10706 ((org-at-table-hline-p))
10707 ((and (not new)
10708 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
10709 (current-buffer)))
10710 (< (point) org-table-aligned-begin-marker)
10711 (>= (point) org-table-aligned-end-marker)))
10712 ;; This is not the same table, force a full re-align
10713 (setq org-table-may-need-update t))
10714 (t ;; realign the current field, based on previous full realign
10715 (let* ((pos (point)) s
10716 (col (org-table-current-column))
10717 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
10718 l f n o e)
10719 (when (> col 0)
10720 (skip-chars-backward "^|\n")
10721 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
10722 (progn
10723 (setq s (match-string 1)
10724 o (match-string 0)
10725 l (max 1 (- (match-end 0) (match-beginning 0) 3))
10726 e (not (= (match-beginning 2) (match-end 2))))
10727 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
10728 l (if e "|" (setq org-table-may-need-update t) ""))
10729 n (format f s))
10730 (if new
10731 (if (<= (length new) l) ;; FIXME: length -> str-width?
10732 (setq n (format f new))
10733 (setq n (concat new "|") org-table-may-need-update t)))
10734 (or (equal n o)
10735 (let (org-table-may-need-update)
10736 (replace-match n))))
10737 (setq org-table-may-need-update t))
10738 (goto-char pos))))))
10740 (defun org-table-next-field ()
10741 "Go to the next field in the current table, creating new lines as needed.
10742 Before doing so, re-align the table if necessary."
10743 (interactive)
10744 (org-table-maybe-eval-formula)
10745 (org-table-maybe-recalculate-line)
10746 (if (and org-table-automatic-realign
10747 org-table-may-need-update)
10748 (org-table-align))
10749 (let ((end (org-table-end)))
10750 (if (org-at-table-hline-p)
10751 (end-of-line 1))
10752 (condition-case nil
10753 (progn
10754 (re-search-forward "|" end)
10755 (if (looking-at "[ \t]*$")
10756 (re-search-forward "|" end))
10757 (if (and (looking-at "-")
10758 org-table-tab-jumps-over-hlines
10759 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
10760 (goto-char (match-beginning 1)))
10761 (if (looking-at "-")
10762 (progn
10763 (beginning-of-line 0)
10764 (org-table-insert-row 'below))
10765 (if (looking-at " ") (forward-char 1))))
10766 (error
10767 (org-table-insert-row 'below)))))
10769 (defun org-table-previous-field ()
10770 "Go to the previous field in the table.
10771 Before doing so, re-align the table if necessary."
10772 (interactive)
10773 (org-table-justify-field-maybe)
10774 (org-table-maybe-recalculate-line)
10775 (if (and org-table-automatic-realign
10776 org-table-may-need-update)
10777 (org-table-align))
10778 (if (org-at-table-hline-p)
10779 (end-of-line 1))
10780 (re-search-backward "|" (org-table-begin))
10781 (re-search-backward "|" (org-table-begin))
10782 (while (looking-at "|\\(-\\|[ \t]*$\\)")
10783 (re-search-backward "|" (org-table-begin)))
10784 (if (looking-at "| ?")
10785 (goto-char (match-end 0))))
10787 (defun org-table-next-row ()
10788 "Go to the next row (same column) in the current table.
10789 Before doing so, re-align the table if necessary."
10790 (interactive)
10791 (org-table-maybe-eval-formula)
10792 (org-table-maybe-recalculate-line)
10793 (if (or (looking-at "[ \t]*$")
10794 (save-excursion (skip-chars-backward " \t") (bolp)))
10795 (newline)
10796 (if (and org-table-automatic-realign
10797 org-table-may-need-update)
10798 (org-table-align))
10799 (let ((col (org-table-current-column)))
10800 (beginning-of-line 2)
10801 (if (or (not (org-at-table-p))
10802 (org-at-table-hline-p))
10803 (progn
10804 (beginning-of-line 0)
10805 (org-table-insert-row 'below)))
10806 (org-table-goto-column col)
10807 (skip-chars-backward "^|\n\r")
10808 (if (looking-at " ") (forward-char 1)))))
10810 (defun org-table-copy-down (n)
10811 "Copy a field down in the current column.
10812 If the field at the cursor is empty, copy into it the content of the nearest
10813 non-empty field above. With argument N, use the Nth non-empty field.
10814 If the current field is not empty, it is copied down to the next row, and
10815 the cursor is moved with it. Therefore, repeating this command causes the
10816 column to be filled row-by-row.
10817 If the variable `org-table-copy-increment' is non-nil and the field is an
10818 integer, it will be incremented while copying."
10819 (interactive "p")
10820 (let* ((colpos (org-table-current-column))
10821 (field (org-table-get-field))
10822 (non-empty (string-match "[^ \t]" field))
10823 (beg (org-table-begin))
10824 txt)
10825 (org-table-check-inside-data-field)
10826 (if non-empty
10827 (progn
10828 (setq txt (org-trim field))
10829 (org-table-next-row)
10830 (org-table-blank-field))
10831 (save-excursion
10832 (setq txt
10833 (catch 'exit
10834 (while (progn (beginning-of-line 1)
10835 (re-search-backward org-table-dataline-regexp
10836 beg t))
10837 (org-table-goto-column colpos t)
10838 (if (and (looking-at
10839 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
10840 (= (setq n (1- n)) 0))
10841 (throw 'exit (match-string 1))))))))
10842 (if txt
10843 (progn
10844 (if (and org-table-copy-increment
10845 (string-match "^[0-9]+$" txt))
10846 (setq txt (format "%d" (+ (string-to-number txt) 1))))
10847 (insert txt)
10848 (org-table-maybe-recalculate-line)
10849 (org-table-align))
10850 (error "No non-empty field found"))))
10852 (defun org-table-check-inside-data-field ()
10853 "Is point inside a table data field?
10854 I.e. not on a hline or before the first or after the last column?
10855 This actually throws an error, so it aborts the current command."
10856 (if (or (not (org-at-table-p))
10857 (= (org-table-current-column) 0)
10858 (org-at-table-hline-p)
10859 (looking-at "[ \t]*$"))
10860 (error "Not in table data field")))
10862 (defvar org-table-clip nil
10863 "Clipboard for table regions.")
10865 (defun org-table-blank-field ()
10866 "Blank the current table field or active region."
10867 (interactive)
10868 (org-table-check-inside-data-field)
10869 (if (and (interactive-p) (org-region-active-p))
10870 (let (org-table-clip)
10871 (org-table-cut-region (region-beginning) (region-end)))
10872 (skip-chars-backward "^|")
10873 (backward-char 1)
10874 (if (looking-at "|[^|\n]+")
10875 (let* ((pos (match-beginning 0))
10876 (match (match-string 0))
10877 (len (org-string-width match)))
10878 (replace-match (concat "|" (make-string (1- len) ?\ )))
10879 (goto-char (+ 2 pos))
10880 (substring match 1)))))
10882 (defun org-table-get-field (&optional n replace)
10883 "Return the value of the field in column N of current row.
10884 N defaults to current field.
10885 If REPLACE is a string, replace field with this value. The return value
10886 is always the old value."
10887 (and n (org-table-goto-column n))
10888 (skip-chars-backward "^|\n")
10889 (backward-char 1)
10890 (if (looking-at "|[^|\r\n]*")
10891 (let* ((pos (match-beginning 0))
10892 (val (buffer-substring (1+ pos) (match-end 0))))
10893 (if replace
10894 (replace-match (concat "|" replace)))
10895 (goto-char (min (point-at-eol) (+ 2 pos)))
10896 val)
10897 (forward-char 1) ""))
10899 (defun org-table-current-column ()
10900 "Find out which column we are in.
10901 When called interactively, column is also displayed in echo area."
10902 (interactive)
10903 (if (interactive-p) (org-table-check-inside-data-field))
10904 (save-excursion
10905 (let ((cnt 0) (pos (point)))
10906 (beginning-of-line 1)
10907 (while (search-forward "|" pos t)
10908 (setq cnt (1+ cnt)))
10909 (if (interactive-p) (message "This is table column %d" cnt))
10910 cnt)))
10912 (defun org-table-goto-column (n &optional on-delim force)
10913 "Move the cursor to the Nth column in the current table line.
10914 With optional argument ON-DELIM, stop with point before the left delimiter
10915 of the field.
10916 If there are less than N fields, just go to after the last delimiter.
10917 However, when FORCE is non-nil, create new columns if necessary."
10918 (interactive "p")
10919 (let ((pos (point-at-eol)))
10920 (beginning-of-line 1)
10921 (when (> n 0)
10922 (while (and (> (setq n (1- n)) -1)
10923 (or (search-forward "|" pos t)
10924 (and force
10925 (progn (end-of-line 1)
10926 (skip-chars-backward "^|")
10927 (insert " | "))))))
10928 ; (backward-char 2) t)))))
10929 (when (and force (not (looking-at ".*|")))
10930 (save-excursion (end-of-line 1) (insert " | ")))
10931 (if on-delim
10932 (backward-char 1)
10933 (if (looking-at " ") (forward-char 1))))))
10935 (defun org-at-table-p (&optional table-type)
10936 "Return t if the cursor is inside an org-type table.
10937 If TABLE-TYPE is non-nil, also check for table.el-type tables."
10938 (if org-enable-table-editor
10939 (save-excursion
10940 (beginning-of-line 1)
10941 (looking-at (if table-type org-table-any-line-regexp
10942 org-table-line-regexp)))
10943 nil))
10945 (defun org-at-table.el-p ()
10946 "Return t if and only if we are at a table.el table."
10947 (and (org-at-table-p 'any)
10948 (save-excursion
10949 (goto-char (org-table-begin 'any))
10950 (looking-at org-table1-hline-regexp))))
10952 (defun org-table-recognize-table.el ()
10953 "If there is a table.el table nearby, recognize it and move into it."
10954 (if org-table-tab-recognizes-table.el
10955 (if (org-at-table.el-p)
10956 (progn
10957 (beginning-of-line 1)
10958 (if (looking-at org-table-dataline-regexp)
10960 (if (looking-at org-table1-hline-regexp)
10961 (progn
10962 (beginning-of-line 2)
10963 (if (looking-at org-table-any-border-regexp)
10964 (beginning-of-line -1)))))
10965 (if (re-search-forward "|" (org-table-end t) t)
10966 (progn
10967 (require 'table)
10968 (if (table--at-cell-p (point))
10970 (message "recognizing table.el table...")
10971 (table-recognize-table)
10972 (message "recognizing table.el table...done")))
10973 (error "This should not happen..."))
10975 nil)
10976 nil))
10978 (defun org-at-table-hline-p ()
10979 "Return t if the cursor is inside a hline in a table."
10980 (if org-enable-table-editor
10981 (save-excursion
10982 (beginning-of-line 1)
10983 (looking-at org-table-hline-regexp))
10984 nil))
10986 (defun org-table-insert-column ()
10987 "Insert a new column into the table."
10988 (interactive)
10989 (if (not (org-at-table-p))
10990 (error "Not at a table"))
10991 (org-table-find-dataline)
10992 (let* ((col (max 1 (org-table-current-column)))
10993 (beg (org-table-begin))
10994 (end (org-table-end))
10995 ;; Current cursor position
10996 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10997 (colpos col))
10998 (goto-char beg)
10999 (while (< (point) end)
11000 (if (org-at-table-hline-p)
11002 (org-table-goto-column col t)
11003 (insert "| "))
11004 (beginning-of-line 2))
11005 (move-marker end nil)
11006 (goto-line linepos)
11007 (org-table-goto-column colpos)
11008 (org-table-align)
11009 (org-table-modify-formulas 'insert col)))
11011 (defun org-table-find-dataline ()
11012 "Find a dataline in the current table, which is needed for column commands."
11013 (if (and (org-at-table-p)
11014 (not (org-at-table-hline-p)))
11016 (let ((col (current-column))
11017 (end (org-table-end)))
11018 (move-to-column col)
11019 (while (and (< (point) end)
11020 (or (not (= (current-column) col))
11021 (org-at-table-hline-p)))
11022 (beginning-of-line 2)
11023 (move-to-column col))
11024 (if (and (org-at-table-p)
11025 (not (org-at-table-hline-p)))
11027 (error
11028 "Please position cursor in a data line for column operations")))))
11030 (defun org-table-delete-column ()
11031 "Delete a column from the table."
11032 (interactive)
11033 (if (not (org-at-table-p))
11034 (error "Not at a table"))
11035 (org-table-find-dataline)
11036 (org-table-check-inside-data-field)
11037 (let* ((col (org-table-current-column))
11038 (beg (org-table-begin))
11039 (end (org-table-end))
11040 ;; Current cursor position
11041 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11042 (colpos col))
11043 (goto-char beg)
11044 (while (< (point) end)
11045 (if (org-at-table-hline-p)
11047 (org-table-goto-column col t)
11048 (and (looking-at "|[^|\n]+|")
11049 (replace-match "|")))
11050 (beginning-of-line 2))
11051 (move-marker end nil)
11052 (goto-line linepos)
11053 (org-table-goto-column colpos)
11054 (org-table-align)
11055 (org-table-modify-formulas 'remove col)))
11057 (defun org-table-move-column-right ()
11058 "Move column to the right."
11059 (interactive)
11060 (org-table-move-column nil))
11061 (defun org-table-move-column-left ()
11062 "Move column to the left."
11063 (interactive)
11064 (org-table-move-column 'left))
11066 (defun org-table-move-column (&optional left)
11067 "Move the current column to the right. With arg LEFT, move to the left."
11068 (interactive "P")
11069 (if (not (org-at-table-p))
11070 (error "Not at a table"))
11071 (org-table-find-dataline)
11072 (org-table-check-inside-data-field)
11073 (let* ((col (org-table-current-column))
11074 (col1 (if left (1- col) col))
11075 (beg (org-table-begin))
11076 (end (org-table-end))
11077 ;; Current cursor position
11078 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11079 (colpos (if left (1- col) (1+ col))))
11080 (if (and left (= col 1))
11081 (error "Cannot move column further left"))
11082 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
11083 (error "Cannot move column further right"))
11084 (goto-char beg)
11085 (while (< (point) end)
11086 (if (org-at-table-hline-p)
11088 (org-table-goto-column col1 t)
11089 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
11090 (replace-match "|\\2|\\1|")))
11091 (beginning-of-line 2))
11092 (move-marker end nil)
11093 (goto-line linepos)
11094 (org-table-goto-column colpos)
11095 (org-table-align)
11096 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
11098 (defun org-table-move-row-down ()
11099 "Move table row down."
11100 (interactive)
11101 (org-table-move-row nil))
11102 (defun org-table-move-row-up ()
11103 "Move table row up."
11104 (interactive)
11105 (org-table-move-row 'up))
11107 (defun org-table-move-row (&optional up)
11108 "Move the current table line down. With arg UP, move it up."
11109 (interactive "P")
11110 (let ((col (current-column))
11111 (pos (point))
11112 (tonew (if up 0 2))
11113 txt)
11114 (beginning-of-line tonew)
11115 (if (not (org-at-table-p))
11116 (progn
11117 (goto-char pos)
11118 (error "Cannot move row further")))
11119 (goto-char pos)
11120 (beginning-of-line 1)
11121 (setq pos (point))
11122 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
11123 (delete-region (point) (1+ (point-at-eol)))
11124 (beginning-of-line tonew)
11125 (insert txt)
11126 (beginning-of-line 0)
11127 (move-to-column col)))
11129 (defun org-table-insert-row (&optional arg)
11130 "Insert a new row above the current line into the table.
11131 With prefix ARG, insert below the current line."
11132 (interactive "P")
11133 (if (not (org-at-table-p))
11134 (error "Not at a table"))
11135 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
11136 (new (org-table-clean-line line)))
11137 ;; Fix the first field if necessary
11138 (if (string-match "^[ \t]*| *[#$] *|" line)
11139 (setq new (replace-match (match-string 0 line) t t new)))
11140 (beginning-of-line (if arg 2 1))
11141 (let (org-table-may-need-update) (insert-before-markers new "\n"))
11142 (beginning-of-line 0)
11143 (re-search-forward "| ?" (point-at-eol) t)
11144 (and org-table-may-need-update (org-table-align))))
11146 (defun org-table-insert-hline (&optional arg)
11147 "Insert a horizontal-line below the current line into the table.
11148 With prefix ARG, insert above the current line."
11149 (interactive "P")
11150 (if (not (org-at-table-p))
11151 (error "Not at a table"))
11152 (let ((line (org-table-clean-line
11153 (buffer-substring (point-at-bol) (point-at-eol))))
11154 (col (current-column)))
11155 (while (string-match "|\\( +\\)|" line)
11156 (setq line (replace-match
11157 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
11158 ?-) "|") t t line)))
11159 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
11160 (beginning-of-line (if arg 1 2))
11161 (insert line "\n")
11162 (beginning-of-line (if arg 1 -1))
11163 (move-to-column col)))
11165 (defun org-table-clean-line (s)
11166 "Convert a table line S into a string with only \"|\" and space.
11167 In particular, this does handle wide and invisible characters."
11168 (if (string-match "^[ \t]*|-" s)
11169 ;; It's a hline, just map the characters
11170 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
11171 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
11172 (setq s (replace-match
11173 (concat "|" (make-string (org-string-width (match-string 1 s))
11174 ?\ ) "|")
11175 t t s)))
11178 (defun org-table-kill-row ()
11179 "Delete the current row or horizontal line from the table."
11180 (interactive)
11181 (if (not (org-at-table-p))
11182 (error "Not at a table"))
11183 (let ((col (current-column)))
11184 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
11185 (if (not (org-at-table-p)) (beginning-of-line 0))
11186 (move-to-column col)))
11188 (defun org-table-sort-lines (beg end numericp)
11189 "Sort table lines in region.
11190 Point and mark define the first and last line to include. Both point and
11191 mark should be in the column that is used for sorting. For example, to
11192 sort according to column 3, put the mark in the first line to sort, in
11193 table column 3. Put point into the last line to be included in the sorting,
11194 also in table column 3. The command will prompt for the sorting method
11195 \(n for numerical, a for alphanumeric)."
11196 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
11197 (setq numericp (string-match "[nN]" numericp))
11198 (org-table-align) ;; Just to be safe
11199 (let* (bcol ecol cmp column lns)
11200 (goto-char beg)
11201 (org-table-check-inside-data-field)
11202 (setq column (org-table-current-column)
11203 beg (move-marker (make-marker) (point-at-bol)))
11204 (goto-char end)
11205 (org-table-check-inside-data-field)
11206 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
11207 (untabify beg end)
11208 (goto-char beg)
11209 (org-table-goto-column column)
11210 (skip-chars-backward "^|")
11211 (setq bcol (current-column))
11212 (org-table-goto-column (1+ column))
11213 (skip-chars-backward "^|")
11214 (setq ecol (1- (current-column)))
11215 (setq cmp (if numericp
11216 (lambda (a b) (< (car a) (car b)))
11217 (lambda (a b) (string< (car a) (car b)))))
11218 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
11219 (org-split-string (buffer-substring beg end) "\n")))
11220 (if numericp
11221 (setq lns (mapcar (lambda(x)
11222 (cons (string-to-number (car x)) (cdr x)))
11223 lns)))
11224 (delete-region beg end)
11225 (move-marker beg nil)
11226 (move-marker end nil)
11227 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
11228 (message "%d lines sorted %s based on column %d"
11229 (length lns)
11230 (if numericp "numerically" "alphabetically") column)))
11232 (defun org-table-cut-region (beg end)
11233 "Copy region in table to the clipboard and blank all relevant fields."
11234 (interactive "r")
11235 (org-table-copy-region beg end 'cut))
11237 (defun org-table-copy-region (beg end &optional cut)
11238 "Copy rectangular region in table to clipboard.
11239 A special clipboard is used which can only be accessed
11240 with `org-table-paste-rectangle'."
11241 (interactive "rP")
11242 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
11243 region cols
11244 (rpl (if cut " " nil)))
11245 (goto-char beg)
11246 (org-table-check-inside-data-field)
11247 (setq l01 (count-lines (point-min) (point))
11248 c01 (org-table-current-column))
11249 (goto-char end)
11250 (org-table-check-inside-data-field)
11251 (setq l02 (count-lines (point-min) (point))
11252 c02 (org-table-current-column))
11253 (setq l1 (min l01 l02) l2 (max l01 l02)
11254 c1 (min c01 c02) c2 (max c01 c02))
11255 (catch 'exit
11256 (while t
11257 (catch 'nextline
11258 (if (> l1 l2) (throw 'exit t))
11259 (goto-line l1)
11260 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
11261 (setq cols nil ic1 c1 ic2 c2)
11262 (while (< ic1 (1+ ic2))
11263 (push (org-table-get-field ic1 rpl) cols)
11264 (setq ic1 (1+ ic1)))
11265 (push (nreverse cols) region)
11266 (setq l1 (1+ l1)))))
11267 (setq org-table-clip (nreverse region))
11268 (if cut (org-table-align))
11269 org-table-clip))
11271 (defun org-table-paste-rectangle ()
11272 "Paste a rectangular region into a table.
11273 The upper right corner ends up in the current field. All involved fields
11274 will be overwritten. If the rectangle does not fit into the present table,
11275 the table is enlarged as needed. The process ignores horizontal separator
11276 lines."
11277 (interactive)
11278 (unless (and org-table-clip (listp org-table-clip))
11279 (error "First cut/copy a region to paste!"))
11280 (org-table-check-inside-data-field)
11281 (let* ((clip org-table-clip)
11282 (line (count-lines (point-min) (point)))
11283 (col (org-table-current-column))
11284 (org-enable-table-editor t)
11285 (org-table-automatic-realign nil)
11286 c cols field)
11287 (while (setq cols (pop clip))
11288 (while (org-at-table-hline-p) (beginning-of-line 2))
11289 (if (not (org-at-table-p))
11290 (progn (end-of-line 0) (org-table-next-field)))
11291 (setq c col)
11292 (while (setq field (pop cols))
11293 (org-table-goto-column c nil 'force)
11294 (org-table-get-field nil field)
11295 (setq c (1+ c)))
11296 (beginning-of-line 2))
11297 (goto-line line)
11298 (org-table-goto-column col)
11299 (org-table-align)))
11301 (defun org-table-convert ()
11302 "Convert from `org-mode' table to table.el and back.
11303 Obviously, this only works within limits. When an Org-mode table is
11304 converted to table.el, all horizontal separator lines get lost, because
11305 table.el uses these as cell boundaries and has no notion of horizontal lines.
11306 A table.el table can be converted to an Org-mode table only if it does not
11307 do row or column spanning. Multiline cells will become multiple cells.
11308 Beware, Org-mode does not test if the table can be successfully converted - it
11309 blindly applies a recipe that works for simple tables."
11310 (interactive)
11311 (require 'table)
11312 (if (org-at-table.el-p)
11313 ;; convert to Org-mode table
11314 (let ((beg (move-marker (make-marker) (org-table-begin t)))
11315 (end (move-marker (make-marker) (org-table-end t))))
11316 (table-unrecognize-region beg end)
11317 (goto-char beg)
11318 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
11319 (replace-match ""))
11320 (goto-char beg))
11321 (if (org-at-table-p)
11322 ;; convert to table.el table
11323 (let ((beg (move-marker (make-marker) (org-table-begin)))
11324 (end (move-marker (make-marker) (org-table-end))))
11325 ;; first, get rid of all horizontal lines
11326 (goto-char beg)
11327 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
11328 (replace-match ""))
11329 ;; insert a hline before first
11330 (goto-char beg)
11331 (org-table-insert-hline 'above)
11332 (beginning-of-line -1)
11333 ;; insert a hline after each line
11334 (while (progn (beginning-of-line 3) (< (point) end))
11335 (org-table-insert-hline))
11336 (goto-char beg)
11337 (setq end (move-marker end (org-table-end)))
11338 ;; replace "+" at beginning and ending of hlines
11339 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
11340 (replace-match "\\1+-"))
11341 (goto-char beg)
11342 (while (re-search-forward "-|[ \t]*$" end t)
11343 (replace-match "-+"))
11344 (goto-char beg)))))
11346 (defun org-table-wrap-region (arg)
11347 "Wrap several fields in a column like a paragraph.
11348 This is useful if you'd like to spread the contents of a field over several
11349 lines, in order to keep the table compact.
11351 If there is an active region, and both point and mark are in the same column,
11352 the text in the column is wrapped to minimum width for the given number of
11353 lines. Generally, this makes the table more compact. A prefix ARG may be
11354 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
11355 formats the selected text to two lines. If the region was longer than two
11356 lines, the remaining lines remain empty. A negative prefix argument reduces
11357 the current number of lines by that amount. The wrapped text is pasted back
11358 into the table. If you formatted it to more lines than it was before, fields
11359 further down in the table get overwritten - so you might need to make space in
11360 the table first.
11362 If there is no region, the current field is split at the cursor position and
11363 the text fragment to the right of the cursor is prepended to the field one
11364 line down.
11366 If there is no region, but you specify a prefix ARG, the current field gets
11367 blank, and the content is appended to the field above."
11368 (interactive "P")
11369 (org-table-check-inside-data-field)
11370 (if (org-region-active-p)
11371 ;; There is a region: fill as a paragraph
11372 (let ((beg (region-beginning))
11373 nlines)
11374 (org-table-cut-region (region-beginning) (region-end))
11375 (if (> (length (car org-table-clip)) 1)
11376 (error "Region must be limited to single column"))
11377 (setq nlines (if arg
11378 (if (< arg 1)
11379 (+ (length org-table-clip) arg)
11380 arg)
11381 (length org-table-clip)))
11382 (setq org-table-clip
11383 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
11384 nil nlines)))
11385 (goto-char beg)
11386 (org-table-paste-rectangle))
11387 ;; No region, split the current field at point
11388 (if arg
11389 ;; combine with field above
11390 (let ((s (org-table-blank-field))
11391 (col (org-table-current-column)))
11392 (beginning-of-line 0)
11393 (while (org-at-table-hline-p) (beginning-of-line 0))
11394 (org-table-goto-column col)
11395 (skip-chars-forward "^|")
11396 (skip-chars-backward " ")
11397 (insert " " (org-trim s))
11398 (org-table-align))
11399 ;; split field
11400 (when (looking-at "\\([^|]+\\)+|")
11401 (let ((s (match-string 1)))
11402 (replace-match " |")
11403 (goto-char (match-beginning 0))
11404 (org-table-next-row)
11405 (insert (org-trim s) " ")
11406 (org-table-align))))))
11408 (defvar org-field-marker nil)
11410 (defun org-table-edit-field (arg)
11411 "Edit table field in a different window.
11412 This is mainly useful for fields that contain hidden parts.
11413 When called with a \\[universal-argument] prefix, just make the full field visible so that
11414 it can be edited in place."
11415 (interactive "P")
11416 (if arg
11417 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
11418 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
11419 (remove-text-properties b e '(org-cwidth t invisible t
11420 display t intangible t))
11421 (if (and (boundp 'font-lock-mode) font-lock-mode)
11422 (font-lock-fontify-block)))
11423 (let ((pos (move-marker (make-marker) (point)))
11424 (field (org-table-get-field))
11425 (cw (current-window-configuration))
11427 (switch-to-buffer-other-window "*Org tmp*")
11428 (erase-buffer)
11429 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
11430 (org-mode)
11431 (goto-char (setq p (point-max)))
11432 (insert (org-trim field))
11433 (remove-text-properties p (point-max)
11434 '(invisible t org-cwidth t display t
11435 intangible t))
11436 (goto-char p)
11437 (set (make-local-variable 'org-finish-function)
11438 'org-table-finish-edit-field)
11439 (set (make-local-variable 'org-window-configuration) cw)
11440 (set (make-local-variable 'org-field-marker) pos)
11441 (message "Edit and finish with C-c C-c"))))
11443 (defun org-table-finish-edit-field ()
11444 "Finish editing a table data field.
11445 Remove all newline characters, insert the result into the table, realign
11446 the table and kill the editing buffer."
11447 (let ((pos org-field-marker)
11448 (cw org-window-configuration)
11449 (cb (current-buffer))
11450 text)
11451 (goto-char (point-min))
11452 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
11453 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
11454 (replace-match " "))
11455 (setq text (org-trim (buffer-string)))
11456 (set-window-configuration cw)
11457 (kill-buffer cb)
11458 (select-window (get-buffer-window (marker-buffer pos)))
11459 (goto-char pos)
11460 (move-marker pos nil)
11461 (org-table-check-inside-data-field)
11462 (org-table-get-field nil text)
11463 (org-table-align)
11464 (message "New field value inserted")))
11466 (defun org-trim (s)
11467 "Remove whitespace at beginning and end of string."
11468 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
11469 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
11472 (defun org-wrap (string &optional width lines)
11473 "Wrap string to either a number of lines, or a width in characters.
11474 If WIDTH is non-nil, the string is wrapped to that width, however many lines
11475 that costs. If there is a word longer than WIDTH, the text is actually
11476 wrapped to the length of that word.
11477 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
11478 many lines, whatever width that takes.
11479 The return value is a list of lines, without newlines at the end."
11480 (let* ((words (org-split-string string "[ \t\n]+"))
11481 (maxword (apply 'max (mapcar 'org-string-width words)))
11482 w ll)
11483 (cond (width
11484 (org-do-wrap words (max maxword width)))
11485 (lines
11486 (setq w maxword)
11487 (setq ll (org-do-wrap words maxword))
11488 (if (<= (length ll) lines)
11490 (setq ll words)
11491 (while (> (length ll) lines)
11492 (setq w (1+ w))
11493 (setq ll (org-do-wrap words w)))
11494 ll))
11495 (t (error "Cannot wrap this")))))
11498 (defun org-do-wrap (words width)
11499 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
11500 (let (lines line)
11501 (while words
11502 (setq line (pop words))
11503 (while (and words (< (+ (length line) (length (car words))) width))
11504 (setq line (concat line " " (pop words))))
11505 (setq lines (push line lines)))
11506 (nreverse lines)))
11508 (defun org-split-string (string &optional separators)
11509 "Splits STRING into substrings at SEPARATORS.
11510 No empty strings are returned if there are matches at the beginning
11511 and end of string."
11512 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
11513 (start 0)
11514 notfirst
11515 (list nil))
11516 (while (and (string-match rexp string
11517 (if (and notfirst
11518 (= start (match-beginning 0))
11519 (< start (length string)))
11520 (1+ start) start))
11521 (< (match-beginning 0) (length string)))
11522 (setq notfirst t)
11523 (or (eq (match-beginning 0) 0)
11524 (and (eq (match-beginning 0) (match-end 0))
11525 (eq (match-beginning 0) start))
11526 (setq list
11527 (cons (substring string start (match-beginning 0))
11528 list)))
11529 (setq start (match-end 0)))
11530 (or (eq start (length string))
11531 (setq list
11532 (cons (substring string start)
11533 list)))
11534 (nreverse list)))
11536 (defun org-table-map-tables (function)
11537 "Apply FUNCTION to the start of all tables in the buffer."
11538 (save-excursion
11539 (save-restriction
11540 (widen)
11541 (goto-char (point-min))
11542 (while (re-search-forward org-table-any-line-regexp nil t)
11543 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
11544 (beginning-of-line 1)
11545 (if (looking-at org-table-line-regexp)
11546 (save-excursion (funcall function)))
11547 (re-search-forward org-table-any-border-regexp nil 1))))
11548 (message "Mapping tables: done"))
11550 (defun org-table-sum (&optional beg end nlast)
11551 "Sum numbers in region of current table column.
11552 The result will be displayed in the echo area, and will be available
11553 as kill to be inserted with \\[yank].
11555 If there is an active region, it is interpreted as a rectangle and all
11556 numbers in that rectangle will be summed. If there is no active
11557 region and point is located in a table column, sum all numbers in that
11558 column.
11560 If at least one number looks like a time HH:MM or HH:MM:SS, all other
11561 numbers are assumed to be times as well (in decimal hours) and the
11562 numbers are added as such.
11564 If NLAST is a number, only the NLAST fields will actually be summed."
11565 (interactive)
11566 (save-excursion
11567 (let (col (timecnt 0) diff h m s org-table-clip)
11568 (cond
11569 ((and beg end)) ; beg and end given explicitly
11570 ((org-region-active-p)
11571 (setq beg (region-beginning) end (region-end)))
11573 (setq col (org-table-current-column))
11574 (goto-char (org-table-begin))
11575 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
11576 (error "No table data"))
11577 (org-table-goto-column col)
11578 ;not needed? (skip-chars-backward "^|")
11579 (setq beg (point))
11580 (goto-char (org-table-end))
11581 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
11582 (error "No table data"))
11583 (org-table-goto-column col)
11584 ;not needed? (skip-chars-forward "^|")
11585 (setq end (point))))
11586 (let* ((items (apply 'append (org-table-copy-region beg end)))
11587 (items1 (cond ((not nlast) items)
11588 ((>= nlast (length items)) items)
11589 (t (setq items (reverse items))
11590 (setcdr (nthcdr (1- nlast) items) nil)
11591 (nreverse items))))
11592 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
11593 items1)))
11594 (res (apply '+ numbers))
11595 (sres (if (= timecnt 0)
11596 (format "%g" res)
11597 (setq diff (* 3600 res)
11598 h (floor (/ diff 3600)) diff (mod diff 3600)
11599 m (floor (/ diff 60)) diff (mod diff 60)
11600 s diff)
11601 (format "%d:%02d:%02d" h m s))))
11602 (kill-new sres)
11603 (if (interactive-p)
11604 (message "%s"
11605 (substitute-command-keys
11606 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
11607 (length numbers) sres))))
11608 sres))))
11610 (defun org-table-get-number-for-summing (s)
11611 (let (n)
11612 (if (string-match "^ *|? *" s)
11613 (setq s (replace-match "" nil nil s)))
11614 (if (string-match " *|? *$" s)
11615 (setq s (replace-match "" nil nil s)))
11616 (setq n (string-to-number s))
11617 (cond
11618 ((and (string-match "0" s)
11619 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
11620 ((string-match "\\`[ \t]+\\'" s) nil)
11621 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
11622 (let ((h (string-to-number (or (match-string 1 s) "0")))
11623 (m (string-to-number (or (match-string 2 s) "0")))
11624 (s (string-to-number (or (match-string 4 s) "0"))))
11625 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
11626 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
11627 ((equal n 0) nil)
11628 (t n))))
11630 (defun org-table-get-vertical-vector (desc &optional tbeg col)
11631 "Get a calc vector from a column, accorting to descriptor DESC.
11632 Optional arguments TBEG and COL can give the beginning of the table and
11633 the current column, to avoid unnecessary parsing."
11634 (save-excursion
11635 (or tbeg (setq tbeg (org-table-begin)))
11636 (or col (setq col (org-table-current-column)))
11637 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
11638 (cond
11639 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
11640 (setq n1 (- (match-end 1) (match-beginning 1)))
11641 (if (match-beginning 3)
11642 (setq n2 (- (match-end 2) (match-beginning 3))))
11643 (setq n (if n2 (max n1 n2) n1))
11644 (setq n1 (if n2 (min n1 n2)))
11645 (setq nn n)
11646 (while (and (> nn 0)
11647 (re-search-backward org-table-hline-regexp tbeg t))
11648 (push (org-current-line) hline-list)
11649 (setq nn (1- nn)))
11650 (setq hline-list (nreverse hline-list))
11651 (goto-line (nth (1- n) hline-list))
11652 (when (re-search-forward org-table-dataline-regexp)
11653 (org-table-goto-column col)
11654 (setq beg (point)))
11655 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
11656 (when (re-search-backward org-table-dataline-regexp)
11657 (org-table-goto-column col)
11658 (setq end (point)))
11659 (setq l (apply 'append (org-table-copy-region beg end)))
11660 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
11661 (if (equal x "") "0" x))
11662 l ",") "]"))
11663 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
11664 (setq n1 (string-to-number (match-string 1 desc))
11665 n2 (string-to-number (match-string 2 desc)))
11666 (beginning-of-line 1)
11667 (save-excursion
11668 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
11669 (org-table-goto-column col)
11670 (setq beg (point))))
11671 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
11672 (org-table-goto-column col)
11673 (setq end (point)))
11674 (setq l (apply 'append (org-table-copy-region beg end)))
11675 (concat "[" (mapconcat
11676 (lambda (x) (setq x (org-trim x))
11677 (if (equal x "") "0" x))
11678 l ",") "]"))
11679 ((string-match "\\([0-9]+\\)" desc)
11680 (beginning-of-line 1)
11681 (when (re-search-backward org-table-dataline-regexp tbeg t
11682 (string-to-number (match-string 0 desc)))
11683 (org-table-goto-column col)
11684 (org-trim (org-table-get-field))))))))
11686 (defvar org-table-formula-history nil)
11688 (defvar org-table-column-names nil
11689 "Alist with column names, derived from the `!' line.")
11690 (defvar org-table-column-name-regexp nil
11691 "Regular expression matching the current column names.")
11692 (defvar org-table-local-parameters nil
11693 "Alist with parameter names, derived from the `$' line.")
11694 (defvar org-table-named-field-locations nil
11695 "Alist with locations of named fields.")
11697 (defun org-table-get-formula (&optional equation named)
11698 "Read a formula from the minibuffer, offer stored formula as default."
11699 (let* ((name (car (rassoc (list (org-current-line)
11700 (org-table-current-column))
11701 org-table-named-field-locations)))
11702 (scol (if named
11703 (if name name
11704 (error "Not in a named field"))
11705 (int-to-string (org-table-current-column))))
11706 (dummy (and name (not named)
11707 (not (y-or-n-p "Replace named-field formula with column equation? " ))
11708 (error "Abort")))
11709 (org-table-may-need-update nil)
11710 (stored-list (org-table-get-stored-formulas))
11711 (stored (cdr (assoc scol stored-list)))
11712 (eq (cond
11713 ((and stored equation (string-match "^ *=? *$" equation))
11714 stored)
11715 ((stringp equation)
11716 equation)
11717 (t (read-string
11718 (format "%s formula $%s=" (if named "Field" "Column") scol)
11719 (or stored "") 'org-table-formula-history
11720 ;stored
11721 ))))
11722 mustsave)
11723 (when (not (string-match "\\S-" eq))
11724 ;; remove formula
11725 (setq stored-list (delq (assoc scol stored-list) stored-list))
11726 (org-table-store-formulas stored-list)
11727 (error "Formula removed"))
11728 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
11729 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
11730 (if (and name (not named))
11731 ;; We set the column equation, delete the named one.
11732 (setq stored-list (delq (assoc name stored-list) stored-list)
11733 mustsave t))
11734 (if stored
11735 (setcdr (assoc scol stored-list) eq)
11736 (setq stored-list (cons (cons scol eq) stored-list)))
11737 (if (or mustsave (not (equal stored eq)))
11738 (org-table-store-formulas stored-list))
11739 eq))
11741 (defun org-table-store-formulas (alist)
11742 "Store the list of formulas below the current table."
11743 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
11744 (save-excursion
11745 (goto-char (org-table-end))
11746 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
11747 (delete-region (point) (match-end 0)))
11748 (insert "#+TBLFM: "
11749 (mapconcat (lambda (x)
11750 (concat "$" (car x) "=" (cdr x)))
11751 alist "::")
11752 "\n")))
11754 (defun org-table-get-stored-formulas ()
11755 "Return an alist with the stored formulas directly after current table."
11756 (interactive)
11757 (let (scol eq eq-alist strings string seen)
11758 (save-excursion
11759 (goto-char (org-table-end))
11760 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
11761 (setq strings (org-split-string (match-string 2) " *:: *"))
11762 (while (setq string (pop strings))
11763 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
11764 (setq scol (match-string 1 string)
11765 eq (match-string 2 string)
11766 eq-alist (cons (cons scol eq) eq-alist))
11767 (if (member scol seen)
11768 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
11769 (push scol seen))))))
11770 (nreverse eq-alist)))
11772 (defun org-table-modify-formulas (action &rest columns)
11773 "Modify the formulas stored below the current table.
11774 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
11775 expected, for the other actions only a single column number is needed."
11776 (let ((list (org-table-get-stored-formulas))
11777 (nmax (length (org-split-string
11778 (buffer-substring (point-at-bol) (point-at-eol))
11779 "|")))
11780 col col1 col2 scol si sc1 sc2)
11781 (cond
11782 ((null list)) ; No action needed if there are no stored formulas
11783 ((eq action 'remove)
11784 (setq col (car columns)
11785 scol (int-to-string col))
11786 (org-table-replace-in-formulas list scol "INVALID")
11787 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
11788 (loop for i from (1+ col) upto nmax by 1 do
11789 (setq si (int-to-string i))
11790 (org-table-replace-in-formulas list si (int-to-string (1- i)))
11791 (if (assoc si list) (setcar (assoc si list)
11792 (int-to-string (1- i))))))
11793 ((eq action 'insert)
11794 (setq col (car columns))
11795 (loop for i from nmax downto col by 1 do
11796 (setq si (int-to-string i))
11797 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
11798 (if (assoc si list) (setcar (assoc si list)
11799 (int-to-string (1+ i))))))
11800 ((eq action 'swap)
11801 (setq col1 (car columns) col2 (nth 1 columns)
11802 sc1 (int-to-string col1) sc2 (int-to-string col2))
11803 ;; Hopefully, ZqZtZ will never be a name in a table
11804 (org-table-replace-in-formulas list sc1 "ZqZtZ")
11805 (org-table-replace-in-formulas list sc2 sc1)
11806 (org-table-replace-in-formulas list "ZqZtZ" sc2)
11807 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
11808 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
11809 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
11810 (t (error "Invalid action in `org-table-modify-formulas'")))
11811 (if list (org-table-store-formulas list))))
11813 (defun org-table-replace-in-formulas (list s1 s2)
11814 (let (elt re s)
11815 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
11816 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
11817 re (concat (regexp-quote s1) "\\>"))
11818 (while (setq elt (pop list))
11819 (setq s (cdr elt))
11820 (while (string-match re s)
11821 (setq s (replace-match s2 t t s)))
11822 (setcdr elt s))))
11824 (defun org-table-get-specials ()
11825 "Get the column names and local parameters for this table."
11826 (save-excursion
11827 (let ((beg (org-table-begin)) (end (org-table-end))
11828 names name fields fields1 field cnt c v line col)
11829 (setq org-table-column-names nil
11830 org-table-local-parameters nil
11831 org-table-named-field-locations nil)
11832 (goto-char beg)
11833 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
11834 (setq names (org-split-string (match-string 1) " *| *")
11835 cnt 1)
11836 (while (setq name (pop names))
11837 (setq cnt (1+ cnt))
11838 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
11839 (push (cons name (int-to-string cnt)) org-table-column-names))))
11840 (setq org-table-column-names (nreverse org-table-column-names))
11841 (setq org-table-column-name-regexp
11842 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
11843 (goto-char beg)
11844 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
11845 (setq fields (org-split-string (match-string 1) " *| *"))
11846 (while (setq field (pop fields))
11847 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
11848 (push (cons (match-string 1 field) (match-string 2 field))
11849 org-table-local-parameters))))
11850 (goto-char beg)
11851 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
11852 (setq c (match-string 1)
11853 fields (org-split-string (match-string 2) " *| *"))
11854 (save-excursion
11855 (beginning-of-line (if (equal c "_") 2 0))
11856 (setq line (org-current-line) col 1)
11857 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
11858 (setq fields1 (org-split-string (match-string 1) " *| *"))))
11859 (while (and fields1 (setq field (pop fields)))
11860 (setq v (pop fields1) col (1+ col))
11861 (when (and (stringp field) (stringp v)
11862 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
11863 (push (cons field v) org-table-local-parameters)
11864 (push (list field line col) org-table-named-field-locations)))))))
11866 (defun org-this-word ()
11867 ;; Get the current word
11868 (save-excursion
11869 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
11870 (end (progn (skip-chars-forward "^ \t\n") (point))))
11871 (buffer-substring-no-properties beg end))))
11873 (defun org-table-maybe-eval-formula ()
11874 "Check if the current field starts with \"=\" or \":=\".
11875 If yes, store the formula and apply it."
11876 ;; We already know we are in a table. Get field will only return a formula
11877 ;; when appropriate. It might return a separator line, but no problem.
11878 (when org-table-formula-evaluate-inline
11879 (let* ((field (org-trim (or (org-table-get-field) "")))
11880 named eq)
11881 (when (string-match "^:?=\\(.*\\)" field)
11882 (setq named (equal (string-to-char field) ?:)
11883 eq (match-string 1 field))
11884 (if (fboundp 'calc-eval)
11885 (org-table-eval-formula (if named '(4) nil) eq))))))
11887 (defvar org-recalc-commands nil
11888 "List of commands triggering the recalculation of a line.
11889 Will be filled automatically during use.")
11891 (defvar org-recalc-marks
11892 '((" " . "Unmarked: no special line, no automatic recalculation")
11893 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
11894 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
11895 ("!" . "Column name definition line. Reference in formula as $name.")
11896 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
11897 ("_" . "Names for values in row below this one.")
11898 ("^" . "Names for values in row above this one.")))
11900 (defun org-table-rotate-recalc-marks (&optional newchar)
11901 "Rotate the recalculation mark in the first column.
11902 If in any row, the first field is not consistent with a mark,
11903 insert a new column for the markers.
11904 When there is an active region, change all the lines in the region,
11905 after prompting for the marking character.
11906 After each change, a message will be displayed indicating the meaning
11907 of the new mark."
11908 (interactive)
11909 (unless (org-at-table-p) (error "Not at a table"))
11910 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
11911 (beg (org-table-begin))
11912 (end (org-table-end))
11913 (l (org-current-line))
11914 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
11915 (l2 (if (org-region-active-p) (org-current-line (region-end))))
11916 (have-col
11917 (save-excursion
11918 (goto-char beg)
11919 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
11920 (col (org-table-current-column))
11921 (forcenew (car (assoc newchar org-recalc-marks)))
11922 epos new)
11923 (when l1
11924 (message "Change region to what mark? Type # * ! $ or SPC: ")
11925 (setq newchar (char-to-string (read-char-exclusive))
11926 forcenew (car (assoc newchar org-recalc-marks))))
11927 (if (and newchar (not forcenew))
11928 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
11929 newchar))
11930 (if l1 (goto-line l1))
11931 (save-excursion
11932 (beginning-of-line 1)
11933 (unless (looking-at org-table-dataline-regexp)
11934 (error "Not at a table data line")))
11935 (unless have-col
11936 (org-table-goto-column 1)
11937 (org-table-insert-column)
11938 (org-table-goto-column (1+ col)))
11939 (setq epos (point-at-eol))
11940 (save-excursion
11941 (beginning-of-line 1)
11942 (org-table-get-field
11943 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
11944 (concat " "
11945 (setq new (or forcenew
11946 (cadr (member (match-string 1) marks))))
11947 " ")
11948 " # ")))
11949 (if (and l1 l2)
11950 (progn
11951 (goto-line l1)
11952 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
11953 (and (looking-at org-table-dataline-regexp)
11954 (org-table-get-field 1 (concat " " new " "))))
11955 (goto-line l1)))
11956 (if (not (= epos (point-at-eol))) (org-table-align))
11957 (goto-line l)
11958 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
11960 (defun org-table-maybe-recalculate-line ()
11961 "Recompute the current line if marked for it, and if we haven't just done it."
11962 (interactive)
11963 (and org-table-allow-automatic-line-recalculation
11964 (not (and (memq last-command org-recalc-commands)
11965 (equal org-last-recalc-line (org-current-line))))
11966 (save-excursion (beginning-of-line 1)
11967 (looking-at org-table-auto-recalculate-regexp))
11968 (fboundp 'calc-eval)
11969 (org-table-recalculate) t))
11971 (defvar org-table-formula-debug nil
11972 "Non-nil means, debug table formulas.
11973 When nil, simply write \"#ERROR\" in corrupted fields.")
11975 (defvar modes)
11976 (defsubst org-set-calc-mode (var &optional value)
11977 (if (stringp var)
11978 (setq var (assoc var '(("D" calc-angle-mode deg)
11979 ("R" calc-angle-mode rad)
11980 ("F" calc-prefer-frac t)
11981 ("S" calc-symbolic-mode t)))
11982 value (nth 2 var) var (nth 1 var)))
11983 (if (memq var modes)
11984 (setcar (cdr (memq var modes)) value)
11985 (cons var (cons value modes)))
11986 modes)
11988 (defun org-table-eval-formula (&optional arg equation
11989 suppress-align suppress-const
11990 suppress-store)
11991 "Replace the table field value at the cursor by the result of a calculation.
11993 This function makes use of Dave Gillespie's Calc package, in my view the
11994 most exciting program ever written for GNU Emacs. So you need to have Calc
11995 installed in order to use this function.
11997 In a table, this command replaces the value in the current field with the
11998 result of a formula. It also installs the formula as the \"current\" column
11999 formula, by storing it in a special line below the table. When called
12000 with a `C-u' prefix, the current field must ba a named field, and the
12001 formula is installed as valid in only this specific field.
12003 When called, the command first prompts for a formula, which is read in
12004 the minibuffer. Previously entered formulas are available through the
12005 history list, and the last used formula is offered as a default.
12006 These stored formulas are adapted correctly when moving, inserting, or
12007 deleting columns with the corresponding commands.
12009 The formula can be any algebraic expression understood by the Calc package.
12010 For details, see the Org-mode manual.
12012 This function can also be called from Lisp programs and offers
12013 additional arguments: EQUATION can be the formula to apply. If this
12014 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
12015 used to speed-up recursive calls by by-passing unnecessary aligns.
12016 SUPPRESS-CONST suppresses the interpretation of constants in the
12017 formula, assuming that this has been done already outside the function.
12018 SUPPRESS-STORE means the formula should not be stored, either because
12019 it is already stored, or because it is a modified equation that should
12020 not overwrite the stored one."
12021 (interactive "P")
12022 (require 'calc)
12023 (org-table-check-inside-data-field)
12024 (org-table-get-specials)
12025 (let* (fields
12026 (ndown (if (integerp arg) arg 1))
12027 (org-table-automatic-realign nil)
12028 (case-fold-search nil)
12029 (down (> ndown 1))
12030 (formula (if (and equation suppress-store)
12031 equation
12032 (org-table-get-formula equation (equal arg '(4)))))
12033 (n0 (org-table-current-column))
12034 (modes (copy-sequence org-calc-default-modes))
12035 n form fmt x ev orig c lispp)
12036 ;; Parse the format string. Since we have a lot of modes, this is
12037 ;; a lot of work. However, I think calc still uses most of the time.
12038 (if (string-match ";" formula)
12039 (let ((tmp (org-split-string formula ";")))
12040 (setq formula (car tmp)
12041 fmt (concat (cdr (assoc "%" org-table-local-parameters))
12042 (nth 1 tmp)))
12043 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
12044 (setq c (string-to-char (match-string 1 fmt))
12045 n (string-to-number (or (match-string 1 fmt) "")))
12046 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
12047 (setq modes (org-set-calc-mode
12048 'calc-float-format
12049 (list (cdr (assoc c '((?n . float) (?f . fix)
12050 (?s . sci) (?e . eng))))
12051 n))))
12052 (setq fmt (replace-match "" t t fmt)))
12053 (while (string-match "[DRFS]" fmt)
12054 (setq modes (org-set-calc-mode (match-string 0 fmt)))
12055 (setq fmt (replace-match "" t t fmt)))
12056 (unless (string-match "\\S-" fmt)
12057 (setq fmt nil))))
12058 (if (and (not suppress-const) org-table-formula-use-constants)
12059 (setq formula (org-table-formula-substitute-names formula)))
12060 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
12061 (while (> ndown 0)
12062 (setq fields (org-split-string
12063 (buffer-substring
12064 (point-at-bol) (point-at-eol)) " *| *"))
12065 (if org-table-formula-numbers-only
12066 (setq fields (mapcar
12067 (lambda (x) (number-to-string (string-to-number x)))
12068 fields)))
12069 (setq ndown (1- ndown))
12070 (setq form (copy-sequence formula)
12071 lispp (equal (substring form 0 2) "'("))
12072 ;; Insert the references to fields in same row
12073 (while (string-match "\\$\\([0-9]+\\)?" form)
12074 (setq n (if (match-beginning 1)
12075 (string-to-number (match-string 1 form))
12077 x (nth (1- n) fields))
12078 (unless x (error "Invalid field specifier \"%s\""
12079 (match-string 0 form)))
12080 (if (equal x "") (setq x "0"))
12081 (setq form (replace-match
12082 (if lispp x (concat "(" x ")"))
12083 t t form)))
12084 ;; Insert ranges in current column
12085 (while (string-match "\\&[-I0-9]+" form)
12086 (setq form (replace-match
12087 (save-match-data
12088 (org-table-get-vertical-vector (match-string 0 form)
12089 nil n0))
12090 t t form)))
12091 (if lispp
12092 (setq ev (eval (eval (read form)))
12093 ev (if (numberp ev) (number-to-string ev) ev))
12094 (setq ev (calc-eval (cons form modes)
12095 (if org-table-formula-numbers-only 'num))))
12097 (when org-table-formula-debug
12098 (with-output-to-temp-buffer "*Help*"
12099 (princ (format "Substitution history of formula
12100 Orig: %s
12101 $xyz-> %s
12102 $1-> %s\n" orig formula form))
12103 (if (listp ev)
12104 (princ (format " %s^\nError: %s"
12105 (make-string (car ev) ?\-) (nth 1 ev)))
12106 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
12107 ev (or fmt "NONE")
12108 (if fmt (format fmt (string-to-number ev)) ev)))))
12109 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
12110 (unless (and (interactive-p) (not ndown))
12111 (unless (let (inhibit-redisplay)
12112 (y-or-n-p "Debugging Formula. Continue to next? "))
12113 (org-table-align)
12114 (error "Abort"))
12115 (delete-window (get-buffer-window "*Help*"))
12116 (message "")))
12117 (if (listp ev) (setq fmt nil ev "#ERROR"))
12118 (org-table-justify-field-maybe
12119 (if fmt (format fmt (string-to-number ev)) ev))
12120 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
12121 (call-interactively 'org-return)
12122 (setq ndown 0)))
12123 (and down (org-table-maybe-recalculate-line))
12124 (or suppress-align (and org-table-may-need-update
12125 (org-table-align)))))
12127 (defun org-table-recalculate (&optional all noalign)
12128 "Recalculate the current table line by applying all stored formulas.
12129 With prefix arg ALL, do this for all lines in the table."
12130 (interactive "P")
12131 (or (memq this-command org-recalc-commands)
12132 (setq org-recalc-commands (cons this-command org-recalc-commands)))
12133 (unless (org-at-table-p) (error "Not at a table"))
12134 (org-table-get-specials)
12135 (let* ((eqlist (sort (org-table-get-stored-formulas)
12136 (lambda (a b) (string< (car a) (car b)))))
12137 (inhibit-redisplay t)
12138 (line-re org-table-dataline-regexp)
12139 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
12140 (thiscol (org-table-current-column))
12141 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
12142 ;; Insert constants in all formulas
12143 (setq eqlist
12144 (mapcar (lambda (x)
12145 (setcdr x (org-table-formula-substitute-names (cdr x)))
12147 eqlist))
12148 ;; Split the equation list
12149 (while (setq eq (pop eqlist))
12150 (if (<= (string-to-char (car eq)) ?9)
12151 (push eq eqlnum)
12152 (push eq eqlname)))
12153 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
12154 (if all
12155 (progn
12156 (setq end (move-marker (make-marker) (1+ (org-table-end))))
12157 (goto-char (setq beg (org-table-begin)))
12158 (if (re-search-forward org-table-calculate-mark-regexp end t)
12159 ;; This is a table with marked lines, only compute selected lines
12160 (setq line-re org-table-recalculate-regexp)
12161 ;; Move forward to the first non-header line
12162 (if (and (re-search-forward org-table-dataline-regexp end t)
12163 (re-search-forward org-table-hline-regexp end t)
12164 (re-search-forward org-table-dataline-regexp end t))
12165 (setq beg (match-beginning 0))
12166 nil))) ;; just leave beg where it is
12167 (setq beg (point-at-bol)
12168 end (move-marker (make-marker) (1+ (point-at-eol)))))
12169 (goto-char beg)
12170 (and all (message "Re-applying formulas to full table..."))
12171 (while (re-search-forward line-re end t)
12172 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
12173 ;; Unprotected line, recalculate
12174 (and all (message "Re-applying formulas to full table...(line %d)"
12175 (setq cnt (1+ cnt))))
12176 (setq org-last-recalc-line (org-current-line))
12177 (setq eql eqlnum)
12178 (while (setq entry (pop eql))
12179 (goto-line org-last-recalc-line)
12180 (org-table-goto-column (string-to-number (car entry)) nil 'force)
12181 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
12182 (goto-line thisline)
12183 (org-table-goto-column thiscol)
12184 (or noalign (and org-table-may-need-update (org-table-align))
12185 (and all (message "Re-applying formulas to %d lines...done" cnt)))
12186 ;; Now do the names fields
12187 (while (setq eq (pop eqlname))
12188 (setq name (car eq)
12189 a (assoc name org-table-named-field-locations))
12190 (when a
12191 (message "Re-applying formula to named field: %s" name)
12192 (goto-line (nth 1 a))
12193 (org-table-goto-column (nth 2 a))
12194 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
12195 ;; back to initial position
12196 (goto-line thisline)
12197 (org-table-goto-column thiscol)
12198 (or noalign (and org-table-may-need-update (org-table-align))
12199 (and all (message "Re-applying formulas...done")))))
12201 (defun org-table-formula-substitute-names (f)
12202 "Replace $const with values in string F."
12203 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
12204 ;; First, check for column names
12205 (while (setq start (string-match org-table-column-name-regexp f start))
12206 (setq start (1+ start))
12207 (setq a (assoc (match-string 1 f) org-table-column-names))
12208 (setq f (replace-match (concat "$" (cdr a)) t t f)))
12209 ;; Expand ranges to vectors
12210 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
12211 (setq n1 (string-to-number (match-string 1 f))
12212 n2 (string-to-number (match-string 2 f))
12213 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
12214 s (concat "[($" (number-to-string (1- nn1)) ")"))
12215 (loop for i from nn1 upto nn2 do
12216 (setq s (concat s ",($" (int-to-string i) ")")))
12217 (setq s (concat s "]"))
12218 (if (< n2 n1) (setq s (concat "rev(" s ")")))
12219 (setq f (replace-match s t t f)))
12220 ;; Parameters and constants
12221 (setq start 0)
12222 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
12223 (setq start (1+ start))
12224 (if (setq a (save-match-data
12225 (org-table-get-constant (match-string 1 f))))
12226 (setq f (replace-match (concat "(" a ")") t t f))))
12227 (if org-table-formula-debug
12228 (put-text-property 0 (length f) :orig-formula f1 f))
12231 (defun org-table-get-constant (const)
12232 "Find the value for a parameter or constant in a formula.
12233 Parameters get priority."
12234 (or (cdr (assoc const org-table-local-parameters))
12235 (cdr (assoc const org-table-formula-constants))
12236 (and (fboundp 'constants-get) (constants-get const))
12237 "#UNDEFINED_NAME"))
12239 (defvar org-edit-formulas-map (make-sparse-keymap))
12240 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
12241 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
12242 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
12244 (defvar org-pos)
12246 (defun org-table-edit-formulas ()
12247 "Edit the formulas of the current table in a separate buffer."
12248 (interactive)
12249 (unless (org-at-table-p)
12250 (error "Not at a table"))
12251 (org-table-get-specials)
12252 (let ((eql (org-table-get-stored-formulas))
12253 (pos (move-marker (make-marker) (point)))
12254 (wc (current-window-configuration))
12255 entry loc s)
12256 (switch-to-buffer-other-window "*Edit Formulas*")
12257 (erase-buffer)
12258 (fundamental-mode)
12259 (set (make-local-variable 'org-pos) pos)
12260 (set (make-local-variable 'org-window-configuration) wc)
12261 (use-local-map org-edit-formulas-map)
12262 (setq s "# Edit formulas and finish with `C-c C-c'.
12263 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
12264 # Use `C-c ?' to get information about $name at point.
12265 # To cancel editing, press `C-c C-q'.\n")
12266 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12267 (insert s)
12268 (while (setq entry (pop eql))
12269 (when (setq loc (assoc (car entry) org-table-named-field-locations))
12270 (setq s (format "# Named formula, referring to column %d in line %d\n"
12271 (nth 2 loc) (nth 1 loc)))
12272 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12273 (insert s))
12274 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
12275 (remove-text-properties 0 (length s) '(face nil) s)
12276 (insert s))
12277 (goto-char (point-min))
12278 (message "Edit formulas and finish with `C-c C-c'.")))
12280 (defun org-show-variable ()
12281 "Show the location/value of the $ expression at point."
12282 (interactive)
12283 (let (var (pos org-pos) (win (selected-window)) e)
12284 (save-excursion
12285 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
12286 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
12287 (setq var (match-string 1))
12288 (error "No variable at point")))
12289 (cond
12290 ((setq e (assoc var org-table-named-field-locations))
12291 (switch-to-buffer-other-window (marker-buffer pos))
12292 (goto-line (nth 1 e))
12293 (org-table-goto-column (nth 2 e))
12294 (select-window win)
12295 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
12296 ((setq e (assoc var org-table-column-names))
12297 (switch-to-buffer-other-window (marker-buffer pos))
12298 (goto-char pos)
12299 (goto-char (org-table-begin))
12300 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
12301 (org-table-end) t)
12302 (progn
12303 (goto-char (match-beginning 1))
12304 (message "Named column (column %s)" (cdr e)))
12305 (error "Column name not found"))
12306 (select-window win))
12307 ((string-match "^[0-9]$" var)
12308 ;; column number
12309 (switch-to-buffer-other-window (marker-buffer pos))
12310 (goto-char pos)
12311 (goto-char (org-table-begin))
12312 (recenter 1)
12313 (if (re-search-forward org-table-dataline-regexp
12314 (org-table-end) t)
12315 (progn
12316 (goto-char (match-beginning 0))
12317 (org-table-goto-column (string-to-number var))
12318 (message "Column %s" var))
12319 (error "Column name not found"))
12320 (select-window win))
12321 ((setq e (assoc var org-table-local-parameters))
12322 (switch-to-buffer-other-window (marker-buffer pos))
12323 (goto-char pos)
12324 (goto-char (org-table-begin))
12325 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
12326 (progn
12327 (goto-char (match-beginning 1))
12328 (message "Local parameter."))
12329 (error "Parameter not found"))
12330 (select-window win))
12332 (cond
12333 ((setq e (assoc var org-table-formula-constants))
12334 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
12335 ((setq e (and (fboundp 'constants-get) (constants-get var)))
12336 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
12337 (t (error "Undefined name $%s" var)))))))
12339 (defun org-finish-edit-formulas (&optional arg)
12340 "Parse the buffer for formula definitions and install them.
12341 With prefix ARG, apply the new formulas to the table."
12342 (interactive "P")
12343 (let ((pos org-pos) eql)
12344 (goto-char (point-min))
12345 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
12346 (push (cons (match-string 1) (match-string 2)) eql))
12347 (set-window-configuration org-window-configuration)
12348 (select-window (get-buffer-window (marker-buffer pos)))
12349 (goto-char pos)
12350 (unless (org-at-table-p)
12351 (error "Lost table position - cannot install formulae"))
12352 (org-table-store-formulas eql)
12353 (move-marker pos nil)
12354 (kill-buffer "*Edit Formulas*")
12355 (if arg
12356 (org-table-recalculate 'all)
12357 (message "New formulas installed - press C-u C-c C-c to apply."))))
12359 (defun org-abort-edit-formulas ()
12360 "Abort editing formulas, without installing the changes."
12361 (interactive)
12362 (let ((pos org-pos))
12363 (set-window-configuration org-window-configuration)
12364 (select-window (get-buffer-window (marker-buffer pos)))
12365 (goto-char pos)
12366 (message "Formula editing aborted without installing changes")))
12368 ;;; The orgtbl minor mode
12370 ;; Define a minor mode which can be used in other modes in order to
12371 ;; integrate the org-mode table editor.
12373 ;; This is really a hack, because the org-mode table editor uses several
12374 ;; keys which normally belong to the major mode, for example the TAB and
12375 ;; RET keys. Here is how it works: The minor mode defines all the keys
12376 ;; necessary to operate the table editor, but wraps the commands into a
12377 ;; function which tests if the cursor is currently inside a table. If that
12378 ;; is the case, the table editor command is executed. However, when any of
12379 ;; those keys is used outside a table, the function uses `key-binding' to
12380 ;; look up if the key has an associated command in another currently active
12381 ;; keymap (minor modes, major mode, global), and executes that command.
12382 ;; There might be problems if any of the keys used by the table editor is
12383 ;; otherwise used as a prefix key.
12385 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
12386 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
12387 ;; addresses this by checking explicitly for both bindings.
12389 ;; The optimized version (see variable `orgtbl-optimized') takes over
12390 ;; all keys which are bound to `self-insert-command' in the *global map*.
12391 ;; Some modes bind other commands to simple characters, for example
12392 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
12393 ;; active, this binding is ignored inside tables and replaced with a
12394 ;; modified self-insert.
12396 (defvar orgtbl-mode nil
12397 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
12398 table editor in arbitrary modes.")
12399 (make-variable-buffer-local 'orgtbl-mode)
12401 (defvar orgtbl-mode-map (make-keymap)
12402 "Keymap for `orgtbl-mode'.")
12404 ;;;###autoload
12405 (defun turn-on-orgtbl ()
12406 "Unconditionally turn on `orgtbl-mode'."
12407 (orgtbl-mode 1))
12409 ;;;###autoload
12410 (defun orgtbl-mode (&optional arg)
12411 "The `org-mode' table editor as a minor mode for use in other modes."
12412 (interactive)
12413 (if (eq major-mode 'org-mode)
12414 ;; Exit without error, in case some hook functions calls this
12415 ;; by accident in org-mode.
12416 (message "Orgtbl-mode is not useful in org-mode, command ignored")
12417 (setq orgtbl-mode
12418 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
12419 (if orgtbl-mode
12420 (progn
12421 (and (orgtbl-setup) (defun orgtbl-setup () nil))
12422 ;; Make sure we are first in minor-mode-map-alist
12423 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
12424 (and c (setq minor-mode-map-alist
12425 (cons c (delq c minor-mode-map-alist)))))
12426 (set (make-local-variable (quote org-table-may-need-update)) t)
12427 (org-add-hook 'before-change-functions 'org-before-change-function
12428 nil 'local)
12429 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
12430 auto-fill-inhibit-regexp)
12431 (set (make-local-variable 'auto-fill-inhibit-regexp)
12432 (if auto-fill-inhibit-regexp
12433 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
12434 "[ \t]*|"))
12435 (org-add-to-invisibility-spec '(org-cwidth))
12436 (easy-menu-add orgtbl-mode-menu)
12437 (run-hooks 'orgtbl-mode-hook))
12438 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
12439 (org-cleanup-narrow-column-properties)
12440 (org-remove-from-invisibility-spec '(org-cwidth))
12441 (remove-hook 'before-change-functions 'org-before-change-function t)
12442 (easy-menu-remove orgtbl-mode-menu)
12443 (force-mode-line-update 'all))))
12445 (defun org-cleanup-narrow-column-properties ()
12446 "Remove all properties related to narrow-column invisibility."
12447 (let ((s 1))
12448 (while (setq s (text-property-any s (point-max)
12449 'display org-narrow-column-arrow))
12450 (remove-text-properties s (1+ s) '(display t)))
12451 (setq s 1)
12452 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
12453 (remove-text-properties s (1+ s) '(org-cwidth t)))
12454 (setq s 1)
12455 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
12456 (remove-text-properties s (1+ s) '(invisible t)))))
12458 ;; Install it as a minor mode.
12459 (put 'orgtbl-mode :included t)
12460 (put 'orgtbl-mode :menu-tag "Org Table Mode")
12461 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
12463 (defun orgtbl-make-binding (fun n &rest keys)
12464 "Create a function for binding in the table minor mode.
12465 FUN is the command to call inside a table. N is used to create a unique
12466 command name. KEYS are keys that should be checked in for a command
12467 to execute outside of tables."
12468 (eval
12469 (list 'defun
12470 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
12471 '(arg)
12472 (concat "In tables, run `" (symbol-name fun) "'.\n"
12473 "Outside of tables, run the binding of `"
12474 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
12475 "'.")
12476 '(interactive "p")
12477 (list 'if
12478 '(org-at-table-p)
12479 (list 'call-interactively (list 'quote fun))
12480 (list 'let '(orgtbl-mode)
12481 (list 'call-interactively
12482 (append '(or)
12483 (mapcar (lambda (k)
12484 (list 'key-binding k))
12485 keys)
12486 '('orgtbl-error))))))))
12488 (defun orgtbl-error ()
12489 "Error when there is no default binding for a table key."
12490 (interactive)
12491 (error "This key is has no function outside tables"))
12493 (defun orgtbl-setup ()
12494 "Setup orgtbl keymaps."
12495 (let ((nfunc 0)
12496 (bindings
12497 (list
12498 '([(meta shift left)] org-table-delete-column)
12499 '([(meta left)] org-table-move-column-left)
12500 '([(meta right)] org-table-move-column-right)
12501 '([(meta shift right)] org-table-insert-column)
12502 '([(meta shift up)] org-table-kill-row)
12503 '([(meta shift down)] org-table-insert-row)
12504 '([(meta up)] org-table-move-row-up)
12505 '([(meta down)] org-table-move-row-down)
12506 '("\C-c\C-w" org-table-cut-region)
12507 '("\C-c\M-w" org-table-copy-region)
12508 '("\C-c\C-y" org-table-paste-rectangle)
12509 '("\C-c-" org-table-insert-hline)
12510 ; '([(shift tab)] org-table-previous-field)
12511 '("\C-m" org-table-next-row)
12512 (list (org-key 'S-return) 'org-table-copy-down)
12513 '([(meta return)] org-table-wrap-region)
12514 '("\C-c\C-q" org-table-wrap-region)
12515 '("\C-c?" org-table-current-column)
12516 '("\C-c " org-table-blank-field)
12517 '("\C-c+" org-table-sum)
12518 '("\C-c=" org-table-eval-formula)
12519 '("\C-c'" org-table-edit-formulas)
12520 '("\C-c`" org-table-edit-field)
12521 '("\C-c*" org-table-recalculate)
12522 '("\C-c|" org-table-create-or-convert-from-region)
12523 '("\C-c^" org-table-sort-lines)
12524 '([(control ?#)] org-table-rotate-recalc-marks)))
12525 elt key fun cmd)
12526 (while (setq elt (pop bindings))
12527 (setq nfunc (1+ nfunc))
12528 (setq key (car elt)
12529 fun (nth 1 elt)
12530 cmd (orgtbl-make-binding fun nfunc key))
12531 (define-key orgtbl-mode-map key cmd))
12532 ;; Special treatment needed for TAB and RET
12533 (define-key orgtbl-mode-map [(return)]
12534 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
12535 (define-key orgtbl-mode-map "\C-m"
12536 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
12537 (define-key orgtbl-mode-map [(tab)]
12538 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
12539 (define-key orgtbl-mode-map "\C-i"
12540 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
12541 (define-key orgtbl-mode-map "\C-i"
12542 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
12543 (define-key orgtbl-mode-map "\C-c\C-c"
12544 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
12545 (when orgtbl-optimized
12546 ;; If the user wants maximum table support, we need to hijack
12547 ;; some standard editing functions
12548 (org-remap orgtbl-mode-map
12549 'self-insert-command 'orgtbl-self-insert-command
12550 'delete-char 'org-delete-char
12551 'delete-backward-char 'org-delete-backward-char)
12552 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
12553 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
12554 '("OrgTbl"
12555 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
12556 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
12557 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
12558 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
12559 "--"
12560 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
12561 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
12562 ["Copy Field from Above"
12563 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
12564 "--"
12565 ("Column"
12566 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
12567 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
12568 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
12569 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
12570 "--"
12571 ["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])
12572 ("Row"
12573 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
12574 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
12575 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
12576 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
12577 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
12578 "--"
12579 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
12580 ("Rectangle"
12581 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
12582 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
12583 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
12584 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
12585 "--"
12586 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
12587 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12588 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
12589 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
12590 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
12591 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
12592 ["Sum Column/Rectangle" org-table-sum
12593 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
12594 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
12595 ["Debug Formulas"
12596 (setq org-table-formula-debug (not org-table-formula-debug))
12597 :style toggle :selected org-table-formula-debug]
12601 (defun orgtbl-tab (arg)
12602 "Justification and field motion for `orgtbl-mode'."
12603 (interactive "P")
12604 (if arg (org-table-edit-field t)
12605 (org-table-justify-field-maybe)
12606 (org-table-next-field)))
12608 (defun orgtbl-ret ()
12609 "Justification and field motion for `orgtbl-mode'."
12610 (interactive)
12611 (org-table-justify-field-maybe)
12612 (org-table-next-row))
12614 (defun orgtbl-self-insert-command (N)
12615 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12616 If the cursor is in a table looking at whitespace, the whitespace is
12617 overwritten, and the table is not marked as requiring realignment."
12618 (interactive "p")
12619 (if (and (org-at-table-p)
12621 (and org-table-auto-blank-field
12622 (member last-command
12623 '(orgtbl-hijacker-command-100
12624 orgtbl-hijacker-command-101
12625 orgtbl-hijacker-command-102
12626 orgtbl-hijacker-command-103
12627 orgtbl-hijacker-command-104
12628 orgtbl-hijacker-command-105))
12629 (org-table-blank-field))
12631 (eq N 1)
12632 (looking-at "[^|\n]* +|"))
12633 (let (org-table-may-need-update)
12634 (goto-char (1- (match-end 0)))
12635 (delete-backward-char 1)
12636 (goto-char (match-beginning 0))
12637 (self-insert-command N))
12638 (setq org-table-may-need-update t)
12639 (let (orgtbl-mode)
12640 (call-interactively (key-binding (vector last-input-event))))))
12642 (defun org-force-self-insert (N)
12643 "Needed to enforce self-insert under remapping."
12644 (interactive "p")
12645 (self-insert-command N))
12647 ;;; Exporting
12649 (defconst org-level-max 20)
12651 (defvar org-export-html-preamble nil
12652 "Preamble, to be inserted just after <body>. Set by publishing functions.")
12653 (defvar org-export-html-postamble nil
12654 "Preamble, to be inserted just before </body>. Set by publishing functions.")
12655 (defvar org-export-html-auto-preamble t
12656 "Should default preamble be inserted? Set by publishing functions.")
12657 (defvar org-export-html-auto-postamble t
12658 "Should default postamble be inserted? Set by publishing functions.")
12660 (defconst org-export-plist-vars
12661 '((:language . org-export-default-language)
12662 (:headline-levels . org-export-headline-levels)
12663 (:section-numbers . org-export-with-section-numbers)
12664 (:table-of-contents . org-export-with-toc)
12665 (:archived-trees . org-export-with-archived-trees)
12666 (:emphasize . org-export-with-emphasize)
12667 (:sub-superscript . org-export-with-sub-superscripts)
12668 (:TeX-macros . org-export-with-TeX-macros)
12669 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
12670 (:fixed-width . org-export-with-fixed-width)
12671 (:timestamps . org-export-with-timestamps)
12672 (:tables . org-export-with-tables)
12673 (:table-auto-headline . org-export-highlight-first-table-line)
12674 (:style . org-export-html-style)
12675 (:convert-org-links . org-export-html-link-org-files-as-html)
12676 (:inline-images . org-export-html-inline-images)
12677 (:expand-quoted-html . org-export-html-expand)
12678 (:timestamp . org-export-html-with-timestamp)
12679 (:publishing-directory . org-export-publishing-directory)
12680 (:preamble . org-export-html-preamble)
12681 (:postamble . org-export-html-postamble)
12682 (:auto-preamble . org-export-html-auto-preamble)
12683 (:auto-postamble . org-export-html-auto-postamble)
12684 (:author . user-full-name)
12685 (:email . user-mail-address)))
12687 (defun org-default-export-plist ()
12688 "Return the property list with default settings for the export variables."
12689 (let ((l org-export-plist-vars) rtn e)
12690 (while (setq e (pop l))
12691 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
12692 rtn))
12694 (defun org-infile-export-plist ()
12695 "Return the property list with file-local settings for export."
12696 (save-excursion
12697 (goto-char 0)
12698 (let ((re (org-make-options-regexp
12699 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12700 p key val text options)
12701 (while (re-search-forward re nil t)
12702 (setq key (org-match-string-no-properties 1)
12703 val (org-match-string-no-properties 2))
12704 (cond
12705 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
12706 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
12707 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
12708 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
12709 ((string-equal key "TEXT")
12710 (setq text (if text (concat text "\n" val) val)))
12711 ((string-equal key "OPTIONS") (setq options val))))
12712 (setq p (plist-put p :text text))
12713 (when options
12714 (let ((op '(("H" . :headline-levels)
12715 ("num" . :section-numbers)
12716 ("toc" . :table-of-contents)
12717 ("\\n" . :preserve-breaks)
12718 ("@" . :expand-quoted-html)
12719 (":" . :fixed-width)
12720 ("|" . :tables)
12721 ("^" . :sub-superscript)
12722 ("*" . :emphasize)
12723 ("TeX" . :TeX-macros)
12724 ("LaTeX" . :LaTeX-fragments)))
12726 (while (setq o (pop op))
12727 (if (string-match (concat (regexp-quote (car o))
12728 ":\\([^ \t\n\r;,.]*\\)")
12729 options)
12730 (setq p (plist-put p (cdr o)
12731 (car (read-from-string
12732 (match-string 1 options)))))))))
12733 p)))
12735 (defun org-combine-plists (&rest plists)
12736 "Create a single property list from all plists in PLISTS.
12737 The process starts by copying the last list, and then setting properties
12738 from the other lists. Settings in the first list are the most significant
12739 ones and overrule settings in the other lists."
12740 (let ((rtn (copy-sequence (pop plists)))
12741 p v ls)
12742 (while plists
12743 (setq ls (pop plists))
12744 (while ls
12745 (setq p (pop ls) v (pop ls))
12746 (setq rtn (plist-put rtn p v))))
12747 rtn))
12749 (defun org-export-directory (type plist)
12750 (let* ((val (plist-get plist :publishing-directory))
12751 (dir (if (listp val)
12752 (or (cdr (assoc type val)) ".")
12753 val)))
12754 dir))
12756 (defun org-export-find-first-heading-line (list)
12757 "Remove all lines from LIST which are before the first headline."
12758 (let ((orig-list list)
12759 (re (concat "^" outline-regexp)))
12760 (while (and list
12761 (not (string-match re (car list))))
12762 (pop list))
12763 (or list orig-list)))
12765 (defun org-skip-comments (lines)
12766 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
12767 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
12768 (re2 "^\\(\\*+\\)[ \t\n\r]")
12769 rtn line level)
12770 (while (setq line (pop lines))
12771 (cond
12772 ((and (string-match re1 line)
12773 (setq level (- (match-end 1) (match-beginning 1))))
12774 ;; Beginning of a COMMENT subtree. Skip it.
12775 (while (and (setq line (pop lines))
12776 (or (not (string-match re2 line))
12777 (> (- (match-end 1) (match-beginning 1)) level))))
12778 (setq lines (cons line lines)))
12779 ((string-match "^#" line)
12780 ;; an ordinary comment line
12782 ((and org-export-table-remove-special-lines
12783 (string-match "^[ \t]*|" line)
12784 (or (string-match "^[ \t]*| *[!_^] *|" line)
12785 (and (string-match "| *<[0-9]+> *|" line)
12786 (not (string-match "| *[^ <|]" line)))))
12787 ;; a special table line that should be removed
12789 (t (setq rtn (cons line rtn)))))
12790 (nreverse rtn)))
12792 (defun org-export (&optional arg)
12793 (interactive)
12794 (let ((help "[t] insert the export option template
12795 \[v] limit export to visible part of outline tree
12797 \[a] export as ASCII
12798 \[h] export as HTML
12799 \[b] export as HTML and browse immediately
12800 \[x] export as XOXO
12802 \[i] export current file as iCalendar file
12803 \[I] export all agenda files as iCalendar files
12804 \[c] export agenda files into combined iCalendar file
12806 \[F] publish current file
12807 \[P] publish current project
12808 \[X] publish... (project will be prompted for)
12809 \[A] publish all projects")
12810 (cmds
12811 '((?t . org-insert-export-options-template)
12812 (?v . org-export-visible)
12813 (?a . org-export-as-ascii)
12814 (?h . org-export-as-html)
12815 (?b . org-export-as-html-and-open)
12816 (?x . org-export-as-xoxo)
12817 (?i . org-export-icalendar-this-file)
12818 (?I . org-export-icalendar-all-agenda-files)
12819 (?c . org-export-icalendar-combine-agenda-files)
12820 (?F . org-publish-current-file)
12821 (?P . org-publish-current-project)
12822 (?X . org-publish)
12823 (?A . org-publish-all)))
12824 r1 r2 ass)
12825 (save-window-excursion
12826 (delete-other-windows)
12827 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
12828 (princ help))
12829 (message "Select command: ")
12830 (setq r1 (read-char-exclusive)))
12831 (setq r2 (if (< r1 27) (+ r1 96) r1))
12832 (if (setq ass (assq r2 cmds))
12833 (call-interactively (cdr ass))
12834 (error "No command associated with key %c" r1))))
12836 ;; ASCII
12838 (defconst org-html-entities
12839 '(("nbsp")
12840 ("iexcl")
12841 ("cent")
12842 ("pound")
12843 ("curren")
12844 ("yen")
12845 ("brvbar")
12846 ("sect")
12847 ("uml")
12848 ("copy")
12849 ("ordf")
12850 ("laquo")
12851 ("not")
12852 ("shy")
12853 ("reg")
12854 ("macr")
12855 ("deg")
12856 ("plusmn")
12857 ("sup2")
12858 ("sup3")
12859 ("acute")
12860 ("micro")
12861 ("para")
12862 ("middot")
12863 ("odot"."o")
12864 ("star"."*")
12865 ("cedil")
12866 ("sup1")
12867 ("ordm")
12868 ("raquo")
12869 ("frac14")
12870 ("frac12")
12871 ("frac34")
12872 ("iquest")
12873 ("Agrave")
12874 ("Aacute")
12875 ("Acirc")
12876 ("Atilde")
12877 ("Auml")
12878 ("Aring") ("AA"."&Aring;")
12879 ("AElig")
12880 ("Ccedil")
12881 ("Egrave")
12882 ("Eacute")
12883 ("Ecirc")
12884 ("Euml")
12885 ("Igrave")
12886 ("Iacute")
12887 ("Icirc")
12888 ("Iuml")
12889 ("ETH")
12890 ("Ntilde")
12891 ("Ograve")
12892 ("Oacute")
12893 ("Ocirc")
12894 ("Otilde")
12895 ("Ouml")
12896 ("times")
12897 ("Oslash")
12898 ("Ugrave")
12899 ("Uacute")
12900 ("Ucirc")
12901 ("Uuml")
12902 ("Yacute")
12903 ("THORN")
12904 ("szlig")
12905 ("agrave")
12906 ("aacute")
12907 ("acirc")
12908 ("atilde")
12909 ("auml")
12910 ("aring")
12911 ("aelig")
12912 ("ccedil")
12913 ("egrave")
12914 ("eacute")
12915 ("ecirc")
12916 ("euml")
12917 ("igrave")
12918 ("iacute")
12919 ("icirc")
12920 ("iuml")
12921 ("eth")
12922 ("ntilde")
12923 ("ograve")
12924 ("oacute")
12925 ("ocirc")
12926 ("otilde")
12927 ("ouml")
12928 ("divide")
12929 ("oslash")
12930 ("ugrave")
12931 ("uacute")
12932 ("ucirc")
12933 ("uuml")
12934 ("yacute")
12935 ("thorn")
12936 ("yuml")
12937 ("fnof")
12938 ("Alpha")
12939 ("Beta")
12940 ("Gamma")
12941 ("Delta")
12942 ("Epsilon")
12943 ("Zeta")
12944 ("Eta")
12945 ("Theta")
12946 ("Iota")
12947 ("Kappa")
12948 ("Lambda")
12949 ("Mu")
12950 ("Nu")
12951 ("Xi")
12952 ("Omicron")
12953 ("Pi")
12954 ("Rho")
12955 ("Sigma")
12956 ("Tau")
12957 ("Upsilon")
12958 ("Phi")
12959 ("Chi")
12960 ("Psi")
12961 ("Omega")
12962 ("alpha")
12963 ("beta")
12964 ("gamma")
12965 ("delta")
12966 ("epsilon")
12967 ("varepsilon"."&epsilon;")
12968 ("zeta")
12969 ("eta")
12970 ("theta")
12971 ("iota")
12972 ("kappa")
12973 ("lambda")
12974 ("mu")
12975 ("nu")
12976 ("xi")
12977 ("omicron")
12978 ("pi")
12979 ("rho")
12980 ("sigmaf") ("varsigma"."&sigmaf;")
12981 ("sigma")
12982 ("tau")
12983 ("upsilon")
12984 ("phi")
12985 ("chi")
12986 ("psi")
12987 ("omega")
12988 ("thetasym") ("vartheta"."&thetasym;")
12989 ("upsih")
12990 ("piv")
12991 ("bull") ("bullet"."&bull;")
12992 ("hellip") ("dots"."&hellip;")
12993 ("prime")
12994 ("Prime")
12995 ("oline")
12996 ("frasl")
12997 ("weierp")
12998 ("image")
12999 ("real")
13000 ("trade")
13001 ("alefsym")
13002 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
13003 ("uarr") ("uparrow"."&uarr;")
13004 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
13005 ("darr")("downarrow"."&darr;")
13006 ("harr") ("leftrightarrow"."&harr;")
13007 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
13008 ("lArr") ("Leftarrow"."&lArr;")
13009 ("uArr") ("Uparrow"."&uArr;")
13010 ("rArr") ("Rightarrow"."&rArr;")
13011 ("dArr") ("Downarrow"."&dArr;")
13012 ("hArr") ("Leftrightarrow"."&hArr;")
13013 ("forall")
13014 ("part") ("partial"."&part;")
13015 ("exist") ("exists"."&exist;")
13016 ("empty") ("emptyset"."&empty;")
13017 ("nabla")
13018 ("isin") ("in"."&isin;")
13019 ("notin")
13020 ("ni")
13021 ("prod")
13022 ("sum")
13023 ("minus")
13024 ("lowast") ("ast"."&lowast;")
13025 ("radic")
13026 ("prop") ("proptp"."&prop;")
13027 ("infin") ("infty"."&infin;")
13028 ("ang") ("angle"."&ang;")
13029 ("and") ("vee"."&and;")
13030 ("or") ("wedge"."&or;")
13031 ("cap")
13032 ("cup")
13033 ("int")
13034 ("there4")
13035 ("sim")
13036 ("cong") ("simeq"."&cong;")
13037 ("asymp")("approx"."&asymp;")
13038 ("ne") ("neq"."&ne;")
13039 ("equiv")
13040 ("le")
13041 ("ge")
13042 ("sub") ("subset"."&sub;")
13043 ("sup") ("supset"."&sup;")
13044 ("nsub")
13045 ("sube")
13046 ("supe")
13047 ("oplus")
13048 ("otimes")
13049 ("perp")
13050 ("sdot") ("cdot"."&sdot;")
13051 ("lceil")
13052 ("rceil")
13053 ("lfloor")
13054 ("rfloor")
13055 ("lang")
13056 ("rang")
13057 ("loz") ("Diamond"."&loz;")
13058 ("spades") ("spadesuit"."&spades;")
13059 ("clubs") ("clubsuit"."&clubs;")
13060 ("hearts") ("diamondsuit"."&hearts;")
13061 ("diams") ("diamondsuit"."&diams;")
13062 ("quot")
13063 ("amp")
13064 ("lt")
13065 ("gt")
13066 ("OElig")
13067 ("oelig")
13068 ("Scaron")
13069 ("scaron")
13070 ("Yuml")
13071 ("circ")
13072 ("tilde")
13073 ("ensp")
13074 ("emsp")
13075 ("thinsp")
13076 ("zwnj")
13077 ("zwj")
13078 ("lrm")
13079 ("rlm")
13080 ("ndash")
13081 ("mdash")
13082 ("lsquo")
13083 ("rsquo")
13084 ("sbquo")
13085 ("ldquo")
13086 ("rdquo")
13087 ("bdquo")
13088 ("dagger")
13089 ("Dagger")
13090 ("permil")
13091 ("lsaquo")
13092 ("rsaquo")
13093 ("euro")
13095 ("arccos"."arccos")
13096 ("arcsin"."arcsin")
13097 ("arctan"."arctan")
13098 ("arg"."arg")
13099 ("cos"."cos")
13100 ("cosh"."cosh")
13101 ("cot"."cot")
13102 ("coth"."coth")
13103 ("csc"."csc")
13104 ("deg"."deg")
13105 ("det"."det")
13106 ("dim"."dim")
13107 ("exp"."exp")
13108 ("gcd"."gcd")
13109 ("hom"."hom")
13110 ("inf"."inf")
13111 ("ker"."ker")
13112 ("lg"."lg")
13113 ("lim"."lim")
13114 ("liminf"."liminf")
13115 ("limsup"."limsup")
13116 ("ln"."ln")
13117 ("log"."log")
13118 ("max"."max")
13119 ("min"."min")
13120 ("Pr"."Pr")
13121 ("sec"."sec")
13122 ("sin"."sin")
13123 ("sinh"."sinh")
13124 ("sup"."sup")
13125 ("tan"."tan")
13126 ("tanh"."tanh")
13128 "Entities for TeX->HTML translation.
13129 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
13130 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
13131 In that case, \"\\ent\" will be translated to \"&other;\".
13132 The list contains HTML entities for Latin-1, Greek and other symbols.
13133 It is supplemented by a number of commonly used TeX macros with appropriate
13134 translations. There is currently no way for users to extend this.")
13136 (defun org-cleaned-string-for-export (string &rest parameters)
13137 "Cleanup a buffer substring so that links can be created safely."
13138 (interactive)
13139 (let* ((re-radio (and org-target-link-regexp
13140 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
13141 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
13142 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
13143 (re-archive (concat ":" org-archive-tag ":"))
13144 rtn)
13145 (save-excursion
13146 (set-buffer (get-buffer-create " org-mode-tmp"))
13147 (erase-buffer)
13148 (insert string)
13149 (let ((org-inhibit-startup t)) (org-mode))
13151 ;; Get rid of archived trees
13152 (when (not (eq org-export-with-archived-trees t))
13153 (goto-char (point-min))
13154 (while (re-search-forward re-archive nil t)
13155 (if (not (org-on-heading-p))
13156 (org-end-of-subtree t)
13157 (beginning-of-line 1)
13158 (delete-region
13159 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
13160 (org-end-of-subtree)))))
13162 ;; Find targets in comments and move them out of comments,
13163 ;; but mark them as targets that should be invisible
13164 (goto-char (point-min))
13165 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
13166 (replace-match "\\1(INVISIBLE)"))
13168 ;; Find matches for radio targets and turn them into internal links
13169 (goto-char (point-min))
13170 (when re-radio
13171 (while (re-search-forward re-radio nil t)
13172 (replace-match "\\1[[\\2]]")))
13174 ;; Find all links that contain a newline and put them into a single line
13175 (goto-char (point-min))
13176 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
13177 (replace-match "\\1 \\3")
13178 (goto-char (match-beginning 0)))
13180 ;; Convert LaTeX fragments to images
13181 (when (memq :LaTeX-fragments parameters)
13182 (org-format-latex
13183 (concat "ltxpng/" (file-name-sans-extension
13184 (file-name-nondirectory
13185 org-current-export-file)))
13186 org-current-export-dir nil "Creating LaTeX image %s"))
13187 (message "Exporting...")
13189 ;; Normalize links: Convert angle and plain links into bracket links
13190 (goto-char (point-min))
13191 (while (re-search-forward re-plain-link nil t)
13192 (replace-match
13193 (concat
13194 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13195 t t))
13196 (goto-char (point-min))
13197 (while (re-search-forward re-angle-link nil t)
13198 (replace-match
13199 (concat
13200 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13201 t t))
13203 ;; Find multiline emphasis and put them into single line
13204 (when (memq :emph-multiline parameters)
13205 (goto-char (point-min))
13206 (while (re-search-forward org-emph-re nil t)
13207 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
13208 (goto-char (1- (match-end 0)))))
13210 ;; Remove comments
13211 (goto-char (point-min))
13212 (while (re-search-forward "^#.*\n?" nil t)
13213 (replace-match ""))
13214 (setq rtn (buffer-string)))
13215 (kill-buffer " org-mode-tmp")
13216 rtn))
13218 (defun org-solidify-link-text (s &optional alist)
13219 "Take link text and make a safe target out of it."
13220 (save-match-data
13221 (let* ((rtn
13222 (mapconcat
13223 'identity
13224 (org-split-string s "[ \t\r\n]+") "--"))
13225 (a (assoc rtn alist)))
13226 (or (cdr a) rtn))))
13228 (defun org-convert-to-odd-levels ()
13229 "Convert an org-mode file with all levels allowed to one with odd levels.
13230 This will leave level 1 alone, convert level 2 to level 3, level 3 to
13231 level 5 etc."
13232 (interactive)
13233 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
13234 (let ((org-odd-levels-only nil) n)
13235 (save-excursion
13236 (goto-char (point-min))
13237 (while (re-search-forward "^\\*\\*+" nil t)
13238 (setq n (1- (length (match-string 0))))
13239 (while (>= (setq n (1- n)) 0)
13240 (org-demote))
13241 (end-of-line 1))))))
13244 (defun org-convert-to-oddeven-levels ()
13245 "Convert an org-mode file with only odd levels to one with odd and even levels.
13246 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
13247 section with an even level, conversion would destroy the structure of the file. An error
13248 is signaled in this case."
13249 (interactive)
13250 (goto-char (point-min))
13251 ;; First check if there are no even levels
13252 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
13253 (org-show-hierarchy-above)
13254 (error "Not all levels are odd in this file. Conversion not possible."))
13255 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
13256 (let ((org-odd-levels-only nil) n)
13257 (save-excursion
13258 (goto-char (point-min))
13259 (while (re-search-forward "^\\*\\*+" nil t)
13260 (setq n (/ (length (match-string 0)) 2))
13261 (while (>= (setq n (1- n)) 0)
13262 (org-promote))
13263 (end-of-line 1))))))
13265 (defun org-tr-level (n)
13266 "Make N odd if required."
13267 (if org-odd-levels-only (1+ (/ n 2)) n))
13269 (defvar org-last-level nil) ; dynamically scoped variable
13270 (defvar org-ascii-current-indentation nil) ; For communication
13272 (defun org-export-as-ascii (arg)
13273 "Export the outline as a pretty ASCII file.
13274 If there is an active region, export only the region.
13275 The prefix ARG specifies how many levels of the outline should become
13276 underlined headlines. The default is 3."
13277 (interactive "P")
13278 (setq-default org-todo-line-regexp org-todo-line-regexp)
13279 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13280 (org-infile-export-plist)))
13281 (region
13282 (buffer-substring
13283 (if (org-region-active-p) (region-beginning) (point-min))
13284 (if (org-region-active-p) (region-end) (point-max))))
13285 (lines (org-export-find-first-heading-line
13286 (org-skip-comments
13287 (org-split-string
13288 (org-cleaned-string-for-export region)
13289 "[\r\n]"))))
13290 (org-ascii-current-indentation '(0 . 0))
13291 (org-startup-with-deadline-check nil)
13292 (level 0) line txt
13293 (umax nil)
13294 (case-fold-search nil)
13295 (filename (concat (file-name-as-directory
13296 (org-export-directory :ascii opt-plist))
13297 (file-name-sans-extension
13298 (file-name-nondirectory buffer-file-name))
13299 ".txt"))
13300 (buffer (find-file-noselect filename))
13301 (levels-open (make-vector org-level-max nil))
13302 (odd org-odd-levels-only)
13303 (date (format-time-string "%Y/%m/%d" (current-time)))
13304 (time (format-time-string "%X" (org-current-time)))
13305 (author (plist-get opt-plist :author))
13306 (title (or (plist-get opt-plist :title)
13307 (file-name-sans-extension
13308 (file-name-nondirectory buffer-file-name))))
13309 (email (plist-get opt-plist :email))
13310 (language (plist-get opt-plist :language))
13311 (text nil)
13312 (todo nil)
13313 (lang-words nil))
13315 (setq org-last-level 1)
13316 (org-init-section-numbers)
13318 (find-file-noselect filename)
13320 (setq lang-words (or (assoc language org-export-language-setup)
13321 (assoc "en" org-export-language-setup)))
13322 (if org-export-ascii-show-new-buffer
13323 (switch-to-buffer-other-window buffer)
13324 (set-buffer buffer))
13325 (erase-buffer)
13326 (fundamental-mode)
13327 ;; create local variables for all options, to make sure all called
13328 ;; functions get the correct information
13329 (mapcar (lambda (x)
13330 (set (make-local-variable (cdr x))
13331 (plist-get opt-plist (car x))))
13332 org-export-plist-vars)
13333 (set (make-local-variable 'org-odd-levels-only) odd)
13334 (setq umax (if arg (prefix-numeric-value arg)
13335 org-export-headline-levels))
13337 ;; File header
13338 (if title (org-insert-centered title ?=))
13339 (insert "\n")
13340 (if (or author email)
13341 (insert (concat (nth 1 lang-words) ": " (or author "")
13342 (if email (concat " <" email ">") "")
13343 "\n")))
13344 (if (and date time)
13345 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
13346 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
13348 (insert "\n\n")
13350 (if org-export-with-toc
13351 (progn
13352 (insert (nth 3 lang-words) "\n"
13353 (make-string (length (nth 3 lang-words)) ?=) "\n")
13354 (mapcar '(lambda (line)
13355 (if (string-match org-todo-line-regexp
13356 line)
13357 ;; This is a headline
13358 (progn
13359 (setq level (- (match-end 1) (match-beginning 1))
13360 level (org-tr-level level)
13361 txt (match-string 3 line)
13362 todo
13363 (or (and org-export-mark-todo-in-toc
13364 (match-beginning 2)
13365 (not (equal (match-string 2 line)
13366 org-done-string)))
13367 ; TODO, not DONE
13368 (and org-export-mark-todo-in-toc
13369 (= level umax)
13370 (org-search-todo-below
13371 line lines level))))
13372 (setq txt (org-html-expand-for-ascii txt))
13374 (if org-export-with-section-numbers
13375 (setq txt (concat (org-section-number level)
13376 " " txt)))
13377 (if (<= level umax)
13378 (progn
13379 (insert
13380 (make-string (* (1- level) 4) ?\ )
13381 (format (if todo "%s (*)\n" "%s\n") txt))
13382 (setq org-last-level level))
13383 ))))
13384 lines)))
13386 (org-init-section-numbers)
13387 (while (setq line (pop lines))
13388 ;; Remove the quoted HTML tags.
13389 (setq line (org-html-expand-for-ascii line))
13390 ;; Remove targets
13391 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
13392 (setq line (replace-match "" t t line)))
13393 ;; Replace internal links
13394 (while (string-match org-bracket-link-regexp line)
13395 (setq line (replace-match
13396 (if (match-end 3) "[\\3]" "[\\1]")
13397 t nil line)))
13398 (cond
13399 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13400 ;; a Headline
13401 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13402 txt (match-string 2 line))
13403 (org-ascii-level-start level txt umax lines))
13405 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
13406 (normal-mode)
13407 (save-buffer)
13408 ;; remove display and invisible chars
13409 (let (beg end)
13410 (goto-char (point-min))
13411 (while (setq beg (next-single-property-change (point) 'display))
13412 (setq end (next-single-property-change beg 'display))
13413 (delete-region beg end)
13414 (goto-char beg)
13415 (insert "=>"))
13416 (goto-char (point-min))
13417 (while (setq beg (next-single-property-change (point) 'org-cwidth))
13418 (setq end (next-single-property-change beg 'org-cwidth))
13419 (delete-region beg end)
13420 (goto-char beg)))
13421 (goto-char (point-min))))
13423 (defun org-search-todo-below (line lines level)
13424 "Search the subtree below LINE for any TODO entries."
13425 (let ((rest (cdr (memq line lines)))
13426 (re org-todo-line-regexp)
13427 line lv todo)
13428 (catch 'exit
13429 (while (setq line (pop rest))
13430 (if (string-match re line)
13431 (progn
13432 (setq lv (- (match-end 1) (match-beginning 1))
13433 todo (and (match-beginning 2)
13434 (not (equal (match-string 2 line)
13435 org-done-string))))
13436 ; TODO, not DONE
13437 (if (<= lv level) (throw 'exit nil))
13438 (if todo (throw 'exit t))))))))
13440 (defun org-html-expand-for-ascii (line)
13441 "Handle quoted HTML for ASCII export."
13442 (if org-export-html-expand
13443 (while (string-match "@<[^<>\n]*>" line)
13444 ;; We just remove the tags for now.
13445 (setq line (replace-match "" nil nil line))))
13446 line)
13448 (defun org-insert-centered (s &optional underline)
13449 "Insert the string S centered and underline it with character UNDERLINE."
13450 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
13451 (insert (make-string ind ?\ ) s "\n")
13452 (if underline
13453 (insert (make-string ind ?\ )
13454 (make-string (string-width s) underline)
13455 "\n"))))
13457 (defun org-ascii-level-start (level title umax &optional lines)
13458 "Insert a new level in ASCII export."
13459 (let (char (n (- level umax 1)) (ind 0))
13460 (if (> level umax)
13461 (progn
13462 (insert (make-string (* 2 n) ?\ )
13463 (char-to-string (nth (% n (length org-export-ascii-bullets))
13464 org-export-ascii-bullets))
13465 " " title "\n")
13466 ;; find the indentation of the next non-empty line
13467 (catch 'stop
13468 (while lines
13469 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
13470 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
13471 (throw 'stop (setq ind (org-get-indentation (car lines)))))
13472 (pop lines)))
13473 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
13474 (if (or (not (equal (char-before) ?\n))
13475 (not (equal (char-before (1- (point))) ?\n)))
13476 (insert "\n"))
13477 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
13478 (if org-export-with-section-numbers
13479 (setq title (concat (org-section-number level) " " title)))
13480 (insert title "\n" (make-string (string-width title) char) "\n")
13481 (setq org-ascii-current-indentation '(0 . 0)))))
13483 (defun org-export-visible (type arg)
13484 "Create a copy of the visible part of the current buffer, and export it.
13485 The copy is created in a temporary buffer and removed after use.
13486 TYPE is the final key (as a string) that also select the export command in
13487 the `C-c C-e' export dispatcher.
13488 As a special case, if the you type SPC at the prompt, the temporary
13489 org-mode file will not be removed but presented to you so that you can
13490 continue to use it. The prefix arg ARG is passed through to the exporting
13491 command."
13492 (interactive
13493 (list (progn
13494 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
13495 (read-char-exclusive))
13496 current-prefix-arg))
13497 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
13498 (error "Invalid export key"))
13499 (let* ((binding (cdr (assoc type
13500 '((?a . org-export-as-ascii)
13501 (?\C-a . org-export-as-ascii)
13502 (?b . org-export-as-html-and-open)
13503 (?\C-b . org-export-as-html-and-open)
13504 (?h . org-export-as-html)
13505 (?x . org-export-as-xoxo)))))
13506 (keepp (equal type ?\ ))
13507 (file buffer-file-name)
13508 (buffer (get-buffer-create "*Org Export Visible*"))
13509 s e)
13510 (with-current-buffer buffer (erase-buffer))
13511 (save-excursion
13512 (setq s (goto-char (point-min)))
13513 (while (not (= (point) (point-max)))
13514 (goto-char (org-find-invisible))
13515 (append-to-buffer buffer s (point))
13516 (setq s (goto-char (org-find-visible))))
13517 (goto-char (point-min))
13518 (unless keepp
13519 ;; Copy all comment lines to the end, to make sure #+ settings are
13520 ;; still available for the second export step. Kind of a hack, but
13521 ;; does do the trick.
13522 (if (looking-at "#[^\r\n]*")
13523 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
13524 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
13525 (append-to-buffer buffer (1+ (match-beginning 0))
13526 (min (point-max) (1+ (match-end 0))))))
13527 (set-buffer buffer)
13528 (let ((buffer-file-name file)
13529 (org-inhibit-startup t))
13530 (org-mode)
13531 (show-all)
13532 (unless keepp (funcall binding arg))))
13533 (if (not keepp)
13534 (kill-buffer buffer)
13535 (switch-to-buffer-other-window buffer)
13536 (goto-char (point-min)))))
13538 (defun org-find-visible ()
13539 (if (featurep 'noutline)
13540 (let ((s (point)))
13541 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13542 (get-char-property s 'invisible)))
13544 (skip-chars-forward "^\n")
13545 (point)))
13546 (defun org-find-invisible ()
13547 (if (featurep 'noutline)
13548 (let ((s (point)))
13549 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13550 (not (get-char-property s 'invisible))))
13552 (skip-chars-forward "^\r")
13553 (point)))
13556 ;; HTML
13558 (defun org-get-current-options ()
13559 "Return a string with current options as keyword options.
13560 Does include HTML export options as well as TODO and CATEGORY stuff."
13561 (format
13562 "#+TITLE: %s
13563 #+AUTHOR: %s
13564 #+EMAIL: %s
13565 #+LANGUAGE: %s
13566 #+TEXT: Some descriptive text to be emitted. Several lines OK.
13567 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
13568 #+CATEGORY: %s
13569 #+SEQ_TODO: %s
13570 #+TYP_TODO: %s
13571 #+STARTUP: %s %s %s %s %s %s
13572 #+TAGS: %s
13573 #+ARCHIVE: %s
13575 (buffer-name) (user-full-name) user-mail-address org-export-default-language
13576 org-export-headline-levels
13577 org-export-with-section-numbers
13578 org-export-with-toc
13579 org-export-preserve-breaks
13580 org-export-html-expand
13581 org-export-with-fixed-width
13582 org-export-with-tables
13583 org-export-with-sub-superscripts
13584 org-export-with-emphasize
13585 org-export-with-TeX-macros
13586 org-export-with-LaTeX-fragments
13587 (file-name-nondirectory buffer-file-name)
13588 (if (equal org-todo-interpretation 'sequence)
13589 (mapconcat 'identity org-todo-keywords " ")
13590 "TODO FEEDBACK VERIFY DONE")
13591 (if (equal org-todo-interpretation 'type)
13592 (mapconcat 'identity org-todo-keywords " ")
13593 "Me Jason Marie DONE")
13594 (cdr (assoc org-startup-folded
13595 '((nil . "showall") (t . "overview") (content . "content"))))
13596 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
13597 (if org-odd-levels-only "odd" "oddeven")
13598 (if org-hide-leading-stars "hidestars" "showstars")
13599 (if org-startup-align-all-tables "align" "noalign")
13600 (if org-log-done "logging" "nologging")
13601 (if org-tag-alist (mapconcat 'car org-tag-alist " ") "")
13602 org-archive-location
13605 (defun org-insert-export-options-template ()
13606 "Insert into the buffer a template with information for exporting."
13607 (interactive)
13608 (if (not (bolp)) (newline))
13609 (let ((s (org-get-current-options)))
13610 (and (string-match "#\\+CATEGORY" s)
13611 (setq s (substring s 0 (match-beginning 0))))
13612 (insert s)))
13614 (defun org-toggle-fixed-width-section (arg)
13615 "Toggle the fixed-width export.
13616 If there is no active region, the QUOTE keyword at the current headline is
13617 inserted or removed. When present, it causes the text between this headline
13618 and the next to be exported as fixed-width text, and unmodified.
13619 If there is an active region, this command adds or removes a colon as the
13620 first character of this line. If the first character of a line is a colon,
13621 this line is also exported in fixed-width font."
13622 (interactive "P")
13623 (let* ((cc 0)
13624 (regionp (org-region-active-p))
13625 (beg (if regionp (region-beginning) (point)))
13626 (end (if regionp (region-end)))
13627 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13628 (re "[ \t]*\\(:\\)")
13629 off)
13630 (if regionp
13631 (save-excursion
13632 (goto-char beg)
13633 (setq cc (current-column))
13634 (beginning-of-line 1)
13635 (setq off (looking-at re))
13636 (while (> nlines 0)
13637 (setq nlines (1- nlines))
13638 (beginning-of-line 1)
13639 (cond
13640 (arg
13641 (move-to-column cc t)
13642 (insert ":\n")
13643 (forward-line -1))
13644 ((and off (looking-at re))
13645 (replace-match "" t t nil 1))
13646 ((not off) (move-to-column cc t) (insert ":")))
13647 (forward-line 1)))
13648 (save-excursion
13649 (org-back-to-heading)
13650 (if (looking-at (concat outline-regexp
13651 "\\( +\\<" org-quote-string "\\>\\)"))
13652 (replace-match "" t t nil 1)
13653 (if (looking-at outline-regexp)
13654 (progn
13655 (goto-char (match-end 0))
13656 (insert " " org-quote-string))))))))
13658 (defun org-export-as-html-and-open (arg)
13659 "Export the outline as HTML and immediately open it with a browser.
13660 If there is an active region, export only the region.
13661 The prefix ARG specifies how many levels of the outline should become
13662 headlines. The default is 3. Lower levels will become bulleted lists."
13663 (interactive "P")
13664 (org-export-as-html arg 'hidden)
13665 (org-open-file buffer-file-name))
13667 (defun org-export-as-html-batch ()
13668 "Call `org-export-as-html', may be used in batch processing as
13669 emacs --batch
13670 --load=$HOME/lib/emacs/org.el
13671 --eval \"(setq org-export-headline-levels 2)\"
13672 --visit=MyFile --funcall org-export-as-html-batch"
13673 (org-export-as-html org-export-headline-levels 'hidden))
13675 (defun org-export-as-html (arg &optional hidden ext-plist)
13676 "Export the outline as a pretty HTML file.
13677 If there is an active region, export only the region.
13678 The prefix ARG specifies how many levels of the outline should become
13679 headlines. The default is 3. Lower levels will become bulleted lists.
13680 When HIDDEN is non-nil, don't display the HTML buffer.
13681 EXT-PLIST is a property list with external parameters overriding
13682 org-mode's default settings, but still inferior to file-local settings."
13683 (interactive "P")
13684 (message "Exporting...")
13685 (setq-default org-todo-line-regexp org-todo-line-regexp)
13686 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
13687 (setq-default org-done-string org-done-string)
13688 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13689 ext-plist
13690 (org-infile-export-plist)))
13692 (style (plist-get opt-plist :style))
13693 (link-validate (plist-get opt-plist :link-validation-function))
13694 valid
13695 (odd org-odd-levels-only)
13696 (region-p (org-region-active-p))
13697 (region
13698 (buffer-substring
13699 (if region-p (region-beginning) (point-min))
13700 (if region-p (region-end) (point-max))))
13701 ;; The following two are dynamically scoped into other
13702 ;; routines below.
13703 (org-current-export-dir (org-export-directory :html opt-plist))
13704 (org-current-export-file buffer-file-name)
13705 (all_lines
13706 (org-skip-comments (org-split-string
13707 (org-cleaned-string-for-export
13708 region :emph-multiline
13709 (if (plist-get opt-plist :LaTeX-fragments)
13710 :LaTeX-fragments))
13711 "[\r\n]")))
13712 (lines (org-export-find-first-heading-line all_lines))
13713 (level 0) (line "") (origline "") txt todo
13714 (umax nil)
13715 (filename (concat (file-name-as-directory
13716 (org-export-directory :html opt-plist))
13717 (file-name-sans-extension
13718 (file-name-nondirectory buffer-file-name))
13719 ".html"))
13720 (current-dir (file-name-directory buffer-file-name))
13721 (buffer (find-file-noselect filename))
13722 (levels-open (make-vector org-level-max nil))
13723 (date (format-time-string "%Y/%m/%d" (current-time)))
13724 (time (format-time-string "%X" (org-current-time)))
13725 (author (plist-get opt-plist :author))
13726 (title (or (plist-get opt-plist :title)
13727 (file-name-sans-extension
13728 (file-name-nondirectory buffer-file-name))))
13729 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
13730 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
13731 (inquote nil)
13732 (infixed nil)
13733 (in-local-list nil)
13734 (local-list-num nil)
13735 (local-list-indent nil)
13736 (llt org-plain-list-ordered-item-terminator)
13737 (email (plist-get opt-plist :email))
13738 (language (plist-get opt-plist :language))
13739 (text (plist-get opt-plist :text))
13740 (lang-words nil)
13741 (target-alist nil) tg
13742 (head-count 0) cnt
13743 (start 0)
13744 (coding-system (and (fboundp 'coding-system-get)
13745 (boundp 'buffer-file-coding-system)
13746 buffer-file-coding-system))
13747 (coding-system-for-write (or coding-system coding-system-for-write))
13748 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
13749 (charset (and coding-system
13750 (coding-system-get coding-system 'mime-charset)))
13751 table-open type
13752 table-buffer table-orig-buffer
13753 ind start-is-num starter
13754 rpl path desc descp desc1 desc2 link
13756 (message "Exporting...")
13758 (setq org-last-level 1)
13759 (org-init-section-numbers)
13761 ;; Get the language-dependent settings
13762 (setq lang-words (or (assoc language org-export-language-setup)
13763 (assoc "en" org-export-language-setup)))
13765 ;; Switch to the output buffer
13766 (if (or hidden (not org-export-html-show-new-buffer))
13767 (set-buffer buffer)
13768 (switch-to-buffer-other-window buffer))
13769 (erase-buffer)
13770 (fundamental-mode)
13771 (let ((case-fold-search nil)
13772 (org-odd-levels-only odd))
13773 ;; create local variables for all options, to make sure all called
13774 ;; functions get the correct information
13775 (mapcar (lambda (x)
13776 (set (make-local-variable (cdr x))
13777 (plist-get opt-plist (car x))))
13778 org-export-plist-vars)
13779 (setq umax (if arg (prefix-numeric-value arg)
13780 org-export-headline-levels))
13782 ;; File header
13783 (insert (format
13784 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
13785 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
13786 <html xmlns=\"http://www.w3.org/1999/xhtml\"
13787 lang=\"%s\" xml:lang=\"%s\">
13788 <head>
13789 <title>%s</title>
13790 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
13791 <meta name=\"generator\" content=\"Org-mode\"/>
13792 <meta name=\"generated\" content=\"%s %s\"/>
13793 <meta name=\"author\" content=\"%s\"/>
13795 </head><body>
13797 language language (org-html-expand title) (or charset "iso-8859-1")
13798 date time author style))
13801 (insert (or (plist-get opt-plist :preamble) ""))
13803 (when (plist-get opt-plist :auto-preamble)
13804 (if title (insert (concat "<h1 class=\"title\">"
13805 (org-html-expand title) "</h1>\n")))
13807 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
13809 (if org-export-with-toc
13810 (progn
13811 (insert (format "<h2>%s</h2>\n" (nth 3 lang-words)))
13812 (insert "<ul>\n<li>")
13813 (setq lines
13814 (mapcar '(lambda (line)
13815 (if (string-match org-todo-line-regexp line)
13816 ;; This is a headline
13817 (progn
13818 (setq level (- (match-end 1) (match-beginning 1))
13819 level (org-tr-level level)
13820 txt (save-match-data
13821 (org-html-expand
13822 (org-html-cleanup-toc-line
13823 (match-string 3 line))))
13824 todo
13825 (or (and org-export-mark-todo-in-toc
13826 (match-beginning 2)
13827 (not (equal (match-string 2 line)
13828 org-done-string)))
13829 ; TODO, not DONE
13830 (and org-export-mark-todo-in-toc
13831 (= level umax)
13832 (org-search-todo-below
13833 line lines level))))
13834 (if org-export-with-section-numbers
13835 (setq txt (concat (org-section-number level)
13836 " " txt)))
13837 (if (<= level umax)
13838 (progn
13839 (setq head-count (+ head-count 1))
13840 (if (> level org-last-level)
13841 (progn
13842 (setq cnt (- level org-last-level))
13843 (while (>= (setq cnt (1- cnt)) 0)
13844 (insert "\n<ul>\n<li>"))
13845 (insert "\n")))
13846 (if (< level org-last-level)
13847 (progn
13848 (setq cnt (- org-last-level level))
13849 (while (>= (setq cnt (1- cnt)) 0)
13850 (insert "</li>\n</ul>"))
13851 (insert "\n")))
13852 ;; Check for targets
13853 (while (string-match org-target-regexp line)
13854 (setq tg (match-string 1 line)
13855 line (replace-match
13856 (concat "@<span class=\"target\">" tg "@</span> ")
13857 t t line))
13858 (push (cons (org-solidify-link-text tg)
13859 (format "sec-%d" head-count))
13860 target-alist))
13861 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
13862 (setq txt (replace-match "" t t txt)))
13863 (insert
13864 (format
13865 (if todo
13866 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
13867 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
13868 head-count txt))
13870 (setq org-last-level level))
13872 line)
13873 lines))
13874 (while (> org-last-level 0)
13875 (setq org-last-level (1- org-last-level))
13876 (insert "</li>\n</ul>\n"))
13878 (setq head-count 0)
13879 (org-init-section-numbers)
13881 (while (setq line (pop lines) origline line)
13882 (catch 'nextline
13884 ;; end of quote section?
13885 (when (and inquote (string-match "^\\*+" line))
13886 (insert "</pre>\n")
13887 (setq inquote nil))
13888 ;; inside a quote section?
13889 (when inquote
13890 (insert (org-html-protect line) "\n")
13891 (throw 'nextline nil))
13893 ;; verbatim lines
13894 (when (and org-export-with-fixed-width
13895 (string-match "^[ \t]*:\\(.*\\)" line))
13896 (when (not infixed)
13897 (setq infixed t)
13898 (insert "<pre>\n"))
13899 (insert (org-html-protect (match-string 1 line)) "\n")
13900 (when (and lines
13901 (not (string-match "^[ \t]*\\(:.*\\)"
13902 (car lines))))
13903 (setq infixed nil)
13904 (insert "</pre>\n"))
13905 (throw 'nextline nil))
13908 ;; make targets to anchors
13909 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
13910 (cond
13911 ((match-end 2)
13912 (setq line (replace-match
13913 (concat "@<a name=\""
13914 (org-solidify-link-text (match-string 1 line))
13915 "\">\\nbsp@</a>")
13916 t t line)))
13917 ((and org-export-with-toc (equal (string-to-char line) ?*))
13918 (setq line (replace-match
13919 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
13920 ; (concat "@<i>" (match-string 1 line) "@</i> ")
13921 t t line)))
13923 (setq line (replace-match
13924 (concat "@<a name=\""
13925 (org-solidify-link-text (match-string 1 line))
13926 "\" class=\"target\">" (match-string 1 line) "@</a> ")
13927 t t line)))))
13929 (setq line (org-html-handle-time-stamps line))
13931 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
13932 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
13933 ;; Also handle sub_superscripts and checkboxes
13934 (setq line (org-html-expand line))
13936 ;; Format the links
13937 (setq start 0)
13938 (while (string-match org-bracket-link-analytic-regexp line start)
13939 (setq start (match-beginning 0))
13940 (setq type (if (match-end 2) (match-string 2 line) "internal"))
13941 (setq path (match-string 3 line))
13942 (setq desc1 (if (match-end 5) (match-string 5 line))
13943 desc2 (if (match-end 2) (concat type ":" path) path)
13944 descp (and desc1 (not (equal desc1 desc2)))
13945 desc (or desc1 desc2))
13946 ;; FIXME: do we need to unescape here somewhere?
13947 (cond
13948 ((equal type "internal")
13949 (setq rpl
13950 (concat
13951 "<a href=\"#"
13952 (org-solidify-link-text path target-alist)
13953 "\">" desc "</a>")))
13954 ((member type '("http" "https" "ftp" "mailto" "news"))
13955 ;; standard URL
13956 (setq link (concat type ":" path))
13957 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
13958 ((string= type "file")
13959 ;; FILE link
13960 (let* ((filename path)
13961 (abs-p (file-name-absolute-p filename))
13962 thefile file-is-image-p search)
13963 (save-match-data
13964 (if (string-match "::\\(.*\\)" filename)
13965 (setq search (match-string 1 filename)
13966 filename (replace-match "" t nil filename)))
13967 (setq valid
13968 (if (functionp link-validate)
13969 (funcall link-validate filename current-dir)
13970 t))
13971 (setq file-is-image-p
13972 (string-match (org-image-file-name-regexp) filename))
13973 (setq thefile (if abs-p (expand-file-name filename) filename))
13974 (when (and org-export-html-link-org-files-as-html
13975 (string-match "\\.org$" thefile))
13976 (setq thefile (concat (substring thefile 0
13977 (match-beginning 0))
13978 ".html"))
13979 (if (and search
13980 ;; make sure this is can be used as target search
13981 (not (string-match "^[0-9]*$" search))
13982 (not (string-match "^\\*" search))
13983 (not (string-match "^/.*/$" search)))
13984 (setq thefile (concat thefile "#"
13985 (org-solidify-link-text
13986 (org-link-unescape search)))))
13987 (when (string-match "^file:" desc)
13988 (setq desc (replace-match "" t t desc))
13989 (if (string-match "\\.org$" desc)
13990 (setq desc (replace-match "" t t desc))))))
13991 (setq rpl (if (and file-is-image-p
13992 (or (eq t org-export-html-inline-images)
13993 (and org-export-html-inline-images
13994 (not descp))))
13995 (concat "<img src=\"" thefile "\"/>")
13996 (concat "<a href=\"" thefile "\">" desc "</a>")))
13997 (if (not valid) (setq rpl desc))))
13998 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
13999 (setq rpl (concat "<i>&lt;" type ":"
14000 (save-match-data (org-link-unescape path))
14001 "&gt;</i>"))))
14002 (setq line (replace-match rpl t t line)
14003 start (+ start (length rpl))))
14004 ;; TODO items
14005 (if (and (string-match org-todo-line-regexp line)
14006 (match-beginning 2))
14007 (if (equal (match-string 2 line) org-done-string)
14008 (setq line (replace-match
14009 "<span class=\"done\">\\2</span>"
14010 t nil line 2))
14011 (setq line (replace-match "<span class=\"todo\">\\2</span>"
14012 t nil line 2))))
14014 (cond
14015 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14016 ;; This is a headline
14017 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14018 txt (match-string 2 line))
14019 (if (string-match quote-re0 txt)
14020 (setq txt (replace-match "" t t txt)))
14021 (if (<= level umax) (setq head-count (+ head-count 1)))
14022 (when in-local-list
14023 ;; Close any local lists before inserting a new header line
14024 (while local-list-num
14025 (org-close-li)
14026 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14027 (pop local-list-num))
14028 (setq local-list-indent nil
14029 in-local-list nil))
14030 (org-html-level-start level txt umax
14031 (and org-export-with-toc (<= level umax))
14032 head-count)
14033 ;; QUOTES
14034 (when (string-match quote-re line)
14035 (insert "<pre>")
14036 (setq inquote t)))
14038 ((and org-export-with-tables
14039 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
14040 (if (not table-open)
14041 ;; New table starts
14042 (setq table-open t table-buffer nil table-orig-buffer nil))
14043 ;; Accumulate lines
14044 (setq table-buffer (cons line table-buffer)
14045 table-orig-buffer (cons origline table-orig-buffer))
14046 (when (or (not lines)
14047 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
14048 (car lines))))
14049 (setq table-open nil
14050 table-buffer (nreverse table-buffer)
14051 table-orig-buffer (nreverse table-orig-buffer))
14052 (org-close-par-maybe)
14053 (insert (org-format-table-html table-buffer table-orig-buffer))))
14055 ;; Normal lines
14056 (when (string-match
14057 (cond
14058 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14059 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14060 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14061 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
14062 line)
14063 (setq ind (org-get-string-indentation line)
14064 start-is-num (match-beginning 4)
14065 starter (if (match-beginning 2)
14066 (substring (match-string 2 line) 0 -1))
14067 line (substring line (match-beginning 5)))
14068 (unless (string-match "[^ \t]" line)
14069 ;; empty line. Pretend indentation is large.
14070 (setq ind (1+ (or (car local-list-indent) 1))))
14071 (while (and in-local-list
14072 (or (and (= ind (car local-list-indent))
14073 (not starter))
14074 (< ind (car local-list-indent))))
14075 (org-close-li)
14076 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14077 (pop local-list-num) (pop local-list-indent)
14078 (setq in-local-list local-list-indent))
14079 (cond
14080 ((and starter
14081 (or (not in-local-list)
14082 (> ind (car local-list-indent))))
14083 ;; Start new (level of ) list
14084 (org-close-par-maybe)
14085 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
14086 (push start-is-num local-list-num)
14087 (push ind local-list-indent)
14088 (setq in-local-list t))
14089 (starter
14090 ;; continue current list
14091 (org-close-li)
14092 (insert "<li>\n")))
14093 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
14094 (setq line
14095 (replace-match
14096 (if (equal (match-string 1 line) "X")
14097 "<b>[X]</b>"
14098 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
14099 t t line))))
14101 ;; Empty lines start a new paragraph. If hand-formatted lists
14102 ;; are not fully interpreted, lines starting with "-", "+", "*"
14103 ;; also start a new paragraph.
14104 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
14106 ;; Check if the line break needs to be conserved
14107 (cond
14108 ((string-match "\\\\\\\\[ \t]*$" line)
14109 (setq line (replace-match "<br/>" t t line)))
14110 (org-export-preserve-breaks
14111 (setq line (concat line "<br/>"))))
14113 (insert line "\n")))))
14115 ;; Properly close all local lists and other lists
14116 (when inquote (insert "</pre>\n"))
14117 (when in-local-list
14118 ;; Close any local lists before inserting a new header line
14119 (while local-list-num
14120 (org-close-li)
14121 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
14122 (pop local-list-num))
14123 (setq local-list-indent nil
14124 in-local-list nil))
14125 (org-html-level-start 1 nil umax
14126 (and org-export-with-toc (<= level umax))
14127 head-count)
14129 (when (plist-get opt-plist :auto-postamble)
14130 (when author
14131 (insert "<p class=\"author\"> "
14132 (nth 1 lang-words) ": " author "\n")
14133 (when email
14134 (insert "<a href=\"mailto:" email "\">&lt;"
14135 email "&gt;</a>\n"))
14136 (insert "</p>\n"))
14137 (when (and date time)
14138 (insert "<p class=\"date\"> "
14139 (nth 2 lang-words) ": "
14140 date " " time "</p>\n")))
14142 (if org-export-html-with-timestamp
14143 (insert org-export-html-html-helper-timestamp))
14144 (insert (or (plist-get opt-plist :postamble) ""))
14145 (insert "</body>\n</html>\n")
14146 (normal-mode)
14147 ;; remove empty paragraphs and lists
14148 (goto-char (point-min))
14149 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
14150 (replace-match ""))
14151 (goto-char (point-min))
14152 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
14153 (replace-match ""))
14154 (save-buffer)
14155 (goto-char (point-min))
14156 (message "Exporting... done"))))
14159 (defun org-format-table-html (lines olines)
14160 "Find out which HTML converter to use and return the HTML code."
14161 (if (string-match "^[ \t]*|" (car lines))
14162 ;; A normal org table
14163 (org-format-org-table-html lines)
14164 ;; Table made by table.el - test for spanning
14165 (let* ((hlines (delq nil (mapcar
14166 (lambda (x)
14167 (if (string-match "^[ \t]*\\+-" x) x
14168 nil))
14169 lines)))
14170 (first (car hlines))
14171 (ll (and (string-match "\\S-+" first)
14172 (match-string 0 first)))
14173 (re (concat "^[ \t]*" (regexp-quote ll)))
14174 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
14175 hlines))))
14176 (if (and (not spanning)
14177 (not org-export-prefer-native-exporter-for-tables))
14178 ;; We can use my own converter with HTML conversions
14179 (org-format-table-table-html lines)
14180 ;; Need to use the code generator in table.el, with the original text.
14181 (org-format-table-table-html-using-table-generate-source olines)))))
14183 (defun org-format-org-table-html (lines)
14184 "Format a table into HTML."
14185 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14186 (setq lines (nreverse lines))
14187 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14188 (setq lines (nreverse lines))
14189 (when org-export-table-remove-special-lines
14190 ;; Check if the table has a marking column. If yes remove the
14191 ;; column and the special lines
14192 (let* ((special
14193 (not
14194 (memq nil
14195 (mapcar
14196 (lambda (x)
14197 (or (string-match "^[ \t]*|-" x)
14198 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
14199 lines)))))
14200 (if special
14201 (setq lines
14202 (delq nil
14203 (mapcar
14204 (lambda (x)
14205 (if (string-match "^[ \t]*| *[!_^] *|" x)
14206 nil ; ignore this line
14207 (and (or (string-match "^[ \t]*|-+\\+" x)
14208 (string-match "^[ \t]*|[^|]*|" x))
14209 (replace-match "|" t t x))))
14210 lines))))))
14212 (let ((head (and org-export-highlight-first-table-line
14213 (delq nil (mapcar
14214 (lambda (x) (string-match "^[ \t]*|-" x))
14215 (cdr lines)))))
14216 line fields html)
14217 (setq html (concat org-export-html-table-tag "\n"))
14218 (while (setq line (pop lines))
14219 (catch 'next-line
14220 (if (string-match "^[ \t]*|-" line)
14221 (progn
14222 (setq head nil) ;; head ends here, first time around
14223 ;; ignore this line
14224 (throw 'next-line t)))
14225 ;; Break the line into fields
14226 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14227 (setq html (concat
14228 html
14229 "<tr>"
14230 (mapconcat (lambda (x)
14231 (if head
14232 (concat "<th>" x "</th>")
14233 (concat "<td>" x "</td>")))
14234 fields "")
14235 "</tr>\n"))))
14236 (setq html (concat html "</table>\n"))
14237 html))
14239 (defun org-fake-empty-table-line (line)
14240 "Replace everything except \"|\" with spaces."
14241 (let ((i (length line))
14242 (newstr (copy-sequence line)))
14243 (while (> i 0)
14244 (setq i (1- i))
14245 (if (not (eq (aref newstr i) ?|))
14246 (aset newstr i ?\ )))
14247 newstr))
14249 (defun org-format-table-table-html (lines)
14250 "Format a table generated by table.el into HTML.
14251 This conversion does *not* use `table-generate-source' from table.el.
14252 This has the advantage that Org-mode's HTML conversions can be used.
14253 But it has the disadvantage, that no cell- or row-spanning is allowed."
14254 (let (line field-buffer
14255 (head org-export-highlight-first-table-line)
14256 fields html empty)
14257 (setq html (concat org-export-html-table-tag "\n"))
14258 (while (setq line (pop lines))
14259 (setq empty "&nbsp;")
14260 (catch 'next-line
14261 (if (string-match "^[ \t]*\\+-" line)
14262 (progn
14263 (if field-buffer
14264 (progn
14265 (setq html (concat
14266 html
14267 "<tr>"
14268 (mapconcat
14269 (lambda (x)
14270 (if (equal x "") (setq x empty))
14271 (if head
14272 (concat "<th>" x "</th>\n")
14273 (concat "<td>" x "</td>\n")))
14274 field-buffer "\n")
14275 "</tr>\n"))
14276 (setq head nil)
14277 (setq field-buffer nil)))
14278 ;; Ignore this line
14279 (throw 'next-line t)))
14280 ;; Break the line into fields and store the fields
14281 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14282 (if field-buffer
14283 (setq field-buffer (mapcar
14284 (lambda (x)
14285 (concat x "<br/>" (pop fields)))
14286 field-buffer))
14287 (setq field-buffer fields))))
14288 (setq html (concat html "</table>\n"))
14289 html))
14291 (defun org-format-table-table-html-using-table-generate-source (lines)
14292 "Format a table into html, using `table-generate-source' from table.el.
14293 This has the advantage that cell- or row-spanning is allowed.
14294 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
14295 (require 'table)
14296 (with-current-buffer (get-buffer-create " org-tmp1 ")
14297 (erase-buffer)
14298 (insert (mapconcat 'identity lines "\n"))
14299 (goto-char (point-min))
14300 (if (not (re-search-forward "|[^+]" nil t))
14301 (error "Error processing table"))
14302 (table-recognize-table)
14303 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
14304 (table-generate-source 'html " org-tmp2 ")
14305 (set-buffer " org-tmp2 ")
14306 (buffer-substring (point-min) (point-max))))
14308 (defun org-html-handle-time-stamps (s)
14309 "Format time stamps in string S, or remove them."
14310 (catch 'exit
14311 (let (r b)
14312 (while (string-match org-maybe-keyword-time-regexp s)
14313 ;; FIXME: is it good to never export CLOCK, or do we need control?
14314 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
14315 (throw 'exit ""))
14316 (or b (setq b (substring s 0 (match-beginning 0))))
14317 (if (not org-export-with-timestamps)
14318 (setq r (concat r (substring s 0 (match-beginning 0)))
14319 s (substring s (match-end 0)))
14320 (setq r (concat
14321 r (substring s 0 (match-beginning 0))
14322 (if (match-end 1)
14323 (format "@<span class=\"timestamp-kwd\">%s @</span>"
14324 (match-string 1 s)))
14325 (format " @<span class=\"timestamp\">%s@</span>"
14326 (substring (match-string 3 s) 1 -1)))
14327 s (substring s (match-end 0)))))
14328 ;; Line break if line started and ended with time stamp stuff
14329 (if (not r)
14331 (setq r (concat r s))
14332 (unless (string-match "\\S-" (concat b s))
14333 (setq r (concat r "@<br/>")))
14334 r))))
14336 (defun org-html-protect (s)
14337 ;; convert & to &amp;, < to &lt; and > to &gt;
14338 (let ((start 0))
14339 (while (string-match "&" s start)
14340 (setq s (replace-match "&amp;" t t s)
14341 start (1+ (match-beginning 0))))
14342 (while (string-match "<" s)
14343 (setq s (replace-match "&lt;" t t s)))
14344 (while (string-match ">" s)
14345 (setq s (replace-match "&gt;" t t s))))
14348 (defun org-html-cleanup-toc-line (s)
14349 "Remove tags and time staps from lines going into the toc."
14350 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
14351 (setq s (replace-match "" t t s)))
14352 (while (string-match org-maybe-keyword-time-regexp s)
14353 (setq s (replace-match "" t t s)))
14356 (defun org-html-expand (string)
14357 "Prepare STRING for HTML export. Applies all active conversions.
14358 If there are links in the string, don't modify these."
14359 (let* (m s l res)
14360 (while (setq m (string-match org-bracket-link-regexp string))
14361 (setq s (substring string 0 m)
14362 l (match-string 0 string)
14363 string (substring string (match-end 0)))
14364 (push (org-html-do-expand s) res)
14365 (push l res))
14366 (push (org-html-do-expand string) res)
14367 (apply 'concat (nreverse res))))
14369 (defun org-html-do-expand (s)
14370 "Apply all active conversions to translate special ASCII to HTML."
14371 (setq s (org-html-protect s))
14372 (if org-export-html-expand
14373 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
14374 (setq s (replace-match "<\\1>" t nil s))))
14375 (if org-export-with-emphasize
14376 (setq s (org-export-html-convert-emphasize s)))
14377 (if org-export-with-sub-superscripts
14378 (setq s (org-export-html-convert-sub-super s)))
14379 (if org-export-with-TeX-macros
14380 (let ((start 0) wd ass)
14381 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
14382 (setq wd (match-string 1 s))
14383 (if (setq ass (assoc wd org-html-entities))
14384 (setq s (replace-match (or (cdr ass)
14385 (concat "&" (car ass) ";"))
14386 t t s))
14387 (setq start (+ start (length wd)))))))
14390 (defun org-create-multibrace-regexp (left right n)
14391 "Create a regular expression which will match a balanced sexp.
14392 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
14393 as single character strings.
14394 The regexp returned will match the entire expression including the
14395 delimiters. It will also define a single group which contains the
14396 match except for the outermost delimiters. The maximum depth of
14397 stacked delimiters is N. Escaping delimiters is not possible."
14398 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
14399 (or "\\|")
14400 (re nothing)
14401 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
14402 (while (> n 1)
14403 (setq n (1- n)
14404 re (concat re or next)
14405 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
14406 (concat left "\\(" re "\\)" right)))
14408 (defvar org-match-substring-regexp
14409 (concat
14410 "\\([^\\]\\)\\([_^]\\)\\("
14411 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
14412 "\\|"
14413 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
14414 "\\|"
14415 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
14416 "The regular expression matching a sub- or superscript.")
14418 (defun org-export-html-convert-sub-super (string)
14419 "Convert sub- and superscripts in STRING to HTML."
14420 (let (key c)
14421 (while (string-match org-match-substring-regexp string)
14422 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
14423 (setq c (or (match-string 8 string)
14424 (match-string 6 string)
14425 (match-string 5 string)))
14426 (setq string (replace-match
14427 (concat (match-string 1 string)
14428 "<" key ">" c "</" key ">")
14429 t t string)))
14430 (while (string-match "\\\\\\([_^]\\)" string)
14431 (setq string (replace-match (match-string 1 string) t t string))))
14432 string)
14434 (defun org-export-html-convert-emphasize (string)
14435 "Apply emphasis."
14436 (while (string-match org-emph-re string)
14437 (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)))
14438 string)
14440 (defvar org-par-open nil)
14441 (defun org-open-par ()
14442 "Insert <p>, but first close previous paragraph if any."
14443 (org-close-par-maybe)
14444 (insert "\n<p>")
14445 (setq org-par-open t))
14446 (defun org-close-par-maybe ()
14447 "Close paragraph if there is one open."
14448 (when org-par-open
14449 (insert "</p>")
14450 (setq org-par-open nil)))
14451 (defun org-close-li ()
14452 "Close <li> if necessary."
14453 (org-close-par-maybe)
14454 (insert "</li>\n"))
14455 ; (when (save-excursion
14456 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
14457 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
14458 ; (insert "</li>"))))
14460 (defun org-html-level-start (level title umax with-toc head-count)
14461 "Insert a new level in HTML export.
14462 When TITLE is nil, just close all open levels."
14463 (org-close-par-maybe)
14464 (let ((l (1+ (max level umax))))
14465 (while (<= l org-level-max)
14466 (if (aref levels-open (1- l))
14467 (progn
14468 (org-html-level-close l)
14469 (aset levels-open (1- l) nil)))
14470 (setq l (1+ l)))
14471 (when title
14472 ;; If title is nil, this means this function is called to close
14473 ;; all levels, so the rest is done only if title is given
14474 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14475 (setq title (replace-match
14476 (if org-export-with-tags
14477 (save-match-data
14478 (concat
14479 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
14480 (mapconcat 'identity (org-split-string
14481 (match-string 1 title) ":")
14482 "&nbsp;")
14483 "</span>"))
14485 t t title)))
14486 (if (> level umax)
14487 (progn
14488 (if (aref levels-open (1- level))
14489 (progn
14490 (org-close-li)
14491 (insert "<li>" title "<br/>\n"))
14492 (aset levels-open (1- level) t)
14493 (org-close-par-maybe)
14494 (insert "<ul>\n<li>" title "<br/>\n")))
14495 (if org-export-with-section-numbers
14496 (setq title (concat (org-section-number level) " " title)))
14497 (setq level (+ level 1))
14498 (if with-toc
14499 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
14500 level head-count title level))
14501 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
14502 (org-open-par)))))
14504 (defun org-html-level-close (&rest args)
14505 "Terminate one level in HTML export."
14506 (org-close-li)
14507 (insert "</ul>"))
14509 ;; Variable holding the vector with section numbers
14510 (defvar org-section-numbers (make-vector org-level-max 0))
14512 (defun org-init-section-numbers ()
14513 "Initialize the vector for the section numbers."
14514 (let* ((level -1)
14515 (numbers (nreverse (org-split-string "" "\\.")))
14516 (depth (1- (length org-section-numbers)))
14517 (i depth) number-string)
14518 (while (>= i 0)
14519 (if (> i level)
14520 (aset org-section-numbers i 0)
14521 (setq number-string (or (car numbers) "0"))
14522 (if (string-match "\\`[A-Z]\\'" number-string)
14523 (aset org-section-numbers i
14524 (- (string-to-char number-string) ?A -1))
14525 (aset org-section-numbers i (string-to-number number-string)))
14526 (pop numbers))
14527 (setq i (1- i)))))
14529 (defun org-section-number (&optional level)
14530 "Return a string with the current section number.
14531 When LEVEL is non-nil, increase section numbers on that level."
14532 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
14533 (when level
14534 (when (> level -1)
14535 (aset org-section-numbers
14536 level (1+ (aref org-section-numbers level))))
14537 (setq idx (1+ level))
14538 (while (<= idx depth)
14539 (if (not (= idx 1))
14540 (aset org-section-numbers idx 0))
14541 (setq idx (1+ idx))))
14542 (setq idx 0)
14543 (while (<= idx depth)
14544 (setq n (aref org-section-numbers idx))
14545 (setq string (concat string (if (not (string= string "")) "." "")
14546 (int-to-string n)))
14547 (setq idx (1+ idx)))
14548 (save-match-data
14549 (if (string-match "\\`\\([@0]\\.\\)+" string)
14550 (setq string (replace-match "" t nil string)))
14551 (if (string-match "\\(\\.0\\)+\\'" string)
14552 (setq string (replace-match "" t nil string))))
14553 string))
14556 ;;;###autoload
14557 (defun org-export-icalendar-this-file ()
14558 "Export current file as an iCalendar file.
14559 The iCalendar file will be located in the same directory as the Org-mode
14560 file, but with extension `.ics'."
14561 (interactive)
14562 (org-export-icalendar nil buffer-file-name))
14564 (defun org-export-as-xoxo-insert-into (buffer &rest output)
14565 (with-current-buffer buffer
14566 (apply 'insert output)))
14568 (defun org-export-as-xoxo (&optional buffer)
14569 "Export the org buffer as XOXO.
14570 The XOXO buffer is named *xoxo-<source buffer name>*"
14571 (interactive (list (current-buffer)))
14572 ;; A quickie abstraction
14574 ;; Output everything as XOXO
14575 (with-current-buffer (get-buffer buffer)
14576 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
14577 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14578 (org-infile-export-plist)))
14579 (filename (concat (file-name-as-directory
14580 (org-export-directory :xoxo opt-plist))
14581 (file-name-sans-extension
14582 (file-name-nondirectory buffer-file-name))
14583 ".html"))
14584 (out (find-file-noselect filename))
14585 (last-level 1)
14586 (hanging-li nil))
14587 ;; Check the output buffer is empty.
14588 (with-current-buffer out (erase-buffer))
14589 ;; Kick off the output
14590 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
14591 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
14592 (let* ((hd (match-string-no-properties 1))
14593 (level (length hd))
14594 (text (concat
14595 (match-string-no-properties 2)
14596 (save-excursion
14597 (goto-char (match-end 0))
14598 (let ((str ""))
14599 (catch 'loop
14600 (while 't
14601 (forward-line)
14602 (if (looking-at "^[ \t]\\(.*\\)")
14603 (setq str (concat str (match-string-no-properties 1)))
14604 (throw 'loop str)))))))))
14606 ;; Handle level rendering
14607 (cond
14608 ((> level last-level)
14609 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
14611 ((< level last-level)
14612 (dotimes (- (- last-level level) 1)
14613 (if hanging-li
14614 (org-export-as-xoxo-insert-into out "</li>\n"))
14615 (org-export-as-xoxo-insert-into out "</ol>\n"))
14616 (when hanging-li
14617 (org-export-as-xoxo-insert-into out "</li>\n")
14618 (setq hanging-li nil)))
14620 ((equal level last-level)
14621 (if hanging-li
14622 (org-export-as-xoxo-insert-into out "</li>\n")))
14625 (setq last-level level)
14627 ;; And output the new li
14628 (setq hanging-li 't)
14629 (if (equal ?+ (elt text 0))
14630 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
14631 (org-export-as-xoxo-insert-into out "<li>" text))))
14633 ;; Finally finish off the ol
14634 (dotimes (- last-level 1)
14635 (if hanging-li
14636 (org-export-as-xoxo-insert-into out "</li>\n"))
14637 (org-export-as-xoxo-insert-into out "</ol>\n"))
14639 ;; Finish the buffer off and clean it up.
14640 (switch-to-buffer-other-window out)
14641 (indent-region (point-min) (point-max) nil)
14642 (save-buffer)
14643 (goto-char (point-min))
14646 ;;;###autoload
14647 (defun org-export-icalendar-all-agenda-files ()
14648 "Export all files in `org-agenda-files' to iCalendar .ics files.
14649 Each iCalendar file will be located in the same directory as the Org-mode
14650 file, but with extension `.ics'."
14651 (interactive)
14652 (apply 'org-export-icalendar nil (org-agenda-files t)))
14654 ;;;###autoload
14655 (defun org-export-icalendar-combine-agenda-files ()
14656 "Export all files in `org-agenda-files' to a single combined iCalendar file.
14657 The file is stored under the name `org-combined-agenda-icalendar-file'."
14658 (interactive)
14659 (apply 'org-export-icalendar t (org-agenda-files t)))
14661 (defun org-export-icalendar (combine &rest files)
14662 "Create iCalendar files for all elements of FILES.
14663 If COMBINE is non-nil, combine all calendar entries into a single large
14664 file and store it under the name `org-combined-agenda-icalendar-file'."
14665 (save-excursion
14666 (let* ((dir (org-export-directory
14667 :ical (list :publishing-directory
14668 org-export-publishing-directory)))
14669 file ical-file ical-buffer category started org-agenda-new-buffers)
14671 (when combine
14672 (setq ical-file
14673 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
14674 org-combined-agenda-icalendar-file
14675 (expand-file-name org-combined-agenda-icalendar-file dir))
14676 ical-buffer (org-get-agenda-file-buffer ical-file))
14677 (set-buffer ical-buffer) (erase-buffer))
14678 (while (setq file (pop files))
14679 (catch 'nextfile
14680 (org-check-agenda-file file)
14681 (set-buffer (org-get-agenda-file-buffer file))
14682 (unless combine
14683 (setq ical-file (concat (file-name-as-directory dir)
14684 (file-name-sans-extension
14685 (file-name-nondirectory buffer-file-name))
14686 ".ics"))
14687 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
14688 (with-current-buffer ical-buffer (erase-buffer)))
14689 (setq category (or org-category
14690 (file-name-sans-extension
14691 (file-name-nondirectory buffer-file-name))))
14692 (if (symbolp category) (setq category (symbol-name category)))
14693 (let ((standard-output ical-buffer))
14694 (if combine
14695 (and (not started) (setq started t)
14696 (org-start-icalendar-file org-icalendar-combined-name))
14697 (org-start-icalendar-file category))
14698 (org-print-icalendar-entries combine category)
14699 (when (or (and combine (not files)) (not combine))
14700 (org-finish-icalendar-file)
14701 (set-buffer ical-buffer)
14702 (save-buffer)
14703 (run-hooks 'org-after-save-iCalendar-file-hook)))))
14704 (org-release-buffers org-agenda-new-buffers))))
14706 (defvar org-after-save-iCalendar-file-hook nil
14707 "Hook run after an iCalendar file has been saved.
14708 The iCalendar buffer is still current when this hook is run.
14709 A good way to use this is to tell a desktop calenndar application to re-read
14710 the iCalendar file.")
14712 (defun org-print-icalendar-entries (&optional combine category)
14713 "Print iCalendar entries for the current Org-mode file to `standard-output'.
14714 When COMBINE is non nil, add the category to each line."
14715 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
14716 (dts (org-ical-ts-to-string
14717 (format-time-string (cdr org-time-stamp-formats) (current-time))
14718 "DTSTART"))
14719 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
14720 (save-excursion
14721 (goto-char (point-min))
14722 (while (re-search-forward org-ts-regexp nil t)
14723 (setq pos (match-beginning 0)
14724 ts (match-string 0)
14725 inc t
14726 hd (org-get-heading))
14727 (if (looking-at re2)
14728 (progn
14729 (goto-char (match-end 0))
14730 (setq ts2 (match-string 1) inc nil))
14731 (setq ts2 ts
14732 tmp (buffer-substring (max (point-min)
14733 (- pos org-ds-keyword-length))
14734 pos)
14735 deadlinep (string-match org-deadline-regexp tmp)
14736 scheduledp (string-match org-scheduled-regexp tmp)
14737 ;; donep (org-entry-is-done-p)
14739 (if (or (string-match org-tr-regexp hd)
14740 (string-match org-ts-regexp hd))
14741 (setq hd (replace-match "" t t hd)))
14742 (if combine
14743 (setq hd (concat hd " (category " category ")")))
14744 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
14745 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
14746 (princ (format "BEGIN:VEVENT
14749 SUMMARY:%s
14750 END:VEVENT\n"
14751 (org-ical-ts-to-string ts "DTSTART")
14752 (org-ical-ts-to-string ts2 "DTEND" inc)
14753 hd)))
14754 (when org-icalendar-include-todo
14755 (goto-char (point-min))
14756 (while (re-search-forward org-todo-line-regexp nil t)
14757 (setq state (match-string 1))
14758 (unless (equal state org-done-string)
14759 (setq hd (match-string 3))
14760 (if (string-match org-priority-regexp hd)
14761 (setq pri (string-to-char (match-string 2 hd))
14762 hd (concat (substring hd 0 (match-beginning 1))
14763 (substring hd (- (match-end 1)))))
14764 (setq pri org-default-priority))
14765 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
14766 (- org-lowest-priority ?A))))))
14768 (princ (format "BEGIN:VTODO
14770 SUMMARY:%s
14771 SEQUENCE:1
14772 PRIORITY:%d
14773 END:VTODO\n"
14774 dts hd pri))))))))
14776 (defun org-start-icalendar-file (name)
14777 "Start an iCalendar file by inserting the header."
14778 (let ((user user-full-name)
14779 (name (or name "unknown"))
14780 (timezone (cadr (current-time-zone))))
14781 (princ
14782 (format "BEGIN:VCALENDAR
14783 VERSION:2.0
14784 X-WR-CALNAME:%s
14785 PRODID:-//%s//Emacs with Org-mode//EN
14786 X-WR-TIMEZONE:%s
14787 CALSCALE:GREGORIAN\n" name user timezone))))
14789 (defun org-finish-icalendar-file ()
14790 "Finish an iCalendar file by inserting the END statement."
14791 (princ "END:VCALENDAR\n"))
14793 (defun org-ical-ts-to-string (s keyword &optional inc)
14794 "Take a time string S and convert it to iCalendar format.
14795 KEYWORD is added in front, to make a complete line like DTSTART....
14796 When INC is non-nil, increase the hour by two (if time string contains
14797 a time), or the day by one (if it does not contain a time)."
14798 (let ((t1 (org-parse-time-string s 'nodefault))
14799 t2 fmt have-time time)
14800 (if (and (car t1) (nth 1 t1) (nth 2 t1))
14801 (setq t2 t1 have-time t)
14802 (setq t2 (org-parse-time-string s)))
14803 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
14804 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
14805 (when inc
14806 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
14807 (setq time (encode-time s mi h d m y)))
14808 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
14809 (concat keyword (format-time-string fmt time))))
14811 ;;; LaTeX stuff
14813 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14814 "Keymap for the minor `org-cdlatex-mode'.")
14816 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14817 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14818 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14819 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14820 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14822 (defvar org-cdlatex-texmathp-advice-is-done nil
14823 "Flag remembering if we have applied the advice to texmathp already.")
14825 (define-minor-mode org-cdlatex-mode
14826 "Toggle the minor `org-cdlatex-mode'.
14827 This mode supports entering LaTeX environment and math in LaTeX fragments
14828 in Org-mode.
14829 \\{org-cdlatex-mode-map}"
14830 nil " OCDL" nil
14831 (when org-cdlatex-mode (require 'cdlatex))
14832 (unless org-cdlatex-texmathp-advice-is-done
14833 (setq org-cdlatex-texmathp-advice-is-done t)
14834 (defadvice texmathp (around org-math-always-on activate)
14835 "Always return t in org-mode buffers.
14836 This is because we want to insert math symbols without dollars even outside
14837 the LaTeX math segments. If Orgmode thinks that point is actually inside
14838 en embedded LaTeX fragement, let texmathp do its job.
14839 \\[org-cdlatex-mode-map]"
14840 (interactive)
14841 (let (p)
14842 (cond
14843 ((not (eq major-mode 'org-mode)) ad-do-it)
14844 ((eq this-command 'cdlatex-math-symbol)
14845 (setq ad-return-value t
14846 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14848 (let ((p (org-inside-LaTeX-fragment-p)))
14849 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14850 (setq ad-return-value t
14851 texmathp-why '("Org-mode embedded math" . 0))
14852 (if p ad-do-it)))))))))
14854 (defun turn-on-org-cdlatex ()
14855 "Unconditionally turn on `org-cdlatex-mode'."
14856 (org-cdlatex-mode 1))
14858 (defun org-inside-LaTeX-fragment-p ()
14859 "Test if point is inside a LaTeX fragment.
14860 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14861 sequence appearing also before point.
14862 Even though the matchers for math are configurable, this function assumes
14863 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14864 delimiters are skipped when they have been removed by customization.
14865 The return value is nil, or a cons cell with the delimiter and
14866 and the position of this delimiter.
14868 This function does a reasonably good job, but can locally be fooled by
14869 for example currency specifications. For example it will assume being in
14870 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14871 fragments that are properly closed, but during editing, we have to live
14872 with the uncertainty caused by missing closing delimiters. This function
14873 looks only before point, not after."
14874 (catch 'exit
14875 (let ((pos (point))
14876 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14877 (lim (progn
14878 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14879 (point)))
14880 dd-on str (start 0) m re)
14881 (goto-char pos)
14882 (when dodollar
14883 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14884 re (nth 1 (assoc "$" org-latex-regexps)))
14885 (while (string-match re str start)
14886 (cond
14887 ((= (match-end 0) (length str))
14888 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
14889 ((= (match-end 0) (- (length str) 5))
14890 (throw 'exit nil))
14891 (t (setq start (match-end 0))))))
14892 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14893 (goto-char pos)
14894 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14895 (and (match-beginning 2) (throw 'exit nil))
14896 ;; count $$
14897 (while (re-search-backward "\\$\\$" lim t)
14898 (setq dd-on (not dd-on)))
14899 (goto-char pos)
14900 (if dd-on (cons "$$" m))))))
14903 (defun org-try-cdlatex-tab ()
14904 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14905 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14906 - inside a LaTeX fragment, or
14907 - after the first word in a line, where an abbreviation expansion could
14908 insert a LaTeX environment."
14909 ;; FIXME: This may still need refinement.
14910 (when org-cdlatex-mode
14911 (cond
14912 ((save-excursion
14913 (skip-chars-backward "a-zA-Z0-9*")
14914 (skip-chars-backward " \t")
14915 (bolp))
14916 (cdlatex-tab) t)
14917 ((org-inside-LaTeX-fragment-p)
14918 (cdlatex-tab) t)
14919 (t nil))))
14921 (defun org-cdlatex-underscore-caret (&optional arg)
14922 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14923 Revert to the normal definition outside of these fragments."
14924 (interactive "P")
14925 (if (org-inside-LaTeX-fragment-p)
14926 (call-interactively 'cdlatex-sub-superscript)
14927 (let (org-cdlatex-mode)
14928 (call-interactively (key-binding (vector last-input-event))))))
14930 (defun org-cdlatex-math-modify (&optional arg)
14931 "Execute `cdlatex-math-modify' in LaTeX fragments.
14932 Revert to the normal definition outside of these fragments."
14933 (interactive "P")
14934 (if (org-inside-LaTeX-fragment-p)
14935 (call-interactively 'cdlatex-math-modify)
14936 (let (org-cdlatex-mode)
14937 (call-interactively (key-binding (vector last-input-event))))))
14939 (defvar org-latex-fragment-image-overlays nil
14940 "List of overlays carrying the images of latex fragments.")
14941 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14943 (defun org-remove-latex-fragment-image-overlays ()
14944 "Remove all overlays with LaTeX fragment images in current buffer."
14945 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14946 (setq org-latex-fragment-image-overlays nil))
14948 (defun org-preview-latex-fragment (&optional subtree)
14949 "Preview the LaTeX fragment at point, or all locally or globally.
14950 If the cursor is in a LaTeX fragment, create the image and overlay
14951 it over the source code. If there is no fragment at point, display
14952 all fragments in the current text, from one headline to the next. With
14953 prefix SUBTREE, display all fragments in the current subtree. With a
14954 double prefix `C-u C-u', or when the cursor is before the first headline,
14955 display all fragments in the buffer.
14956 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14957 (interactive "P")
14958 (org-remove-latex-fragment-image-overlays)
14959 (save-excursion
14960 (save-restriction
14961 (let (beg end at msg)
14962 (cond
14963 ((or (equal subtree '(16))
14964 (not (save-excursion
14965 (re-search-backward (concat "^" outline-regexp) nil t))))
14966 (setq beg (point-min) end (point-max)
14967 msg "Creating images for buffer...%s"))
14968 ((equal subtree '(4))
14969 (org-back-to-heading)
14970 (setq beg (point) end (org-end-of-subtree)
14971 msg "Creating images for subtree...%s"))
14973 (if (setq at (org-inside-LaTeX-fragment-p))
14974 (goto-char (max (point-min) (- (cdr at) 2)))
14975 (org-back-to-heading))
14976 (setq beg (point) end (progn (outline-next-heading) (point))
14977 msg (if at "Creating image...%s"
14978 "Creating images for entry...%s"))))
14979 (message msg "")
14980 (narrow-to-region beg end)
14981 (org-format-latex
14982 (concat "ltxpng/" (file-name-sans-extension
14983 (file-name-nondirectory
14984 buffer-file-name)))
14985 default-directory 'overlays msg at)
14986 (message msg "done. Use `C-c C-c' to remove images.")))))
14988 (defvar org-latex-regexps
14989 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14990 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14991 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14992 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
14993 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14994 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
14995 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
14996 "Regular expressions for matching embedded LaTeX.")
14998 (defun org-format-latex (prefix &optional dir overlays msg at)
14999 "Replace LaTeX fragments with links to an image, and produce images."
15000 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15001 (let* ((prefixnodir (file-name-nondirectory prefix))
15002 (absprefix (expand-file-name prefix dir))
15003 (todir (file-name-directory absprefix))
15004 (opt org-format-latex-options)
15005 (matchers (plist-get opt :matchers))
15006 (re-list org-latex-regexps)
15007 (cnt 0) txt link beg end re e oldfiles
15008 m n block linkfile movefile ov)
15009 ;; Make sure the directory exists
15010 (or (file-directory-p todir) (make-directory todir))
15011 ;; Check if there are old images files with this prefix, and remove them
15012 (setq oldfiles (directory-files
15013 todir 'full
15014 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
15015 (while oldfiles (delete-file (pop oldfiles)))
15016 ;; Check the different regular expressions
15017 (while (setq e (pop re-list))
15018 (setq m (car e) re (nth 1 e) n (nth 2 e)
15019 block (if (nth 3 e) "\n\n" ""))
15020 (when (member m matchers)
15021 (goto-char (point-min))
15022 (while (re-search-forward re nil t)
15023 (when (or (not at) (equal (cdr at) (match-beginning n)))
15024 (setq txt (match-string n)
15025 beg (match-beginning n) end (match-end n)
15026 cnt (1+ cnt)
15027 linkfile (format "%s_%04d.png" prefix cnt)
15028 movefile (format "%s_%04d.png" absprefix cnt)
15029 link (concat block "[[file:" linkfile "]]" block))
15030 (if msg (message msg cnt))
15031 (goto-char beg)
15032 (org-create-formula-image
15033 txt movefile opt)
15034 (if overlays
15035 (progn
15036 (setq ov (org-make-overlay beg end))
15037 (if (featurep 'xemacs)
15038 (progn
15039 (org-overlay-put ov 'invisible t)
15040 (org-overlay-put
15041 ov 'end-glyph
15042 (make-glyph (vector 'png :file movefile))))
15043 (org-overlay-put
15044 ov 'display
15045 (list 'image :type 'png :file movefile :ascent 'center)))
15046 (push ov org-latex-fragment-image-overlays)
15047 (goto-char end))
15048 (delete-region beg end)
15049 (insert link))))))))
15051 ;; This function borrows from Ganesh Swami's latex2png.el
15052 (defun org-create-formula-image (string tofile options)
15053 (let* ((tmpdir (if (featurep 'xemacs)
15054 (temp-directory)
15055 temporary-file-directory))
15056 (texfilebase (make-temp-name
15057 (expand-file-name "orgtex" tmpdir)))
15059 ;(texfilebase (make-temp-file "orgtex"))
15060 ; (dummy (delete-file texfilebase))
15061 (texfile (concat texfilebase ".tex"))
15062 (dvifile (concat texfilebase ".dvi"))
15063 (pngfile (concat texfilebase ".png"))
15064 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15065 (fg (or (plist-get options :foreground) "Black"))
15066 (bg (or (plist-get options :background) "Transparent")))
15067 (with-temp-file texfile
15068 (insert "\\documentclass{article}
15069 \\usepackage{fullpage}
15070 \\usepackage{amssymb}
15071 \\usepackage[usenames]{color}
15072 \\usepackage{amsmath}
15073 \\usepackage{latexsym}
15074 \\usepackage[mathscr]{eucal}
15075 \\pagestyle{empty}
15076 \\begin{document}\n" string "\n\\end{document}\n"))
15077 (let ((dir default-directory))
15078 (condition-case nil
15079 (progn
15080 (cd tmpdir)
15081 (call-process "latex" nil nil nil texfile))
15082 (error nil))
15083 (cd dir))
15084 (if (not (file-exists-p dvifile))
15085 (progn (message "Failed to create dvi file from %s" texfile) nil)
15086 (call-process "dvipng" nil nil nil
15087 "-E" "-fg" fg "-bg" bg
15088 "-x" scale "-y" scale "-T" "tight"
15089 "-o" pngfile
15090 dvifile)
15091 (if (not (file-exists-p pngfile))
15092 (progn (message "Failed to create png file from %s" texfile) nil)
15093 ;; Use the requested file name and clean up
15094 (copy-file pngfile tofile 'replace)
15095 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15096 (delete-file (concat texfilebase e)))
15097 pngfile))))
15099 ;;; Key bindings
15101 ;; - Bindings in Org-mode map are currently
15102 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
15103 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
15104 ;; e (?) useful from outline-mode
15105 ;; i k @ expendable from outline-mode
15106 ;; 0123456789 % & ()_{} " ` free
15108 ;; Make `C-c C-x' a prefix key
15109 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
15111 ;; TAB key with modifiers
15112 (define-key org-mode-map "\C-i" 'org-cycle)
15113 (define-key org-mode-map [(tab)] 'org-cycle)
15114 (define-key org-mode-map [(meta tab)] 'org-complete)
15115 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
15116 ;; The following line is necessary under Suse GNU/Linux
15117 (unless (featurep 'xemacs)
15118 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
15119 (define-key org-mode-map [(shift tab)] 'org-shifttab)
15121 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
15122 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
15123 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15124 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
15125 (define-key org-mode-map [(meta return)] 'org-meta-return)
15126 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
15127 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
15129 ;; Cursor keys with modifiers
15130 (define-key org-mode-map [(meta left)] 'org-metaleft)
15131 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
15132 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
15133 (define-key org-mode-map [(meta right)] 'org-metaright)
15134 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
15135 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
15136 (define-key org-mode-map [(meta up)] 'org-metaup)
15137 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
15138 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
15139 (define-key org-mode-map [(meta down)] 'org-metadown)
15140 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
15141 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
15143 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15144 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
15145 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
15146 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
15147 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
15148 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
15149 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
15150 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
15151 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
15152 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
15153 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
15154 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
15155 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
15156 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
15157 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
15158 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
15160 ;; All the other keys
15162 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15163 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
15164 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
15165 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
15166 (define-key org-mode-map "\C-c\C-j" 'org-goto)
15167 (define-key org-mode-map "\C-c\C-t" 'org-todo)
15168 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
15169 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
15170 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
15171 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15172 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
15173 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
15174 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
15175 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
15176 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
15177 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
15178 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
15179 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
15180 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
15181 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
15182 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15183 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15184 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15185 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15186 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
15187 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
15188 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15189 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
15190 (define-key org-mode-map "\C-c]" 'org-remove-file)
15191 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
15192 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
15193 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
15194 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15195 (define-key org-mode-map "\C-m" 'org-return)
15196 (define-key org-mode-map "\C-c?" 'org-table-current-column)
15197 (define-key org-mode-map "\C-c " 'org-table-blank-field)
15198 (define-key org-mode-map "\C-c+" 'org-table-sum)
15199 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
15200 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
15201 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
15202 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15203 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
15204 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15205 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
15206 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
15207 (define-key org-mode-map "\C-c\C-e" 'org-export)
15208 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15210 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
15211 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15212 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15213 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15215 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15216 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15217 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15218 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15219 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15220 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15221 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15223 (when (featurep 'xemacs)
15224 (define-key org-mode-map 'button3 'popup-mode-menu))
15226 (defsubst org-table-p () (org-at-table-p))
15228 (defun org-self-insert-command (N)
15229 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15230 If the cursor is in a table looking at whitespace, the whitespace is
15231 overwritten, and the table is not marked as requiring realignment."
15232 (interactive "p")
15233 (if (and (org-table-p)
15234 (progn
15235 ;; check if we blank the field, and if that triggers align
15236 (and org-table-auto-blank-field
15237 (member last-command
15238 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
15239 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15240 ;; got extra space, this field does not determine column width
15241 (let (org-table-may-need-update) (org-table-blank-field))
15242 ;; no extra space, this field may determine column width
15243 (org-table-blank-field)))
15245 (eq N 1)
15246 (looking-at "[^|\n]* |"))
15247 (let (org-table-may-need-update)
15248 (goto-char (1- (match-end 0)))
15249 (delete-backward-char 1)
15250 (goto-char (match-beginning 0))
15251 (self-insert-command N))
15252 (setq org-table-may-need-update t)
15253 (self-insert-command N)))
15255 (defun org-delete-backward-char (N)
15256 "Like `delete-backward-char', insert whitespace at field end in tables.
15257 When deleting backwards, in tables this function will insert whitespace in
15258 front of the next \"|\" separator, to keep the table aligned. The table will
15259 still be marked for re-alignment if the field did fill the entire column,
15260 because, in this case the deletion might narrow the column."
15261 (interactive "p")
15262 (if (and (org-table-p)
15263 (eq N 1)
15264 (string-match "|" (buffer-substring (point-at-bol) (point)))
15265 (looking-at ".*?|"))
15266 (let ((pos (point))
15267 (noalign (looking-at "[^|\n\r]* |"))
15268 (c org-table-may-need-update))
15269 (backward-delete-char N)
15270 (skip-chars-forward "^|")
15271 (insert " ")
15272 (goto-char (1- pos))
15273 ;; noalign: if there were two spaces at the end, this field
15274 ;; does not determine the width of the column.
15275 (if noalign (setq org-table-may-need-update c)))
15276 (backward-delete-char N)))
15278 (defun org-delete-char (N)
15279 "Like `delete-char', but insert whitespace at field end in tables.
15280 When deleting characters, in tables this function will insert whitespace in
15281 front of the next \"|\" separator, to keep the table aligned. The table will
15282 still be marked for re-alignment if the field did fill the entire column,
15283 because, in this case the deletion might narrow the column."
15284 (interactive "p")
15285 (if (and (org-table-p)
15286 (not (bolp))
15287 (not (= (char-after) ?|))
15288 (eq N 1))
15289 (if (looking-at ".*?|")
15290 (let ((pos (point))
15291 (noalign (looking-at "[^|\n\r]* |"))
15292 (c org-table-may-need-update))
15293 (replace-match (concat
15294 (substring (match-string 0) 1 -1)
15295 " |"))
15296 (goto-char pos)
15297 ;; noalign: if there were two spaces at the end, this field
15298 ;; does not determine the width of the column.
15299 (if noalign (setq org-table-may-need-update c)))
15300 (delete-char N))
15301 (delete-char N)))
15303 ;; How to do this: Measure non-white length of current string
15304 ;; If equal to column width, we should realign.
15306 (defun org-remap (map &rest commands)
15307 "In MAP, remap the functions given in COMMANDS.
15308 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15309 (let (new old)
15310 (while commands
15311 (setq old (pop commands) new (pop commands))
15312 (if (fboundp 'command-remapping)
15313 (define-key map (vector 'remap old) new)
15314 (substitute-key-definition old new map global-map)))))
15316 (when (eq org-enable-table-editor 'optimized)
15317 ;; If the user wants maximum table support, we need to hijack
15318 ;; some standard editing functions
15319 (org-remap org-mode-map
15320 'self-insert-command 'org-self-insert-command
15321 'delete-char 'org-delete-char
15322 'delete-backward-char 'org-delete-backward-char)
15323 (define-key org-mode-map "|" 'org-force-self-insert))
15325 (defun org-shiftcursor-error ()
15326 "Throw an error because Shift-Cursor command was applied in wrong context."
15327 (error "This command is active in special context like tables, headlines or timestamps"))
15329 (defun org-shifttab (&optional arg)
15330 "Global visibility cycling or move to previous table field.
15331 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15332 on context.
15333 See the individual commands for more information."
15334 (interactive "P")
15335 (cond
15336 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15337 (t (call-interactively 'org-global-cycle))))
15339 (defun org-shiftmetaleft ()
15340 "Promote subtree or delete table column.
15341 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
15342 See the individual commands for more information."
15343 (interactive)
15344 (cond
15345 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15346 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15347 ((org-at-item-p) (call-interactively 'org-outdent-item))
15348 (t (org-shiftcursor-error))))
15350 (defun org-shiftmetaright ()
15351 "Demote subtree or insert table column.
15352 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
15353 See the individual commands for more information."
15354 (interactive)
15355 (cond
15356 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15357 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15358 ((org-at-item-p) (call-interactively 'org-indent-item))
15359 (t (org-shiftcursor-error))))
15361 (defun org-shiftmetaup (&optional arg)
15362 "Move subtree up or kill table row.
15363 Calls `org-move-subtree-up' or `org-table-kill-row' or
15364 `org-move-item-up' depending on context. See the individual commands
15365 for more information."
15366 (interactive "P")
15367 (cond
15368 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15369 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15370 ((org-at-item-p) (call-interactively 'org-move-item-up))
15371 (t (org-shiftcursor-error))))
15372 (defun org-shiftmetadown (&optional arg)
15373 "Move subtree down or insert table row.
15374 Calls `org-move-subtree-down' or `org-table-insert-row' or
15375 `org-move-item-down', depending on context. See the individual
15376 commands for more information."
15377 (interactive "P")
15378 (cond
15379 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15380 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15381 ((org-at-item-p) (call-interactively 'org-move-item-down))
15382 (t (org-shiftcursor-error))))
15384 (defun org-metaleft (&optional arg)
15385 "Promote heading or move table column to left.
15386 Calls `org-do-promote' or `org-table-move-column', depending on context.
15387 With no specific context, calls the Emacs default `backward-word'.
15388 See the individual commands for more information."
15389 (interactive "P")
15390 (cond
15391 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15392 ((or (org-on-heading-p) (org-region-active-p))
15393 (call-interactively 'org-do-promote))
15394 (t (call-interactively 'backward-word))))
15396 (defun org-metaright (&optional arg)
15397 "Demote subtree or move table column to right.
15398 Calls `org-do-demote' or `org-table-move-column', depending on context.
15399 With no specific context, calls the Emacs default `forward-word'.
15400 See the individual commands for more information."
15401 (interactive "P")
15402 (cond
15403 ((org-at-table-p) (call-interactively 'org-table-move-column))
15404 ((or (org-on-heading-p) (org-region-active-p))
15405 (call-interactively 'org-do-demote))
15406 (t (call-interactively 'forward-word))))
15408 (defun org-metaup (&optional arg)
15409 "Move subtree up or move table row up.
15410 Calls `org-move-subtree-up' or `org-table-move-row' or
15411 `org-move-item-up', depending on context. See the individual commands
15412 for more information."
15413 (interactive "P")
15414 (cond
15415 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15416 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15417 ((org-at-item-p) (call-interactively 'org-move-item-up))
15418 (t (org-shiftcursor-error))))
15420 (defun org-metadown (&optional arg)
15421 "Move subtree down or move table row down.
15422 Calls `org-move-subtree-down' or `org-table-move-row' or
15423 `org-move-item-down', depending on context. See the individual
15424 commands for more information."
15425 (interactive "P")
15426 (cond
15427 ((org-at-table-p) (call-interactively 'org-table-move-row))
15428 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15429 ((org-at-item-p) (call-interactively 'org-move-item-down))
15430 (t (org-shiftcursor-error))))
15432 (defun org-shiftup (&optional arg)
15433 "Increase item in timestamp or increase priority of current headline.
15434 Calls `org-timestamp-up' or `org-priority-up', depending on context.
15435 See the individual commands for more information."
15436 (interactive "P")
15437 (cond
15438 ((org-at-timestamp-p) (call-interactively 'org-timestamp-up))
15439 ((org-on-heading-p) (call-interactively 'org-priority-up))
15440 ((org-at-item-p) (call-interactively 'org-previous-item))
15441 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
15443 (defun org-shiftdown (&optional arg)
15444 "Decrease item in timestamp or decrease priority of current headline.
15445 Calls `org-timestamp-down' or `org-priority-down', depending on context.
15446 See the individual commands for more information."
15447 (interactive "P")
15448 (cond
15449 ((org-at-timestamp-p) (call-interactively 'org-timestamp-down))
15450 ((org-on-heading-p) (call-interactively 'org-priority-down))
15451 (t (call-interactively 'org-next-item))))
15453 (defun org-shiftright ()
15454 "Next TODO keyword or timestamp one day later, depending on context."
15455 (interactive)
15456 (cond
15457 ((org-at-timestamp-p) (call-interactively 'org-timestamp-up-day))
15458 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
15459 (t (org-shiftcursor-error))))
15461 (defun org-shiftleft ()
15462 "Previous TODO keyword or timestamp one day earlier, depending on context."
15463 (interactive)
15464 (cond
15465 ((org-at-timestamp-p) (call-interactively 'org-timestamp-down-day))
15466 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
15467 (t (org-shiftcursor-error))))
15469 (defun org-copy-special ()
15470 "Copy region in table or copy current subtree.
15471 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15472 See the individual commands for more information."
15473 (interactive)
15474 (call-interactively
15475 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15477 (defun org-cut-special ()
15478 "Cut region in table or cut current subtree.
15479 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15480 See the individual commands for more information."
15481 (interactive)
15482 (call-interactively
15483 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15485 (defun org-paste-special (arg)
15486 "Paste rectangular region into table, or past subtree relative to level.
15487 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15488 See the individual commands for more information."
15489 (interactive "P")
15490 (if (org-at-table-p)
15491 (org-table-paste-rectangle)
15492 (org-paste-subtree arg)))
15494 (defun org-ctrl-c-ctrl-c (&optional arg)
15495 "Set tags in headline, or update according to changed information at point.
15497 This command does many different things, depending on context:
15499 - If the cursor is in a headline, prompt for tags and insert them
15500 into the current line, aligned to `org-tags-column'. When called
15501 with prefix arg, realign all tags in the current buffer.
15503 - If the cursor is in one of the special #+KEYWORD lines, this
15504 triggers scanning the buffer for these lines and updating the
15505 information.
15507 - If the cursor is inside a table, realign the table. This command
15508 works even if the automatic table editor has been turned off.
15510 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15511 the entire table.
15513 - If the cursor is inside a table created by the table.el package,
15514 activate that table.
15516 - If the current buffer is a remember buffer, close note and file it.
15517 with a prefix argument, file it without further interaction to the default
15518 location.
15520 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15521 links in this buffer.
15523 - If the cursor is on a numbered item in a plain list, renumber the
15524 ordered list."
15525 (interactive "P")
15526 (let ((org-enable-table-editor t))
15527 (cond
15528 ((or org-clock-overlays org-occur-highlights
15529 org-latex-fragment-image-overlays)
15530 (org-remove-clock-overlays)
15531 (org-remove-occur-highlights)
15532 (org-remove-latex-fragment-image-overlays)
15533 (message "Temporary highlights/overlays removed from current buffer"))
15534 ((and (local-variable-p 'org-finish-function (current-buffer))
15535 (fboundp org-finish-function))
15536 (funcall org-finish-function))
15537 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15538 ((org-on-heading-p) (call-interactively 'org-set-tags))
15539 ((org-at-table.el-p)
15540 (require 'table)
15541 (beginning-of-line 1)
15542 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15543 (call-interactively 'table-recognize-table))
15544 ((org-at-table-p)
15545 (org-table-maybe-eval-formula)
15546 (if arg
15547 (call-interactively 'org-table-recalculate)
15548 (org-table-maybe-recalculate-line))
15549 (call-interactively 'org-table-align))
15550 ((org-at-item-checkbox-p)
15551 (call-interactively 'org-toggle-checkbox))
15552 ((org-at-item-p)
15553 (call-interactively 'org-renumber-ordered-list))
15554 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
15555 (cond
15556 ((equal (match-string 1) "TBLFM")
15557 ;; Recalculate the table before this line
15558 (save-excursion
15559 (beginning-of-line 1)
15560 (skip-chars-backward " \r\n\t")
15561 (if (org-at-table-p)
15562 (org-call-with-arg 'org-table-recalculate t))))
15564 (call-interactively 'org-mode-restart))))
15565 (t (error "C-c C-c can do nothing useful at this location.")))))
15567 (defun org-mode-restart ()
15568 "Restart Org-mode, to scan again for special lines.
15569 Also updates the keyword regular expressions."
15570 (interactive)
15571 (let ((org-inhibit-startup t)) (org-mode))
15572 (message "Org-mode restarted to refresh keyword and special line setup"))
15574 (defun org-return ()
15575 "Goto next table row or insert a newline.
15576 Calls `org-table-next-row' or `newline', depending on context.
15577 See the individual commands for more information."
15578 (interactive)
15579 (cond
15580 ((org-at-table-p)
15581 (org-table-justify-field-maybe)
15582 (call-interactively 'org-table-next-row))
15583 (t (newline))))
15585 (defun org-meta-return (&optional arg)
15586 "Insert a new heading or wrap a region in a table.
15587 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15588 See the individual commands for more information."
15589 (interactive "P")
15590 (cond
15591 ((org-at-table-p)
15592 (call-interactively 'org-table-wrap-region))
15593 (t (call-interactively 'org-insert-heading))))
15595 ;;; Menu entries
15597 ;; Define the Org-mode menus
15598 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15599 '("Tbl"
15600 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
15601 ["Next Field" org-cycle (org-at-table-p)]
15602 ["Previous Field" org-shifttab (org-at-table-p)]
15603 ["Next Row" org-return (org-at-table-p)]
15604 "--"
15605 ["Blank Field" org-table-blank-field (org-at-table-p)]
15606 ["Edit Field" org-table-edit-field (org-at-table-p)]
15607 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15608 "--"
15609 ("Column"
15610 ["Move Column Left" org-metaleft (org-at-table-p)]
15611 ["Move Column Right" org-metaright (org-at-table-p)]
15612 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15613 ["Insert Column" org-shiftmetaright (org-at-table-p)]
15614 "--"
15615 ["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])
15616 ("Row"
15617 ["Move Row Up" org-metaup (org-at-table-p)]
15618 ["Move Row Down" org-metadown (org-at-table-p)]
15619 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15620 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15621 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15622 "--"
15623 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
15624 ("Rectangle"
15625 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15626 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15627 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15628 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15629 "--"
15630 ("Calculate"
15631 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15632 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15633 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
15634 "--"
15635 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15636 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15637 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15638 "--"
15639 ["Sum Column/Rectangle" org-table-sum
15640 (or (org-at-table-p) (org-region-active-p))]
15641 ["Which Column?" org-table-current-column (org-at-table-p)])
15642 ["Debug Formulas"
15643 (setq org-table-formula-debug (not org-table-formula-debug))
15644 :style toggle :selected org-table-formula-debug]
15645 "--"
15646 ["Create" org-table-create (and (not (org-at-table-p))
15647 org-enable-table-editor)]
15648 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15649 ["Import from File" org-table-import (not (org-at-table-p))]
15650 ["Export to File" org-table-export (org-at-table-p)]
15651 "--"
15652 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15654 (easy-menu-define org-org-menu org-mode-map "Org menu"
15655 '("Org"
15656 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
15657 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
15658 ["Sparse Tree" org-occur t]
15659 ["Show All" show-all t]
15660 "--"
15661 ["New Heading" org-insert-heading t]
15662 ("Navigate Headings"
15663 ["Up" outline-up-heading t]
15664 ["Next" outline-next-visible-heading t]
15665 ["Previous" outline-previous-visible-heading t]
15666 ["Next Same Level" outline-forward-same-level t]
15667 ["Previous Same Level" outline-backward-same-level t]
15668 "--"
15669 ["Jump" org-goto t])
15670 ("Edit Structure"
15671 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15672 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15673 "--"
15674 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15675 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15676 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15677 "--"
15678 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15679 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15680 ["Demote Heading" org-metaright (not (org-at-table-p))]
15681 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15682 "--"
15683 ["Convert to odd levels" org-convert-to-odd-levels t]
15684 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15685 ("Archive"
15686 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15687 ["Check and Tag Children" (org-toggle-archive-tag (4))
15688 :active t :keys "C-u C-c C-x C-a"]
15689 ["Sparse trees open ARCHIVE trees"
15690 (setq org-sparse-tree-open-archived-trees
15691 (not org-sparse-tree-open-archived-trees))
15692 :style toggle :selected org-sparse-tree-open-archived-trees]
15693 ["Cycling opens ARCHIVE trees"
15694 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15695 :style toggle :selected org-cycle-open-archived-trees]
15696 ["Agenda includes ARCHIVE trees"
15697 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
15698 :style toggle :selected (not org-agenda-skip-archived-trees)]
15699 "--"
15700 ["Move Subtree to Archive" org-archive-subtree t]
15701 ["Check and Move Children" (org-archive-subtree '(4))
15702 :active t :keys "C-u C-c $"])
15703 "--"
15704 ("TODO Lists"
15705 ["TODO/DONE/-" org-todo t]
15706 ["Show TODO Tree" org-show-todo-tree t]
15707 ["Global TODO list" org-todo-list t]
15708 "--"
15709 ["Set Priority" org-priority t]
15710 ["Priority Up" org-shiftup t]
15711 ["Priority Down" org-shiftdown t])
15712 ("Dates and Scheduling"
15713 ["Timestamp" org-time-stamp t]
15714 ["Timestamp (inactive)" org-time-stamp-inactive t]
15715 ("Change Date"
15716 ["1 Day Later" org-timestamp-up-day t]
15717 ["1 Day Earlier" org-timestamp-down-day t]
15718 ["1 ... Later" org-shiftup t]
15719 ["1 ... Earlier" org-shiftdown t])
15720 ["Compute Time Range" org-evaluate-time-range t]
15721 ["Schedule Item" org-schedule t]
15722 ["Deadline" org-deadline t]
15723 "--"
15724 ["Goto Calendar" org-goto-calendar t]
15725 ["Date from Calendar" org-date-from-calendar t])
15726 ("Logging work"
15727 ["Clock in" org-clock-in t]
15728 ["Clock out" org-clock-out t]
15729 ["Clock cancel" org-clock-cancel t]
15730 ["Display times" org-clock-display t]
15731 ["Create clock table" org-clock-report t]
15732 "--"
15733 ["Record DONE time"
15734 (progn (setq org-log-done (not org-log-done))
15735 (message "Switching to %s will %s record a timestamp"
15736 org-done-string
15737 (if org-log-done "automatically" "not")))
15738 :style toggle :selected org-log-done])
15739 "--"
15740 ["Agenda Command" org-agenda t]
15741 ("File List for Agenda")
15742 ("Special views current file"
15743 ["TODO Tree" org-show-todo-tree t]
15744 ["Check Deadlines" org-check-deadlines t]
15745 ["Timeline" org-timeline t]
15746 ["Tags Tree" org-tags-sparse-tree t])
15747 "--"
15748 ("Hyperlinks"
15749 ["Store Link (Global)" org-store-link t]
15750 ["Insert Link" org-insert-link t]
15751 ["Follow Link" org-open-at-point t]
15752 "--"
15753 ["Descriptive Links"
15754 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15755 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
15756 ["Literal Links"
15757 (progn
15758 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15759 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
15760 "--"
15761 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
15762 (save-excursion (goto-char (point-min))
15763 (re-search-forward "<[a-z]+:" nil t))])
15764 "--"
15765 ["Export/Publish" org-export t]
15766 ("LaTeX"
15767 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15768 :selected org-cdlatex-mode]
15769 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15770 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15771 ["Modify math symbol" org-cdlatex-math-modify
15772 (org-inside-LaTeX-fragment-p)]
15773 ["Export LaTeX fragments as images"
15774 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
15775 :style toggle :selected org-export-with-LaTeX-fragments])
15776 "--"
15777 ("Documentation"
15778 ["Show Version" org-version t]
15779 ["Info Documentation" org-info t])
15780 ("Customize"
15781 ["Browse Org Group" org-customize t]
15782 "--"
15783 ["Expand This Menu" org-create-customize-menu
15784 (fboundp 'customize-menu-create)])
15785 "--"
15786 ["Refresh setup" org-mode-restart t]
15789 (defun org-info (&optional node)
15790 "Read documentation for Org-mode in the info system.
15791 With optional NODE, go directly to that node."
15792 (interactive)
15793 (require 'info)
15794 (Info-goto-node (format "(org)%s" (or node ""))))
15796 (defun org-install-agenda-files-menu ()
15797 (let ((bl (buffer-list)))
15798 (save-excursion
15799 (while bl
15800 (set-buffer (pop bl))
15801 (if (eq major-mode 'org-mode) (setq bl nil)))
15802 (when (eq major-mode 'org-mode)
15803 (easy-menu-change
15804 '("Org") "File List for Agenda"
15805 (append
15806 (list
15807 ["Edit File List" (org-edit-agenda-file-list) t]
15808 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15809 ["Remove Current File from List" org-remove-file t]
15810 ["Cycle through agenda files" org-cycle-agenda-files t]
15811 "--")
15812 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15814 ;;; Documentation
15816 (defun org-customize ()
15817 "Call the customize function with org as argument."
15818 (interactive)
15819 (customize-browse 'org))
15821 (defun org-create-customize-menu ()
15822 "Create a full customization menu for Org-mode, insert it into the menu."
15823 (interactive)
15824 (if (fboundp 'customize-menu-create)
15825 (progn
15826 (easy-menu-change
15827 '("Org") "Customize"
15828 `(["Browse Org group" org-customize t]
15829 "--"
15830 ,(customize-menu-create 'org)
15831 ["Set" Custom-set t]
15832 ["Save" Custom-save t]
15833 ["Reset to Current" Custom-reset-current t]
15834 ["Reset to Saved" Custom-reset-saved t]
15835 ["Reset to Standard Settings" Custom-reset-standard t]))
15836 (message "\"Org\"-menu now contains full customization menu"))
15837 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15839 ;;; Miscellaneous stuff
15841 (defun org-context ()
15842 "Return a list of contexts of the current cursor position.
15843 If several contexts apply, all are returned.
15844 Each context entry is a list with a symbol naming the context, and
15845 two positions indicating start and end of the context. Possible
15846 contexts are:
15848 :headline anywhere in a headline
15849 :headline-stars on the leading stars in a headline
15850 :todo-keyword on a TODO keyword (including DONE) in a headline
15851 :tags on the TAGS in a headline
15852 :priority on the priority cookie in a headline
15853 :item on the first line of a plain list item
15854 :item-bullet on the bullet/number of a plain list item
15855 :checkbox on the checkbox in a plain list item
15856 :table in an org-mode table
15857 :table-special on a special filed in a table
15858 :table-table in a table.el table
15859 :link on a hyperline
15860 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15861 :target on a <<target>>
15862 :radio-target on a <<<radio-target>>>
15863 :latex-fragment on a LaTeX fragment
15864 :latex-preview on a LaTeX fragment with overlayed preview image
15866 This function expects the position to be visible because it uses font-lock
15867 faces as a help to recognize the following contexts: :table-special, :link,
15868 and :keyword."
15869 (let* ((f (get-text-property (point) 'face))
15870 (faces (if (listp f) f (list f)))
15871 (p (point)) clist o)
15872 ;; First the large context
15873 (cond
15874 ((org-on-heading-p)
15875 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15876 (when (progn
15877 (beginning-of-line 1)
15878 (looking-at org-todo-line-tags-regexp))
15879 (push (org-point-in-group p 1 :headline-stars) clist)
15880 (push (org-point-in-group p 2 :todo-keyword) clist)
15881 (push (org-point-in-group p 4 :tags) clist))
15882 (goto-char p)
15883 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15884 (if (looking-at "\\[#[A-Z]\\]")
15885 (push (org-point-in-group p 0 :priority) clist)))
15887 ((org-at-item-p)
15888 (push (org-point-in-group p 2 :item-bullet) clist)
15889 (push (list :item (point-at-bol)
15890 (save-excursion (org-end-of-item) (point)))
15891 clist)
15892 (and (org-at-item-checkbox-p)
15893 (push (org-point-in-group p 0 :checkbox) clist)))
15895 ((org-at-table-p)
15896 (push (list :table (org-table-begin) (org-table-end)) clist)
15897 (if (memq 'org-formula faces)
15898 (push (list :table-special
15899 (previous-single-property-change p 'face)
15900 (next-single-property-change p 'face)) clist)))
15901 ((org-at-table-p 'any)
15902 (push (list :table-table) clist)))
15903 (goto-char p)
15905 ;; Now the small context
15906 (cond
15907 ((org-at-timestamp-p)
15908 (push (org-point-in-group p 0 :timestamp) clist))
15909 ((memq 'org-link faces)
15910 (push (list :link
15911 (previous-single-property-change p 'face)
15912 (next-single-property-change p 'face)) clist))
15913 ((memq 'org-special-keyword faces)
15914 (push (list :keyword
15915 (previous-single-property-change p 'face)
15916 (next-single-property-change p 'face)) clist))
15917 ((org-on-target-p)
15918 (push (org-point-in-group p 0 :target) clist)
15919 (goto-char (1- (match-beginning 0)))
15920 (if (looking-at org-radio-target-regexp)
15921 (push (org-point-in-group p 0 :radio-target) clist))
15922 (goto-char p))
15923 ((setq o (car (delq nil
15924 (mapcar
15925 (lambda (x)
15926 (if (memq x org-latex-fragment-image-overlays) x))
15927 (org-overlays-at (point))))))
15928 (push (list :latex-fragment
15929 (org-overlay-start o) (org-overlay-end o)) clist)
15930 (push (list :latex-preview
15931 (org-overlay-start o) (org-overlay-end o)) clist))
15932 ((org-inside-LaTeX-fragment-p)
15933 ;; FIXME: positions wring.
15934 (push (list :latex-fragment (point) (point)) clist)))
15936 (setq clist (nreverse (delq nil clist)))
15937 clist))
15939 (defun org-point-in-group (point group &optional context)
15940 "Check if POINT is in match-group GROUP.
15941 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15942 match. If the match group does ot exist or point is not inside it,
15943 return nil."
15944 (and (match-beginning group)
15945 (>= point (match-beginning group))
15946 (<= point (match-end group))
15947 (if context
15948 (list context (match-beginning group) (match-end group))
15949 t)))
15951 (defun org-move-line-down (arg)
15952 "Move the current line down. With prefix argument, move it past ARG lines."
15953 (interactive "p")
15954 (let ((col (current-column))
15955 beg end pos)
15956 (beginning-of-line 1) (setq beg (point))
15957 (beginning-of-line 2) (setq end (point))
15958 (beginning-of-line (+ 1 arg))
15959 (setq pos (move-marker (make-marker) (point)))
15960 (insert (delete-and-extract-region beg end))
15961 (goto-char pos)
15962 (move-to-column col)))
15964 (defun org-move-line-up (arg)
15965 "Move the current line up. With prefix argument, move it past ARG lines."
15966 (interactive "p")
15967 (let ((col (current-column))
15968 beg end pos)
15969 (beginning-of-line 1) (setq beg (point))
15970 (beginning-of-line 2) (setq end (point))
15971 (beginning-of-line (- arg))
15972 (setq pos (move-marker (make-marker) (point)))
15973 (insert (delete-and-extract-region beg end))
15974 (goto-char pos)
15975 (move-to-column col)))
15977 ;; Paragraph filling stuff.
15978 ;; We want this to be just right, so use the full arsenal.
15980 (defun org-set-autofill-regexps ()
15981 (interactive)
15982 ;; In the paragraph separator we include headlines, because filling
15983 ;; text in a line directly attached to a headline would otherwise
15984 ;; fill the headline as well.
15985 (set (make-local-variable 'comment-start-skip) "^#+[ \t]*")
15986 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
15987 ;; The paragraph starter includes hand-formatted lists.
15988 (set (make-local-variable 'paragraph-start)
15989 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15990 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15991 ;; But only if the user has not turned off tables or fixed-width regions
15992 (set (make-local-variable 'auto-fill-inhibit-regexp)
15993 (concat "\\*\\|#"
15994 "\\|[ \t]*" org-keyword-time-regexp
15995 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15996 (concat
15997 "\\|[ \t]*["
15998 (if org-enable-table-editor "|" "")
15999 (if org-enable-fixed-width-editor ":" "")
16000 "]"))))
16001 ;; We use our own fill-paragraph function, to make sure that tables
16002 ;; and fixed-width regions are not wrapped. That function will pass
16003 ;; through to `fill-paragraph' when appropriate.
16004 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
16005 ;; Adaptive filling: To get full control, first make sure that
16006 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16007 (set (make-local-variable 'adaptive-fill-regexp) "\000")
16008 (set (make-local-variable 'adaptive-fill-function)
16009 'org-adaptive-fill-function))
16011 (defun org-fill-paragraph (&optional justify)
16012 "Re-align a table, pass through to fill-paragraph if no table."
16013 (let ((table-p (org-at-table-p))
16014 (table.el-p (org-at-table.el-p)))
16015 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
16016 (table.el-p t) ; skip table.el tables
16017 (table-p (org-table-align) t) ; align org-mode tables
16018 (t nil)))) ; call paragraph-fill
16020 ;; For reference, this is the default value of adaptive-fill-regexp
16021 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16023 (defun org-adaptive-fill-function ()
16024 "Return a fill prefix for org-mode files.
16025 In particular, this makes sure hanging paragraphs for hand-formatted lists
16026 work correctly."
16027 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
16028 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
16030 ;; Functions needed for Emacs/XEmacs region compatibility
16032 (defun org-add-hook (hook function &optional append local)
16033 "Add-hook, compatible with both Emacsen."
16034 (if (and local (featurep 'xemacs))
16035 (add-local-hook hook function append)
16036 (add-hook hook function append local)))
16038 (defun org-region-active-p ()
16039 "Is `transient-mark-mode' on and the region active?
16040 Works on both Emacs and XEmacs."
16041 (if org-ignore-region
16043 (if (featurep 'xemacs)
16044 (and zmacs-regions (region-active-p))
16045 (and transient-mark-mode mark-active))))
16047 (defun org-add-to-invisibility-spec (arg)
16048 "Add elements to `buffer-invisibility-spec'.
16049 See documentation for `buffer-invisibility-spec' for the kind of elements
16050 that can be added."
16051 (cond
16052 ((fboundp 'add-to-invisibility-spec)
16053 (add-to-invisibility-spec arg))
16054 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
16055 (setq buffer-invisibility-spec (list arg)))
16057 (setq buffer-invisibility-spec
16058 (cons arg buffer-invisibility-spec)))))
16060 (defun org-remove-from-invisibility-spec (arg)
16061 "Remove elements from `buffer-invisibility-spec'."
16062 (if (fboundp 'remove-from-invisibility-spec)
16063 (remove-from-invisibility-spec arg)
16064 (if (consp buffer-invisibility-spec)
16065 (setq buffer-invisibility-spec
16066 (delete arg buffer-invisibility-spec)))))
16068 (defun org-in-invisibility-spec-p (arg)
16069 "Is ARG a member of `buffer-invisibility-spec'?"
16070 (if (consp buffer-invisibility-spec)
16071 (member arg buffer-invisibility-spec)
16072 nil))
16074 (defun org-image-file-name-regexp ()
16075 "Return regexp matching the file names of images."
16076 (if (fboundp 'image-file-name-regexp)
16077 (image-file-name-regexp)
16078 (let ((image-file-name-extensions
16079 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16080 "xbm" "xpm" "pbm" "pgm" "ppm")))
16081 (concat "\\."
16082 (regexp-opt (nconc (mapcar 'upcase
16083 image-file-name-extensions)
16084 image-file-name-extensions)
16086 "\\'"))))
16088 ;; Functions needed for compatibility with old outline.el.
16090 ;; Programming for the old outline.el (that uses selective display
16091 ;; instead of `invisible' text properties) is a nightmare, mostly
16092 ;; because regular expressions can no longer be anchored at
16093 ;; beginning/end of line. Therefore a number of function need special
16094 ;; treatment when the old outline.el is being used.
16096 ;; The following functions capture almost the entire compatibility code
16097 ;; between the different versions of outline-mode. The only other
16098 ;; places where this is important are the font-lock-keywords, and in
16099 ;; `org-export-visible'. Search for `org-noutline-p' to find them.
16101 ;; C-a should go to the beginning of a *visible* line, also in the
16102 ;; new outline.el. I guess this should be patched into Emacs?
16103 (defun org-beginning-of-line ()
16104 "Go to the beginning of the current line. If that is invisible, continue
16105 to a visible line beginning. This makes the function of C-a more intuitive."
16106 (interactive)
16107 (beginning-of-line 1)
16108 (if (bobp)
16110 (backward-char 1)
16111 (if (org-invisible-p)
16112 (while (and (not (bobp)) (org-invisible-p))
16113 (backward-char 1)
16114 (beginning-of-line 1))
16115 (forward-char 1))))
16117 (when org-noutline-p
16118 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
16120 (defun org-invisible-p ()
16121 "Check if point is at a character currently not visible."
16122 (if org-noutline-p
16123 ;; Early versions of noutline don't have `outline-invisible-p'.
16124 (if (fboundp 'outline-invisible-p)
16125 (outline-invisible-p)
16126 (get-char-property (point) 'invisible))
16127 (save-excursion
16128 (skip-chars-backward "^\r\n")
16129 (equal (char-before) ?\r))))
16131 (defun org-invisible-p2 ()
16132 "Check if point is at a character currently not visible."
16133 (save-excursion
16134 (if org-noutline-p
16135 (progn
16136 (if (and (eolp) (not (bobp))) (backward-char 1))
16137 ;; Early versions of noutline don't have `outline-invisible-p'.
16138 (if (fboundp 'outline-invisible-p)
16139 (outline-invisible-p)
16140 (get-char-property (point) 'invisible)))
16141 (skip-chars-backward "^\r\n")
16142 (equal (char-before) ?\r))))
16144 (defun org-back-to-heading (&optional invisible-ok)
16145 "Move to previous heading line, or beg of this line if it's a heading.
16146 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
16147 (if org-noutline-p
16148 (outline-back-to-heading invisible-ok)
16149 (if (and (or (bobp) (memq (char-before) '(?\n ?\r)))
16150 (looking-at outline-regexp))
16152 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
16153 outline-regexp)
16154 nil t)
16155 (if invisible-ok
16156 (progn (goto-char (or (match-end 1) (match-beginning 0)))
16157 (looking-at outline-regexp)))
16158 (error "Before first heading")))))
16160 (defun org-on-heading-p (&optional invisible-ok)
16161 "Return t if point is on a (visible) heading line.
16162 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
16163 (if org-noutline-p
16164 (outline-on-heading-p 'invisible-ok)
16165 (save-excursion
16166 (skip-chars-backward "^\n\r")
16167 (and (looking-at outline-regexp)
16168 (or invisible-ok
16169 (bobp)
16170 (equal (char-before) ?\n))))))
16172 (defun org-on-target-p ()
16173 (let ((pos (point)))
16174 (save-excursion
16175 (skip-chars-forward "<")
16176 (and (re-search-backward "<<" nil t)
16177 (or (looking-at org-radio-target-regexp)
16178 (looking-at org-target-regexp))
16179 (<= (match-beginning 0) pos)
16180 (>= (1+ (match-end 0)) pos)))))
16182 (defun org-up-heading-all (arg)
16183 "Move to the heading line of which the present line is a subheading.
16184 This function considers both visible and invisible heading lines.
16185 With argument, move up ARG levels."
16186 (if org-noutline-p
16187 (if (fboundp 'outline-up-heading-all)
16188 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16189 (outline-up-heading arg t)) ; emacs 22 version of outline.el
16190 (org-back-to-heading t)
16191 (looking-at outline-regexp)
16192 (if (<= (- (match-end 0) (match-beginning 0)) arg)
16193 (error "Cannot move up %d levels" arg)
16194 (re-search-backward
16195 (concat "[\n\r]" (regexp-quote
16196 (make-string (- (match-end 0) (match-beginning 0) arg)
16197 ?*))
16198 "[^*]"))
16199 (forward-char 1))))
16201 (defun org-show-hidden-entry ()
16202 "Show an entry where even the heading is hidden."
16203 (save-excursion
16204 (if (not org-noutline-p)
16205 (progn
16206 (org-back-to-heading t)
16207 (org-flag-heading nil)))
16208 (org-show-entry)))
16210 (defun org-check-occur-regexp (regexp)
16211 "If REGEXP starts with \"^\", modify it to check for \\r as well.
16212 Of course, only for the old outline mode."
16213 (if org-noutline-p
16214 regexp
16215 (if (string-match "^\\^" regexp)
16216 (concat "[\n\r]" (substring regexp 1))
16217 regexp)))
16219 (defun org-flag-heading (flag &optional entry)
16220 "Flag the current heading. FLAG non-nil means make invisible.
16221 When ENTRY is non-nil, show the entire entry."
16222 (save-excursion
16223 (org-back-to-heading t)
16224 (if (not org-noutline-p)
16225 ;; Make the current headline visible
16226 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
16227 ;; Check if we should show the entire entry
16228 (if entry
16229 (progn
16230 (org-show-entry)
16231 (save-excursion
16232 (and (outline-next-heading)
16233 (org-flag-heading nil))))
16234 (outline-flag-region (max 1 (1- (point)))
16235 (save-excursion (outline-end-of-heading) (point))
16236 (if org-noutline-p
16237 flag
16238 (if flag ?\r ?\n))))))
16240 (defun org-end-of-subtree (&optional invisible-OK)
16241 ;; This is an exact copy of the original function, but it uses
16242 ;; `org-back-to-heading', to make it work also in invisible
16243 ;; trees. And is uses an invisible-OK argument.
16244 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16245 (org-back-to-heading invisible-OK)
16246 (let ((first t)
16247 (level (funcall outline-level)))
16248 (while (and (not (eobp))
16249 (or first (> (funcall outline-level) level)))
16250 (setq first nil)
16251 (outline-next-heading))
16252 (if (memq (preceding-char) '(?\n ?\^M))
16253 (progn
16254 ;; Go to end of line before heading
16255 (forward-char -1)
16256 (if (memq (preceding-char) '(?\n ?\^M))
16257 ;; leave blank line before heading
16258 (forward-char -1)))))
16259 (point))
16261 (defun org-show-subtree ()
16262 "Show everything after this heading at deeper levels."
16263 (outline-flag-region
16264 (point)
16265 (save-excursion
16266 (outline-end-of-subtree) (outline-next-heading) (point))
16267 (if org-noutline-p nil ?\n)))
16269 (defun org-show-entry ()
16270 "Show the body directly following this heading.
16271 Show the heading too, if it is currently invisible."
16272 (interactive)
16273 (save-excursion
16274 (org-back-to-heading t)
16275 (outline-flag-region
16276 (max 1 (1- (point)))
16277 (save-excursion
16278 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
16279 (or (match-beginning 1) (point-max)))
16280 (if org-noutline-p nil ?\n))))
16282 (defun org-make-options-regexp (kwds)
16283 "Make a regular expression for keyword lines."
16284 (concat
16285 (if org-noutline-p "^" "[\n\r]")
16286 "#?[ \t]*\\+\\("
16287 (mapconcat 'regexp-quote kwds "\\|")
16288 "\\):[ \t]*"
16289 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
16291 ;; Make `bookmark-jump' show the jump location if it was hidden.
16292 (eval-after-load "bookmark"
16293 '(if (boundp 'bookmark-after-jump-hook)
16294 ;; We can use the hook
16295 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16296 ;; Hook not available, use advice
16297 (defadvice bookmark-jump (after org-make-visible activate)
16298 "Make the position visible."
16299 (org-bookmark-jump-unhide))))
16301 (defun org-bookmark-jump-unhide ()
16302 "Unhide the current position, to show the bookmark location."
16303 (and (eq major-mode 'org-mode)
16304 (or (org-invisible-p)
16305 (save-excursion (goto-char (max (point-min) (1- (point))))
16306 (org-invisible-p)))
16307 (org-show-hierarchy-above)))
16309 ;;; Experimental code
16311 ;;; Finish up
16313 (provide 'org)
16315 (run-hooks 'org-load-hook)
16317 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16318 ;;; org.el ends here