Release 4.44
[org-mode/org-mode-NeilSmithlineMods.git] / org.el
blob1fcac6855d93b82033d94063cd2060576ab826e2
1 ;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 4.44
9 ;;
10 ;; This file is part of GNU Emacs.
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.44
94 ;; - Clock table can be done for a limited time interval.
95 ;; - Obsolete support for the old outline mode has been removed.
96 ;; - Bug fixes and code cleaning.
98 ;; Version 4.43
99 ;; - Bug fixes
100 ;; - `s' key in the agenda saves all org-mode buffers.
102 ;; Version 4.41
103 ;; - Shift-curser keys can modify inactive time stamps (inactive time
104 ;; stamps are the ones in [...] brackets.
105 ;; - Toggle all checkboxes in a region/below a headline.
106 ;; - Bug fixes.
108 ;; Version 4.40
109 ;; - Bug fixes.
111 ;; Version 4.39
112 ;; - Special tag ARCHIVE keeps a subtree closed and away from agenda lists.
113 ;; - LaTeX code in Org-mode files can be converted to images for HTML.
114 ;; - Bug fixes.
115 ;; - CDLaTeX-mode features can be used in Org-mode to help inserting
116 ;; LaTeX environment and math.
118 ;; Version 4.38
119 ;; - noutline.el is now required (important for XEmacs users only).
120 ;; - Dynamic blocks.
121 ;; - Archiving of all level 1 trees without open TODO items.
122 ;; - Clock reports can be inserted into the file in a special section.
123 ;; - FAQ removed from the manual, now only on the web.
124 ;; - Bug fixes.
126 ;; Version 4.37
127 ;; - Clock-feature for measuring time spent on specific items.
128 ;; - Improved emphasizing allows configuration and stacking.
130 ;; Version 4.36
131 ;; - Improved indentation of ASCII export, when headlines become items.
132 ;; - Handling of 12am and 12pm fixed. Times beyond 24:00 can be used
133 ;; and will not lead to conflicts.
134 ;; - Support for mutually exclusive TAGS with the fast tags interface.
135 ;; - Bug fixes.
137 ;; Version 4.35
138 ;; - HTML export is now valid XHTML.
139 ;; - Timeline can also show dates without entries. See new option
140 ;; `org-timeline-show-empty-dates'.
141 ;; - The bullets created by the ASCII exporter can now be configured.
142 ;; See the new option `org-export-ascii-bullets'.
143 ;; - New face `org-upcoming-deadline' (was `org-scheduled-previously').
144 ;; - New function `org-context' to allow testing for local context.
146 ;; Version 4.34
147 ;; - Bug fixes.
149 ;; Version 4.33
150 ;; - New commands to move through plain lists: S-up and S-down.
151 ;; - Bug fixes and documentation update.
153 ;; Version 4.32
154 ;; - Fast (single-key-per-tag) interface for setting TAGS.
155 ;; - The list of legal tags can be configured globally and locally.
156 ;; - Elisp and Info links (thanks to Todd Neal).
157 ;; - `org-export-publishing-directory' can be an alist, with different
158 ;; directories for different export types.
159 ;; - All context-sensitive commands use `call-interactively' to dispatch.
160 ;; - `org-confirm-shell-links' renamed to `org-confirm-shell-link-function'.
161 ;; - Bug fixes.
163 ;; Version 4.31
164 ;; - Bug fixes.
166 ;; Version 4.30
167 ;; - Modified installation: Autoloads have been collected in org-install.el.
168 ;; - Logging (org-log-done) is now a #+STARTUP option.
169 ;; - Checkboxes in plain list items, following up on Frank Ruell's idea.
170 ;; - File links inserted with C-c C-l will use relative paths if the linked
171 ;; file is in the current directory or a subdirectory of it.
172 ;; - New variable `org-link-file-path-type' to specify preference for
173 ;; relative and absolute paths.
174 ;; - New CSS classes for tags, timestamps, timestamp keywords.
175 ;; - Bug and typo fixes.
177 ;; Version 4.29
178 ;; - Inlining images in HTML export now depends on wheather the link
179 ;; contains a description or not.
180 ;; - TODO items can be scheduled from the global TODO list using C-c C-s.
181 ;; - TODO items already scheduled can be made to disappear from the global
182 ;; todo list, see `org-agenda-todo-ignore-scheduled'.
183 ;; - In Tables, formulas may also be Lisp forms.
184 ;; - Exporting the visible part of an outline with `C-c C-x v' works now
185 ;; for all available exporters.
186 ;; - Bug fixes, lots of them :-(
188 ;; Version 4.28
189 ;; - Bug fixes.
191 ;; Version 4.27
192 ;; - HTML exporter generalized to receive external options.
193 ;; As part of the process, author, email and date have been moved to the
194 ;; end of the HTML file.
195 ;; - Support for customizable file search in file links.
196 ;; - BibTeX database links as first application of the above.
197 ;; - New option `org-agenda-todo-list-sublevels' to turn off listing TODO
198 ;; entries that are sublevels of another TODO entry.
201 ;;; Code:
203 (eval-when-compile
204 (require 'cl)
205 (require 'calendar))
206 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
207 ;; the file noutline.el being loaded.
208 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
209 ;; We require noutline, which might be provided in outline.el
210 (require 'outline) (require 'noutline)
211 ;; Other stuff we need.
212 (require 'time-date)
213 (require 'easymenu)
215 ;;; Customization variables
217 (defvar org-version "4.44"
218 "The version number of the file org.el.")
219 (defun org-version ()
220 (interactive)
221 (message "Org-mode version %s" org-version))
223 ;; Compatibility constants
224 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
225 (defconst org-format-transports-properties-p
226 (let ((x "a"))
227 (add-text-properties 0 1 '(test t) x)
228 (get-text-property 0 'test (format "%s" x)))
229 "Does format transport text properties?")
231 (defgroup org nil
232 "Outline-based notes management and organizer."
233 :tag "Org"
234 :group 'outlines
235 :group 'hypermedia
236 :group 'calendar)
238 (defgroup org-startup nil
239 "Options concerning startup of Org-mode."
240 :tag "Org Startup"
241 :group 'org)
243 (defcustom org-startup-folded t
244 "Non-nil means, entering Org-mode will switch to OVERVIEW.
245 This can also be configured on a per-file basis by adding one of
246 the following lines anywhere in the buffer:
248 #+STARTUP: fold
249 #+STARTUP: nofold
250 #+STARTUP: content"
251 :group 'org-startup
252 :type '(choice
253 (const :tag "nofold: show all" nil)
254 (const :tag "fold: overview" t)
255 (const :tag "content: all headlines" content)))
257 (defcustom org-startup-truncated t
258 "Non-nil means, entering Org-mode will set `truncate-lines'.
259 This is useful since some lines containing links can be very long and
260 uninteresting. Also tables look terrible when wrapped."
261 :group 'org-startup
262 :type 'boolean)
264 (defcustom org-startup-align-all-tables nil
265 "Non-nil means, align all tables when visiting a file.
266 This is useful when the column width in tables is forced with <N> cookies
267 in table fields. Such tables will look correct only after the first re-align.
268 This can also be configured on a per-file basis by adding one of
269 the following lines anywhere in the buffer:
270 #+STARTUP: align
271 #+STARTUP: noalign"
272 :group 'org-startup
273 :type 'boolean)
275 (defcustom org-startup-with-deadline-check nil
276 "Non-nil means, entering Org-mode will run the deadline check.
277 This means, if you start editing an org file, you will get an
278 immediate reminder of any due deadlines.
279 This can also be configured on a per-file basis by adding one of
280 the following lines anywhere in the buffer:
281 #+STARTUP: dlcheck
282 #+STARTUP: nodlcheck"
283 :group 'org-startup
284 :type 'boolean)
286 (defcustom org-insert-mode-line-in-empty-file nil
287 "Non-nil means insert the first line setting Org-mode in empty files.
288 When the function `org-mode' is called interactively in an empty file, this
289 normally means that the file name does not automatically trigger Org-mode.
290 To ensure that the file will always be in Org-mode in the future, a
291 line enforcing Org-mode will be inserted into the buffer, if this option
292 has been set."
293 :group 'org-startup
294 :type 'boolean)
296 (defcustom org-CUA-compatible nil
297 "Non-nil means use alternative key bindings for S-<cursor movement>.
298 Org-mode used S-<cursor movement> for changing timestamps and priorities.
299 S-<cursor movement> is also used for example by `CUA-mode' to select text.
300 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
301 alternative bindings. Setting this variable to t will replace the following
302 keys both in Org-mode and in the Org-agenda buffer.
304 S-RET -> C-S-RET
305 S-up -> M-p
306 S-down -> M-n
307 S-left -> M--
308 S-right -> M-+
310 If you do not like the alternative keys, take a look at the variable
311 `org-disputed-keys'.
313 This option is only relevant at load-time of Org-mode. Changing it requires
314 a restart of Emacs to become effective."
315 :group 'org-startup
316 :type 'boolean)
318 (defvar org-disputed-keys
319 '((S-up [(shift up)] [(meta ?p)])
320 (S-down [(shift down)] [(meta ?n)])
321 (S-left [(shift left)] [(meta ?-)])
322 (S-right [(shift right)] [(meta ?+)])
323 (S-return [(shift return)] [(control shift return)]))
324 "Keys for which Org-mode and other modes compete.
325 This is an alist, cars are symbols for lookup, 1st element is the default key,
326 second element will be used when `org-CUA-compatible' is t.")
328 (defun org-key (key)
329 "Select a key according to `org-CUA-compatible'."
330 (nth (if org-CUA-compatible 2 1)
331 (or (assq key org-disputed-keys)
332 (error "Invalid Key %s in `org-key'" key))))
334 (defcustom org-ellipsis nil
335 "The ellipsis to use in the Org-mode outline.
336 When nil, just use the standard three dots. When a string, use that instead,
337 and just in Org-mode (which will then use its own display table).
338 Changing this requires executing `M-x org-mode' in a buffer to become
339 effective."
340 :group 'org-startup
341 :type '(choice (const :tag "Default" nil)
342 (string :tag "String" :value "...#")))
344 (defvar org-display-table nil
345 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
347 (defgroup org-keywords nil
348 "Keywords in Org-mode."
349 :tag "Org Keywords"
350 :group 'org)
352 (defcustom org-deadline-string "DEADLINE:"
353 "String to mark deadline entries.
354 A deadline is this string, followed by a time stamp. Should be a word,
355 terminated by a colon. You can insert a schedule keyword and
356 a timestamp with \\[org-deadline].
357 Changes become only effective after restarting Emacs."
358 :group 'org-keywords
359 :type 'string)
361 (defcustom org-scheduled-string "SCHEDULED:"
362 "String to mark scheduled TODO entries.
363 A schedule is this string, followed by a time stamp. Should be a word,
364 terminated by a colon. You can insert a schedule keyword and
365 a timestamp with \\[org-schedule].
366 Changes become only effective after restarting Emacs."
367 :group 'org-keywords
368 :type 'string)
370 (defcustom org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry."
372 :group 'org-keywords
373 :type 'string)
375 (defcustom org-clock-string "CLOCK:"
376 "String used as prefix for timestamps clocking work hours on an item."
377 :group 'org-keywords
378 :type 'string)
380 (defcustom org-comment-string "COMMENT"
381 "Entries starting with this keyword will never be exported.
382 An entry can be toggled between COMMENT and normal with
383 \\[org-toggle-comment].
384 Changes become only effective after restarting Emacs."
385 :group 'org-keywords
386 :type 'string)
388 (defcustom org-quote-string "QUOTE"
389 "Entries starting with this keyword will be exported in fixed-width font.
390 Quoting applies only to the text in the entry following the headline, and does
391 not extend beyond the next headline, even if that is lower level.
392 An entry can be toggled between QUOTE and normal with
393 \\[org-toggle-fixed-width-section]."
394 :group 'org-keywords
395 :type 'string)
397 (defgroup org-structure nil
398 "Options concerning the general structure of Org-mode files."
399 :tag "Org Structure"
400 :group 'org)
402 (defgroup org-cycle nil
403 "Options concerning visibility cycling in Org-mode."
404 :tag "Org Cycle"
405 :group 'org-structure)
407 (defcustom org-cycle-global-at-bob t
408 "Cycle globally if cursor is at beginning of buffer and not at a headline.
409 This makes it possible to do global cycling without having to use S-TAB or
410 C-u TAB. For this special case to work, the first line of the buffer
411 must not be a headline - it may be empty ot some other text. When used in
412 this way, `org-cycle-hook' is disables temporarily, to make sure the
413 cursor stays at the beginning of the buffer.
414 When this option is nil, don't do anything special at the beginning
415 of the buffer."
416 :group 'org-cycle
417 :type 'boolean)
419 (defcustom org-cycle-emulate-tab t
420 "Where should `org-cycle' emulate TAB.
421 nil Never
422 white Only in completely white lines
423 whitestart Only at the beginning of lines, before the first non-white char.
424 t Everywhere except in headlines
425 If TAB is used in a place where it does not emulate TAB, the current subtree
426 visibility is cycled."
427 :group 'org-cycle
428 :type '(choice (const :tag "Never" nil)
429 (const :tag "Only in completely white lines" white)
430 (const :tag "Before first char in a line" whitestart)
431 (const :tag "Everywhere except in headlines" t)
434 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
435 org-optimize-window-after-visibility-change)
436 "Hook that is run after `org-cycle' has changed the buffer visibility.
437 The function(s) in this hook must accept a single argument which indicates
438 the new state that was set by the most recent `org-cycle' command. The
439 argument is a symbol. After a global state change, it can have the values
440 `overview', `content', or `all'. After a local state change, it can have
441 the values `folded', `children', or `subtree'."
442 :group 'org-cycle
443 :type 'hook)
445 (defgroup org-edit-structure nil
446 "Options concerning structure editing in Org-mode."
447 :tag "Org Edit Structure"
448 :group 'org-structure)
450 (defcustom org-odd-levels-only nil
451 "Non-nil means, skip even levels and only use odd levels for the outline.
452 This has the effect that two stars are being added/taken away in
453 promotion/demotion commands. It also influences how levels are
454 handled by the exporters.
455 Changing it requires restart of `font-lock-mode' to become effective
456 for fontification also in regions already fontified.
457 You may also set this on a per-file basis by adding one of the following
458 lines to the buffer:
460 #+STARTUP: odd
461 #+STARTUP: oddeven"
462 :group 'org-edit-structure
463 :group 'org-font-lock
464 :type 'boolean)
466 (defcustom org-adapt-indentation t
467 "Non-nil means, adapt indentation when promoting and demoting.
468 When this is set and the *entire* text in an entry is indented, the
469 indentation is increased by one space in a demotion command, and
470 decreased by one in a promotion command. If any line in the entry
471 body starts at column 0, indentation is not changed at all."
472 :group 'org-edit-structure
473 :type 'boolean)
475 (defcustom org-insert-heading-hook nil
476 "Hook being run after inserting a new heading."
477 :group 'org-edit-structure
478 :type 'boolean)
480 (defcustom org-enable-fixed-width-editor t
481 "Non-nil means, lines starting with \":\" are treated as fixed-width.
482 This currently only means, they are never auto-wrapped.
483 When nil, such lines will be treated like ordinary lines.
484 See also the QUOTE keyword."
485 :group 'org-edit-structure
486 :type 'boolean)
488 (defgroup org-sparse-trees nil
489 "Options concerning sparse trees in Org-mode."
490 :tag "Org Sparse Trees"
491 :group 'org-structure)
493 (defcustom org-highlight-sparse-tree-matches t
494 "Non-nil means, highlight all matches that define a sparse tree.
495 The highlights will automatically disappear the next time the buffer is
496 changed by an edit command."
497 :group 'org-sparse-trees
498 :type 'boolean)
500 (defcustom org-show-hierarchy-above t
501 "Non-nil means, show full hierarchy when showing a spot in the tree.
502 Turning this off makes sparse trees more compact, but also less clear."
503 :group 'org-sparse-trees
504 :type 'boolean)
506 (defcustom org-show-following-heading t
507 "Non-nil means, show heading following match in `org-occur'.
508 When doing an `org-occur' it is useful to show the headline which
509 follows the match, even if they do not match the regexp. This makes it
510 easier to edit directly inside the sparse tree. However, if you use
511 `org-occur' mainly as an overview, the following headlines are
512 unnecessary clutter."
513 :group 'org-sparse-trees
514 :type 'boolean)
516 (defcustom org-occur-hook '(org-first-headline-recenter)
517 "Hook that is run after `org-occur' has constructed a sparse tree.
518 This can be used to recenter the window to show as much of the structure
519 as possible."
520 :group 'org-sparse-trees
521 :type 'hook)
523 (defgroup org-plain-lists nil
524 "Options concerning plain lists in Org-mode."
525 :tag "Org Plain lists"
526 :group 'org-structure)
528 (defcustom org-cycle-include-plain-lists nil
529 "Non-nil means, include plain lists into visibility cycling.
530 This means that during cycling, plain list items will *temporarily* be
531 interpreted as outline headlines with a level given by 1000+i where i is the
532 indentation of the bullet. In all other operations, plain list items are
533 not seen as headlines. For example, you cannot assign a TODO keyword to
534 such an item."
535 :group 'org-plain-lists
536 :type 'boolean)
539 (defcustom org-plain-list-ordered-item-terminator t
540 "The character that makes a line with leading number an ordered list item.
541 Valid values are ?. and ?\). To get both terminators, use t. While
542 ?. may look nicer, it creates the danger that a line with leading
543 number may be incorrectly interpreted as an item. ?\) therefore is
544 the safe choice."
545 :group 'org-plain-lists
546 :type '(choice (const :tag "dot like in \"2.\"" ?.)
547 (const :tag "paren like in \"2)\"" ?\))
548 (const :tab "both" t)))
550 (defcustom org-auto-renumber-ordered-lists t
551 "Non-nil means, automatically renumber ordered plain lists.
552 Renumbering happens when the sequence have been changed with
553 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
554 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
555 :group 'org-plain-lists
556 :type 'boolean)
558 (defgroup org-archive nil
559 "Options concerning archiving in Org-mode."
560 :tag "Org Archive"
561 :group 'org-structure)
563 (defcustom org-archive-tag "ARCHIVE"
564 "The tag that marks a subtree as archived.
565 An archived subtree does not open during visibility cycling, and does
566 not contribute to the agenda listings."
567 :group 'org-archive
568 :group 'org-keywords
569 :type 'string)
571 (defcustom org-agenda-skip-archived-trees t
572 "Non-nil means, the agenda will skip any items located in archived trees.
573 An archived tree is a tree marked with the tag ARCHIVE."
574 :group 'org-archive
575 :group 'org-agenda-display
576 :type 'boolean)
578 (defcustom org-cycle-open-archived-trees nil
579 "Non-nil means, `org-cycle' will open archived trees.
580 An archived tree is a tree marked with the tag ARCHIVE.
581 When nil, archived trees will stay folded. You can still open them with
582 normal outline commands like `show-all', but not with the cycling commands."
583 :group 'org-archive
584 :group 'org-cycle
585 :type 'boolean)
587 (defcustom org-sparse-tree-open-archived-trees nil
588 "Non-nil means sparse tree construction shows matches in archived trees.
589 When nil, matches in these trees are highlighted, but the trees are kept in
590 collapsed state."
591 :group 'org-archive
592 :group 'org-sparse-trees
593 :type 'boolean)
595 (defcustom org-archive-location "%s_archive::"
596 "The location where subtrees should be archived.
597 This string consists of two parts, separated by a double-colon.
599 The first part is a file name - when omitted, archiving happens in the same
600 file. %s will be replaced by the current file name (without directory part).
601 Archiving to a different file is useful to keep archived entries from
602 contributing to the Org-mode Agenda.
604 The part after the double colon is a headline. The archived entries will be
605 filed under that headline. When omitted, the subtrees are simply filed away
606 at the end of the file, as top-level entries.
608 Here are a few examples:
609 \"%s_archive::\"
610 If the current file is Projects.org, archive in file
611 Projects.org_archive, as top-level trees. This is the default.
613 \"::* Archived Tasks\"
614 Archive in the current file, under the top-level headline
615 \"* Archived Tasks\".
617 \"~/org/archive.org::\"
618 Archive in file ~/org/archive.org (absolute path), as top-level trees.
620 \"basement::** Finished Tasks\"
621 Archive in file ./basement (relative path), as level 3 trees
622 below the level 2 heading \"** Finished Tasks\".
624 You may set this option on a per-file basis by adding to the buffer a
625 line like
627 #+ARCHIVE: basement::** Finished Tasks"
628 :group 'org-archive
629 :type 'string)
631 (defcustom org-archive-mark-done t
632 "Non-nil means, mark entries as DONE when they are moved to the archive file."
633 :group 'org-archive
634 :type 'boolean)
636 (defcustom org-archive-stamp-time t
637 "Non-nil means, add a time stamp to entries moved to an archive file.
638 The time stamp will be added directly after the TODO state keyword in the
639 first line, so it is probably best to use this in combinations with
640 `org-archive-mark-done'."
641 :group 'org-archive
642 :type 'boolean)
644 (defgroup org-table nil
645 "Options concerning tables in Org-mode."
646 :tag "Org Table"
647 :group 'org)
649 (defcustom org-enable-table-editor 'optimized
650 "Non-nil means, lines starting with \"|\" are handled by the table editor.
651 When nil, such lines will be treated like ordinary lines.
653 When equal to the symbol `optimized', the table editor will be optimized to
654 do the following:
655 - Use automatic overwrite mode in front of whitespace in table fields.
656 This make the structure of the table stay in tact as long as the edited
657 field does not exceed the column width.
658 - Minimize the number of realigns. Normally, the table is aligned each time
659 TAB or RET are pressed to move to another field. With optimization this
660 happens only if changes to a field might have changed the column width.
661 Optimization requires replacing the functions `self-insert-command',
662 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
663 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
664 very good at guessing when a re-align will be necessary, but you can always
665 force one with \\[org-ctrl-c-ctrl-c].
667 If you would like to use the optimized version in Org-mode, but the
668 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
670 This variable can be used to turn on and off the table editor during a session,
671 but in order to toggle optimization, a restart is required.
673 See also the variable `org-table-auto-blank-field'."
674 :group 'org-table
675 :type '(choice
676 (const :tag "off" nil)
677 (const :tag "on" t)
678 (const :tag "on, optimized" optimized)))
680 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
681 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
682 In the optimized version, the table editor takes over all simple keys that
683 normally just insert a character. In tables, the characters are inserted
684 in a way to minimize disturbing the table structure (i.e. in overwrite mode
685 for empty fields). Outside tables, the correct binding of the keys is
686 restored.
688 The default for this option is t if the optimized version is also used in
689 Org-mode. See the variable `org-enable-table-editor' for details. Changing
690 this variable requires a restart of Emacs to become effective."
691 :group 'org-table
692 :type 'boolean)
694 (defgroup org-table-settings nil
695 "Settings for tables in Org-mode."
696 :tag "Org Table Settings"
697 :group 'org-table)
699 (defcustom org-table-default-size "5x2"
700 "The default size for newly created tables, Columns x Rows."
701 :group 'org-table-settings
702 :type 'string)
704 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
705 "Regular expression for recognizing numbers in table columns.
706 If a table column contains mostly numbers, it will be aligned to the
707 right. If not, it will be aligned to the left.
709 The default value of this option is a regular expression which allows
710 anything which looks remotely like a number as used in scientific
711 context. For example, all of the following will be considered a
712 number:
713 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
715 Other options offered by the customize interface are more restrictive."
716 :group 'org-table-settings
717 :type '(choice
718 (const :tag "Positive Integers"
719 "^[0-9]+$")
720 (const :tag "Integers"
721 "^[-+]?[0-9]+$")
722 (const :tag "Floating Point Numbers"
723 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
724 (const :tag "Floating Point Number or Integer"
725 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
726 (const :tag "Exponential, Floating point, Integer"
727 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
728 (const :tag "Very General Number-Like"
729 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
730 (string :tag "Regexp:")))
732 (defcustom org-table-number-fraction 0.5
733 "Fraction of numbers in a column required to make the column align right.
734 In a column all non-white fields are considered. If at least this
735 fraction of fields is matched by `org-table-number-fraction',
736 alignment to the right border applies."
737 :group 'org-table-settings
738 :type 'number)
740 (defgroup org-table-editing nil
741 "Bahavior of tables during editing in Org-mode."
742 :tag "Org Table Editing"
743 :group 'org-table)
745 (defcustom org-table-automatic-realign t
746 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
747 When nil, aligning is only done with \\[org-table-align], or after column
748 removal/insertion."
749 :group 'org-table-editing
750 :type 'boolean)
752 (defcustom org-table-limit-column-width t ;kw
753 "Non-nil means, allow to limit the width of table columns with <N> fields."
754 :group 'org-table-editing
755 :type 'boolean)
757 (defcustom org-table-auto-blank-field t
758 "Non-nil means, automatically blank table field when starting to type into it.
759 This only happens when typing immediately after a field motion
760 command (TAB, S-TAB or RET).
761 Only relevant when `org-enable-table-editor' is equal to `optimized'."
762 :group 'org-table-editing
763 :type 'boolean)
765 (defcustom org-table-tab-jumps-over-hlines t
766 "Non-nil means, tab in the last column of a table with jump over a hline.
767 If a horizontal separator line is following the current line,
768 `org-table-next-field' can either create a new row before that line, or jump
769 over the line. When this option is nil, a new line will be created before
770 this line."
771 :group 'org-table-editing
772 :type 'boolean)
774 (defcustom org-table-tab-recognizes-table.el t
775 "Non-nil means, TAB will automatically notice a table.el table.
776 When it sees such a table, it moves point into it and - if necessary -
777 calls `table-recognize-table'."
778 :group 'org-table-editing
779 :type 'boolean)
781 (defgroup org-table-calculation nil
782 "Options concerning tables in Org-mode."
783 :tag "Org Table Calculation"
784 :group 'org-table)
786 (defcustom org-table-copy-increment t
787 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
788 :group 'org-table-calculation
789 :type 'boolean)
791 (defcustom org-calc-default-modes
792 '(calc-internal-prec 12
793 calc-float-format (float 5)
794 calc-angle-mode deg
795 calc-prefer-frac nil
796 calc-symbolic-mode nil
797 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
798 calc-display-working-message t
800 "List with Calc mode settings for use in calc-eval for table formulas.
801 The list must contain alternating symbols (Calc modes variables and values).
802 Don't remove any of the default settings, just change the values. Org-mode
803 relies on the variables to be present in the list."
804 :group 'org-table-calculation
805 :type 'plist)
807 (defcustom org-table-formula-evaluate-inline t
808 "Non-nil means, TAB and RET evaluate a formula in current table field.
809 If the current field starts with an equal sign, it is assumed to be a formula
810 which should be evaluated as described in the manual and in the documentation
811 string of the command `org-table-eval-formula'. This feature requires the
812 Emacs calc package.
813 When this variable is nil, formula calculation is only available through
814 the command \\[org-table-eval-formula]."
815 :group 'org-table-calculation
816 :type 'boolean)
819 (defcustom org-table-formula-use-constants t
820 "Non-nil means, interpret constants in formulas in tables.
821 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
822 by the value given in `org-table-formula-constants', or by a value obtained
823 from the `constants.el' package."
824 :group 'org-table-calculation
825 :type 'boolean)
827 (defcustom org-table-formula-constants nil
828 "Alist with constant names and values, for use in table formulas.
829 The car of each element is a name of a constant, without the `$' before it.
830 The cdr is the value as a string. For example, if you'd like to use the
831 speed of light in a formula, you would configure
833 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
835 and then use it in an equation like `$1*$c'."
836 :group 'org-table-calculation
837 :type '(repeat
838 (cons (string :tag "name")
839 (string :tag "value"))))
841 (defcustom org-table-formula-numbers-only nil
842 "Non-nil means, calculate only with numbers in table formulas.
843 Then all input fields will be converted to a number, and the result
844 must also be a number. When nil, calc's full potential is available
845 in table calculations, including symbolics etc."
846 :group 'org-table-calculation
847 :type 'boolean)
849 (defcustom org-table-allow-automatic-line-recalculation t
850 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
851 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
852 :group 'org-table-calculation
853 :type 'boolean)
855 (defgroup org-link nil
856 "Options concerning links in Org-mode."
857 :tag "Org Link"
858 :group 'org)
860 (defcustom org-descriptive-links t
861 "Non-nil means, hide link part and only show description of bracket links.
862 Bracket links are like [[link][descritpion]]. This variable sets the initial
863 state in new org-mode buffers. The setting can then be toggled on a
864 per-buffer basis from the Org->Hyperlinks menu."
865 :group 'org-link
866 :type 'boolean)
868 (defcustom org-link-style 'bracket
869 "The style of links to be inserted with \\[org-insert-link].
870 Possible values are:
871 bracket [[link][description]]. This is recommended
872 plain Description \\n link. The old way, no longer recommended."
873 :group 'org-link
874 :type '(choice
875 (const :tag "Bracket (recommended)" bracket)
876 (const :tag "Plain (no longer recommended)" plain)))
878 (defcustom org-link-format "%s"
879 "Default format for external, URL-like linkes in the buffer.
880 This is a format string for printf, %s will be replaced by the link text.
881 The recommended value is just \"%s\", since links will be protected by
882 enclosing them in double brackets. If you prefer plain links (see variable
883 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
884 additional URL: prefix, so the format would be \"<URL:%s>\"."
885 :group 'org-link
886 :type '(choice
887 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
888 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
889 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
890 (string :tag "Other" :value "<%s>")))
892 (defcustom org-link-file-path-type 'adaptive
893 "How the path name in file links should be stored.
894 Valid values are:
896 relative relative to the current directory, i.e. the directory of the file
897 into which the link is being inserted.
898 absolute absolute path, if possible with ~ for home directory.
899 noabbrev absolute path, no abbreviation of home directory.
900 adaptive Use relative path for files in the current directory and sub-
901 directories of it. For other files, use an absolute path."
902 :group 'org-link
903 :type '(choice
904 (const relative)
905 (const absolute)
906 (const noabbrev)
907 (const adaptive)))
909 (defcustom org-activate-links '(bracket angle plain radio tag date)
910 "Types of links that should be activated in Org-mode files.
911 This is a list of symbols, each leading to the activation of a certain link
912 type. In principle, it does not hurt to turn on most link types - there may
913 be a small gain when turning off unused link types. The types are:
915 bracket The recommended [[link][description]] or [[link]] links with hiding.
916 angular Links in angular brackes that may contain whitespace like
917 <bbdb:Carsten Dominik>.
918 plain Plain links in normal text, no whitespace, like http://google.com.
919 radio Text that is matched by a radio target, see manual for details.
920 tag Tag settings in a headline (link to tag search).
921 date Time stamps (link to calendar).
922 camel CamelCase words defining text searches.
924 Changing this variable requires a restart of Emacs to become effective."
925 :group 'org-link
926 :type '(set (const :tag "Double bracket links (new style)" bracket)
927 (const :tag "Angular bracket links (old style)" angular)
928 (const :tag "plain text links" plain)
929 (const :tag "Radio target matches" radio)
930 (const :tag "Tags" tag)
931 (const :tag "Timestamps" date)
932 (const :tag "CamelCase words" camel)))
934 (defgroup org-link-store nil
935 "Options concerning storing links in Org-mode"
936 :tag "Org Store Link"
937 :group 'org-link)
939 (defcustom org-context-in-file-links t
940 "Non-nil means, file links from `org-store-link' contain context.
941 A search string will be added to the file name with :: as separator and
942 used to find the context when the link is activated by the command
943 `org-open-at-point'.
944 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
945 negates this setting for the duration of the command."
946 :group 'org-link-store
947 :type 'boolean)
949 (defcustom org-file-link-context-use-camel-case nil
950 "Non-nil means, use CamelCase to store a search context in a file link.
951 When nil, the search string simply consists of the words of the string.
952 CamelCase is deprecated, and support for it may be dropped in the future."
953 :group 'org-link-store
954 :type 'boolean)
956 (defcustom org-keep-stored-link-after-insertion nil
957 "Non-nil means, keep link in list for entire session.
959 The command `org-store-link' adds a link pointing to the current
960 location to an internal list. These links accumulate during a session.
961 The command `org-insert-link' can be used to insert links into any
962 Org-mode file (offering completion for all stored links). When this
963 option is nil, every link which has been inserted once using \\[org-insert-link]
964 will be removed from the list, to make completing the unused links
965 more efficient."
966 :group 'org-link-store
967 :type 'boolean)
969 (defcustom org-usenet-links-prefer-google nil
970 "Non-nil means, `org-store-link' will create web links to Google groups.
971 When nil, Gnus will be used for such links.
972 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
973 negates this setting for the duration of the command."
974 :group 'org-link-store
975 :type 'boolean)
977 (defgroup org-link-follow nil
978 "Options concerning following links in Org-mode"
979 :tag "Org Follow Link"
980 :group 'org-link)
982 (defcustom org-tab-follows-link nil
983 "Non-nil means, on links TAB will follow the link.
984 Needs to be set before org.el is loaded."
985 :group 'org-link-follow
986 :type 'boolean)
988 (defcustom org-return-follows-link nil
989 "Non-nil means, on links RET will follow the link.
990 Needs to be set before org.el is loaded."
991 :group 'org-link-follow
992 :type 'boolean)
994 (defcustom org-mouse-1-follows-link t
995 "Non-nil means, mouse-1 on a link will follow the link.
996 A longer mouse click will still set point. Does not wortk on XEmacs.
997 Needs to be set before org.el is loaded."
998 :group 'org-link-follow
999 :type 'boolean)
1001 (defcustom org-mark-ring-length 4
1002 "Number of different positions to be recorded in the ring
1003 Changing this requires a restart of Emacs to work correctly."
1004 :group 'org-link-follow
1005 :type 'interger)
1007 (defcustom org-link-frame-setup
1008 '((vm . vm-visit-folder-other-frame)
1009 (gnus . gnus-other-frame)
1010 (file . find-file-other-window))
1011 "Setup the frame configuration for following links.
1012 When following a link with Emacs, it may often be useful to display
1013 this link in another window or frame. This variable can be used to
1014 set this up for the different types of links.
1015 For VM, use any of
1016 `vm-visit-folder'
1017 `vm-visit-folder-other-frame'
1018 For Gnus, use any of
1019 `gnus'
1020 `gnus-other-frame'
1021 For FILE, use any of
1022 `find-file'
1023 `find-file-other-window'
1024 `find-file-other-frame'
1025 For the calendar, use the variable `calendar-setup'.
1026 For BBDB, it is currently only possible to display the matches in
1027 another window."
1028 :group 'org-link-follow
1029 :type '(list
1030 (cons (const vm)
1031 (choice
1032 (const vm-visit-folder)
1033 (const vm-visit-folder-other-window)
1034 (const vm-visit-folder-other-frame)))
1035 (cons (const gnus)
1036 (choice
1037 (const gnus)
1038 (const gnus-other-frame)))
1039 (cons (const file)
1040 (choice
1041 (const find-file)
1042 (const find-file-other-window)
1043 (const find-file-other-frame)))))
1045 (defcustom org-open-non-existing-files nil
1046 "Non-nil means, `org-open-file' will open non-existing file.
1047 When nil, an error will be generated."
1048 :group 'org-link-follow
1049 :type 'boolean)
1051 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1052 "Non-nil means, ask for confirmation before executing shell links.
1053 Shell links can be dangerous, just thing about a link
1055 [[shell:rm -rf ~/*][Google Search]]
1057 This link would show up in your Org-mode document as \"Google Search\"
1058 but really it would remove your entire home directory.
1059 Therefore I *definitely* advise against setting this variable to nil.
1060 Just change it to `y-or-n-p' of you want to confirm with a single key press
1061 rather than having to type \"yes\"."
1062 :group 'org-link-follow
1063 :type '(choice
1064 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1065 (const :tag "with y-or-n (faster)" y-or-n-p)
1066 (const :tag "no confirmation (dangerous)" nil)))
1068 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1069 "Non-nil means, ask for confirmation before executing elisp links.
1070 Elisp links can be dangerous, just thing about a link
1072 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1074 This link would show up in your Org-mode document as \"Google Search\"
1075 but really it would remove your entire home directory.
1076 Therefore I *definitely* advise against setting this variable to nil.
1077 Just change it to `y-or-n-p' of you want to confirm with a single key press
1078 rather than having to type \"yes\"."
1079 :group 'org-link-follow
1080 :type '(choice
1081 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1082 (const :tag "with y-or-n (faster)" y-or-n-p)
1083 (const :tag "no confirmation (dangerous)" nil)))
1085 (defconst org-file-apps-defaults-gnu
1086 '((remote . emacs)
1087 (t . mailcap))
1088 "Default file applications on a UNIX or GNU/Linux system.
1089 See `org-file-apps'.")
1091 (defconst org-file-apps-defaults-macosx
1092 '((remote . emacs)
1093 (t . "open %s")
1094 ("ps" . "gv %s")
1095 ("ps.gz" . "gv %s")
1096 ("eps" . "gv %s")
1097 ("eps.gz" . "gv %s")
1098 ("dvi" . "xdvi %s")
1099 ("fig" . "xfig %s"))
1100 "Default file applications on a MacOS X system.
1101 The system \"open\" is known as a default, but we use X11 applications
1102 for some files for which the OS does not have a good default.
1103 See `org-file-apps'.")
1105 (defconst org-file-apps-defaults-windowsnt
1106 (list
1107 '(remote . emacs)
1108 (cons t
1109 (list (if (featurep 'xemacs)
1110 'mswindows-shell-execute
1111 'w32-shell-execute)
1112 "open" 'file)))
1113 "Default file applications on a Windows NT system.
1114 The system \"open\" is used for most files.
1115 See `org-file-apps'.")
1117 (defcustom org-file-apps
1119 ("txt" . emacs)
1120 ("tex" . emacs)
1121 ("ltx" . emacs)
1122 ("org" . emacs)
1123 ("el" . emacs)
1124 ("bib" . emacs)
1126 "External applications for opening `file:path' items in a document.
1127 Org-mode uses system defaults for different file types, but
1128 you can use this variable to set the application for a given file
1129 extension. The entries in this list are cons cells where the car identifies
1130 files and the cdr the corresponding command. Possible values for the
1131 file identifier are
1132 \"ext\" A string identifying an extension
1133 `directory' Matches a directory
1134 `remote' Matches a remote file, accessible through tramp or efs.
1135 Remote files most likely should be visited through emacs
1136 because external applications cannot handle such paths.
1137 t Default for all remaining files
1139 Possible values for the command are:
1140 `emacs' The file will be visited by the current Emacs process.
1141 `default' Use the default application for this file type.
1142 string A command to be executed by a shell; %s will be replaced
1143 by the path to the file.
1144 sexp A Lisp form which will be evaluated. The file path will
1145 be available in the Lisp variable `file'.
1146 For more examples, see the system specific constants
1147 `org-file-apps-defaults-macosx'
1148 `org-file-apps-defaults-windowsnt'
1149 `org-file-apps-defaults-gnu'."
1150 :group 'org-link-follow
1151 :type '(repeat
1152 (cons (choice :value ""
1153 (string :tag "Extension")
1154 (const :tag "Default for unrecognized files" t)
1155 (const :tag "Remote file" remote)
1156 (const :tag "Links to a directory" directory))
1157 (choice :value ""
1158 (const :tag "Visit with Emacs" emacs)
1159 (const :tag "Use system default" default)
1160 (string :tag "Command")
1161 (sexp :tag "Lisp form")))))
1163 (defcustom org-mhe-search-all-folders nil
1164 "Non-nil means, that the search for the mh-message will be extended to
1165 all folders if the message cannot be found in the folder given in the link.
1166 Searching all folders is very effective with one of the search engines
1167 supported by MH-E, but will be slow with pick."
1168 :group 'org-link-follow
1169 :type 'boolean)
1171 (defgroup org-remember nil
1172 "Options concerning interaction with remember.el."
1173 :tag "Org Remember"
1174 :group 'org)
1176 (defcustom org-directory "~/org"
1177 "Directory with org files.
1178 This directory will be used as default to prompt for org files.
1179 Used by the hooks for remember.el."
1180 :group 'org-remember
1181 :type 'directory)
1183 (defcustom org-default-notes-file "~/.notes"
1184 "Default target for storing notes.
1185 Used by the hooks for remember.el. This can be a string, or nil to mean
1186 the value of `remember-data-file'."
1187 :group 'org-remember
1188 :type '(choice
1189 (const :tag "Default from remember-data-file" nil)
1190 file))
1192 (defcustom org-remember-templates nil
1193 "Templates for the creation of remember buffers.
1194 When nil, just let remember make the buffer.
1195 When not nil, this is a list of 3-element lists. In each entry, the first
1196 element is a character, a unique key to select this template.
1197 The second element is the template. The third element is optional and can
1198 specify a destination file for remember items created with this template.
1199 The default file is given by `org-default-notes-file'.
1201 The template specifies the structure of the remember buffer. It should have
1202 a first line starting with a star, to act as the org-mode headline.
1203 Furthermore, the following %-escapes will be replaced with content:
1204 %t time stamp, date only
1205 %T time stamp with date and time
1206 %u inactive time stamp, date only
1207 %U inactive time stamp with date and time
1208 %n user name
1209 %a annotation, normally the link created with org-store-link
1210 %i initial content, the region when remember is called with C-u.
1211 If %i is indented, the entire inserted text will be indented as well.
1212 %? This will be removed, and the cursor placed at this position."
1213 :group 'org-remember
1214 :type '(repeat :tag "enabled"
1215 (list :value (?a "\n" nil)
1216 (character :tag "Selection Key")
1217 (string :tag "Template")
1218 (file :tag "Destination file (optional)"))))
1220 (defcustom org-reverse-note-order nil
1221 "Non-nil means, store new notes at the beginning of a file or entry.
1222 When nil, new notes will be filed to the end of a file or entry."
1223 :group 'org-remember
1224 :type '(choice
1225 (const :tag "Reverse always" t)
1226 (const :tag "Reverse never" nil)
1227 (repeat :tag "By file name regexp"
1228 (cons regexp boolean))))
1230 (defgroup org-todo nil
1231 "Options concerning TODO items in Org-mode."
1232 :tag "Org TODO"
1233 :group 'org)
1235 (defcustom org-todo-keywords '("TODO" "DONE")
1236 "List of TODO entry keywords.
1237 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1238 considered to mean that the entry is \"done\". All the other mean that
1239 action is required, and will make the entry show up in todo lists, diaries
1240 etc.
1241 The command \\[org-todo] cycles an entry through these states, and an
1242 additional state where no keyword is present. For details about this
1243 cycling, see also the variable `org-todo-interpretation'
1244 Changes become only effective after restarting Emacs."
1245 :group 'org-todo
1246 :group 'org-keywords
1247 :type '(repeat (string :tag "Keyword")))
1249 (defcustom org-todo-interpretation 'sequence
1250 "Controls how TODO keywords are interpreted.
1251 This variable is only relevant if `org-todo-keywords' contains more than two
1252 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1254 When `sequence', \\[org-todo] will always switch to the next state in the
1255 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1256 to state when executed several times in direct succession. Otherwise, it
1257 switches directly to DONE from any state.
1258 See the manual for more information."
1259 :group 'org-todo
1260 :group 'org-keywords
1261 :type '(choice (const sequence)
1262 (const type)))
1264 (defcustom org-after-todo-state-change-hook nil
1265 "Hook which is run after the state of a TODO item was changed.
1266 The new state (a string with a TODO keyword, or nil) is available in the
1267 Lisp variable `state'."
1268 :group 'org-todo
1269 :type 'hook)
1271 (defcustom org-log-done nil
1272 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1273 When the state of an entry is changed from nothing to TODO, remove a previous
1274 closing date.
1275 This can also be configured on a per-file basis by adding one of
1276 the following lines anywhere in the buffer:
1278 #+STARTUP: logging
1279 #+STARTUP: nologging"
1280 :group 'org-todo
1281 :type 'boolean)
1283 (defgroup org-priorities nil
1284 "Priorities in Org-mode."
1285 :tag "Org Priorities"
1286 :group 'org-todo)
1288 (defcustom org-default-priority ?B
1289 "The default priority of TODO items.
1290 This is the priority an item get if no explicit priority is given."
1291 :group 'org-priorities
1292 :type 'character)
1294 (defcustom org-lowest-priority ?C
1295 "The lowest priority of TODO items. A character like ?A, ?B etc."
1296 :group 'org-priorities
1297 :type 'character)
1299 (defgroup org-time nil
1300 "Options concerning time stamps and deadlines in Org-mode."
1301 :tag "Org Time"
1302 :group 'org)
1304 (defcustom org-insert-labeled-timestamps-at-point nil
1305 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1306 When nil, these labeled time stamps are forces into the second line of an
1307 entry, just after the headline. When scheduling from the global TODO list,
1308 the time stamp will always be forced into the second line."
1309 :group 'org-time
1310 :type 'boolean)
1312 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1313 "Formats for `format-time-string' which are used for time stamps.
1314 It is not recommended to change this constant.")
1316 (defcustom org-time-stamp-rounding-minutes 0
1317 "Number of minutes to round time stamps to upon insertion.
1318 When zero, insert the time unmodified. Useful rounding numbers
1319 should be factors of 60, so for example 5, 10, 15.
1320 When this is not zero, you can still force an exact time-stamp by using
1321 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1322 :group 'org-time
1323 :type 'integer)
1325 (defcustom org-deadline-warning-days 30
1326 "No. of days before expiration during which a deadline becomes active.
1327 This variable governs the display in the org file."
1328 :group 'org-time
1329 :type 'number)
1331 (defcustom org-popup-calendar-for-date-prompt t
1332 "Non-nil means, pop up a calendar when prompting for a date.
1333 In the calendar, the date can be selected with mouse-1. However, the
1334 minibuffer will also be active, and you can simply enter the date as well.
1335 When nil, only the minibuffer will be available."
1336 :group 'org-time
1337 :type 'boolean)
1339 (defcustom org-calendar-follow-timestamp-change t
1340 "Non-nil means, make the calendar window follow timestamp changes.
1341 When a timestamp is modified and the calendar window is visible, it will be
1342 moved to the new date."
1343 :group 'org-time
1344 :type 'boolean)
1346 (defgroup org-tags nil
1347 "Options concerning tags in Org-mode."
1348 :tag "Org Tags"
1349 :group 'org)
1351 (defcustom org-tag-alist nil
1352 "List of tags allowed in Org-mode files.
1353 When this list is nil, Org-mode will base TAG input on what is already in the
1354 buffer.
1355 The value of this variable is an alist, the car may be (and should) be a
1356 character that is used to select that tag through the fast-tag-selection
1357 interface. See the manual for details."
1358 :group 'org-tags
1359 :type '(repeat
1360 (choice
1361 (cons (string :tag "Tag name")
1362 (character :tag "Access char"))
1363 (const :tag "Start radio group" (:startgroup))
1364 (const :tag "End radio group" (:endgroup)))))
1366 (defcustom org-use-fast-tag-selection 'auto
1367 "Non-nil means, use fast tag selection scheme.
1368 This is a special interface to select and deselect tags with single keys.
1369 When nil, fast selection is never used.
1370 When the symbol `auto', fast selection is used if and only if selection
1371 characters for tags have been configured, either through the variable
1372 `org-tag-alist' or through a #+TAGS line in the buffer.
1373 When t, fast selection is always used and selection keys are assigned
1374 automatically if necessary."
1375 :group 'org-tags
1376 :type '(choice
1377 (const :tag "Always" t)
1378 (const :tag "Never" nil)
1379 (const :tag "When selection characters are configured" 'auto)))
1381 (defcustom org-tags-column 48
1382 "The column to which tags should be indented in a headline.
1383 If this number is positive, it specifies the column. If it is negative,
1384 it means that the tags should be flushright to that column. For example,
1385 -79 works well for a normal 80 character screen."
1386 :group 'org-tags
1387 :type 'integer)
1389 (defcustom org-auto-align-tags t
1390 "Non-nil means, realign tags after pro/demotion of TODO state change.
1391 These operations change the length of a headline and therefore shift
1392 the tags around. With this options turned on, after each such operation
1393 the tags are again aligned to `org-tags-column'."
1394 :group 'org-tags
1395 :type 'boolean)
1397 (defcustom org-use-tag-inheritance t
1398 "Non-nil means, tags in levels apply also for sublevels.
1399 When nil, only the tags directly given in a specific line apply there.
1400 If you turn off this option, you very likely want to turn on the
1401 companion option `org-tags-match-list-sublevels'."
1402 :group 'org-tags
1403 :type 'boolean)
1405 (defcustom org-tags-match-list-sublevels nil
1406 "Non-nil means list also sublevels of headlines matching tag search.
1407 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1408 the sublevels of a headline matching a tag search often also match
1409 the same search. Listing all of them can create very long lists.
1410 Setting this variable to nil causes subtrees of a match to be skipped.
1411 This option is off by default, because inheritance in on. If you turn
1412 inheritance off, you very likely want to turn this option on.
1414 As a special case, if the tag search is restricted to TODO items, the
1415 value of this variable is ignored and sublevels are always checked, to
1416 make sure all corresponding TODO items find their way into the list."
1417 :group 'org-tags
1418 :type 'boolean)
1420 (defvar org-tags-history nil
1421 "History of minibuffer reads for tags.")
1422 (defvar org-last-tags-completion-table nil
1423 "The last used completion table for tags.")
1425 (defgroup org-agenda nil
1426 "Options concerning agenda display Org-mode."
1427 :tag "Org Agenda"
1428 :group 'org)
1430 (defvar org-category nil
1431 "Variable used by org files to set a category for agenda display.
1432 Such files should use a file variable to set it, for example
1434 -*- mode: org; org-category: \"ELisp\"
1436 or contain a special line
1438 #+CATEGORY: ELisp
1440 If the file does not specify a category, then file's base name
1441 is used instead.")
1442 (make-variable-buffer-local 'org-category)
1444 (defcustom org-agenda-files nil
1445 "The files to be used for agenda display.
1446 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1447 \\[org-remove-file]. You can also use customize to edit the list.
1449 If the value of the variable is not a list but a single file name, then
1450 the list of agenda files is actually stored and maintained in that file, one
1451 agenda file per line."
1452 :group 'org-agenda
1453 :type '(choice
1454 (repeat :tag "List of files" file)
1455 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1457 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1458 "Custom commands for the agenda.
1459 These commands will be offered on the splash screen displayed by the
1460 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1462 key The key (a single char as a string) to be associated with the command.
1463 type The command type, any of the following symbols:
1464 todo Entries with a specific TODO keyword, in all agenda files.
1465 tags Tags match in all agenda files.
1466 tags-todo Tags match in all agenda files, TODO entries only.
1467 todo-tree Sparse tree of specific TODO keyword in *current* file.
1468 tags-tree Sparse tree with all tags matches in *current* file.
1469 occur-tree Occur sparse tree for current file.
1470 match What to search for:
1471 - a single keyword for TODO keyword searches
1472 - a tags match expression for tags searches
1473 - a regular expression for occur searches"
1474 :group 'org-agenda
1475 :type '(repeat
1476 (list (string :tag "Key")
1477 (choice :tag "Type"
1478 (const :tag "Tags search in all agenda files" tags)
1479 (const :tag "Tags search of TODO entries, all agenda files" tags-todo)
1480 (const :tag "TODO keyword search in all agenda files" todo)
1481 (const :tag "Tags sparse tree in current buffer" tags-tree)
1482 (const :tag "TODO keyword tree in current buffer" todo-tree)
1483 (const :tag "Occur tree in current buffer" occur-tree))
1484 (string :tag "Match"))))
1486 (defcustom org-agenda-todo-list-sublevels t
1487 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1488 When nil, the sublevels of a TODO entry are not checked, resulting in
1489 potentially much shorter TODO lists."
1490 :group 'org-agenda
1491 :group 'org-todo
1492 :type 'boolean)
1494 (defcustom org-agenda-todo-ignore-scheduled nil
1495 "Non-nil means, don't show scheduled entries in the global todo list.
1496 The idea behind this is that by scheduling it, you have already taken care
1497 of this item."
1498 :group 'org-agenda
1499 :group 'org-todo
1500 :type 'boolean)
1502 (defcustom org-agenda-include-all-todo nil
1503 "Non-nil means, the agenda will always contain all TODO entries.
1504 When nil, date-less entries will only be shown if `org-agenda' is called
1505 with a prefix argument.
1506 When non-nil, the TODO entries will be listed at the top of the agenda, before
1507 the entries for specific days."
1508 :group 'org-agenda
1509 :type 'boolean)
1511 (defcustom org-agenda-include-diary nil
1512 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1513 :group 'org-agenda
1514 :type 'boolean)
1516 (defcustom org-calendar-to-agenda-key [?c]
1517 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1518 The command `org-calendar-goto-agenda' will be bound to this key. The
1519 default is the character `c' because then `c' can be used to switch back and
1520 forth between agenda and calendar."
1521 :group 'org-agenda
1522 :type 'sexp)
1524 (defgroup org-agenda-setup nil
1525 "Options concerning setting up the Agenda window in Org Mode."
1526 :tag "Org Agenda Window Setup"
1527 :group 'org-agenda)
1529 (defcustom org-agenda-mouse-1-follows-link nil
1530 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1531 A longer mouse click will still set point. Does not wortk on XEmacs.
1532 Needs to be set before org.el is loaded."
1533 :group 'org-agenda-setup
1534 :type 'boolean)
1536 (defcustom org-agenda-start-with-follow-mode nil
1537 "The initial value of follwo-mode in a newly created agenda window."
1538 :group 'org-agenda-setup
1539 :type 'boolean)
1541 (defcustom org-select-agenda-window t
1542 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1543 When nil, cursor will remain in the current window."
1544 :group 'org-agenda-setup
1545 :type 'boolean)
1547 (defcustom org-fit-agenda-window t
1548 "Non-nil means, change window size of agenda to fit content."
1549 :group 'org-agenda-setup
1550 :type 'boolean)
1552 (defgroup org-agenda-display nil
1553 "Options concerning what to display initially in Agenda."
1554 :tag "Org Agenda Display"
1555 :group 'org-agenda)
1557 (defcustom org-agenda-show-all-dates t
1558 "Non-nil means, `org-agenda' shows every day in the selected range.
1559 When nil, only the days which actually have entries are shown."
1560 :group 'org-agenda-display
1561 :type 'boolean)
1563 (defcustom org-agenda-start-on-weekday 1
1564 "Non-nil means, start the overview always on the specified weekday.
1565 0 denotes Sunday, 1 denotes Monday etc.
1566 When nil, always start on the current day."
1567 :group 'org-agenda-display
1568 :type '(choice (const :tag "Today" nil)
1569 (number :tag "Weekday No.")))
1571 (defcustom org-agenda-ndays 7
1572 "Number of days to include in overview display.
1573 Should be 1 or 7."
1574 :group 'org-agenda-display
1575 :type 'number)
1577 (defcustom org-agenda-use-time-grid t
1578 "Non-nil means, show a time grid in the agenda schedule.
1579 A time grid is a set of lines for specific times (like every two hours between
1580 8:00 and 20:00). The items scheduled for a day at specific times are
1581 sorted in between these lines.
1582 For details about when the grid will be shown, and what it will look like, see
1583 the variable `org-agenda-time-grid'."
1584 :group 'org-agenda-display
1585 :type 'boolean)
1587 (defcustom org-agenda-time-grid
1588 '((daily today require-timed)
1589 "----------------"
1590 (800 1000 1200 1400 1600 1800 2000))
1592 "The settings for time grid for agenda display.
1593 This is a list of three items. The first item is again a list. It contains
1594 symbols specifying conditions when the grid should be displayed:
1596 daily if the agenda shows a single day
1597 weekly if the agenda shows an entire week
1598 today show grid on current date, independent of daily/weekly display
1599 require-timed show grid only if at least on item has a time specification
1601 The second item is a string which will be places behing the grid time.
1603 The third item is a list of integers, indicating the times that should have
1604 a grid line."
1605 :group 'org-agenda-display
1606 :type
1607 '(list
1608 (set :greedy t :tag "Grid Display Options"
1609 (const :tag "Show grid in single day agenda display" daily)
1610 (const :tag "Show grid in weekly agenda display" weekly)
1611 (const :tag "Always show grid for today" today)
1612 (const :tag "Show grid only if any timed entries are present"
1613 require-timed)
1614 (const :tag "Skip grid times already present in an entry"
1615 remove-match))
1616 (string :tag "Grid String")
1617 (repeat :tag "Grid Times" (integer :tag "Time"))))
1619 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1620 "Sorting structure for the agenda items of a single day.
1621 This is a list of symbols which will be used in sequence to determine
1622 if an entry should be listed before another entry. The following
1623 symbols are recognized:
1625 time-up Put entries with time-of-day indications first, early first
1626 time-down Put entries with time-of-day indications first, late first
1627 category-keep Keep the default order of categories, corresponding to the
1628 sequence in `org-agenda-files'.
1629 category-up Sort alphabetically by category, A-Z.
1630 category-down Sort alphabetically by category, Z-A.
1631 priority-up Sort numerically by priority, high priority last.
1632 priority-down Sort numerically by priority, high priority first.
1634 The different possibilities will be tried in sequence, and testing stops
1635 if one comparison returns a \"not-equal\". For example, the default
1636 '(time-up category-keep priority-down)
1637 means: Pull out all entries having a specified time of day and sort them,
1638 in order to make a time schedule for the current day the first thing in the
1639 agenda listing for the day. Of the entries without a time indication, keep
1640 the grouped in categories, don't sort the categories, but keep them in
1641 the sequence given in `org-agenda-files'. Within each category sort by
1642 priority.
1644 Leaving out `category-keep' would mean that items will be sorted across
1645 categories by priority."
1646 :group 'org-agenda-display
1647 :type '(repeat
1648 (choice
1649 (const time-up)
1650 (const time-down)
1651 (const category-keep)
1652 (const category-up)
1653 (const category-down)
1654 (const priority-up)
1655 (const priority-down))))
1657 (defcustom org-sort-agenda-notime-is-late t
1658 "Non-nil means, items without time are considered late.
1659 This is only relevant for sorting. When t, items which have no explicit
1660 time like 15:30 will be considered as 99:01, i.e. later than any items which
1661 do have a time. When nil, the default time is before 0:00. You can use this
1662 option to decide if the schedule for today should come before or after timeless
1663 agenda entries."
1664 :group 'org-agenda-display
1665 :type 'boolean)
1668 (defgroup org-agenda-prefix nil
1669 "Options concerning the entry prefix in the Org-mode agenda display."
1670 :tag "Org Agenda Prefix"
1671 :group 'org-agenda)
1673 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1674 "Format specification for the prefix of items in the agenda buffer.
1675 This format works similar to a printf format, with the following meaning:
1677 %c the category of the item, \"Diary\" for entries from the diary, or
1678 as given by the CATEGORY keyword or derived from the file name.
1679 %T the first tag of the item.
1680 %t the time-of-day specification if one applies to the entry, in the
1681 format HH:MM
1682 %s Scheduling/Deadline information, a short string
1684 All specifiers work basically like the standard `%s' of printf, but may
1685 contain two additional characters: A question mark just after the `%' and
1686 a whitespace/punctuation character just before the final letter.
1688 If the first character after `%' is a question mark, the entire field
1689 will only be included if the corresponding value applies to the
1690 current entry. This is useful for fields which should have fixed
1691 width when present, but zero width when absent. For example,
1692 \"%?-12t\" will result in a 12 character time field if a time of the
1693 day is specified, but will completely disappear in entries which do
1694 not contain a time.
1696 If there is punctuation or whitespace character just before the final
1697 format letter, this character will be appended to the field value if
1698 the value is not empty. For example, the format \"%-12:c\" leads to
1699 \"Diary: \" if the category is \"Diary\". If the category were be
1700 empty, no additional colon would be interted.
1702 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1703 - Indent the line with two space characters
1704 - Give the category in a 12 chars wide field, padded with whitespace on
1705 the right (because of `-'). Append a colon if there is a category
1706 (because of `:').
1707 - If there is a time-of-day, put it into a 12 chars wide field. If no
1708 time, don't put in an empty field, just skip it (because of '?').
1709 - Finally, put the scheduling information and append a whitespace.
1711 As another example, if you don't want the time-of-day of entries in
1712 the prefix, you could use:
1714 (setq org-agenda-prefix-format \" %-11:c% s\")
1716 See also the variables `org-agenda-remove-times-when-in-prefix' and
1717 `org-agenda-remove-tags-when-in-prefix'."
1718 :type 'string
1719 :group 'org-agenda-prefix)
1721 (defvar org-prefix-format-compiled nil
1722 "The compiled version of the most recently used prefix format.
1723 Depending on which command was used last, this may be the compiled version
1724 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1726 (defcustom org-agenda-remove-times-when-in-prefix t
1727 "Non-nil means, remove duplicate time specifications in agenda items.
1728 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1729 time-of-day specification in a headline or diary entry is extracted and
1730 placed into the prefix. If this option is non-nil, the original specification
1731 \(a timestamp or -range, or just a plain time(range) specification like
1732 11:30-4pm) will be removed for agenda display. This makes the agenda less
1733 cluttered.
1734 The option can be t or nil. It may also be the symbol `beg', indicating
1735 that the time should only be removed what it is located at the beginning of
1736 the headline/diary entry."
1737 :group 'org-agenda-prefix
1738 :type '(choice
1739 (const :tag "Always" t)
1740 (const :tag "Never" nil)
1741 (const :tag "When at beginning of entry" beg)))
1743 (defcustom org-agenda-remove-tags-when-in-prefix nil
1744 "Non-nil means, remove the tags from the headline copy in the agenda.
1745 When this is the symbol `prefix', only remove tags when
1746 `org-agenda-prefix-format' contains a `%T' specifier."
1747 :group 'org-agenda-prefix
1748 :type '(choice
1749 (const :tag "Always" t)
1750 (const :tag "Never" nil)
1751 (const :tag "When prefix format contains %T" prefix)))
1753 (defgroup org-agenda-timeline nil
1754 "Options concerning the timeline buffer in Org Mode."
1755 :tag "Org Agenda Timeline"
1756 :group 'org-agenda)
1758 (defcustom org-timeline-prefix-format " % s"
1759 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1760 :type 'string
1761 :group 'org-agenda-timeline)
1763 (defcustom org-select-timeline-window t
1764 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1765 When nil, cursor will remain in the current window."
1766 :group 'org-agenda-timeline
1767 :type 'boolean)
1769 (defcustom org-timeline-show-empty-dates 3
1770 "Non-nil means, `org-timeline' also shows dates without an entry.
1771 When nil, only the days which actually have entries are shown.
1772 When t, all days between the first and the last date are shown.
1773 When an integer, show also empty dates, but if there is a gap of more than
1774 N days, just insert a special line indicating the size of the gap."
1775 :group 'org-agenda-timeline
1776 :type '(choice
1777 (const :tag "None" nil)
1778 (const :tag "All" t)
1779 (number :tag "at most")))
1781 (defgroup org-latex nil
1782 "Options for embedding LaTeX code into Org-mode"
1783 :tag "Org LaTeX"
1784 :group 'org)
1786 (defcustom org-format-latex-options
1787 '(:foreground "Black" :background "Transparent" :scale 1.0
1788 :matchers ("begin" "$" "$$" "\\(" "\\["))
1789 "Options for creating images from LaTeX fragments.
1790 This is a property list with the following properties:
1791 :foreground the foreground color, for example \"Black\".
1792 :background the background color, or \"Transparent\".
1793 :scale a scaling factor for the size of the images
1794 :matchers a list indicating which matchers should be used to
1795 find LaTeX fragments. Valid members of this list are:
1796 \"begin\" find environments
1797 \"$\" find math expressions surrounded by $...$
1798 \"$$\" find math expressions surrounded by $$....$$
1799 \"\\(\" find math expressions surrounded by \\(...\\)
1800 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1801 :group 'org-latex
1802 :type 'plist)
1804 (defgroup org-export nil
1805 "Options for exporting org-listings."
1806 :tag "Org Export"
1807 :group 'org)
1809 (defgroup org-export-general nil
1810 "General options for exporting Org-mode files."
1811 :tag "Org Export General"
1812 :group 'org-export)
1814 (defcustom org-export-publishing-directory "."
1815 "Path to the location where exported files should be located.
1816 This path may be relative to the directory where the Org-mode file lives.
1817 The default is to put them into the same directory as the Org-mode file.
1818 The variable may also be an alist with export types `:html', `:ascii',
1819 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1820 is relative, it is interpreted relative to the directory where the exported
1821 Org-mode files lives."
1822 :group 'org-export-general
1823 :type '(choice
1824 (directory)
1825 (repeat
1826 (cons
1827 (choice :tag "Type"
1828 (const :html) (const :ascii) (const :ical) (const :xoxo))
1829 (directory)))))
1831 (defcustom org-export-language-setup
1832 '(("en" "Author" "Date" "Table of Contents")
1833 ("cs" "Autor" "Datum" "Obsah")
1834 ("da" "Ophavsmand" "Dato" "Indhold")
1835 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1836 ("es" "Autor" "Fecha" "\xccndice")
1837 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1838 ("it" "Autore" "Data" "Indice")
1839 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1840 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1841 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1842 "Terms used in export text, translated to different languages.
1843 Use the variable `org-export-default-language' to set the language,
1844 or use the +OPTION lines for a per-file setting."
1845 :group 'org-export-general
1846 :type '(repeat
1847 (list
1848 (string :tag "HTML language tag")
1849 (string :tag "Author")
1850 (string :tag "Date")
1851 (string :tag "Table of Contents"))))
1853 (defcustom org-export-default-language "en"
1854 "The default language of HTML export, as a string.
1855 This should have an association in `org-export-language-setup'."
1856 :group 'org-export-general
1857 :type 'string)
1859 (defcustom org-export-headline-levels 3
1860 "The last level which is still exported as a headline.
1861 Inferior levels will produce itemize lists when exported.
1862 Note that a numeric prefix argument to an exporter function overrides
1863 this setting.
1865 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1866 :group 'org-export-general
1867 :type 'number)
1869 (defcustom org-export-with-section-numbers t
1870 "Non-nil means, add section numbers to headlines when exporting.
1872 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1873 :group 'org-export-general
1874 :type 'boolean)
1876 (defcustom org-export-with-toc t
1877 "Non-nil means, create a table of contents in exported files.
1878 The TOC contains headlines with levels up to`org-export-headline-levels'.
1880 Headlines which contain any TODO items will be marked with \"(*)\" in
1881 ASCII export, and with red color in HTML output.
1883 In HTML output, the TOC will be clickable.
1885 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1886 :group 'org-export-general
1887 :type 'boolean)
1889 (defcustom org-export-mark-todo-in-toc nil
1890 "Non-nil means, mark TOC lines that contain any open TODO items."
1891 :group 'org-export-general
1892 :type 'boolean)
1894 (defcustom org-export-preserve-breaks nil
1895 "Non-nil means, preserve all line breaks when exporting.
1896 Normally, in HTML output paragraphs will be reformatted. In ASCII
1897 export, line breaks will always be preserved, regardless of this variable.
1899 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1900 :group 'org-export-general
1901 :type 'boolean)
1903 (defcustom org-export-with-archived-trees 'headline
1904 "Whether subtrees with the ARCHIVE tag should be exported.
1905 This can have three different values
1906 nil Do not export, pretend this tree is not present
1907 t Do export the entire tree
1908 headline Only export the headline, but skip the tree below it."
1909 :group 'org-export-general
1910 :group 'org-archive
1911 :type '(choice
1912 (const :tag "not at all" nil)
1913 (const :tag "headline only" 'headline)
1914 (const :tag "entirely" t)))
1916 (defcustom org-export-with-timestamps t
1917 "Nil means, do not export time stamps and associated keywords."
1918 :group 'org-export
1919 :type 'boolean)
1921 (defcustom org-export-remove-timestamps-from-toc t
1922 "Nil means, remove timestamps from the table of contents entries."
1923 :group 'org-export
1924 :type 'boolean)
1926 (defcustom org-export-with-tags t
1927 "Nil means, do not export tags, just remove them from headlines."
1928 :group 'org-export-general
1929 :type 'boolean)
1931 (defcustom org-export-with-timestamps t
1932 "Nil means, do not export timestamps and associated keywords."
1933 :group 'org-export-general
1934 :type 'boolean)
1936 (defgroup org-export-translation nil
1937 "Options for translating special ascii sequences for the export backends."
1938 :tag "Org Export Translation"
1939 :group 'org-export)
1941 (defcustom org-export-with-emphasize t
1942 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1943 If the export target supports emphasizing text, the word will be
1944 typeset in bold, italic, or underlined, respectively. Works only for
1945 single words, but you can say: I *really* *mean* *this*.
1946 Not all export backends support this.
1948 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1949 :group 'org-export-translation
1950 :type 'boolean)
1952 (defcustom org-export-with-sub-superscripts t
1953 "Non-nil means, interpret \"_\" and \"^\" for export.
1954 When this option is turned on, you can use TeX-like syntax for sub- and
1955 superscripts. Several characters after \"_\" or \"^\" will be
1956 considered as a single item - so grouping with {} is normally not
1957 needed. For example, the following things will be parsed as single
1958 sub- or superscripts.
1960 10^24 or 10^tau several digits will be considered 1 item.
1961 10^-12 or 10^-tau a leading sign with digits or a word
1962 x^2-y^3 will be read as x^2 - y^3, because items are
1963 terminated by almost any nonword/nondigit char.
1964 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1966 Still, ambiguity is possible - so when in doubt use {} to enclose the
1967 sub/superscript.
1968 Not all export backends support this, but HTML does.
1970 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1971 :group 'org-export-translation
1972 :type 'boolean)
1974 (defcustom org-export-with-TeX-macros t
1975 "Non-nil means, interpret simple TeX-like macros when exporting.
1976 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1977 No only real TeX macros will work here, but the standard HTML entities
1978 for math can be used as macro names as well. For a list of supported
1979 names in HTML export, see the constant `org-html-entities'.
1980 Not all export backends support this.
1982 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1983 :group 'org-export-translation
1984 :group 'org-latex
1985 :type 'boolean)
1987 (defcustom org-export-with-LaTeX-fragments nil
1988 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
1989 When set, the exporter will find LaTeX environments if the \\begin line is
1990 the first non-white thing on a line. It will also find the math delimiters
1991 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
1992 display math.
1994 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
1995 :group 'org-export-translation
1996 :group 'org-latex
1997 :type 'boolean)
1999 (defcustom org-export-with-fixed-width t
2000 "Non-nil means, lines starting with \":\" will be in fixed width font.
2001 This can be used to have pre-formatted text, fragments of code etc. For
2002 example:
2003 : ;; Some Lisp examples
2004 : (while (defc cnt)
2005 : (ding))
2006 will be looking just like this in also HTML. See also the QUOTE keyword.
2007 Not all export backends support this.
2009 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2010 :group 'org-export-translation
2011 :type 'boolean)
2013 (defcustom org-match-sexp-depth 3
2014 "Number of stacked braces for sub/superscript matching.
2015 This has to be set before loading org.el to be effective."
2016 :group 'org-export-translation
2017 :type 'integer)
2019 (defgroup org-export-tables nil
2020 "Options for exporting tables in Org-mode."
2021 :tag "Org Export Tables"
2022 :group 'org-export)
2024 (defcustom org-export-with-tables t
2025 "If non-nil, lines starting with \"|\" define a table.
2026 For example:
2028 | Name | Address | Birthday |
2029 |-------------+----------+-----------|
2030 | Arthur Dent | England | 29.2.2100 |
2032 Not all export backends support this.
2034 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2035 :group 'org-export-tables
2036 :type 'boolean)
2038 (defcustom org-export-highlight-first-table-line t
2039 "Non-nil means, highlight the first table line.
2040 In HTML export, this means use <th> instead of <td>.
2041 In tables created with table.el, this applies to the first table line.
2042 In Org-mode tables, all lines before the first horizontal separator
2043 line will be formatted with <th> tags."
2044 :group 'org-export-tables
2045 :type 'boolean)
2047 (defcustom org-export-table-remove-special-lines t
2048 "Remove special lines and marking characters in calculating tables.
2049 This removes the special marking character column from tables that are set
2050 up for spreadsheet calculations. It also removes the entire lines
2051 marked with `!', `_', or `^'. The lines with `$' are kept, because
2052 the values of constants may be useful to have."
2053 :group 'org-export-tables
2054 :type 'boolean)
2056 (defcustom org-export-prefer-native-exporter-for-tables nil
2057 "Non-nil means, always export tables created with table.el natively.
2058 Natively means, use the HTML code generator in table.el.
2059 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2060 the table does not use row- or column-spanning). This has the
2061 advantage, that the automatic HTML conversions for math symbols and
2062 sub/superscripts can be applied. Org-mode's HTML generator is also
2063 much faster."
2064 :group 'org-export-tables
2065 :type 'boolean)
2067 (defgroup org-export-ascii nil
2068 "Options specific for ASCII export of Org-mode files."
2069 :tag "Org Export ASCII"
2070 :group 'org-export)
2072 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2073 "Characters for underlining headings in ASCII export.
2074 In the given sequence, these characters will be used for level 1, 2, ..."
2075 :group 'org-export-ascii
2076 :type '(repeat character))
2078 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2079 "Bullet characters for headlines converted to lists in ASCII export.
2080 The first character is is used for the first lest level generated in this
2081 way, and so on. If there are more levels than characters given here,
2082 the list will be repeated.
2083 Note that plain lists will keep the same bullets as the have in the
2084 Org-mode file."
2085 :group 'org-export-ascii
2086 :type '(repeat character))
2088 (defcustom org-export-ascii-show-new-buffer t
2089 "Non-nil means, popup buffer containing the exported ASCII text.
2090 Otherwise the buffer will just be saved to a file and stay hidden."
2091 :group 'org-export-ascii
2092 :type 'boolean)
2094 (defgroup org-export-xml nil
2095 "Options specific for XML export of Org-mode files."
2096 :tag "Org Export XML"
2097 :group 'org-export)
2099 (defgroup org-export-html nil
2100 "Options specific for HTML export of Org-mode files."
2101 :tag "Org Export HTML"
2102 :group 'org-export)
2104 (defcustom org-export-html-style
2105 "<style type=\"text/css\">
2106 html {
2107 font-family: Times, serif;
2108 font-size: 12pt;
2110 .title { text-align: center; }
2111 .todo { color: red; }
2112 .done { color: green; }
2113 .timestamp { color: grey }
2114 .timestamp-kwd { color: CadetBlue }
2115 .tag { background-color:lightblue; font-weight:normal }
2116 .target { background-color: lavender; }
2117 pre {
2118 border: 1pt solid #AEBDCC;
2119 background-color: #F3F5F7;
2120 padding: 5pt;
2121 font-family: courier, monospace;
2123 table { border-collapse: collapse; }
2124 td, th {
2125 vertical-align: top;
2126 border: 1pt solid #ADB9CC;
2128 </style>"
2129 "The default style specification for exported HTML files.
2130 Since there are different ways of setting style information, this variable
2131 needs to contain the full HTML structure to provide a style, including the
2132 surrounding HTML tags. The style specifications should include definitions
2133 for new classes todo, done, title, and deadline. For example, legal values
2134 would be:
2136 <style type=\"text/css\">
2137 p { font-weight: normal; color: gray; }
2138 h1 { color: black; }
2139 .title { text-align: center; }
2140 .todo, .deadline { color: red; }
2141 .done { color: green; }
2142 </style>
2144 or, if you want to keep the style in a file,
2146 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2148 As the value of this option simply gets inserted into the HTML <head> header,
2149 you can \"misuse\" it to add arbitrary text to the header."
2150 :group 'org-export-html
2151 :type 'string)
2153 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2154 "Format for typesetting the document title in HTML export."
2155 :group 'org-export-html
2156 :type 'string)
2158 (defcustom org-export-html-toplevel-hlevel 2
2159 "The <H> level for level 1 headings in HTML export."
2160 :group 'org-export-html
2161 :type 'string)
2163 (defcustom org-export-html-link-org-files-as-html t
2164 "Non-nil means, make file links to `file.org' point to `file.html'.
2165 When org-mode is exporting an org-mode file to HTML, links to
2166 non-html files are directly put into a href tag in HTML.
2167 However, links to other Org-mode files (recognized by the
2168 extension `.org.) should become links to the corresponding html
2169 file, assuming that the linked org-mode file will also be
2170 converted to HTML.
2171 When nil, the links still point to the plain `.org' file."
2172 :group 'org-export-html
2173 :type 'boolean)
2175 (defcustom org-export-html-inline-images 'maybe
2176 "Non-nil means, inline images into exported HTML pages.
2177 This is done using an <img> tag. When nil, an anchor with href is used to
2178 link to the image. If this option is `maybe', then images in links with
2179 an empty description will be inlined, while images with a description will
2180 be linked only."
2181 :group 'org-export-html
2182 :type '(choice (const :tag "Never" nil)
2183 (const :tag "Always" t)
2184 (const :tag "When there is no description" maybe)))
2186 (defcustom org-export-html-expand t
2187 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2188 When nil, these tags will be exported as plain text and therefore
2189 not be interpreted by a browser.
2191 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2192 :group 'org-export-html
2193 :type 'boolean)
2195 (defcustom org-export-html-table-tag
2196 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2197 "The HTML tag used to start a table.
2198 This must be a <table> tag, but you may change the options like
2199 borders and spacing."
2200 :group 'org-export-html
2201 :type 'string)
2203 (defcustom org-export-html-with-timestamp nil
2204 "If non-nil, write `org-export-html-html-helper-timestamp'
2205 into the exported HTML text. Otherwise, the buffer will just be saved
2206 to a file."
2207 :group 'org-export-html
2208 :type 'boolean)
2210 (defcustom org-export-html-html-helper-timestamp
2211 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2212 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2213 :group 'org-export-html
2214 :type 'string)
2216 (defcustom org-export-html-show-new-buffer nil
2217 "Non-nil means, popup buffer containing the exported html text.
2218 Otherwise, the buffer will just be saved to a file and stay hidden."
2219 :group 'org-export-html
2220 :type 'boolean)
2222 (defgroup org-export-icalendar nil
2223 "Options specific for iCalendar export of Org-mode files."
2224 :tag "Org Export iCalendar"
2225 :group 'org-export)
2227 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2228 "The file name for the iCalendar file covering all agenda files.
2229 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2230 The file name should be absolute."
2231 :group 'org-export-icalendar
2232 :type 'file)
2234 (defcustom org-icalendar-include-todo nil
2235 "Non-nil means, export to iCalendar files should also cover TODO items."
2236 :group 'org-export-icalendar
2237 :type 'boolean)
2239 (defcustom org-icalendar-combined-name "OrgMode"
2240 "Calendar name for the combined iCalendar representing all agenda files."
2241 :group 'org-export-icalendar
2242 :type 'string)
2244 (defgroup org-font-lock nil
2245 "Font-lock settings for highlighting in Org-mode."
2246 :tag "Org Font Lock"
2247 :group 'org)
2249 (defcustom org-level-color-stars-only nil
2250 "Non-nil means fontify only the stars in each headline.
2251 When nil, the entire headline is fontified.
2252 Changing it requires restart of `font-lock-mode' to become effective
2253 also in regions already fontified."
2254 :group 'org-font-lock
2255 :type 'boolean)
2257 (defcustom org-hide-leading-stars nil
2258 "Non-nil means, hide the first N-1 stars in a headline.
2259 This works by using the face `org-hide' for these stars. This
2260 face is white for a light background, and black for a dark
2261 background. You may have to customize the face `org-hide' to
2262 make this work.
2263 Changing it requires restart of `font-lock-mode' to become effective
2264 also in regions already fontified.
2265 You may also set this on a per-file basis by adding one of the following
2266 lines to the buffer:
2268 #+STARTUP: hidestars
2269 #+STARTUP: showstars"
2270 :group 'org-font-lock
2271 :type 'boolean)
2273 (defcustom org-fontify-done-headline nil
2274 "Non-nil means, change the face of a headline if it is marked DONE.
2275 Normally, only the TODO/DONE keyword indicates the state of a headline.
2276 When this is non-nil, the headline after the keyword is set to the
2277 `org-headline-done' as an additional indication."
2278 :group 'org-font-lock
2279 :type 'boolean)
2281 (defcustom org-fontify-emphasized-text t
2282 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2283 Changing this variable requires a restart of Emacs to take effect."
2284 :group 'org-font-lock
2285 :type 'boolean)
2287 (defvar org-emph-re nil
2288 "Regular expression for matching emphasis.")
2289 (defvar org-emphasis-regexp-components) ; defined just below
2290 (defvar org-emphasis-alist) ; defined just below
2291 (defun org-set-emph-re (var val)
2292 "Set variable and compute the emphasis regular expression."
2293 (set var val)
2294 (when (and (boundp 'org-emphasis-alist)
2295 (boundp 'org-emphasis-regexp-components)
2296 org-emphasis-alist org-emphasis-regexp-components)
2297 (let* ((e org-emphasis-regexp-components)
2298 (pre (car e))
2299 (post (nth 1 e))
2300 (border (nth 2 e))
2301 (body (nth 3 e))
2302 (nl (nth 4 e))
2303 (stacked (nth 5 e))
2304 (body1 (concat body "*?"))
2305 (markers (mapconcat 'car org-emphasis-alist "")))
2306 ;; make sure special characters appear at the right position in the class
2307 (if (string-match "\\^" markers)
2308 (setq markers (concat (replace-match "" t t markers) "^")))
2309 (if (string-match "-" markers)
2310 (setq markers (concat (replace-match "" t t markers) "-")))
2311 (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2312 ;; Make the regexp
2313 (setq org-emph-re
2314 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2315 "\\("
2316 "\\([" markers "]\\)"
2317 "\\("
2318 "[^" border markers "]"
2319 body1
2320 "[^" border markers "]"
2321 "\\)"
2322 "\\3\\)"
2323 "\\([" post (if stacked markers) "]\\|$\\)")))))
2325 (defcustom org-emphasis-regexp-components
2326 '(" \t(" " \t.,?;:'\")" " \t\r\n,." "." 1 nil)
2327 "Components used to build the reqular expression for emphasis.
2328 This is a list with 6 entries. Terminology: In an emphasis string
2329 like \" *strong word* \", we call the initial space PREMATCH, the final
2330 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2331 and \"trong wor\" is the body. The different components in this variable
2332 specify what is allowed/forbidden in each part:
2334 pre Chars allowed as prematch. Beginning of line will be allowed too.
2335 post Chars allowed as postmatch. End of line will be allowed too.
2336 border The chars *forbidden* as border characters. In addition to the
2337 characters given here, all marker characters are forbidden too.
2338 body-regexp A regexp like \".\" to match a body character. Don't use
2339 non-shy groups here, and don't allow newline here.
2340 newline The maximum number of newlines allowed in an emphasis exp.
2341 stacked Non-nil means, allow stacked styles. This works only in HTML
2342 export. When this is set, all marker characters (as given in
2343 `org-emphasis-alist') will be allowed as pre/post, aiding
2344 inside-out matching.
2345 Use customize to modify this, or restart emacs after changing it."
2346 :group 'org-font-lock
2347 :set 'org-set-emph-re
2348 :type '(list
2349 (sexp :tag "Allowed chars in pre ")
2350 (sexp :tag "Allowed chars in post ")
2351 (sexp :tag "Forbidden chars in border ")
2352 (sexp :tag "Regexp for body ")
2353 (integer :tag "number of newlines allowed")
2354 (boolean :tag "Stacking allowed ")))
2356 (defcustom org-emphasis-alist
2357 '(("*" bold "<b>" "</b>")
2358 ("/" italic "<i>" "</i>")
2359 ("_" underline "<u>" "</u>")
2360 ("=" shadow "<code>" "</code>")
2361 ("+" (:strike-through t) "<del>" "</del>")
2363 "Special syntax for emphasised text.
2364 Text starting and ending with a special character will be emphasized, for
2365 example *bold*, _underlined_ and /italic/. This variable sets the marker
2366 characters, the face to bbe used by font-lock for highlighting in Org-mode
2367 emacs buffers, and the HTML tags to be used for this.
2368 Use customize to modify this, or restart emacs after changing it."
2369 :group 'org-font-lock
2370 :set 'org-set-emph-re
2371 :type '(repeat
2372 (list
2373 (string :tag "Marker character")
2374 (choice
2375 (face :tag "Font-lock-face")
2376 (plist :tag "Face property list"))
2377 (string :tag "HTML start tag")
2378 (string :tag "HTML end tag"))))
2380 (defgroup org-faces nil
2381 "Faces in Org-mode."
2382 :tag "Org Faces"
2383 :group 'org-font-lock)
2385 (defun org-compatible-face (specs)
2386 "Make a compatible face specification.
2387 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2388 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2389 to the top of the list. The `min-colors' attribute will be removed from
2390 any other entries, and any resulting duplicates will be removed entirely."
2391 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2392 (let (r e a)
2393 (while (setq e (pop specs))
2394 (cond
2395 ((memq (car e) '(t default)) (push e r))
2396 ((setq a (member '(min-colors 8) (car e)))
2397 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2398 (cdr e)))))
2399 ((setq a (assq 'min-colors (car e)))
2400 (setq e (cons (delq a (car e)) (cdr e)))
2401 (or (assoc (car e) r) (push e r)))
2402 (t (or (assoc (car e) r) (push e r)))))
2403 (nreverse r))
2404 specs))
2406 (defface org-hide
2407 '((((background light)) (:foreground "white"))
2408 (((background dark)) (:foreground "black")))
2409 "Face used to hide leading stars in headlines.
2410 The forground color of this face should be equal to the background
2411 color of the frame."
2412 :group 'org-faces)
2414 (defface org-level-1 ;; font-lock-function-name-face
2415 (org-compatible-face
2416 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2417 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2418 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2419 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2420 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2421 (t (:bold t))))
2422 "Face used for level 1 headlines."
2423 :group 'org-faces)
2425 (defface org-level-2 ;; font-lock-variable-name-face
2426 (org-compatible-face
2427 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2428 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2429 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2430 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2431 (t (:bold t))))
2432 "Face used for level 2 headlines."
2433 :group 'org-faces)
2435 (defface org-level-3 ;; font-lock-keyword-face
2436 (org-compatible-face
2437 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2438 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2439 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2440 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2441 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2442 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2443 (t (:bold t))))
2444 "Face used for level 3 headlines."
2445 :group 'org-faces)
2447 (defface org-level-4 ;; font-lock-comment-face
2448 (org-compatible-face
2449 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2450 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2451 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2452 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2453 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2454 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2455 (t (:bold t))))
2456 "Face used for level 4 headlines."
2457 :group 'org-faces)
2459 (defface org-level-5 ;; font-lock-type-face
2460 (org-compatible-face
2461 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2462 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2463 (((class color) (min-colors 8)) (:foreground "green"))))
2464 "Face used for level 5 headlines."
2465 :group 'org-faces)
2467 (defface org-level-6 ;; font-lock-constant-face
2468 (org-compatible-face
2469 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2470 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2471 (((class color) (min-colors 8)) (:foreground "magenta"))))
2472 "Face used for level 6 headlines."
2473 :group 'org-faces)
2475 (defface org-level-7 ;; font-lock-builtin-face
2476 (org-compatible-face
2477 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2478 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2479 (((class color) (min-colors 8)) (:foreground "blue"))))
2480 "Face used for level 7 headlines."
2481 :group 'org-faces)
2483 (defface org-level-8 ;; font-lock-string-face
2484 (org-compatible-face
2485 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2486 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2487 (((class color) (min-colors 8)) (:foreground "green"))))
2488 "Face used for level 8 headlines."
2489 :group 'org-faces)
2491 (defface org-special-keyword ;; font-lock-string-face
2492 (org-compatible-face
2493 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2494 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2495 (t (:italic t))))
2496 "Face used for special keywords."
2497 :group 'org-faces)
2499 (defface org-warning ;; font-lock-warning-face
2500 (org-compatible-face
2501 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2502 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2503 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2504 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2505 (t (:bold t))))
2506 "Face for deadlines and TODO keywords."
2507 :group 'org-faces)
2509 (defface org-headline-done ;; font-lock-string-face
2510 (org-compatible-face
2511 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2512 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2513 (((class color) (min-colors 8) (background light)) (:bold nil))))
2514 "Face used to indicate that a headline is DONE.
2515 This face is only used if `org-fontify-done-headline' is set."
2516 :group 'org-faces)
2518 (defface org-archived ; similar to shadow
2519 (org-compatible-face
2520 '((((class color grayscale) (min-colors 88) (background light))
2521 (:foreground "grey50"))
2522 (((class color grayscale) (min-colors 88) (background dark))
2523 (:foreground "grey70"))
2524 (((class color) (min-colors 8) (background light))
2525 (:foreground "green"))
2526 (((class color) (min-colors 8) (background dark))
2527 (:foreground "yellow"))))
2528 "Face for headline with the ARCHIVE tag."
2529 :group 'org-faces)
2531 (defface org-link
2532 '((((class color) (background light)) (:foreground "Purple" :underline t))
2533 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2534 (t (:underline t)))
2535 "Face for links."
2536 :group 'org-faces)
2538 (defface org-date
2539 '((((class color) (background light)) (:foreground "Purple" :underline t))
2540 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2541 (t (:underline t)))
2542 "Face for links."
2543 :group 'org-faces)
2545 (defface org-tag
2546 '((t (:bold t)))
2547 "Face for tags."
2548 :group 'org-faces)
2550 (defface org-todo ;; font-lock-warning-face
2551 (org-compatible-face
2552 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2553 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2554 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2555 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2556 (t (:inverse-video t :bold t))))
2557 "Face for TODO keywords."
2558 :group 'org-faces)
2560 (defface org-done ;; font-lock-type-face
2561 (org-compatible-face
2562 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2563 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2564 (((class color) (min-colors 8)) (:foreground "green"))
2565 (t (:bold t))))
2566 "Face used for DONE."
2567 :group 'org-faces)
2569 (defface org-table ;; font-lock-function-name-face
2570 (org-compatible-face
2571 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2572 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2573 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2574 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2575 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2576 (((class color) (min-colors 8) (background dark)))))
2577 "Face used for tables."
2578 :group 'org-faces)
2580 (defface org-formula
2581 (org-compatible-face
2582 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2583 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2584 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2585 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2586 (t (:bold t :italic t))))
2587 "Face for formulas."
2588 :group 'org-faces)
2590 (defface org-scheduled-today
2591 (org-compatible-face
2592 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2593 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2594 (((class color) (min-colors 8)) (:foreground "green"))
2595 (t (:bold t :italic t))))
2596 "Face for items scheduled for a certain day."
2597 :group 'org-faces)
2599 (defface org-scheduled-previously
2600 (org-compatible-face
2601 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2602 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2603 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2604 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2605 (t (:bold t))))
2606 "Face for items scheduled previously, and not yet done."
2607 :group 'org-faces)
2609 (defface org-upcoming-deadline
2610 (org-compatible-face
2611 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2612 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2613 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2614 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2615 (t (:bold t))))
2616 "Face for items scheduled previously, and not yet done."
2617 :group 'org-faces)
2619 (defface org-time-grid ;; font-lock-variable-name-face
2620 (org-compatible-face
2621 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2622 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2623 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2624 "Face used for time grids."
2625 :group 'org-faces)
2627 (defconst org-level-faces
2628 '(org-level-1 org-level-2 org-level-3 org-level-4
2629 org-level-5 org-level-6 org-level-7 org-level-8
2631 (defconst org-n-levels (length org-level-faces))
2634 ;; Variables for pre-computed regular expressions, all buffer local
2635 (defvar org-done-string nil
2636 "The last string in `org-todo-keywords', indicating an item is DONE.")
2637 (make-variable-buffer-local 'org-done-string)
2638 (defvar org-todo-regexp nil
2639 "Matches any of the TODO state keywords.")
2640 (make-variable-buffer-local 'org-todo-regexp)
2641 (defvar org-not-done-regexp nil
2642 "Matches any of the TODO state keywords except the last one.")
2643 (make-variable-buffer-local 'org-not-done-regexp)
2644 (defvar org-todo-line-regexp nil
2645 "Matches a headline and puts TODO state into group 2 if present.")
2646 (make-variable-buffer-local 'org-todo-line-regexp)
2647 (defvar org-todo-line-tags-regexp nil
2648 "Matches a headline and puts TODO state into group 2 if present.
2649 Also put tags into group 4 if tags are present.")
2650 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2651 (defvar org-nl-done-regexp nil
2652 "Matches newline followed by a headline with the DONE keyword.")
2653 (make-variable-buffer-local 'org-nl-done-regexp)
2654 (defvar org-looking-at-done-regexp nil
2655 "Matches the DONE keyword a point.")
2656 (make-variable-buffer-local 'org-looking-at-done-regexp)
2657 (defvar org-todo-kwd-priority-p nil
2658 "Do TODO items have priorities?")
2659 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2660 (defvar org-todo-kwd-max-priority nil
2661 "Maximum priority of TODO items.")
2662 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2663 (defvar org-ds-keyword-length 12
2664 "Maximum length of the Deadline and SCHEDULED keywords.")
2665 (make-variable-buffer-local 'org-ds-keyword-length)
2666 (defvar org-deadline-regexp nil
2667 "Matches the DEADLINE keyword.")
2668 (make-variable-buffer-local 'org-deadline-regexp)
2669 (defvar org-deadline-time-regexp nil
2670 "Matches the DEADLINE keyword together with a time stamp.")
2671 (make-variable-buffer-local 'org-deadline-time-regexp)
2672 (defvar org-deadline-line-regexp nil
2673 "Matches the DEADLINE keyword and the rest of the line.")
2674 (make-variable-buffer-local 'org-deadline-line-regexp)
2675 (defvar org-scheduled-regexp nil
2676 "Matches the SCHEDULED keyword.")
2677 (make-variable-buffer-local 'org-scheduled-regexp)
2678 (defvar org-scheduled-time-regexp nil
2679 "Matches the SCHEDULED keyword together with a time stamp.")
2680 (make-variable-buffer-local 'org-scheduled-time-regexp)
2681 (defvar org-closed-time-regexp nil
2682 "Matches the CLOSED keyword together with a time stamp.")
2683 (make-variable-buffer-local 'org-closed-time-regexp)
2685 (defvar org-keyword-time-regexp nil
2686 "Matches any of the 3 keywords, together with the time stamp.")
2687 (make-variable-buffer-local 'org-keyword-time-regexp)
2688 (defvar org-maybe-keyword-time-regexp nil
2689 "Matches a timestamp, possibly preceeded by a keyword.")
2690 (make-variable-buffer-local 'org-keyword-time-regexp)
2692 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2693 mouse-map t)
2694 "Properties to remove when a string without properties is wanted.")
2696 (defsubst org-match-string-no-properties (num &optional string)
2697 (if (featurep 'xemacs)
2698 (let ((s (match-string num string)))
2699 (remove-text-properties 0 (length s) org-rm-props s)
2701 (match-string-no-properties num string)))
2703 (defsubst org-no-properties (s)
2704 (remove-text-properties 0 (length s) org-rm-props s)
2707 (defsubst org-set-local (var value)
2708 "Make VAR local in current buffer and set it to VALUE."
2709 (set (make-variable-buffer-local var) value))
2711 (defsubst org-mode-p ()
2712 "Check if the current buffer is in Org-mode."
2713 (eq major-mode 'org-mode))
2715 (defun org-set-regexps-and-options ()
2716 "Precompute regular expressions for current buffer."
2717 (when (org-mode-p)
2718 (let ((re (org-make-options-regexp
2719 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2720 "STARTUP" "ARCHIVE" "TAGS" "CALC")))
2721 (splitre "[ \t]+")
2722 kwds int key value cat arch tags)
2723 (save-excursion
2724 (save-restriction
2725 (widen)
2726 (goto-char (point-min))
2727 (while (re-search-forward re nil t)
2728 (setq key (match-string 1) value (org-match-string-no-properties 2))
2729 (cond
2730 ((equal key "CATEGORY")
2731 (if (string-match "[ \t]+$" value)
2732 (setq value (replace-match "" t t value)))
2733 (setq cat (intern value)))
2734 ((equal key "SEQ_TODO")
2735 (setq int 'sequence
2736 kwds (append kwds (org-split-string value splitre))))
2737 ((equal key "PRI_TODO")
2738 (setq int 'priority
2739 kwds (append kwds (org-split-string value splitre))))
2740 ((equal key "TYP_TODO")
2741 (setq int 'type
2742 kwds (append kwds (org-split-string value splitre))))
2743 ((equal key "TAGS")
2744 (setq tags (append tags (org-split-string value splitre))))
2745 ((equal key "STARTUP")
2746 (let ((opts (org-split-string value splitre))
2747 (set '(("fold" org-startup-folded t)
2748 ("overview" org-startup-folded t)
2749 ("nofold" org-startup-folded nil)
2750 ("showall" org-startup-folded nil)
2751 ("content" org-startup-folded content)
2752 ("hidestars" org-hide-leading-stars t)
2753 ("showstars" org-hide-leading-stars nil)
2754 ("odd" org-odd-levels-only t)
2755 ("oddeven" org-odd-levels-only nil)
2756 ("align" org-startup-align-all-tables t)
2757 ("noalign" org-startup-align-all-tables nil)
2758 ("logging" org-log-done t)
2759 ("nologging" org-log-done nil)
2760 ("dlcheck" org-startup-with-deadline-check t)
2761 ("nodlcheck" org-startup-with-deadline-check nil)))
2762 l var val)
2763 (while (setq l (assoc (pop opts) set))
2764 (setq var (nth 1 l) val (nth 2 l))
2765 (set (make-local-variable var) val))))
2766 ((equal key "ARCHIVE")
2767 (string-match " *$" value)
2768 (setq arch (replace-match "" t t value))
2769 (remove-text-properties 0 (length arch)
2770 '(face t fontified t) arch)))
2772 (and cat (org-set-local 'org-category cat))
2773 (and kwds (org-set-local 'org-todo-keywords kwds))
2774 (and arch (org-set-local 'org-archive-location arch))
2775 (and int (org-set-local 'org-todo-interpretation int))
2776 (when tags
2777 (let (e tgs)
2778 (while (setq e (pop tags))
2779 (cond
2780 ((equal e "{") (push '(:startgroup) tgs))
2781 ((equal e "}") (push '(:endgroup) tgs))
2782 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2783 (push (cons (match-string 1 e)
2784 (string-to-char (match-string 2 e)))
2785 tgs))
2786 (t (push (list e) tgs))))
2787 (org-set-local 'org-tag-alist nil)
2788 (while (setq e (pop tgs))
2789 (or (and (stringp (car e))
2790 (assoc (car e) org-tag-alist))
2791 (push e org-tag-alist))))))
2793 ;; Compute the regular expressions and other local variables
2794 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2795 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2796 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2797 (length org-scheduled-string)))
2798 org-done-string
2799 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2800 org-todo-regexp
2801 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2802 "\\|") "\\)\\>")
2803 org-not-done-regexp
2804 (concat "\\<\\("
2805 (mapconcat 'regexp-quote
2806 (nreverse (cdr (reverse org-todo-keywords)))
2807 "\\|")
2808 "\\)\\>")
2809 org-todo-line-regexp
2810 (concat "^\\(\\*+\\)[ \t]*\\("
2811 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2812 "\\)? *\\(.*\\)")
2813 org-nl-done-regexp
2814 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2815 org-todo-line-tags-regexp
2816 (concat "^\\(\\*+\\)[ \t]*\\("
2817 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2818 "\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
2819 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2820 org-deadline-regexp (concat "\\<" org-deadline-string)
2821 org-deadline-time-regexp
2822 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2823 org-deadline-line-regexp
2824 (concat "\\<\\(" org-deadline-string "\\).*")
2825 org-scheduled-regexp
2826 (concat "\\<" org-scheduled-string)
2827 org-scheduled-time-regexp
2828 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2829 org-closed-time-regexp
2830 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2831 org-keyword-time-regexp
2832 (concat "\\<\\(" org-scheduled-string
2833 "\\|" org-deadline-string
2834 "\\|" org-closed-string
2835 "\\|" org-clock-string "\\)"
2836 " *[[<]\\([^]>]+\\)[]>]")
2837 org-maybe-keyword-time-regexp
2838 (concat "\\(\\<\\(" org-scheduled-string
2839 "\\|" org-deadline-string
2840 "\\|" org-closed-string
2841 "\\|" org-clock-string "\\)\\)?"
2842 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
2844 (org-set-font-lock-defaults)))
2846 ;; Tell the compiler about dynamically scoped variables,
2847 ;; and variables from other packages
2848 (defvar calc-embedded-close-formula) ; defined by the calc package
2849 (defvar calc-embedded-open-formula) ; defined by the calc package
2850 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
2851 (defvar zmacs-regions) ; XEmacs regions
2852 (defvar original-date) ; dynamically scoped in calendar
2853 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2854 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2855 (defvar org-html-entities) ; defined later in this file
2856 (defvar org-goto-start-pos) ; dynamically scoped parameter
2857 (defvar org-time-was-given) ; dynamically scoped parameter
2858 (defvar org-ts-what) ; dynamically scoped parameter
2859 (defvar org-current-export-file) ; dynamically scoped parameter
2860 (defvar org-current-export-dir) ; dynamically scoped parameter
2861 (defvar mark-active) ; Emacs only, not available in XEmacs.
2862 (defvar timecnt) ; dynamically scoped parameter
2863 (defvar levels-open) ; dynamically scoped parameter
2864 (defvar entry) ; dynamically scoped parameter
2865 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
2866 (defvar date) ; dynamically scoped parameter
2867 (defvar description) ; dynamically scoped parameter
2868 (defvar ans1) ; dynamically scoped parameter
2869 (defvar ans2) ; dynamically scoped parameter
2870 (defvar starting-day) ; local variable
2871 (defvar include-all-loc) ; local variable
2872 (defvar vm-message-pointer) ; from vm
2873 (defvar vm-folder-directory) ; from vm
2874 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2875 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2876 (defvar gnus-group-name) ; from gnus
2877 (defvar gnus-article-current) ; from gnus
2878 (defvar w3m-current-url) ; from w3m
2879 (defvar w3m-current-title) ; from w3m
2880 (defvar mh-progs) ; from MH-E
2881 (defvar mh-current-folder) ; from MH-E
2882 (defvar mh-show-folder-buffer) ; from MH-E
2883 (defvar mh-index-folder) ; from MH-E
2884 (defvar mh-searcher) ; from MH-E
2885 (defvar org-selected-point) ; dynamically scoped parameter
2886 (defvar calendar-mode-map) ; from calendar.el
2887 (defvar last-arg) ; local variable
2888 (defvar remember-save-after-remembering) ; from remember.el
2889 (defvar remember-data-file) ; from remember.el
2890 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2891 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2892 (defvar orgtbl-mode) ; defined later in this file
2893 (defvar Info-current-file) ; from info.el
2894 (defvar Info-current-node) ; from info.el
2895 (defvar texmathp-why) ; from texmathp.el
2896 (defvar org-latex-regexps)
2898 ;;; Define the mode
2900 (defvar org-mode-map
2901 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2902 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22.")
2903 (copy-keymap outline-mode-map))
2904 "Keymap for Org-mode.")
2906 (defvar org-struct-menu) ; defined later in this file
2907 (defvar org-org-menu) ; defined later in this file
2908 (defvar org-tbl-menu) ; defined later in this file
2910 ;; We use a before-change function to check if a table might need
2911 ;; an update.
2912 (defvar org-table-may-need-update t
2913 "Indicates that a table might need an update.
2914 This variable is set by `org-before-change-function'.
2915 `org-table-align' sets it back to nil.")
2916 (defvar org-mode-hook nil)
2917 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2918 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2921 ;;;###autoload
2922 (define-derived-mode org-mode outline-mode "Org"
2923 "Outline-based notes management and organizer, alias
2924 \"Carsten's outline-mode for keeping track of everything.\"
2926 Org-mode develops organizational tasks around a NOTES file which
2927 contains information about projects as plain text. Org-mode is
2928 implemented on top of outline-mode, which is ideal to keep the content
2929 of large files well structured. It supports ToDo items, deadlines and
2930 time stamps, which magically appear in the diary listing of the Emacs
2931 calendar. Tables are easily created with a built-in table editor.
2932 Plain text URL-like links connect to websites, emails (VM), Usenet
2933 messages (Gnus), BBDB entries, and any files related to the project.
2934 For printing and sharing of notes, an Org-mode file (or a part of it)
2935 can be exported as a structured ASCII or HTML file.
2937 The following commands are available:
2939 \\{org-mode-map}"
2941 ;; Get rid of Outline menus, they are not needed
2942 ;; Need to do this here because define-derived-mode sets up
2943 ;; the keymap so late.
2944 (if (featurep 'xemacs)
2945 (progn
2946 ;; Assume this is Greg's port, it used easymenu
2947 (easy-menu-remove outline-mode-menu-heading)
2948 (easy-menu-remove outline-mode-menu-show)
2949 (easy-menu-remove outline-mode-menu-hide))
2950 (define-key org-mode-map [menu-bar headings] 'undefined)
2951 (define-key org-mode-map [menu-bar hide] 'undefined)
2952 (define-key org-mode-map [menu-bar show] 'undefined))
2954 (easy-menu-add org-org-menu)
2955 (easy-menu-add org-tbl-menu)
2956 (org-install-agenda-files-menu)
2957 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2958 (org-add-to-invisibility-spec '(org-cwidth))
2959 (when (featurep 'xemacs)
2960 (org-set-local 'line-move-ignore-invisible t))
2961 (setq outline-regexp "\\*+")
2962 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2963 (setq outline-level 'org-outline-level)
2964 (when (and org-ellipsis (stringp org-ellipsis))
2965 (unless org-display-table
2966 (setq org-display-table (make-display-table)))
2967 (set-display-table-slot org-display-table
2968 4 (string-to-vector org-ellipsis))
2969 (setq buffer-display-table org-display-table))
2970 (org-set-regexps-and-options)
2971 ;; Calc embedded
2972 (org-set-local 'calc-embedded-open-mode "# ")
2973 (modify-syntax-entry ?# "<")
2974 (if org-startup-truncated (setq truncate-lines t))
2975 (org-set-local 'font-lock-unfontify-region-function
2976 'org-unfontify-region)
2977 ;; Activate before-change-function
2978 (org-set-local 'org-table-may-need-update t)
2979 (org-add-hook 'before-change-functions 'org-before-change-function nil
2980 'local)
2981 ;; Check for running clock before killing a buffer
2982 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
2983 ;; Paragraphs and auto-filling
2984 (org-set-autofill-regexps)
2985 (org-update-radio-target-regexp)
2987 (if (and org-insert-mode-line-in-empty-file
2988 (interactive-p)
2989 (= (point-min) (point-max)))
2990 (insert " -*- mode: org -*-\n\n"))
2992 (unless org-inhibit-startup
2993 (when org-startup-align-all-tables
2994 (let ((bmp (buffer-modified-p)))
2995 (org-table-map-tables 'org-table-align)
2996 (set-buffer-modified-p bmp)))
2997 (if org-startup-with-deadline-check
2998 (call-interactively 'org-check-deadlines)
2999 (cond
3000 ((eq org-startup-folded t)
3001 (org-cycle '(4)))
3002 ((eq org-startup-folded 'content)
3003 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3004 (org-cycle '(4)) (org-cycle '(4))))))))
3006 (defsubst org-call-with-arg (command arg)
3007 "Call COMMAND interactively, but pretend prefix are was ARG."
3008 (let ((current-prefix-arg arg)) (call-interactively command)))
3010 (defsubst org-current-line (&optional pos)
3011 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
3013 (defun org-current-time ()
3014 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3015 (if (> org-time-stamp-rounding-minutes 0)
3016 (let ((r org-time-stamp-rounding-minutes)
3017 (time (decode-time)))
3018 (apply 'encode-time
3019 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3020 (nthcdr 2 time))))
3021 (current-time)))
3023 (defun org-add-props (string plist &rest props)
3024 "Add text properties to entire string, from beginning to end.
3025 PLIST may be a list of properties, PROPS are individual properties and values
3026 that will be added to PLIST. Returns the string that was modified."
3027 (add-text-properties
3028 0 (length string) (if props (append plist props) plist) string)
3029 string)
3030 (put 'org-add-props 'lisp-indent-function 2)
3033 ;;; Font-Lock stuff
3035 (defvar org-mouse-map (make-sparse-keymap))
3036 (define-key org-mouse-map
3037 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3038 (define-key org-mouse-map
3039 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3040 (when org-mouse-1-follows-link
3041 (define-key org-mouse-map [follow-link] 'mouse-face))
3042 (when org-tab-follows-link
3043 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3044 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3045 (when org-return-follows-link
3046 (define-key org-mouse-map [(return)] 'org-open-at-point)
3047 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3049 (require 'font-lock)
3051 (defconst org-non-link-chars "]\t\n\r<>")
3052 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3053 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3054 (defconst org-link-re-with-space
3055 (concat
3056 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3057 "\\([^" org-non-link-chars " ]"
3058 "[^" org-non-link-chars "]*"
3059 "[^" org-non-link-chars " ]\\)>?")
3060 "Matches a link with spaces, optional angular brackets around it.")
3062 (defconst org-link-re-with-space2
3063 (concat
3064 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3065 "\\([^" org-non-link-chars " ]"
3066 "[^]\t\n\r]*"
3067 "[^" org-non-link-chars " ]\\)>?")
3068 "Matches a link with spaces, optional angular brackets around it.")
3070 (defconst org-angle-link-re
3071 (concat
3072 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3073 "\\([^" org-non-link-chars " ]"
3074 "[^" org-non-link-chars "]*"
3075 "\\)>")
3076 "Matches link with angular brackets, spaces are allowed.")
3077 (defconst org-plain-link-re
3078 (concat
3079 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3080 "\\([^]\t\n\r<>,;() ]+\\)")
3081 "Matches plain link, without spaces.")
3083 (defconst org-bracket-link-regexp
3084 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3085 "Matches a link in double brackets.")
3087 (defconst org-bracket-link-analytic-regexp
3088 (concat
3089 "\\[\\["
3090 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3091 "\\([^]]+\\)"
3092 "\\]"
3093 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3094 "\\]"))
3095 ; 1: http:
3096 ; 2: http
3097 ; 3: path
3098 ; 4: [desc]
3099 ; 5: desc
3102 (defconst org-ts-lengths
3103 (cons (length (format-time-string (car org-time-stamp-formats)))
3104 (length (format-time-string (cdr org-time-stamp-formats))))
3105 "This holds the lengths of the two different time formats.")
3106 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3107 "Regular expression for fast time stamp matching.")
3108 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3109 "Regular expression for fast time stamp matching.")
3110 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3111 "Regular expression matching time strings for analysis.")
3112 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3113 "Regular expression matching time stamps, with groups.")
3114 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3115 "Regular expression matching time stamps (also [..]), with groups.")
3116 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3117 "Regular expression matching a time stamp range.")
3118 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3119 org-ts-regexp "\\)?")
3120 "Regular expression matching a time stamp or time stamp range.")
3122 (defvar org-�§emph-face nil)
3124 (defun org-do-emphasis-faces (limit)
3125 "Run through the buffer and add overlays to links."
3126 (if (re-search-forward org-emph-re limit t)
3127 (progn
3128 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3129 'face
3130 (nth 1 (assoc (match-string 3)
3131 org-emphasis-alist)))
3132 (add-text-properties (match-beginning 2) (match-end 2)
3133 '(font-lock-multiline t))
3134 (backward-char 1)
3135 t)))
3137 (defun org-activate-plain-links (limit)
3138 "Run through the buffer and add overlays to links."
3139 (if (re-search-forward org-plain-link-re limit t)
3140 (progn
3141 (add-text-properties (match-beginning 0) (match-end 0)
3142 (list 'mouse-face 'highlight
3143 'keymap org-mouse-map
3145 t)))
3147 (defun org-activate-angle-links (limit)
3148 "Run through the buffer and add overlays to links."
3149 (if (re-search-forward org-angle-link-re limit t)
3150 (progn
3151 (add-text-properties (match-beginning 0) (match-end 0)
3152 (list 'mouse-face 'highlight
3153 'keymap org-mouse-map
3155 t)))
3157 (defun org-activate-bracket-links (limit)
3158 "Run through the buffer and add overlays to bracketed links."
3159 (if (re-search-forward org-bracket-link-regexp limit t)
3160 (let* ((help (concat "LINK: "
3161 (org-match-string-no-properties 1)))
3162 ;; FIXME: above we should remove the escapes.
3163 ;; but that requires another match, protecting match data,
3164 ;; a lot of overhead for font-lock.
3165 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
3166 'keymap org-mouse-map 'mouse-face 'highlight
3167 'help-echo help))
3168 (vp (list 'rear-nonsticky t
3169 'keymap org-mouse-map 'mouse-face 'highlight
3170 'help-echo help)))
3171 ;; We need to remove the invisible property here. Table narrowing
3172 ;; may have made some of this invisible.
3173 (remove-text-properties (match-beginning 0) (match-end 0)
3174 '(invisible nil))
3175 (if (match-end 3)
3176 (progn
3177 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3178 (add-text-properties (match-beginning 3) (match-end 3) vp)
3179 (add-text-properties (match-end 3) (match-end 0) ip))
3180 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3181 (add-text-properties (match-beginning 1) (match-end 1) vp)
3182 (add-text-properties (match-end 1) (match-end 0) ip))
3183 t)))
3185 (defun org-activate-dates (limit)
3186 "Run through the buffer and add overlays to dates."
3187 (if (re-search-forward org-tsr-regexp limit t)
3188 (progn
3189 (add-text-properties (match-beginning 0) (match-end 0)
3190 (list 'mouse-face 'highlight
3191 'keymap org-mouse-map))
3192 t)))
3194 (defvar org-target-link-regexp nil
3195 "Regular expression matching radio targets in plain text.")
3196 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3197 "Regular expression matching a link target.")
3198 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3199 "Regular expression matching a link target.")
3201 (defun org-activate-target-links (limit)
3202 "Run through the buffer and add overlays to target matches."
3203 (when org-target-link-regexp
3204 (let ((case-fold-search t))
3205 (if (re-search-forward org-target-link-regexp limit t)
3206 (progn
3207 (add-text-properties (match-beginning 0) (match-end 0)
3208 (list 'mouse-face 'highlight
3209 'keymap org-mouse-map
3210 'help-echo "Radio target link"
3211 'org-linked-text t))
3212 t)))))
3214 (defun org-update-radio-target-regexp ()
3215 "Find all radio targets in this file and update the regular expression."
3216 (interactive)
3217 (when (memq 'radio org-activate-links)
3218 (setq org-target-link-regexp
3219 (org-make-target-link-regexp (org-all-targets 'radio)))
3220 (org-restart-font-lock)))
3222 (defun org-hide-wide-columns (limit)
3223 (let (s e)
3224 (setq s (text-property-any (point) (or limit (point-max))
3225 'org-cwidth t))
3226 (when s
3227 (setq e (next-single-property-change s 'org-cwidth))
3228 (add-text-properties s e '(invisible org-cwidth intangible t))
3229 (goto-char e)
3230 t)))
3232 (defun org-restart-font-lock ()
3233 "Restart font-lock-mode, to force refontification."
3234 (when (and (boundp 'font-lock-mode) font-lock-mode)
3235 (font-lock-mode -1)
3236 (font-lock-mode 1)))
3238 (defun org-all-targets (&optional radio)
3239 "Return a list of all targets in this file.
3240 With optional argument RADIO, only find radio targets."
3241 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3242 rtn)
3243 (save-excursion
3244 (goto-char (point-min))
3245 (while (re-search-forward re nil t)
3246 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3247 rtn)))
3249 (defun org-make-target-link-regexp (targets)
3250 "Make regular expression matching all strings in TARGETS.
3251 The regular expression finds the targets also if there is a line break
3252 between words."
3253 (and targets
3254 (concat
3255 "\\<\\("
3256 (mapconcat
3257 (lambda (x)
3258 (while (string-match " +" x)
3259 (setq x (replace-match "\\s-+" t t x)))
3261 targets
3262 "\\|")
3263 "\\)\\>")))
3265 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3266 "Matches CamelCase words, possibly with a star before it.")
3268 (defun org-activate-camels (limit)
3269 "Run through the buffer and add overlays to dates."
3270 (if (re-search-forward org-camel-regexp limit t)
3271 (progn
3272 (add-text-properties (match-beginning 0) (match-end 0)
3273 (list 'mouse-face 'highlight
3274 'keymap org-mouse-map))
3275 t)))
3277 (defun org-activate-tags (limit)
3278 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3279 (progn
3280 (add-text-properties (match-beginning 1) (match-end 1)
3281 (list 'mouse-face 'highlight
3282 'keymap org-mouse-map))
3283 t)))
3285 (defun org-font-lock-level ()
3286 (save-excursion
3287 (org-back-to-heading t)
3288 (- (match-end 0) (match-beginning 0))))
3290 (defun org-outline-level ()
3291 (save-excursion
3292 (looking-at outline-regexp)
3293 (if (match-beginning 1)
3294 (+ (org-get-string-indentation (match-string 1)) 1000)
3295 (- (match-end 0) (match-beginning 0)))))
3297 (defvar org-font-lock-keywords nil)
3299 (defun org-set-font-lock-defaults ()
3300 (let* ((em org-fontify-emphasized-text)
3301 (lk org-activate-links)
3302 (org-font-lock-extra-keywords
3303 ;; Headlines
3304 (list
3305 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3306 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3307 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3308 (1 'org-table))
3309 ;; Links
3310 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3311 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3312 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3313 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3314 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3315 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3316 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3317 (if org-table-limit-column-width
3318 '(org-hide-wide-columns (0 nil append)))
3319 ;; TODO lines
3320 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3321 '(1 'org-todo t))
3322 ;; Priorities
3323 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3324 ;; Special keywords
3325 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3326 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3327 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3328 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3329 ;; Emphasis
3330 (if em '(org-do-emphasis-faces))
3331 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3332 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3333 2 'bold prepend)
3334 ;; COMMENT
3335 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3336 "\\|" org-quote-string "\\)\\>")
3337 '(1 'org-special-keyword t))
3338 '("^#.*" (0 'font-lock-comment-face t))
3339 ;; DONE
3340 (if org-fontify-done-headline
3341 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3342 '(1 'org-done t) '(2 'org-headline-done t))
3343 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3344 '(1 'org-done t)))
3345 ;; Table stuff
3346 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3347 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3348 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3349 (if org-format-transports-properties-p
3350 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3351 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3353 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3354 ;; Now set the full font-lock-keywords
3355 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3356 (org-set-local 'font-lock-defaults
3357 '(org-font-lock-keywords t nil nil backward-paragraph))
3358 (kill-local-variable 'font-lock-keywords) nil))
3360 (defvar org-m nil)
3361 (defvar org-l nil)
3362 (defvar org-f nil)
3363 (defun org-get-level-face (n)
3364 "Get the right face for match N in font-lock matching of healdines."
3365 (setq org-l (- (match-end 2) (match-beginning 1)))
3366 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3367 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3368 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3369 (cond
3370 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3371 ((eq n 2) org-f)
3372 (t (if org-level-color-stars-only nil org-f))))
3374 (defun org-unfontify-region (beg end &optional maybe_loudly)
3375 "Remove fontification and activation overlays from links."
3376 (font-lock-default-unfontify-region beg end)
3377 (let* ((buffer-undo-list t)
3378 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3379 (inhibit-modification-hooks t)
3380 deactivate-mark buffer-file-name buffer-file-truename)
3381 (remove-text-properties beg end
3382 '(mouse-face nil keymap nil org-linked-text nil
3383 invisible nil intangible nil))))
3384 ;;; Visibility cycling
3386 (defvar org-cycle-global-status nil)
3387 (make-variable-buffer-local 'org-cycle-global-status)
3388 (defvar org-cycle-subtree-status nil)
3389 (make-variable-buffer-local 'org-cycle-subtree-status)
3391 ;;;###autoload
3392 (defun org-cycle (&optional arg)
3393 "Visibility cycling for Org-mode.
3395 - When this function is called with a prefix argument, rotate the entire
3396 buffer through 3 states (global cycling)
3397 1. OVERVIEW: Show only top-level headlines.
3398 2. CONTENTS: Show all headlines of all levels, but no body text.
3399 3. SHOW ALL: Show everything.
3401 - When point is at the beginning of a headline, rotate the subtree started
3402 by this line through 3 different states (local cycling)
3403 1. FOLDED: Only the main headline is shown.
3404 2. CHILDREN: The main headline and the direct children are shown.
3405 From this state, you can move to one of the children
3406 and zoom in further.
3407 3. SUBTREE: Show the entire subtree, including body text.
3409 - When there is a numeric prefix, go up to a heading with level ARG, do
3410 a `show-subtree' and return to the previous cursor position. If ARG
3411 is negative, go up that many levels.
3413 - When point is not at the beginning of a headline, execute
3414 `indent-relative', like TAB normally does. See the option
3415 `org-cycle-emulate-tab' for details.
3417 - Special case: if point is the the beginning of the buffer and there is
3418 no headline in line 1, this function will act as if called with prefix arg."
3419 (interactive "P")
3421 (let* ((outline-regexp
3422 (if org-cycle-include-plain-lists
3423 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
3424 outline-regexp))
3425 (bob-special (and org-cycle-global-at-bob (bobp)
3426 (not (looking-at outline-regexp))))
3427 (org-cycle-hook
3428 (if bob-special
3429 (delq 'org-optimize-window-after-visibility-change
3430 (copy-sequence org-cycle-hook))
3431 org-cycle-hook))
3432 (pos (point)))
3434 (if (or bob-special (equal arg '(4)))
3435 ;; special case: use global cycling
3436 (setq arg t))
3438 (cond
3440 ((org-at-table-p 'any)
3441 ;; Enter the table or move to the next field in the table
3442 (or (org-table-recognize-table.el)
3443 (progn
3444 (if arg (org-table-edit-field t)
3445 (org-table-justify-field-maybe)
3446 (call-interactively 'org-table-next-field)))))
3448 ((eq arg t) ;; Global cycling
3450 (cond
3451 ((and (eq last-command this-command)
3452 (eq org-cycle-global-status 'overview))
3453 ;; We just created the overview - now do table of contents
3454 ;; This can be slow in very large buffers, so indicate action
3455 (message "CONTENTS...")
3456 (org-content)
3457 (message "CONTENTS...done")
3458 (setq org-cycle-global-status 'contents)
3459 (run-hook-with-args 'org-cycle-hook 'contents))
3461 ((and (eq last-command this-command)
3462 (eq org-cycle-global-status 'contents))
3463 ;; We just showed the table of contents - now show everything
3464 (show-all)
3465 (message "SHOW ALL")
3466 (setq org-cycle-global-status 'all)
3467 (run-hook-with-args 'org-cycle-hook 'all))
3470 ;; Default action: go to overview
3471 (org-overview)
3472 (message "OVERVIEW")
3473 (setq org-cycle-global-status 'overview)
3474 (run-hook-with-args 'org-cycle-hook 'overview))))
3476 ((integerp arg)
3477 ;; Show-subtree, ARG levels up from here.
3478 (save-excursion
3479 (org-back-to-heading)
3480 (outline-up-heading (if (< arg 0) (- arg)
3481 (- (funcall outline-level) arg)))
3482 (org-show-subtree)))
3484 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3485 ;; At a heading: rotate between three different views
3486 (org-back-to-heading)
3487 (let ((goal-column 0) eoh eol eos)
3488 ;; First, some boundaries
3489 (save-excursion
3490 (org-back-to-heading)
3491 (save-excursion
3492 (beginning-of-line 2)
3493 (while (and (not (eobp)) ;; this is like `next-line'
3494 (get-char-property (1- (point)) 'invisible))
3495 (beginning-of-line 2)) (setq eol (point)))
3496 (outline-end-of-heading) (setq eoh (point))
3497 (org-end-of-subtree t) (setq eos (point))
3498 (outline-next-heading))
3499 ;; Find out what to do next and set `this-command'
3500 (cond
3501 ((and (= eos eoh)
3502 ;; Nothing is hidden behind this heading
3503 (message "EMPTY ENTRY")
3504 (setq org-cycle-subtree-status nil)))
3505 ((>= eol eos)
3506 ;; Entire subtree is hidden in one line: open it
3507 (org-show-entry)
3508 (show-children)
3509 (message "CHILDREN")
3510 (setq org-cycle-subtree-status 'children)
3511 (run-hook-with-args 'org-cycle-hook 'children))
3512 ((and (eq last-command this-command)
3513 (eq org-cycle-subtree-status 'children))
3514 ;; We just showed the children, now show everything.
3515 (org-show-subtree)
3516 (message "SUBTREE")
3517 (setq org-cycle-subtree-status 'subtree)
3518 (run-hook-with-args 'org-cycle-hook 'subtree))
3520 ;; Default action: hide the subtree.
3521 (hide-subtree)
3522 (message "FOLDED")
3523 (setq org-cycle-subtree-status 'folded)
3524 (run-hook-with-args 'org-cycle-hook 'folded)))))
3526 ;; TAB emulation
3527 (buffer-read-only (org-back-to-heading))
3529 ((org-try-cdlatex-tab))
3531 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3532 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3533 (or (and (eq org-cycle-emulate-tab 'white)
3534 (= (match-end 0) (point-at-eol)))
3535 (and (eq org-cycle-emulate-tab 'whitestart)
3536 (>= (match-end 0) pos))))
3538 (eq org-cycle-emulate-tab t))
3539 (if (and (looking-at "[ \n\r\t]")
3540 (string-match "^[ \t]*$" (buffer-substring
3541 (point-at-bol) (point))))
3542 (progn
3543 (beginning-of-line 1)
3544 (and (looking-at "[ \t]+") (replace-match ""))))
3545 (indent-relative))
3547 (t (save-excursion
3548 (org-back-to-heading)
3549 (org-cycle))))))
3551 ;;;###autoload
3552 (defun org-global-cycle (&optional arg)
3553 "Cycle the global visibility. For details see `org-cycle'."
3554 (interactive "P")
3555 (if (integerp arg)
3556 (progn
3557 (show-all)
3558 (hide-sublevels arg)
3559 (setq org-cycle-global-status 'contents))
3560 (org-cycle '(4))))
3562 (defun org-overview ()
3563 "Switch to overview mode, shoing only top-level headlines.
3564 Really, this shows all headlines with level equal or greater than the level
3565 of the first headline in the buffer. This is important, because if the
3566 first headline is not level one, then (hide-sublevels 1) gives confusing
3567 results."
3568 (interactive)
3569 (hide-sublevels (save-excursion
3570 (goto-char (point-min))
3571 (if (re-search-forward (concat "^" outline-regexp) nil t)
3572 (progn
3573 (goto-char (match-beginning 0))
3574 (funcall outline-level))
3575 1))))
3577 ;; FIXME: allow an argument to give a limiting level for this.
3578 (defun org-content ()
3579 "Show all headlines in the buffer, like a table of contents"
3580 (interactive)
3581 (save-excursion
3582 ;; Visit all headings and show their offspring
3583 (goto-char (point-max))
3584 (catch 'exit
3585 (while (and (progn (condition-case nil
3586 (outline-previous-visible-heading 1)
3587 (error (goto-char (point-min))))
3589 (looking-at outline-regexp))
3590 (show-branches)
3591 (if (bobp) (throw 'exit nil))))))
3594 (defun org-optimize-window-after-visibility-change (state)
3595 "Adjust the window after a change in outline visibility.
3596 This function is the default value of the hook `org-cycle-hook'."
3597 (when (get-buffer-window (current-buffer))
3598 (cond
3599 ((eq state 'overview) (org-first-headline-recenter 1))
3600 ((eq state 'content) nil)
3601 ((eq state 'all) nil)
3602 ((eq state 'folded) nil)
3603 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3604 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3606 (defun org-subtree-end-visible-p ()
3607 "Is the end of the current subtree visible?"
3608 (pos-visible-in-window-p
3609 (save-excursion (org-end-of-subtree t) (point))))
3611 (defun org-first-headline-recenter (&optional N)
3612 "Move cursor to the first headline and recenter the headline.
3613 Optional argument N means, put the headline into the Nth line of the window."
3614 (goto-char (point-min))
3615 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3616 (beginning-of-line)
3617 (recenter (prefix-numeric-value N))))
3619 (defvar org-goto-window-configuration nil)
3620 (defvar org-goto-marker nil)
3621 (defvar org-goto-map (make-sparse-keymap))
3622 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3623 (while (setq cmd (pop cmds))
3624 (substitute-key-definition cmd cmd org-goto-map global-map)))
3625 (define-key org-goto-map "\C-m" 'org-goto-ret)
3626 (define-key org-goto-map [(left)] 'org-goto-left)
3627 (define-key org-goto-map [(right)] 'org-goto-right)
3628 (define-key org-goto-map [(?q)] 'org-goto-quit)
3629 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3630 (define-key org-goto-map "\C-i" 'org-cycle)
3631 (define-key org-goto-map [(tab)] 'org-cycle)
3632 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3633 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3634 (define-key org-goto-map "n" 'outline-next-visible-heading)
3635 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3636 (define-key org-goto-map "f" 'outline-forward-same-level)
3637 (define-key org-goto-map "b" 'outline-backward-same-level)
3638 (define-key org-goto-map "u" 'outline-up-heading)
3639 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3640 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3641 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3642 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3643 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3644 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3645 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3647 (defconst org-goto-help
3648 "Select a location to jump to, press RET
3649 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3651 (defun org-goto ()
3652 "Go to a different location of the document, keeping current visibility.
3654 When you want to go to a different location in a document, the fastest way
3655 is often to fold the entire buffer and then dive into the tree. This
3656 method has the disadvantage, that the previous location will be folded,
3657 which may not be what you want.
3659 This command works around this by showing a copy of the current buffer in
3660 overview mode. You can dive into the tree in that copy, to find the
3661 location you want to reach. When pressing RET, the command returns to the
3662 original buffer in which the visibility is still unchanged. It then jumps
3663 to the new location, making it and the headline hierarchy above it visible."
3664 (interactive)
3665 (let* ((org-goto-start-pos (point))
3666 (selected-point
3667 (org-get-location (current-buffer) org-goto-help)))
3668 (if selected-point
3669 (progn
3670 (org-mark-ring-push org-goto-start-pos)
3671 (goto-char selected-point)
3672 (if (or (org-invisible-p) (org-invisible-p2))
3673 (org-show-hierarchy-above)))
3674 (error "Quit"))))
3676 (defun org-get-location (buf help)
3677 "Let the user select a location in the Org-mode buffer BUF.
3678 This function uses a recursive edit. It returns the selected position
3679 or nil."
3680 (let (org-selected-point)
3681 (save-excursion
3682 (save-window-excursion
3683 (delete-other-windows)
3684 (switch-to-buffer (get-buffer-create "*org-goto*"))
3685 (with-output-to-temp-buffer "*Help*"
3686 (princ help))
3687 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3688 (setq buffer-read-only nil)
3689 (erase-buffer)
3690 (insert-buffer-substring buf)
3691 (let ((org-startup-truncated t)
3692 (org-startup-folded t)
3693 (org-startup-align-all-tables nil)
3694 (org-startup-with-deadline-check nil))
3695 (org-mode))
3696 (setq buffer-read-only t)
3697 (if (boundp 'org-goto-start-pos)
3698 (goto-char org-goto-start-pos)
3699 (goto-char (point-min)))
3700 (org-beginning-of-line)
3701 (message "Select location and press RET")
3702 ;; now we make sure that during selection, ony very few keys work
3703 ;; and that it is impossible to switch to another window.
3704 (let ((gm (current-global-map))
3705 (overriding-local-map org-goto-map))
3706 (unwind-protect
3707 (progn
3708 (use-global-map org-goto-map)
3709 (recursive-edit))
3710 (use-global-map gm)))))
3711 (kill-buffer "*org-goto*")
3712 org-selected-point))
3714 (defun org-goto-ret (&optional arg)
3715 "Finish `org-goto' by going to the new location."
3716 (interactive "P")
3717 (setq org-selected-point (point)
3718 current-prefix-arg arg)
3719 (throw 'exit nil))
3721 (defun org-goto-left ()
3722 "Finish `org-goto' by going to the new location."
3723 (interactive)
3724 (if (org-on-heading-p)
3725 (progn
3726 (beginning-of-line 1)
3727 (setq org-selected-point (point)
3728 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3729 (throw 'exit nil))
3730 (error "Not on a heading")))
3732 (defun org-goto-right ()
3733 "Finish `org-goto' by going to the new location."
3734 (interactive)
3735 (if (org-on-heading-p)
3736 (progn
3737 (outline-end-of-subtree)
3738 (or (eobp) (forward-char 1))
3739 (setq org-selected-point (point)
3740 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3741 (throw 'exit nil))
3742 (error "Not on a heading")))
3744 (defun org-goto-quit ()
3745 "Finish `org-goto' without cursor motion."
3746 (interactive)
3747 (setq org-selected-point nil)
3748 (throw 'exit nil))
3750 ;;; Promotion, Demotion, Inserting new headlines
3752 (defvar org-ignore-region nil
3753 "To temporarily disable the active region.")
3755 (defun org-insert-heading (&optional force-heading)
3756 "Insert a new heading or item with same depth at point.
3757 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3758 If point is at the beginning of a headline, insert a sibling before the
3759 current headline. If point is in the middle of a headline, split the headline
3760 at that position and make the rest of the headline part of the sibling below
3761 the current headline."
3762 (interactive "P")
3763 (if (= (buffer-size) 0)
3764 (insert "\n* ")
3765 (when (or force-heading (not (org-insert-item)))
3766 (let* ((head (save-excursion
3767 (condition-case nil
3768 (progn
3769 (org-back-to-heading)
3770 (match-string 0))
3771 (error "*"))))
3772 pos)
3773 (cond
3774 ((and (org-on-heading-p) (bolp)
3775 (save-excursion (backward-char 1) (not (org-invisible-p))))
3776 (open-line 1))
3777 ((and (bolp) (save-excursion
3778 (backward-char 1) (not (org-invisible-p))))
3779 nil)
3780 (t (newline)))
3781 (insert head) (just-one-space)
3782 (setq pos (point))
3783 (end-of-line 1)
3784 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3785 (run-hooks 'org-insert-heading-hook)))))
3787 (defun org-insert-item (&optional checkbox)
3788 "Insert a new item at the current level.
3789 Return t when things worked, nil when we are not in an item."
3790 (when (save-excursion
3791 (condition-case nil
3792 (progn
3793 (org-beginning-of-item)
3794 (org-at-item-p)
3796 (error nil)))
3797 (let* ((bul (match-string 0))
3798 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3799 (match-end 0)))
3800 pos)
3801 (cond
3802 ((and (org-at-item-p) (<= (point) eow))
3803 ;; before the bullet
3804 (beginning-of-line 1)
3805 (open-line 1))
3806 ((<= (point) eow)
3807 (beginning-of-line 1))
3808 (t (newline)))
3809 (insert bul (if checkbox "[ ]" ""))
3810 (just-one-space)
3811 (setq pos (point))
3812 (end-of-line 1)
3813 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3814 (org-maybe-renumber-ordered-list)
3817 (defun org-insert-todo-heading (arg)
3818 "Insert a new heading with the same level and TODO state as current heading.
3819 If the heading has no TODO state, or if the state is DONE, use the first
3820 state (TODO by default). Also with prefix arg, force first state."
3821 (interactive "P")
3822 (when (not (org-insert-item 'checkbox))
3823 (org-insert-heading)
3824 (save-excursion
3825 (org-back-to-heading)
3826 (outline-previous-heading)
3827 (looking-at org-todo-line-regexp))
3828 (if (or arg
3829 (not (match-beginning 2))
3830 (equal (match-string 2) org-done-string))
3831 (insert (car org-todo-keywords) " ")
3832 (insert (match-string 2) " "))))
3834 (defun org-promote-subtree ()
3835 "Promote the entire subtree.
3836 See also `org-promote'."
3837 (interactive)
3838 (save-excursion
3839 (org-map-tree 'org-promote)))
3841 (defun org-demote-subtree ()
3842 "Demote the entire subtree. See `org-demote'.
3843 See also `org-promote'."
3844 (interactive)
3845 (save-excursion
3846 (org-map-tree 'org-demote)))
3848 (defun org-do-promote ()
3849 "Promote the current heading higher up the tree.
3850 If the region is active in `transient-mark-mode', promote all headings
3851 in the region."
3852 (interactive)
3853 (save-excursion
3854 (if (org-region-active-p)
3855 (org-map-region 'org-promote (region-beginning) (region-end))
3856 (org-promote)))
3857 (org-fix-position-after-promote))
3859 (defun org-do-demote ()
3860 "Demote the current heading lower down the tree.
3861 If the region is active in `transient-mark-mode', demote all headings
3862 in the region."
3863 (interactive)
3864 (save-excursion
3865 (if (org-region-active-p)
3866 (org-map-region 'org-demote (region-beginning) (region-end))
3867 (org-demote)))
3868 (org-fix-position-after-promote))
3870 (defun org-fix-position-after-promote ()
3871 "Make sure that after pro/demotion cursor position is right."
3872 (and (equal (char-after) ?\ )
3873 (equal (char-before) ?*)
3874 (forward-char 1)))
3876 (defun org-get-legal-level (level change)
3877 "Rectify a level change under the influence of `org-odd-levels-only'
3878 LEVEL is a current level, CHANGE is by how much the level should be
3879 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3880 even level numbers will become the next higher odd number."
3881 (if org-odd-levels-only
3882 (cond ((not change) (1+ (* 2 (/ level 2))))
3883 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3884 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3885 (max 1 (+ level change))))
3887 (defun org-promote ()
3888 "Promote the current heading higher up the tree.
3889 If the region is active in `transient-mark-mode', promote all headings
3890 in the region."
3891 (org-back-to-heading t)
3892 (let* ((level (save-match-data (funcall outline-level)))
3893 (up-head (make-string (org-get-legal-level level -1) ?*))
3894 (diff (abs (- level (length up-head)))))
3895 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3896 (replace-match up-head nil t)
3897 ;; Fixup tag positioning
3898 (and org-auto-align-tags (org-set-tags nil t))
3899 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
3901 (defun org-demote ()
3902 "Demote the current heading lower down the tree.
3903 If the region is active in `transient-mark-mode', demote all headings
3904 in the region."
3905 (org-back-to-heading t)
3906 (let* ((level (save-match-data (funcall outline-level)))
3907 (down-head (make-string (org-get-legal-level level 1) ?*))
3908 (diff (abs (- level (length down-head)))))
3909 (replace-match down-head nil t)
3910 ;; Fixup tag positioning
3911 (and org-auto-align-tags (org-set-tags nil t))
3912 (if org-adapt-indentation (org-fixup-indentation diff))))
3914 (defun org-map-tree (fun)
3915 "Call FUN for every heading underneath the current one."
3916 (org-back-to-heading)
3917 (let ((level (funcall outline-level)))
3918 (save-excursion
3919 (funcall fun)
3920 (while (and (progn
3921 (outline-next-heading)
3922 (> (funcall outline-level) level))
3923 (not (eobp)))
3924 (funcall fun)))))
3926 (defun org-map-region (fun beg end)
3927 "Call FUN for every heading between BEG and END."
3928 (let ((org-ignore-region t))
3929 (save-excursion
3930 (setq end (copy-marker end))
3931 (goto-char beg)
3932 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3933 (< (point) end))
3934 (funcall fun))
3935 (while (and (progn
3936 (outline-next-heading)
3937 (< (point) end))
3938 (not (eobp)))
3939 (funcall fun)))))
3941 (defun org-fixup-indentation (diff)
3942 "Change the indentation in the current entry by DIFF
3943 However, if any line in the current entry has no indentation, or if it
3944 would end up with no indentation after the change, nothing at all is done."
3945 (save-excursion
3946 (let ((end (save-excursion (outline-next-heading)
3947 (point-marker)))
3948 (prohibit (if (> diff 0)
3949 "^\\S-"
3950 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
3951 col)
3952 (unless (save-excursion (re-search-forward prohibit end t))
3953 (while (re-search-forward "^[ \t]+" end t)
3954 (goto-char (match-end 0))
3955 (setq col (current-column))
3956 (if (< diff 0) (replace-match ""))
3957 (indent-to (+ diff col))))
3958 (move-marker end nil))))
3960 ;;; Vertical tree motion, cutting and pasting of subtrees
3962 (defun org-move-subtree-up (&optional arg)
3963 "Move the current subtree up past ARG headlines of the same level."
3964 (interactive "p")
3965 (org-move-subtree-down (- (prefix-numeric-value arg))))
3967 (defun org-move-subtree-down (&optional arg)
3968 "Move the current subtree down past ARG headlines of the same level."
3969 (interactive "p")
3970 (setq arg (prefix-numeric-value arg))
3971 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3972 'outline-get-last-sibling))
3973 (ins-point (make-marker))
3974 (cnt (abs arg))
3975 beg end txt folded)
3976 ;; Select the tree
3977 (org-back-to-heading)
3978 (setq beg (point))
3979 (save-match-data
3980 (save-excursion (outline-end-of-heading)
3981 (setq folded (org-invisible-p)))
3982 (outline-end-of-subtree))
3983 (outline-next-heading)
3984 (setq end (point))
3985 ;; Find insertion point, with error handling
3986 (goto-char beg)
3987 (while (> cnt 0)
3988 (or (and (funcall movfunc) (looking-at outline-regexp))
3989 (progn (goto-char beg)
3990 (error "Cannot move past superior level or buffer limit")))
3991 (setq cnt (1- cnt)))
3992 (if (> arg 0)
3993 ;; Moving forward - still need to move over subtree
3994 (progn (outline-end-of-subtree)
3995 (outline-next-heading)
3996 (if (not (or (looking-at (concat "^" outline-regexp))
3997 (bolp)))
3998 (newline))))
3999 (move-marker ins-point (point))
4000 (setq txt (buffer-substring beg end))
4001 (delete-region beg end)
4002 (insert txt)
4003 (goto-char ins-point)
4004 (if folded (hide-subtree))
4005 (move-marker ins-point nil)))
4007 (defvar org-subtree-clip ""
4008 "Clipboard for cut and paste of subtrees.
4009 This is actually only a copy of the kill, because we use the normal kill
4010 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4012 (defvar org-subtree-clip-folded nil
4013 "Was the last copied subtree folded?
4014 This is used to fold the tree back after pasting.")
4016 (defun org-cut-subtree ()
4017 "Cut the current subtree into the clipboard.
4018 This is a short-hand for marking the subtree and then cutting it."
4019 (interactive)
4020 (org-copy-subtree 'cut))
4022 (defun org-copy-subtree (&optional cut)
4023 "Cut the current subtree into the clipboard.
4024 This is a short-hand for marking the subtree and then copying it.
4025 If CUT is non nil, actually cut the subtree."
4026 (interactive)
4027 (let (beg end folded)
4028 (org-back-to-heading)
4029 (setq beg (point))
4030 (save-match-data
4031 (save-excursion (outline-end-of-heading)
4032 (setq folded (org-invisible-p)))
4033 (outline-end-of-subtree))
4034 (if (equal (char-after) ?\n) (forward-char 1))
4035 (setq end (point))
4036 (goto-char beg)
4037 (when (> end beg)
4038 (setq org-subtree-clip-folded folded)
4039 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4040 (setq org-subtree-clip (current-kill 0))
4041 (message "%s: Subtree with %d characters"
4042 (if cut "Cut" "Copied")
4043 (length org-subtree-clip)))))
4045 (defun org-paste-subtree (&optional level tree)
4046 "Paste the clipboard as a subtree, with modification of headline level.
4047 The entire subtree is promoted or demoted in order to match a new headline
4048 level. By default, the new level is derived from the visible headings
4049 before and after the insertion point, and taken to be the inferior headline
4050 level of the two. So if the previous visible heading is level 3 and the
4051 next is level 4 (or vice versa), level 4 will be used for insertion.
4052 This makes sure that the subtree remains an independent subtree and does
4053 not swallow low level entries.
4055 You can also force a different level, either by using a numeric prefix
4056 argument, or by inserting the heading marker by hand. For example, if the
4057 cursor is after \"*****\", then the tree will be shifted to level 5.
4059 If you want to insert the tree as is, just use \\[yank].
4061 If optional TREE is given, use this text instead of the kill ring."
4062 (interactive "P")
4063 (unless (org-kill-is-subtree-p tree)
4064 (error
4065 (substitute-command-keys
4066 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4067 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4068 (^re (concat "^\\(" outline-regexp "\\)"))
4069 (re (concat "\\(" outline-regexp "\\)"))
4070 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4072 (old-level (if (string-match ^re txt)
4073 (- (match-end 0) (match-beginning 0))
4074 -1))
4075 (force-level (cond (level (prefix-numeric-value level))
4076 ((string-match
4077 ^re_ (buffer-substring (point-at-bol) (point)))
4078 (- (match-end 0) (match-beginning 0)))
4079 (t nil)))
4080 (previous-level (save-excursion
4081 (condition-case nil
4082 (progn
4083 (outline-previous-visible-heading 1)
4084 (if (looking-at re)
4085 (- (match-end 0) (match-beginning 0))
4087 (error 1))))
4088 (next-level (save-excursion
4089 (condition-case nil
4090 (progn
4091 (outline-next-visible-heading 1)
4092 (if (looking-at re)
4093 (- (match-end 0) (match-beginning 0))
4095 (error 1))))
4096 (new-level (or force-level (max previous-level next-level)))
4097 (shift (if (or (= old-level -1)
4098 (= new-level -1)
4099 (= old-level new-level))
4101 (- new-level old-level)))
4102 (shift1 shift)
4103 (delta (if (> shift 0) -1 1))
4104 (func (if (> shift 0) 'org-demote 'org-promote))
4105 (org-odd-levels-only nil)
4106 beg end)
4107 ;; Remove the forces level indicator
4108 (if force-level
4109 (delete-region (point-at-bol) (point)))
4110 ;; Make sure we start at the beginning of an empty line
4111 (if (not (bolp)) (insert "\n"))
4112 (if (not (looking-at "[ \t]*$"))
4113 (progn (insert "\n") (backward-char 1)))
4114 ;; Paste
4115 (setq beg (point))
4116 (if (string-match "[ \t\r\n]+\\'" txt)
4117 (setq txt (replace-match "\n" t t txt)))
4118 (insert txt)
4119 (setq end (point))
4120 (if (looking-at "[ \t\r\n]+")
4121 (replace-match "\n"))
4122 (goto-char beg)
4123 ;; Shift if necessary
4124 (if (= shift 0)
4125 (message "Pasted at level %d, without shift" new-level)
4126 (save-restriction
4127 (narrow-to-region beg end)
4128 (while (not (= shift 0))
4129 (org-map-region func (point-min) (point-max))
4130 (setq shift (+ delta shift)))
4131 (goto-char (point-min))
4132 (message "Pasted at level %d, with shift by %d levels"
4133 new-level shift1)))
4134 (if (and kill-ring
4135 (eq org-subtree-clip (current-kill 0))
4136 org-subtree-clip-folded)
4137 ;; The tree was folded before it was killed/copied
4138 (hide-subtree))))
4140 (defun org-kill-is-subtree-p (&optional txt)
4141 "Check if the current kill is an outline subtree, or a set of trees.
4142 Returns nil if kill does not start with a headline, or if the first
4143 headline level is not the largest headline level in the tree.
4144 So this will actually accept several entries of equal levels as well,
4145 which is OK for `org-paste-subtree'.
4146 If optional TXT is given, check this string instead of the current kill."
4147 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4148 (start-level (and kill
4149 (string-match (concat "\\`" outline-regexp) kill)
4150 (- (match-end 0) (match-beginning 0))))
4151 (re (concat "^" outline-regexp))
4152 (start 1))
4153 (if (not start-level)
4154 nil ;; does not even start with a heading
4155 (catch 'exit
4156 (while (setq start (string-match re kill (1+ start)))
4157 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4158 (throw 'exit nil)))
4159 t))))
4161 (defun org-narrow-to-subtree ()
4162 "Narrow buffer to the current subtree."
4163 (interactive)
4164 (save-excursion
4165 (narrow-to-region
4166 (progn (org-back-to-heading) (point))
4167 (progn (org-end-of-subtree t) (point)))))
4169 ;;; Plain list items
4171 (defun org-at-item-p ()
4172 "Is point in a line starting a hand-formatted item?"
4173 (let ((llt org-plain-list-ordered-item-terminator))
4174 (save-excursion
4175 (goto-char (point-at-bol))
4176 (looking-at
4177 (cond
4178 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4179 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4180 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4181 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4183 (defun org-at-item-checkbox-p ()
4184 "Is point at a line starting a plain-list item with a checklet?"
4185 (and (org-at-item-p)
4186 (save-excursion
4187 (goto-char (match-end 0))
4188 (skip-chars-forward " \t")
4189 (looking-at "\\[[ X]\\]"))))
4191 (defun org-toggle-checkbox (&optional arg)
4192 "Toggle the checkbox in the current line."
4193 (interactive "P")
4194 (catch 'exit
4195 (let (beg end status (firstnew 'unknown))
4196 (cond
4197 ((org-region-active-p)
4198 (setq beg (region-beginning) end (region-end)))
4199 ((org-on-heading-p)
4200 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4201 ((org-at-item-checkbox-p)
4202 (save-excursion
4203 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4204 (throw 'exit t))
4205 (t (error "Not at a checkbox or heading, and no active region")))
4206 (save-excursion
4207 (goto-char beg)
4208 (while (< (point) end)
4209 (when (org-at-item-checkbox-p)
4210 (setq status (equal (match-string 0) "[X]"))
4211 (when (eq firstnew 'unknown)
4212 (setq firstnew (not status)))
4213 (replace-match
4214 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4215 (beginning-of-line 2))))))
4217 (defun org-get-indentation (&optional line)
4218 "Get the indentation of the current line, interpreting tabs.
4219 When LINE is given, assume it represents a line and compute its indentation."
4220 (if line
4221 (if (string-match "^ *" (org-remove-tabs line))
4222 (match-end 0))
4223 (save-excursion
4224 (beginning-of-line 1)
4225 (skip-chars-forward " \t")
4226 (current-column))))
4228 (defun org-remove-tabs (s &optional width)
4229 "Replace tabulators in S with spaces.
4230 Assumes that s is a single line, starting in column 0."
4231 (setq width (or width tab-width))
4232 (while (string-match "\t" s)
4233 (setq s (replace-match
4234 (make-string
4235 (- (* width (/ (+ (match-beginning 0) width) width))
4236 (match-beginning 0)) ?\ )
4237 t t s)))
4240 ;; FIXME: document properly.
4241 (defun org-fix-indentation (line ind)
4242 "If the current indenation is smaller than ind1, leave it alone.
4243 If it is larger than ind, reduce it by ind."
4244 (let* ((l (org-remove-tabs line))
4245 (i (org-get-indentation l))
4246 (i1 (car ind)) (i2 (cdr ind)))
4247 (if (>= i i2) (setq l (substring line i2)))
4248 (if (> i1 0)
4249 (concat (make-string i1 ?\ ) l)
4250 l)))
4252 (defun org-beginning-of-item ()
4253 "Go to the beginning of the current hand-formatted item.
4254 If the cursor is not in an item, throw an error."
4255 (interactive)
4256 (let ((pos (point))
4257 (limit (save-excursion (org-back-to-heading)
4258 (beginning-of-line 2) (point)))
4259 ind ind1)
4260 (if (org-at-item-p)
4261 (beginning-of-line 1)
4262 (beginning-of-line 1)
4263 (skip-chars-forward " \t")
4264 (setq ind (current-column))
4265 (if (catch 'exit
4266 (while t
4267 (beginning-of-line 0)
4268 (if (< (point) limit) (throw 'exit nil))
4269 (unless (looking-at "[ \t]*$")
4270 (skip-chars-forward " \t")
4271 (setq ind1 (current-column))
4272 (if (< ind1 ind)
4273 (throw 'exit (org-at-item-p))))))
4275 (goto-char pos)
4276 (error "Not in an item")))))
4278 (defun org-end-of-item ()
4279 "Go to the end of the current hand-formatted item.
4280 If the cursor is not in an item, throw an error."
4281 (interactive)
4282 (let ((pos (point))
4283 (limit (save-excursion (outline-next-heading) (point)))
4284 (ind (save-excursion
4285 (org-beginning-of-item)
4286 (skip-chars-forward " \t")
4287 (current-column)))
4288 ind1)
4289 (if (catch 'exit
4290 (while t
4291 (beginning-of-line 2)
4292 (if (>= (point) limit) (throw 'exit t))
4293 (unless (looking-at "[ \t]*$")
4294 (skip-chars-forward " \t")
4295 (setq ind1 (current-column))
4296 (if (<= ind1 ind) (throw 'exit t)))))
4297 (beginning-of-line 1)
4298 (goto-char pos)
4299 (error "Not in an item"))))
4301 (defun org-next-item ()
4302 "Move to the beginning of the next item in the current plain list.
4303 Error if not at a plain list, or if this is the last item in the list."
4304 (interactive)
4305 (let (ind ind1 (pos (point)))
4306 (org-beginning-of-item)
4307 (setq ind (org-get-indentation))
4308 (org-end-of-item)
4309 (setq ind1 (org-get-indentation))
4310 (unless (and (org-at-item-p) (= ind ind1))
4311 (goto-char pos)
4312 (error "On last item"))))
4314 (defun org-previous-item ()
4315 "Move to the beginning of the previous item in the current plain list.
4316 Error if not at a plain list, or if this is the last item in the list."
4317 (interactive)
4318 (let (beg ind (pos (point)))
4319 (org-beginning-of-item)
4320 (setq beg (point))
4321 (setq ind (org-get-indentation))
4322 (goto-char beg)
4323 (catch 'exit
4324 (while t
4325 (beginning-of-line 0)
4326 (if (looking-at "[ \t]*$")
4328 (if (<= (org-get-indentation) ind)
4329 (throw 'exit t)))))
4330 (condition-case nil
4331 (org-beginning-of-item)
4332 (error (goto-char pos)
4333 (error "On first item")))))
4335 (defun org-move-item-down ()
4336 "Move the plain list item at point down, i.e. swap with following item.
4337 Subitems (items with larger indentation) are considered part of the item,
4338 so this really moves item trees."
4339 (interactive)
4340 (let (beg end ind ind1 (pos (point)) txt)
4341 (org-beginning-of-item)
4342 (setq beg (point))
4343 (setq ind (org-get-indentation))
4344 (org-end-of-item)
4345 (setq end (point))
4346 (setq ind1 (org-get-indentation))
4347 (if (and (org-at-item-p) (= ind ind1))
4348 (progn
4349 (org-end-of-item)
4350 (setq txt (buffer-substring beg end))
4351 (save-excursion
4352 (delete-region beg end))
4353 (setq pos (point))
4354 (insert txt)
4355 (goto-char pos)
4356 (org-maybe-renumber-ordered-list))
4357 (goto-char pos)
4358 (error "Cannot move this item further down"))))
4360 (defun org-move-item-up (arg)
4361 "Move the plain list item at point up, i.e. swap with previous item.
4362 Subitems (items with larger indentation) are considered part of the item,
4363 so this really moves item trees."
4364 (interactive "p")
4365 (let (beg end ind ind1 (pos (point)) txt)
4366 (org-beginning-of-item)
4367 (setq beg (point))
4368 (setq ind (org-get-indentation))
4369 (org-end-of-item)
4370 (setq end (point))
4371 (goto-char beg)
4372 (catch 'exit
4373 (while t
4374 (beginning-of-line 0)
4375 (if (looking-at "[ \t]*$")
4377 (if (<= (setq ind1 (org-get-indentation)) ind)
4378 (throw 'exit t)))))
4379 (condition-case nil
4380 (org-beginning-of-item)
4381 (error (goto-char beg)
4382 (error "Cannot move this item further up")))
4383 (setq ind1 (org-get-indentation))
4384 (if (and (org-at-item-p) (= ind ind1))
4385 (progn
4386 (setq txt (buffer-substring beg end))
4387 (save-excursion
4388 (delete-region beg end))
4389 (setq pos (point))
4390 (insert txt)
4391 (goto-char pos)
4392 (org-maybe-renumber-ordered-list))
4393 (goto-char pos)
4394 (error "Cannot move this item further up"))))
4396 (defun org-maybe-renumber-ordered-list ()
4397 "Renumber the ordered list at point if setup allows it.
4398 This tests the user option `org-auto-renumber-ordered-lists' before
4399 doing the renumbering."
4400 (and org-auto-renumber-ordered-lists
4401 (org-at-item-p)
4402 (match-beginning 3)
4403 (org-renumber-ordered-list 1)))
4405 (defun org-get-string-indentation (s)
4406 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4407 (let ((n -1) (i 0) (w tab-width) c)
4408 (catch 'exit
4409 (while (< (setq n (1+ n)) (length s))
4410 (setq c (aref s n))
4411 (cond ((= c ?\ ) (setq i (1+ i)))
4412 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4413 (t (throw 'exit t)))))
4416 (defun org-renumber-ordered-list (arg)
4417 "Renumber an ordered plain list.
4418 Cursor needs to be in the first line of an item, the line that starts
4419 with something like \"1.\" or \"2)\"."
4420 (interactive "p")
4421 (unless (and (org-at-item-p)
4422 (match-beginning 3))
4423 (error "This is not an ordered list"))
4424 (let ((line (org-current-line))
4425 (col (current-column))
4426 (ind (org-get-string-indentation
4427 (buffer-substring (point-at-bol) (match-beginning 3))))
4428 ;; (term (substring (match-string 3) -1))
4429 ind1 (n (1- arg)))
4430 ;; find where this list begins
4431 (catch 'exit
4432 (while t
4433 (catch 'next
4434 (beginning-of-line 0)
4435 (if (looking-at "[ \t]*$") (throw 'next t))
4436 (skip-chars-forward " \t") (setq ind1 (current-column))
4437 (if (or (< ind1 ind)
4438 (and (= ind1 ind)
4439 (not (org-at-item-p))))
4440 (throw 'exit t)))))
4441 ;; Walk forward and replace these numbers
4442 (catch 'exit
4443 (while t
4444 (catch 'next
4445 (beginning-of-line 2)
4446 (if (eobp) (throw 'exit nil))
4447 (if (looking-at "[ \t]*$") (throw 'next nil))
4448 (skip-chars-forward " \t") (setq ind1 (current-column))
4449 (if (> ind1 ind) (throw 'next t))
4450 (if (< ind1 ind) (throw 'exit t))
4451 (if (not (org-at-item-p)) (throw 'exit nil))
4452 (if (not (match-beginning 3))
4453 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4454 (delete-region (match-beginning 3) (1- (match-end 3)))
4455 (goto-char (match-beginning 3))
4456 (insert (format "%d" (setq n (1+ n)))))))
4457 (goto-line line)
4458 (move-to-column col)))
4460 (defvar org-last-indent-begin-marker (make-marker))
4461 (defvar org-last-indent-end-marker (make-marker))
4463 (defun org-outdent-item (arg)
4464 "Outdent a local list item."
4465 (interactive "p")
4466 (org-indent-item (- arg)))
4468 (defun org-indent-item (arg)
4469 "Indent a local list item."
4470 (interactive "p")
4471 (unless (org-at-item-p)
4472 (error "Not on an item"))
4473 (save-excursion
4474 (let (beg end ind ind1)
4475 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4476 (setq beg org-last-indent-begin-marker
4477 end org-last-indent-end-marker)
4478 (org-beginning-of-item)
4479 (setq beg (move-marker org-last-indent-begin-marker (point)))
4480 (org-end-of-item)
4481 (setq end (move-marker org-last-indent-end-marker (point))))
4482 (goto-char beg)
4483 (skip-chars-forward " \t") (setq ind (current-column))
4484 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4485 (while (< (point) end)
4486 (beginning-of-line 1)
4487 (skip-chars-forward " \t") (setq ind1 (current-column))
4488 (delete-region (point-at-bol) (point))
4489 (indent-to-column (+ ind1 arg))
4490 (beginning-of-line 2)))))
4492 ;;; Archiving
4494 (defun org-archive-subtree (&optional find-done)
4495 "Move the current subtree to the archive.
4496 The archive can be a certain top-level heading in the current file, or in
4497 a different file. The tree will be moved to that location, the subtree
4498 heading be marked DONE, and the current time will be added.
4500 When called with prefix argument FIND-DONE, find whole trees without any
4501 open TODO items and archive them (after getting confirmation from the user).
4502 If the cursor is not at a headline when this comand is called, try all level
4503 1 trees. If the cursor is on a headline, only try the direct children of
4504 this heading. "
4505 (interactive "P")
4506 (if find-done
4507 (org-archive-all-done)
4508 ;; Save all relevant TODO keyword-relatex variables
4510 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4511 (tr-org-todo-keywords org-todo-keywords)
4512 (tr-org-todo-interpretation org-todo-interpretation)
4513 (tr-org-done-string org-done-string)
4514 (tr-org-todo-regexp org-todo-regexp)
4515 (tr-org-todo-line-regexp org-todo-line-regexp)
4516 (this-buffer (current-buffer))
4517 file heading buffer level newfile-p)
4518 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4519 (progn
4520 (setq file (format (match-string 1 org-archive-location)
4521 (file-name-nondirectory buffer-file-name))
4522 heading (match-string 2 org-archive-location)))
4523 (error "Invalid `org-archive-location'"))
4524 (if (> (length file) 0)
4525 (setq newfile-p (not (file-exists-p file))
4526 buffer (find-file-noselect file))
4527 (setq buffer (current-buffer)))
4528 (unless buffer
4529 (error "Cannot access file \"%s\"" file))
4530 (if (and (> (length heading) 0)
4531 (string-match "^\\*+" heading))
4532 (setq level (match-end 0))
4533 (setq heading nil level 0))
4534 (save-excursion
4535 ;; We first only copy, in case something goes wrong
4536 ;; we need to protect this-command, to avoid kill-region sets it,
4537 ;; which would lead to duplication of subtrees
4538 (let (this-command) (org-copy-subtree))
4539 (set-buffer buffer)
4540 ;; Enforce org-mode for the archive buffer
4541 (if (not (org-mode-p))
4542 ;; Force the mode for future visits.
4543 (let ((org-insert-mode-line-in-empty-file t))
4544 (call-interactively 'org-mode)))
4545 (when newfile-p
4546 (goto-char (point-max))
4547 (insert (format "\nArchived entries from file %s\n\n"
4548 (buffer-file-name this-buffer))))
4549 ;; Force the TODO keywords of the original buffer
4550 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4551 (org-todo-keywords tr-org-todo-keywords)
4552 (org-todo-interpretation tr-org-todo-interpretation)
4553 (org-done-string tr-org-done-string)
4554 (org-todo-regexp tr-org-todo-regexp)
4555 (org-todo-line-regexp tr-org-todo-line-regexp))
4556 (goto-char (point-min))
4557 (if heading
4558 (progn
4559 (if (re-search-forward
4560 (concat "\\(^\\|\r\\)"
4561 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4562 nil t)
4563 (goto-char (match-end 0))
4564 ;; Heading not found, just insert it at the end
4565 (goto-char (point-max))
4566 (or (bolp) (insert "\n"))
4567 (insert "\n" heading "\n")
4568 (end-of-line 0))
4569 ;; Make the subtree visible
4570 (show-subtree)
4571 (org-end-of-subtree t)
4572 (skip-chars-backward " \t\r\n]")
4573 (and (looking-at "[ \t\r\n]*")
4574 (replace-match "\n\n")))
4575 ;; No specific heading, just go to end of file.
4576 (goto-char (point-max)) (insert "\n"))
4577 ;; Paste
4578 (org-paste-subtree (1+ level))
4579 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4580 (if org-archive-mark-done
4581 (org-todo (length org-todo-keywords)))
4582 ;; Move cursor to right after the TODO keyword
4583 (when org-archive-stamp-time
4584 (beginning-of-line 1)
4585 (looking-at org-todo-line-regexp)
4586 (goto-char (or (match-end 2) (match-beginning 3)))
4587 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4588 (org-current-time))
4589 ")"))
4590 ;; Save the buffer, if it is not the same buffer.
4591 (if (not (eq this-buffer buffer)) (save-buffer))))
4592 ;; Here we are back in the original buffer. Everything seems to have
4593 ;; worked. So now cut the tree and finish up.
4594 (let (this-command) (org-cut-subtree))
4595 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4596 (message "Subtree archived %s"
4597 (if (eq this-buffer buffer)
4598 (concat "under heading: " heading)
4599 (concat "in file: " (abbreviate-file-name file)))))))
4601 (defun org-archive-all-done (&optional tag)
4602 "Archive sublevels of the current tree without open TODO items.
4603 If the cursor is not on a headline, try all level 1 trees. If
4604 it is on a headline, try all direct children.
4605 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4606 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4607 (rea (concat ".*:" org-archive-tag ":"))
4608 (begm (make-marker))
4609 (endm (make-marker))
4610 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4611 "Move subtree to archive (no open TODO items)? "))
4612 beg end (cntarch 0))
4613 (if (org-on-heading-p)
4614 (progn
4615 (setq re1 (concat "^" (regexp-quote
4616 (make-string
4617 (1+ (- (match-end 0) (match-beginning 0)))
4618 ?*))
4619 " "))
4620 (move-marker begm (point))
4621 (move-marker endm (org-end-of-subtree)))
4622 (setq re1 "^* ")
4623 (move-marker begm (point-min))
4624 (move-marker endm (point-max)))
4625 (save-excursion
4626 (goto-char begm)
4627 (while (re-search-forward re1 endm t)
4628 (setq beg (match-beginning 0)
4629 end (save-excursion (org-end-of-subtree t) (point)))
4630 (goto-char beg)
4631 (if (re-search-forward re end t)
4632 (goto-char end)
4633 (goto-char beg)
4634 (if (and (or (not tag) (not (looking-at rea)))
4635 (y-or-n-p question))
4636 (progn
4637 (if tag
4638 (org-toggle-tag org-archive-tag 'on)
4639 (org-archive-subtree))
4640 (setq cntarch (1+ cntarch)))
4641 (goto-char end)))))
4642 (message "%d trees archived" cntarch)))
4644 (defun org-cycle-hide-archived-subtrees (state)
4645 "Re-hide all archived subtrees after a visibility state change."
4646 (when (and (not org-cycle-open-archived-trees)
4647 (not (memq state '(overview folded))))
4648 (save-excursion
4649 (let* ((globalp (memq state '(contents all)))
4650 (beg (if globalp (point-min) (point)))
4651 (end (if globalp (point-max) (org-end-of-subtree))))
4652 (org-hide-archived-subtrees beg end)))))
4654 (defun org-hide-archived-subtrees (beg end)
4655 "Re-hide all archived subtrees after a visibility state change."
4656 (save-excursion
4657 (let* ((re (concat ":" org-archive-tag ":")))
4658 (goto-char beg)
4659 (while (re-search-forward re end t)
4660 (and (org-on-heading-p) (hide-subtree))
4661 (org-end-of-subtree)))))
4663 (defun org-toggle-tag (tag &optional onoff)
4664 "Toggle the tag TAG for the current line.
4665 If ONOFF is `on' or `off', don't toggle but set to this state."
4666 (unless (org-on-heading-p) (error "Not on headling"))
4667 (let (res current)
4668 (save-excursion
4669 (beginning-of-line)
4670 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
4671 (point-at-eol) t)
4672 (progn
4673 (setq current (match-string 1))
4674 (replace-match ""))
4675 (setq current ""))
4676 (setq current (nreverse (org-split-string current ":")))
4677 (cond
4678 ((eq onoff 'on)
4679 (setq res t)
4680 (or (member tag current) (push tag current)))
4681 ((eq onoff 'off)
4682 (or (not (member tag current)) (setq current (delete tag current))))
4683 (t (if (member tag current)
4684 (setq current (delete tag current))
4685 (setq res t)
4686 (push tag current))))
4687 (end-of-line 1)
4688 (when current
4689 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
4690 (org-set-tags nil t))
4691 res))
4693 (defun org-toggle-archive-tag (&optional arg)
4694 "Toggle the archive tag for the current headline.
4695 With prefix ARG, check all children of current headline and offer tagging
4696 the children that do not contain any open TODO items."
4697 (interactive "P")
4698 (if arg
4699 (org-archive-all-done 'tag)
4700 (let (set)
4701 (save-excursion
4702 (org-back-to-heading t)
4703 (setq set (org-toggle-tag org-archive-tag))
4704 (when set (hide-subtree)))
4705 (and set (beginning-of-line 1))
4706 (message "Subtree %s" (if set "archived" "unarchived")))))
4708 (defun org-prepare-agenda-buffers (files)
4709 "Create buffers for all agenda files, protect archived trees and comments."
4710 (interactive)
4711 (let ((pa '(:org-archived t))
4712 (pc '(:org-comment t))
4713 (pall '(:org-archived t :org-comment t))
4714 (rea (concat ":" org-archive-tag ":"))
4715 bmp file re)
4716 (save-excursion
4717 (while (setq file (pop files))
4718 (org-check-agenda-file file)
4719 (set-buffer (org-get-agenda-file-buffer file))
4720 (widen)
4721 (setq bmp (buffer-modified-p))
4722 (save-excursion
4723 (remove-text-properties (point-min) (point-max) pall)
4724 (when org-agenda-skip-archived-trees
4725 (goto-char (point-min))
4726 (while (re-search-forward rea nil t)
4727 (if (org-on-heading-p)
4728 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
4729 (goto-char (point-min))
4730 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
4731 (while (re-search-forward re nil t)
4732 (add-text-properties
4733 (match-beginning 0) (org-end-of-subtree t) pc)))
4734 (set-buffer-modified-p bmp)))))
4736 (defun org-agenda-skip ()
4737 "Throw to `:skip' in places that should be skipped."
4738 (let ((p (point-at-bol)))
4739 (and org-agenda-skip-archived-trees
4740 (get-text-property p :org-archived)
4741 (org-end-of-subtree)
4742 (throw :skip t))
4743 (and (get-text-property p :org-comment)
4744 (org-end-of-subtree)
4745 (throw :skip t))
4746 (if (equal (char-after p) ?#) (throw :skip t))))
4748 (defun org-agenda-toggle-archive-tag ()
4749 "Toggle the archive tag for the current entry."
4750 (interactive)
4751 (org-agenda-check-no-diary)
4752 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
4753 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
4754 (org-agenda-error)))
4755 (buffer (marker-buffer hdmarker))
4756 (pos (marker-position hdmarker))
4757 (buffer-read-only nil)
4758 newhead)
4759 (with-current-buffer buffer
4760 (widen)
4761 (goto-char pos)
4762 (org-show-hidden-entry)
4763 (save-excursion
4764 (and (outline-next-heading)
4765 (org-flag-heading nil))) ; show the next heading
4766 (call-interactively 'org-toggle-archive-tag)
4767 (end-of-line 1)
4768 (setq newhead (org-get-heading)))
4769 (org-agenda-change-all-lines newhead hdmarker)
4770 (beginning-of-line 1)))
4772 ;;; Dynamic blocks
4774 (defun org-find-dblock (name)
4775 "Find the first dynamic block with name NAME in the buffer.
4776 If not found, stay at current position and return nil."
4777 (let (pos)
4778 (save-excursion
4779 (goto-char (point-min))
4780 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
4781 nil t)
4782 (match-beginning 0))))
4783 (if pos (goto-char pos))
4784 pos))
4786 (defconst org-dblock-start-re
4787 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
4788 "Matches the startline of a dynamic block, with parameters.")
4790 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
4791 "Matches the end of a dyhamic block.")
4793 (defun org-create-dblock (plist)
4794 "Create a dynamic block section, with parameters taken from PLIST.
4795 PLIST must containe a :name entry which is used as name of the block."
4796 (unless (bolp) (newline))
4797 (let ((name (plist-get plist :name)))
4798 (insert "#+BEGIN: " name)
4799 (while plist
4800 (if (eq (car plist) :name)
4801 (setq plist (cddr plist))
4802 (insert " " (prin1-to-string (pop plist)))))
4803 (insert "\n\n#+END:\n")
4804 (beginning-of-line -2)))
4806 (defun org-prepare-dblock ()
4807 "Prepare dynamic block for refresh.
4808 This empties the block, puts the cursor at the insert position and returns
4809 the property list including an extra property :name with the block name."
4810 (unless (looking-at org-dblock-start-re)
4811 (error "Not at a dynamic block"))
4812 (let* ((begdel (1+ (match-end 0)))
4813 (name (match-string 1))
4814 (params (append (list :name name)
4815 (read (concat "(" (match-string 3) ")")))))
4816 (unless (re-search-forward org-dblock-end-re nil t)
4817 (error "Dynamic block not terminated"))
4818 (delete-region begdel (match-beginning 0))
4819 (goto-char begdel)
4820 (open-line 1)
4821 params))
4823 (defun org-map-dblocks (&optional command)
4824 "Apply COMMAND to all dynamic blocks in the current buffer.
4825 If COMMAND is not given, use `org-update-dblock'."
4826 (let ((cmd (or command 'org-update-dblock))
4827 pos)
4828 (save-excursion
4829 (goto-char (point-min))
4830 (while (re-search-forward org-dblock-start-re nil t)
4831 (goto-char (setq pos (match-beginning 0)))
4832 (condition-case nil
4833 (funcall cmd)
4834 (error (message "Error during update of dynamic block")))
4835 (goto-char pos)
4836 (unless (re-search-forward org-dblock-end-re nil t)
4837 (error "Dynamic block not terminated"))))))
4839 (defun org-dblock-update (&optional arg)
4840 "User command for updating dynamic blocks.
4841 Update the dynamic block at point. With prefix ARG, update all dynamic
4842 blocks in the buffer."
4843 (interactive "P")
4844 (if arg
4845 (org-update-all-dblocks)
4846 (or (looking-at org-dblock-start-re)
4847 (org-beginning-of-dblock))
4848 (org-update-dblock)))
4850 (defun org-update-dblock ()
4851 "Update the dynamic block at point
4852 This means to empty the block, parse for parameters and then call
4853 the correct writing function."
4854 (let* ((pos (point))
4855 (params (org-prepare-dblock))
4856 (name (plist-get params :name))
4857 (cmd (intern (concat "org-dblock-write:" name))))
4858 (funcall cmd params)
4859 (goto-char pos)))
4861 (defun org-beginning-of-dblock ()
4862 "Find the beginning of the dynamic block at point.
4863 Error if there is no scuh block at point."
4864 (let ((pos (point))
4865 beg)
4866 (end-of-line 1)
4867 (if (and (re-search-backward org-dblock-start-re nil t)
4868 (setq beg (match-beginning 0))
4869 (re-search-forward org-dblock-end-re nil t)
4870 (> (match-end 0) pos))
4871 (goto-char beg)
4872 (goto-char pos)
4873 (error "Not in a dynamic block"))))
4875 (defun org-update-all-dblocks ()
4876 "Update all dynamic blocks in the buffer.
4877 This function can be used in a hook."
4878 (when (org-mode-p)
4879 (org-map-dblocks 'org-update-dblock)))
4882 ;;; Completion
4884 (defun org-complete (&optional arg)
4885 "Perform completion on word at point.
4886 At the beginning of a headline, this completes TODO keywords as given in
4887 `org-todo-keywords'.
4888 If the current word is preceded by a backslash, completes the TeX symbols
4889 that are supported for HTML support.
4890 If the current word is preceded by \"#+\", completes special words for
4891 setting file options.
4892 At all other locations, this simply calls `ispell-complete-word'."
4893 (interactive "P")
4894 (catch 'exit
4895 (let* ((end (point))
4896 (beg1 (save-excursion
4897 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4898 (skip-chars-backward "a-zA-Z_@0-9")
4899 (point)))
4900 (beg (save-excursion
4901 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4902 (skip-chars-backward "a-zA-Z0-9_:$")
4903 (point)))
4904 (confirm (lambda (x) (stringp (car x))))
4905 (camel (equal (char-before beg) ?*))
4906 (tag (equal (char-before beg1) ?:))
4907 (texp (equal (char-before beg) ?\\))
4908 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
4909 beg)
4910 "#+"))
4911 (completion-ignore-case opt)
4912 (type nil)
4913 (tbl nil)
4914 (table (cond
4915 (opt
4916 (setq type :opt)
4917 (mapcar (lambda (x)
4918 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
4919 (cons (match-string 2 x) (match-string 1 x)))
4920 (org-split-string (org-get-current-options) "\n")))
4921 (texp
4922 (setq type :tex)
4923 org-html-entities)
4924 ((string-match "\\`\\*+[ \t]*\\'"
4925 (buffer-substring (point-at-bol) beg))
4926 (setq type :todo)
4927 (mapcar 'list org-todo-keywords))
4928 (camel
4929 (setq type :camel)
4930 (save-excursion
4931 (goto-char (point-min))
4932 (while (re-search-forward org-todo-line-regexp nil t)
4933 (push (list
4934 (if org-file-link-context-use-camel-case
4935 (org-make-org-heading-camel (match-string 3) t)
4936 (org-make-org-heading-search-string
4937 (match-string 3) t)))
4938 tbl)))
4939 tbl)
4940 (tag (setq type :tag beg beg1)
4941 (or org-tag-alist (org-get-buffer-tags)))
4942 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
4943 (pattern (buffer-substring-no-properties beg end))
4944 (completion (try-completion pattern table confirm)))
4945 (cond ((eq completion t)
4946 (if (equal type :opt)
4947 (insert (substring (cdr (assoc (upcase pattern) table))
4948 (length pattern)))))
4949 ((null completion)
4950 (message "Can't find completion for \"%s\"" pattern)
4951 (ding))
4952 ((not (string= pattern completion))
4953 (delete-region beg end)
4954 (if (string-match " +$" completion)
4955 (setq completion (replace-match "" t t completion)))
4956 (insert completion)
4957 (if (get-buffer-window "*Completions*")
4958 (delete-window (get-buffer-window "*Completions*")))
4959 (if (assoc completion table)
4960 (if (eq type :todo) (insert " ")
4961 (if (eq type :tag) (insert ":"))))
4962 (if (and (equal type :opt) (assoc completion table))
4963 (message "%s" (substitute-command-keys
4964 "Press \\[org-complete] again to insert example settings"))))
4966 (message "Making completion list...")
4967 (let ((list (sort (all-completions pattern table confirm)
4968 'string<)))
4969 (with-output-to-temp-buffer "*Completions*"
4970 (condition-case nil
4971 ;; Protection needed for XEmacs and emacs 21
4972 (display-completion-list list pattern)
4973 (error (display-completion-list list)))))
4974 (message "Making completion list...%s" "done"))))))
4976 ;;; Comments, TODO and DEADLINE
4978 (defun org-toggle-comment ()
4979 "Change the COMMENT state of an entry."
4980 (interactive)
4981 (save-excursion
4982 (org-back-to-heading)
4983 (if (looking-at (concat outline-regexp
4984 "\\( +\\<" org-comment-string "\\>\\)"))
4985 (replace-match "" t t nil 1)
4986 (if (looking-at outline-regexp)
4987 (progn
4988 (goto-char (match-end 0))
4989 (insert " " org-comment-string))))))
4991 (defvar org-last-todo-state-is-todo nil
4992 "This is non-nil when the last TODO state change led to a TODO state.
4993 If the last change removed the TODO tag or switched to DONE, then
4994 this is nil.")
4996 (defun org-todo (&optional arg)
4997 "Change the TODO state of an item.
4998 The state of an item is given by a keyword at the start of the heading,
4999 like
5000 *** TODO Write paper
5001 *** DONE Call mom
5003 The different keywords are specified in the variable `org-todo-keywords'.
5004 By default the available states are \"TODO\" and \"DONE\".
5005 So for this example: when the item starts with TODO, it is changed to DONE.
5006 When it starts with DONE, the DONE is removed. And when neither TODO nor
5007 DONE are present, add TODO at the beginning of the heading.
5009 With prefix arg, use completion to determine the new state. With numeric
5010 prefix arg, switch to that state."
5011 (interactive "P")
5012 (save-excursion
5013 (org-back-to-heading)
5014 (if (looking-at outline-regexp) (goto-char (match-end 0)))
5015 (or (looking-at (concat " +" org-todo-regexp " *"))
5016 (looking-at " *"))
5017 (let* ((this (match-string 1))
5018 (completion-ignore-case t)
5019 (member (member this org-todo-keywords))
5020 (tail (cdr member))
5021 (state (cond
5022 ((equal arg '(4))
5023 ;; Read a state with completion
5024 (completing-read "State: " (mapcar (lambda(x) (list x))
5025 org-todo-keywords)
5026 nil t))
5027 ((eq arg 'right)
5028 (if this
5029 (if tail (car tail) nil)
5030 (car org-todo-keywords)))
5031 ((eq arg 'left)
5032 (if (equal member org-todo-keywords)
5034 (if this
5035 (nth (- (length org-todo-keywords) (length tail) 2)
5036 org-todo-keywords)
5037 org-done-string)))
5038 (arg
5039 ;; user requests a specific state
5040 (nth (1- (prefix-numeric-value arg))
5041 org-todo-keywords))
5042 ((null member) (car org-todo-keywords))
5043 ((null tail) nil) ;; -> first entry
5044 ((eq org-todo-interpretation 'sequence)
5045 (car tail))
5046 ((memq org-todo-interpretation '(type priority))
5047 (if (eq this-command last-command)
5048 (car tail)
5049 (if (> (length tail) 0) org-done-string nil)))
5050 (t nil)))
5051 (next (if state (concat " " state " ") " ")))
5052 (replace-match next t t)
5053 (setq org-last-todo-state-is-todo
5054 (not (equal state org-done-string)))
5055 (when org-log-done
5056 (if (equal state org-done-string)
5057 (org-add-planning-info 'closed (current-time) 'scheduled)
5058 (if (not this)
5059 (org-add-planning-info nil nil 'closed))))
5060 ;; Fixup tag positioning
5061 (and org-auto-align-tags (org-set-tags nil t))
5062 (run-hooks 'org-after-todo-state-change-hook)))
5063 ;; Fixup cursor location if close to the keyword
5064 (if (and (outline-on-heading-p)
5065 (not (bolp))
5066 (save-excursion (beginning-of-line 1)
5067 (looking-at org-todo-line-regexp))
5068 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5069 (progn
5070 (goto-char (or (match-end 2) (match-end 1)))
5071 (just-one-space))))
5073 (defun org-log-done (&optional undone)
5074 "Add a time stamp logging that a TODO entry has been closed.
5075 When UNDONE is non-nil, remove such a time stamp again."
5076 (interactive)
5077 (let (beg end col)
5078 (save-excursion
5079 (org-back-to-heading t)
5080 (setq beg (point))
5081 (looking-at (concat outline-regexp " *"))
5082 (goto-char (match-end 0))
5083 (setq col (current-column))
5084 (outline-next-heading)
5085 (setq end (point))
5086 (goto-char beg)
5087 (when (re-search-forward (concat
5088 "[\r\n]\\([ \t]*"
5089 (regexp-quote org-closed-string)
5090 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
5091 (delete-region (match-beginning 1) (match-end 1)))
5092 (unless undone
5093 (org-back-to-heading t)
5094 (skip-chars-forward "^\n\r")
5095 (goto-char (min (1+ (point)) (point-max)))
5096 (when (not (member (char-before) '(?\r ?\n)))
5097 (insert "\n"))
5098 (indent-to col)
5099 (insert org-closed-string " "
5100 (format-time-string
5101 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5102 (org-current-time))
5103 "\n")))))
5105 (defun org-show-todo-tree (arg)
5106 "Make a compact tree which shows all headlines marked with TODO.
5107 The tree will show the lines where the regexp matches, and all higher
5108 headlines above the match.
5109 With \\[universal-argument] prefix, also show the DONE entries.
5110 With a numeric prefix N, construct a sparse tree for the Nth element
5111 of `org-todo-keywords'."
5112 (interactive "P")
5113 (let ((case-fold-search nil)
5114 (kwd-re
5115 (cond ((null arg) org-not-done-regexp)
5116 ((equal arg '(4)) org-todo-regexp)
5117 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5118 (regexp-quote (nth (1- (prefix-numeric-value arg))
5119 org-todo-keywords)))
5120 (t (error "Invalid prefix argument: %s" arg)))))
5121 (message "%d TODO entries found"
5122 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5124 (defun org-deadline ()
5125 "Insert the DEADLINE: string to make a deadline.
5126 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5127 to modify it to the correct date."
5128 (interactive)
5129 (org-add-planning-info 'deadline nil 'closed))
5131 (defun org-schedule ()
5132 "Insert the SCHEDULED: string to schedule a TODO item.
5133 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5134 to modify it to the correct date."
5135 (interactive)
5136 (org-add-planning-info 'scheduled nil 'closed))
5138 (defun org-add-planning-info (what &optional time &rest remove)
5139 "Insert new timestamp with keyword in the line directly after the headline.
5140 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5141 If non is given, the user is prompted for a date.
5142 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5143 be removed."
5144 (interactive)
5145 (when what (setq time (or time (org-read-date nil 'to-time))))
5146 (when (and org-insert-labeled-timestamps-at-point
5147 (member what '(scheduled deadline)))
5148 (insert
5149 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
5151 (format-time-string (car org-time-stamp-formats) time))
5152 (setq what nil))
5153 (save-excursion
5154 (let (col list elt (buffer-invisibility-spec nil) ts)
5155 (org-back-to-heading t)
5156 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5157 (goto-char (match-end 1))
5158 (setq col (current-column))
5159 (goto-char (1+ (match-end 0)))
5160 (if (and (not (looking-at outline-regexp))
5161 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5162 "[^\r\n]*"))
5163 (not (equal (match-string 1) org-clock-string)))
5164 (narrow-to-region (match-beginning 0) (match-end 0))
5165 (insert "\n")
5166 (backward-char 1)
5167 (narrow-to-region (point) (point))
5168 (indent-to-column col))
5169 ;; Check if we have to remove something.
5170 (setq list (cons what remove))
5171 (while list
5172 (setq elt (pop list))
5173 (goto-char (point-min))
5174 (when (or (and (eq elt 'scheduled)
5175 (re-search-forward org-scheduled-time-regexp nil t))
5176 (and (eq elt 'deadline)
5177 (re-search-forward org-deadline-time-regexp nil t))
5178 (and (eq elt 'closed)
5179 (re-search-forward org-closed-time-regexp nil t)))
5180 (replace-match "")
5181 (if (looking-at " +") (replace-match ""))))
5182 (goto-char (point-max))
5183 (when what
5184 (insert
5185 (if (not (equal (char-before) ?\ )) " " "")
5186 (cond ((eq what 'scheduled) org-scheduled-string)
5187 ((eq what 'deadline) org-deadline-string)
5188 ((eq what 'closed) org-closed-string))
5189 " ")
5190 (insert
5191 (setq ts
5192 (format-time-string
5193 (if (eq what 'closed)
5194 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5195 (car org-time-stamp-formats))
5196 time))))
5197 (goto-char (point-min))
5198 (widen)
5199 (if (looking-at "[ \t]+\r?\n")
5200 (replace-match ""))
5201 ts)))
5203 (defun org-occur (regexp &optional callback)
5204 "Make a compact tree which shows all matches of REGEXP.
5205 The tree will show the lines where the regexp matches, and all higher
5206 headlines above the match. It will also show the heading after the match,
5207 to make sure editing the matching entry is easy.
5208 If CALLBACK is non-nil, it is a function which is called to confirm
5209 that the match should indeed be shown."
5210 (interactive "sRegexp: ")
5211 (org-remove-occur-highlights nil nil t)
5212 (let ((cnt 0))
5213 (save-excursion
5214 (goto-char (point-min))
5215 (org-overview)
5216 (while (re-search-forward regexp nil t)
5217 (when (or (not callback)
5218 (save-match-data (funcall callback)))
5219 (setq cnt (1+ cnt))
5220 (org-highlight-new-match (match-beginning 0) (match-end 0))
5221 (org-show-hierarchy-above))))
5222 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5223 nil 'local)
5224 (unless org-sparse-tree-open-archived-trees
5225 (org-hide-archived-subtrees (point-min) (point-max)))
5226 (run-hooks 'org-occur-hook)
5227 (if (interactive-p)
5228 (message "%d match(es) for regexp %s" cnt regexp))
5229 cnt))
5231 (defun org-show-hierarchy-above ()
5232 "Make sure point and the headings hierarchy above is visible."
5233 (catch 'exit
5234 (if (org-on-heading-p t)
5235 (org-flag-heading nil) ; only show the heading
5236 (and (or (org-invisible-p) (org-invisible-p2))
5237 (org-show-hidden-entry))) ; show entire entry
5238 (save-excursion
5239 (and org-show-following-heading
5240 (outline-next-heading)
5241 (org-flag-heading nil))) ; show the next heading
5242 (when org-show-hierarchy-above
5243 (save-excursion ; show all higher headings
5244 (while (and (condition-case nil
5245 (progn (org-up-heading-all 1) t)
5246 (error nil))
5247 (not (bobp)))
5248 (org-flag-heading nil))))))
5250 ;; Overlay compatibility functions
5251 (defun org-make-overlay (beg end &optional buffer)
5252 (if (featurep 'xemacs)
5253 (make-extent beg end buffer)
5254 (make-overlay beg end buffer)))
5255 (defun org-delete-overlay (ovl)
5256 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5257 (defun org-detatch-overlay (ovl)
5258 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5259 (defun org-move-overlay (ovl beg end &optional buffer)
5260 (if (featurep 'xemacs)
5261 (set-extent-endpoints ovl beg end buffer)
5262 (move-overlay ovl beg end buffer)))
5263 (defun org-overlay-put (ovl prop value)
5264 (if (featurep 'xemacs)
5265 (set-extent-property ovl prop value)
5266 (overlay-put ovl prop value)))
5267 (defun org-overlays-at (pos)
5268 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5269 (defun org-overlay-start (o)
5270 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5271 (defun org-overlay-end (o)
5272 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5274 (defvar org-occur-highlights nil)
5275 (make-variable-buffer-local 'org-occur-highlights)
5276 (defun org-highlight-new-match (beg end)
5277 "Highlight from BEG to END and mark the highlight is an occur headline."
5278 (let ((ov (org-make-overlay beg end)))
5279 (org-overlay-put ov 'face 'secondary-selection)
5280 (push ov org-occur-highlights)))
5282 (defvar org-inhibit-highlight-removal nil)
5283 (defun org-remove-occur-highlights (&optional beg end noremove)
5284 "Remove the occur highlights from the buffer.
5285 BEG and END are ignored. If NOREMOVE is nil, remove this function
5286 from the `before-change-functions' in the current buffer."
5287 (interactive)
5288 (unless org-inhibit-highlight-removal
5289 (mapc 'org-delete-overlay org-occur-highlights)
5290 (setq org-occur-highlights nil)
5291 (unless noremove
5292 (remove-hook 'before-change-functions
5293 'org-remove-occur-highlights 'local))))
5295 ;;; Priorities
5297 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5298 "Regular expression matching the priority indicator.")
5300 (defvar org-remove-priority-next-time nil)
5302 (defun org-priority-up ()
5303 "Increase the priority of the current item."
5304 (interactive)
5305 (org-priority 'up))
5307 (defun org-priority-down ()
5308 "Decrease the priority of the current item."
5309 (interactive)
5310 (org-priority 'down))
5312 (defun org-priority (&optional action)
5313 "Change the priority of an item by ARG.
5314 ACTION can be set, up, or down."
5315 (interactive)
5316 (setq action (or action 'set))
5317 (let (current new news have remove)
5318 (save-excursion
5319 (org-back-to-heading)
5320 (if (looking-at org-priority-regexp)
5321 (setq current (string-to-char (match-string 2))
5322 have t)
5323 (setq current org-default-priority))
5324 (cond
5325 ((eq action 'set)
5326 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5327 (setq new (read-char-exclusive))
5328 (cond ((equal new ?\ ) (setq remove t))
5329 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5330 (error "Priority must be between `%c' and `%c'"
5331 ?A org-lowest-priority))))
5332 ((eq action 'up)
5333 (setq new (1- current)))
5334 ((eq action 'down)
5335 (setq new (1+ current)))
5336 (t (error "Invalid action")))
5337 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5338 (setq news (format "%c" new))
5339 (if have
5340 (if remove
5341 (replace-match "" t t nil 1)
5342 (replace-match news t t nil 2))
5343 (if remove
5344 (error "No priority cookie found in line")
5345 (looking-at org-todo-line-regexp)
5346 (if (match-end 2)
5347 (progn
5348 (goto-char (match-end 2))
5349 (insert " [#" news "]"))
5350 (goto-char (match-beginning 3))
5351 (insert "[#" news "] ")))))
5352 (if remove
5353 (message "Priority removed")
5354 (message "Priority of current item set to %s" news))))
5357 (defun org-get-priority (s)
5358 "Find priority cookie and return priority."
5359 (save-match-data
5360 (if (not (string-match org-priority-regexp s))
5361 (* 1000 (- org-lowest-priority org-default-priority))
5362 (* 1000 (- org-lowest-priority
5363 (string-to-char (match-string 2 s)))))))
5365 ;;; Timestamps
5367 (defvar org-last-changed-timestamp nil)
5369 (defun org-time-stamp (arg)
5370 "Prompt for a date/time and insert a time stamp.
5371 If the user specifies a time like HH:MM, or if this command is called
5372 with a prefix argument, the time stamp will contain date and time.
5373 Otherwise, only the date will be included. All parts of a date not
5374 specified by the user will be filled in from the current date/time.
5375 So if you press just return without typing anything, the time stamp
5376 will represent the current date/time. If there is already a timestamp
5377 at the cursor, it will be modified."
5378 (interactive "P")
5379 (let ((fmt (if arg (cdr org-time-stamp-formats)
5380 (car org-time-stamp-formats)))
5381 (org-time-was-given nil)
5382 time)
5383 (cond
5384 ((and (org-at-timestamp-p)
5385 (eq last-command 'org-time-stamp)
5386 (eq this-command 'org-time-stamp))
5387 (insert "--")
5388 (setq time (let ((this-command this-command))
5389 (org-read-date arg 'totime)))
5390 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5391 (insert (format-time-string fmt time)))
5392 ((org-at-timestamp-p)
5393 (setq time (let ((this-command this-command))
5394 (org-read-date arg 'totime)))
5395 (and (org-at-timestamp-p) (replace-match
5396 (setq org-last-changed-timestamp
5397 (format-time-string fmt time))
5398 t t))
5399 (message "Timestamp updated"))
5401 (setq time (let ((this-command this-command))
5402 (org-read-date arg 'totime)))
5403 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5404 (insert (format-time-string fmt time))))))
5406 (defun org-time-stamp-inactive (&optional arg)
5407 "Insert an inactive time stamp.
5408 An inactive time stamp is enclosed in square brackets instead of angle
5409 brackets. It is inactive in the sense that it does not trigger agenda entries,
5410 does not link to the calendar and cannot be changed with the S-cursor keys.
5411 So these are more for recording a certain time/date."
5412 (interactive "P")
5413 (let ((fmt (if arg (cdr org-time-stamp-formats)
5414 (car org-time-stamp-formats)))
5415 (org-time-was-given nil)
5416 time)
5417 (setq time (org-read-date arg 'totime))
5418 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5419 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
5420 (insert (format-time-string fmt time))))
5422 (defvar org-date-ovl (org-make-overlay 1 1))
5423 (org-overlay-put org-date-ovl 'face 'org-warning)
5424 (org-detatch-overlay org-date-ovl)
5426 (defun org-read-date (&optional with-time to-time)
5427 "Read a date and make things smooth for the user.
5428 The prompt will suggest to enter an ISO date, but you can also enter anything
5429 which will at least partially be understood by `parse-time-string'.
5430 Unrecognized parts of the date will default to the current day, month, year,
5431 hour and minute. For example,
5432 3-2-5 --> 2003-02-05
5433 feb 15 --> currentyear-02-15
5434 sep 12 9 --> 2009-09-12
5435 12:45 --> today 12:45
5436 22 sept 0:34 --> currentyear-09-22 0:34
5437 12 --> currentyear-currentmonth-12
5438 Fri --> nearest Friday (today or later)
5439 etc.
5440 The function understands only English month and weekday abbreviations,
5441 but this can be configured with the variables `parse-time-months' and
5442 `parse-time-weekdays'.
5444 While prompting, a calendar is popped up - you can also select the
5445 date with the mouse (button 1). The calendar shows a period of three
5446 months. To scroll it to other months, use the keys `>' and `<'.
5447 If you don't like the calendar, turn it off with
5448 \(setq org-popup-calendar-for-date-prompt nil)
5450 With optional argument TO-TIME, the date will immediately be converted
5451 to an internal time.
5452 With an optional argument WITH-TIME, the prompt will suggest to also
5453 insert a time. Note that when WITH-TIME is not set, you can still
5454 enter a time, and this function will inform the calling routine about
5455 this change. The calling routine may then choose to change the format
5456 used to insert the time stamp into the buffer to include the time."
5457 (require 'parse-time)
5458 (let* ((org-time-stamp-rounding-minutes
5459 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5460 (ct (org-current-time))
5461 (default-time
5462 ;; Default time is either today, or, when entering a range,
5463 ;; the range start.
5464 (if (save-excursion
5465 (re-search-backward
5466 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5467 (- (point) 20) t))
5468 (apply
5469 'encode-time
5470 (mapcar (lambda(x) (or x 0))
5471 (parse-time-string (match-string 1))))
5472 ct))
5473 (calendar-move-hook nil)
5474 (view-diary-entries-initially nil)
5475 (view-calendar-holidays-initially nil)
5476 (timestr (format-time-string
5477 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5478 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5479 ans ans1 ans2
5480 second minute hour day month year tl wday wday1)
5482 (if org-popup-calendar-for-date-prompt
5483 (save-excursion
5484 (save-window-excursion
5485 (calendar)
5486 (calendar-forward-day (- (time-to-days default-time)
5487 (calendar-absolute-from-gregorian
5488 (calendar-current-date))))
5489 (org-eval-in-calendar nil)
5490 (let* ((old-map (current-local-map))
5491 (map (copy-keymap calendar-mode-map))
5492 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5493 (define-key map (kbd "RET") 'org-calendar-select)
5494 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5495 'org-calendar-select-mouse)
5496 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5497 'org-calendar-select-mouse)
5498 (define-key minibuffer-local-map [(meta shift left)]
5499 (lambda () (interactive)
5500 (org-eval-in-calendar '(calendar-backward-month 1))))
5501 (define-key minibuffer-local-map [(meta shift right)]
5502 (lambda () (interactive)
5503 (org-eval-in-calendar '(calendar-forward-month 1))))
5504 (define-key minibuffer-local-map [(shift up)]
5505 (lambda () (interactive)
5506 (org-eval-in-calendar '(calendar-backward-week 1))))
5507 (define-key minibuffer-local-map [(shift down)]
5508 (lambda () (interactive)
5509 (org-eval-in-calendar '(calendar-forward-week 1))))
5510 (define-key minibuffer-local-map [(shift left)]
5511 (lambda () (interactive)
5512 (org-eval-in-calendar '(calendar-backward-day 1))))
5513 (define-key minibuffer-local-map [(shift right)]
5514 (lambda () (interactive)
5515 (org-eval-in-calendar '(calendar-forward-day 1))))
5516 (define-key minibuffer-local-map ">"
5517 (lambda () (interactive)
5518 (org-eval-in-calendar '(scroll-calendar-left 1))))
5519 (define-key minibuffer-local-map "<"
5520 (lambda () (interactive)
5521 (org-eval-in-calendar '(scroll-calendar-right 1))))
5522 (unwind-protect
5523 (progn
5524 (use-local-map map)
5525 (setq ans (read-string prompt "" nil nil))
5526 (if (not (string-match "\\S-" ans)) (setq ans nil))
5527 (setq ans (or ans1 ans ans2)))
5528 (use-local-map old-map)))))
5529 ;; Naked prompt only
5530 (setq ans (read-string prompt "" nil timestr)))
5531 (org-detatch-overlay org-date-ovl)
5533 (if (string-match
5534 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5535 (progn
5536 (setq year (if (match-end 2)
5537 (string-to-number (match-string 2 ans))
5538 (string-to-number (format-time-string "%Y")))
5539 month (string-to-number (match-string 3 ans))
5540 day (string-to-number (match-string 4 ans)))
5541 (if (< year 100) (setq year (+ 2000 year)))
5542 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5543 t nil ans))))
5544 (setq tl (parse-time-string ans)
5545 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5546 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5547 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5548 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5549 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5550 second (or (nth 0 tl) 0)
5551 wday (nth 6 tl))
5552 (when (and wday (not (nth 3 tl)))
5553 ;; Weekday was given, but no day, so pick that day in the week
5554 ;; on or after the derived date.
5555 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5556 (unless (equal wday wday1)
5557 (setq day (+ day (% (- wday wday1 -7) 7)))))
5558 (if (and (boundp 'org-time-was-given)
5559 (nth 2 tl))
5560 (setq org-time-was-given t))
5561 (if (< year 100) (setq year (+ 2000 year)))
5562 (if to-time
5563 (encode-time second minute hour day month year)
5564 (if (or (nth 1 tl) (nth 2 tl))
5565 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5566 (format "%04d-%02d-%02d" year month day)))))
5568 (defun org-eval-in-calendar (form)
5569 "Eval FORM in the calendar window and return to current window.
5570 Also, store the cursor date in variable ans2."
5571 (let ((sw (selected-window)))
5572 (select-window (get-buffer-window "*Calendar*"))
5573 (eval form)
5574 (when (calendar-cursor-to-date)
5575 (let* ((date (calendar-cursor-to-date))
5576 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5577 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5578 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5579 (select-window sw)))
5581 (defun org-calendar-select ()
5582 "Return to `org-read-date' with the date currently selected.
5583 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5584 (interactive)
5585 (when (calendar-cursor-to-date)
5586 (let* ((date (calendar-cursor-to-date))
5587 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5588 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5589 (if (active-minibuffer-window) (exit-minibuffer))))
5591 (defun org-calendar-select-mouse (ev)
5592 "Return to `org-read-date' with the date currently selected.
5593 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5594 (interactive "e")
5595 (mouse-set-point ev)
5596 (when (calendar-cursor-to-date)
5597 (let* ((date (calendar-cursor-to-date))
5598 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5599 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5600 (if (active-minibuffer-window) (exit-minibuffer))))
5602 (defun org-check-deadlines (ndays)
5603 "Check if there are any deadlines due or past due.
5604 A deadline is considered due if it happens within `org-deadline-warning-days'
5605 days from today's date. If the deadline appears in an entry marked DONE,
5606 it is not shown. The prefix arg NDAYS can be used to test that many
5607 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
5608 (interactive "P")
5609 (let* ((org-warn-days
5610 (cond
5611 ((equal ndays '(4)) 100000)
5612 (ndays (prefix-numeric-value ndays))
5613 (t org-deadline-warning-days)))
5614 (case-fold-search nil)
5615 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5616 (callback
5617 (lambda ()
5618 (and (let ((d1 (time-to-days (current-time)))
5619 (d2 (time-to-days
5620 (org-time-string-to-time (match-string 1)))))
5621 (< (- d2 d1) org-warn-days))
5622 (not (org-entry-is-done-p))))))
5623 (message "%d deadlines past-due or due within %d days"
5624 (org-occur regexp callback)
5625 org-warn-days)))
5627 (defun org-evaluate-time-range (&optional to-buffer)
5628 "Evaluate a time range by computing the difference between start and end.
5629 Normally the result is just printed in the echo area, but with prefix arg
5630 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5631 If the time range is actually in a table, the result is inserted into the
5632 next column.
5633 For time difference computation, a year is assumed to be exactly 365
5634 days in order to avoid rounding problems."
5635 (interactive "P")
5637 (org-clock-update-time-maybe)
5638 (save-excursion
5639 (unless (org-at-date-range-p)
5640 (goto-char (point-at-bol))
5641 (re-search-forward org-tr-regexp (point-at-eol) t))
5642 (if (not (org-at-date-range-p))
5643 (error "Not at a time-stamp range, and none found in current line")))
5644 (let* ((ts1 (match-string 1))
5645 (ts2 (match-string 2))
5646 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5647 (match-end (match-end 0))
5648 (time1 (org-time-string-to-time ts1))
5649 (time2 (org-time-string-to-time ts2))
5650 (t1 (time-to-seconds time1))
5651 (t2 (time-to-seconds time2))
5652 (diff (abs (- t2 t1)))
5653 (negative (< (- t2 t1) 0))
5654 ;; (ys (floor (* 365 24 60 60)))
5655 (ds (* 24 60 60))
5656 (hs (* 60 60))
5657 (fy "%dy %dd %02d:%02d")
5658 (fy1 "%dy %dd")
5659 (fd "%dd %02d:%02d")
5660 (fd1 "%dd")
5661 (fh "%02d:%02d")
5662 y d h m align)
5663 (if havetime
5664 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5666 d (floor (/ diff ds)) diff (mod diff ds)
5667 h (floor (/ diff hs)) diff (mod diff hs)
5668 m (floor (/ diff 60)))
5669 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5671 d (floor (+ (/ diff ds) 0.5))
5672 h 0 m 0))
5673 (if (not to-buffer)
5674 (message (org-make-tdiff-string y d h m))
5675 (when (org-at-table-p)
5676 (goto-char match-end)
5677 (setq align t)
5678 (and (looking-at " *|") (goto-char (match-end 0))))
5679 (if (looking-at
5680 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5681 (replace-match ""))
5682 (if negative (insert " -"))
5683 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5684 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5685 (insert " " (format fh h m))))
5686 (if align (org-table-align))
5687 (message "Time difference inserted")))))
5689 (defun org-make-tdiff-string (y d h m)
5690 (let ((fmt "")
5691 (l nil))
5692 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5693 l (push y l)))
5694 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5695 l (push d l)))
5696 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5697 l (push h l)))
5698 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5699 l (push m l)))
5700 (apply 'format fmt (nreverse l))))
5702 (defun org-time-string-to-time (s)
5703 (apply 'encode-time (org-parse-time-string s)))
5705 (defun org-parse-time-string (s &optional nodefault)
5706 "Parse the standard Org-mode time string.
5707 This should be a lot faster than the normal `parse-time-string'.
5708 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5709 hour and minute fields will be nil if not given."
5710 (if (string-match org-ts-regexp1 s)
5711 (list 0
5712 (if (or (match-beginning 8) (not nodefault))
5713 (string-to-number (or (match-string 8 s) "0")))
5714 (if (or (match-beginning 7) (not nodefault))
5715 (string-to-number (or (match-string 7 s) "0")))
5716 (string-to-number (match-string 4 s))
5717 (string-to-number (match-string 3 s))
5718 (string-to-number (match-string 2 s))
5719 nil nil nil)
5720 (make-list 9 0)))
5722 (defun org-timestamp-up (&optional arg)
5723 "Increase the date item at the cursor by one.
5724 If the cursor is on the year, change the year. If it is on the month or
5725 the day, change that.
5726 With prefix ARG, change by that many units."
5727 (interactive "p")
5728 (org-timestamp-change (prefix-numeric-value arg)))
5730 (defun org-timestamp-down (&optional arg)
5731 "Decrease the date item at the cursor by one.
5732 If the cursor is on the year, change the year. If it is on the month or
5733 the day, change that.
5734 With prefix ARG, change by that many units."
5735 (interactive "p")
5736 (org-timestamp-change (- (prefix-numeric-value arg))))
5738 (defun org-timestamp-up-day (&optional arg)
5739 "Increase the date in the time stamp by one day.
5740 With prefix ARG, change that many days."
5741 (interactive "p")
5742 (if (and (not (org-at-timestamp-p t))
5743 (org-on-heading-p))
5744 (org-todo 'up)
5745 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5747 (defun org-timestamp-down-day (&optional arg)
5748 "Decrease the date in the time stamp by one day.
5749 With prefix ARG, change that many days."
5750 (interactive "p")
5751 (if (and (not (org-at-timestamp-p t))
5752 (org-on-heading-p))
5753 (org-todo 'down)
5754 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5756 (defsubst org-pos-in-match-range (pos n)
5757 (and (match-beginning n)
5758 (<= (match-beginning n) pos)
5759 (>= (match-end n) pos)))
5761 (defun org-at-timestamp-p (&optional also-inactive)
5762 "Determine if the cursor is in or at a timestamp."
5763 (interactive)
5764 (let* ((tsr (if also-inactive org-ts-regexp3 org-ts-regexp2))
5765 (pos (point))
5766 (ans (or (looking-at tsr)
5767 (save-excursion
5768 (skip-chars-backward "^[<\n\r\t")
5769 (if (> (point) 1) (backward-char 1))
5770 (and (looking-at tsr)
5771 (> (- (match-end 0) pos) -1))))))
5772 (and (boundp 'org-ts-what)
5773 (setq org-ts-what
5774 (cond
5775 ((org-pos-in-match-range pos 2) 'year)
5776 ((org-pos-in-match-range pos 3) 'month)
5777 ((org-pos-in-match-range pos 7) 'hour)
5778 ((org-pos-in-match-range pos 8) 'minute)
5779 ((or (org-pos-in-match-range pos 4)
5780 (org-pos-in-match-range pos 5)) 'day)
5781 (t 'day))))
5782 ans))
5784 (defun org-timestamp-change (n &optional what)
5785 "Change the date in the time stamp at point.
5786 The date will be changed by N times WHAT. WHAT can be `day', `month',
5787 `year', `minute', `second'. If WHAT is not given, the cursor position
5788 in the timestamp determines what will be changed."
5789 (let ((fmt (car org-time-stamp-formats))
5790 org-ts-what
5791 (pos (point))
5792 ts time time0)
5793 (if (not (org-at-timestamp-p t))
5794 (error "Not at a timestamp"))
5795 (setq org-ts-what (or what org-ts-what))
5796 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5797 (- (match-end 0) (match-beginning 0))))
5799 (cdr org-time-stamp-formats)
5800 (car org-time-stamp-formats)))
5801 (if (= (char-after (match-beginning 0)) ?\[)
5802 (setq fmt (concat "[" (substring fmt 1 -1) "]")))
5803 (setq ts (match-string 0))
5804 (replace-match "")
5805 (setq time0 (org-parse-time-string ts))
5806 (setq time
5807 (apply 'encode-time
5808 (append
5809 (list (or (car time0) 0))
5810 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5811 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5812 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5813 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5814 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5815 (nthcdr 6 time0))))
5816 (if (eq what 'calendar)
5817 (let ((cal-date
5818 (save-excursion
5819 (save-match-data
5820 (set-buffer "*Calendar*")
5821 (calendar-cursor-to-date)))))
5822 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5823 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5824 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5825 (setcar time0 (or (car time0) 0))
5826 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5827 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5828 (setq time (apply 'encode-time time0))))
5829 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5830 (org-clock-update-time-maybe)
5831 (goto-char pos)
5832 ;; Try to recenter the calendar window, if any
5833 (if (and org-calendar-follow-timestamp-change
5834 (get-buffer-window "*Calendar*" t)
5835 (memq org-ts-what '(day month year)))
5836 (org-recenter-calendar (time-to-days time)))))
5838 (defun org-recenter-calendar (date)
5839 "If the calendar is visible, recenter it to DATE."
5840 (let* ((win (selected-window))
5841 (cwin (get-buffer-window "*Calendar*" t))
5842 (calendar-move-hook nil))
5843 (when cwin
5844 (select-window cwin)
5845 (calendar-goto-date (if (listp date) date
5846 (calendar-gregorian-from-absolute date)))
5847 (select-window win))))
5849 (defun org-goto-calendar (&optional arg)
5850 "Go to the Emacs calendar at the current date.
5851 If there is a time stamp in the current line, go to that date.
5852 A prefix ARG can be used to force the current date."
5853 (interactive "P")
5854 (let ((tsr org-ts-regexp) diff
5855 (calendar-move-hook nil)
5856 (view-calendar-holidays-initially nil)
5857 (view-diary-entries-initially nil))
5858 (if (or (org-at-timestamp-p)
5859 (save-excursion
5860 (beginning-of-line 1)
5861 (looking-at (concat ".*" tsr))))
5862 (let ((d1 (time-to-days (current-time)))
5863 (d2 (time-to-days
5864 (org-time-string-to-time (match-string 1)))))
5865 (setq diff (- d2 d1))))
5866 (calendar)
5867 (calendar-goto-today)
5868 (if (and diff (not arg)) (calendar-forward-day diff))))
5870 (defun org-date-from-calendar ()
5871 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5872 If there is already a time stamp at the cursor position, update it."
5873 (interactive)
5874 (org-timestamp-change 0 'calendar))
5876 ;;; The clock for measuring work time.
5878 (defvar org-clock-marker (make-marker)
5879 "Marker recording the last clock-in.")
5881 (defun org-clock-in ()
5882 "Start the clock on the current item.
5883 If necessary, clock-out of the currently active clock."
5884 (interactive)
5885 (org-clock-out t)
5886 (let (ts)
5887 (save-excursion
5888 (org-back-to-heading t)
5889 (beginning-of-line 2)
5890 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5891 (not (equal (match-string 1) org-clock-string)))
5892 (beginning-of-line 1))
5893 (insert "\n") (backward-char 1)
5894 (indent-relative)
5895 (insert org-clock-string " "
5896 (setq ts (concat "[" (format-time-string
5897 (substring
5898 (cdr org-time-stamp-formats) 1 -1)
5899 (current-time))
5900 "]")))
5901 (move-marker org-clock-marker (point))
5902 (message "Clock started at %s" ts))))
5904 (defun org-clock-out (&optional fail-quietly)
5905 "Stop the currently running clock.
5906 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
5907 (interactive)
5908 (catch 'exit
5909 (if (not (marker-buffer org-clock-marker))
5910 (if fail-quietly (throw 'exit t) (error "No active clock")))
5911 (let (ts te s h m)
5912 (save-excursion
5913 (set-buffer (marker-buffer org-clock-marker))
5914 (goto-char org-clock-marker)
5915 (beginning-of-line 1)
5916 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5917 (equal (match-string 1) org-clock-string))
5918 (setq ts (match-string 2))
5919 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
5920 (goto-char org-clock-marker)
5921 (setq te (concat "[" (format-time-string
5922 (substring
5923 (cdr org-time-stamp-formats) 1 -1)
5924 (current-time))
5925 "]"))
5926 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
5927 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
5928 h (floor (/ s 3600))
5929 s (- s (* 3600 h))
5930 m (floor (/ s 60))
5931 s (- s (* 60 s)))
5932 (insert "--" te " => " (format "%2d:%02d" h m))
5933 (move-marker org-clock-marker nil)
5934 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
5936 (defun org-clock-cancel ()
5937 "Cancel the running clock be removing the start timestamp."
5938 (interactive)
5939 (if (not (marker-buffer org-clock-marker))
5940 (error "No active clock"))
5941 (save-excursion
5942 (set-buffer (marker-buffer org-clock-marker))
5943 (goto-char org-clock-marker)
5944 (delete-region (1- (point-at-bol)) (point-at-eol)))
5945 (message "Clock canceled"))
5947 (defvar org-clock-file-total-minutes nil
5948 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
5949 (make-variable-buffer-local 'org-clock-file-total-minutes)
5951 (defun org-clock-sum (&optional tstart tend)
5952 "Sum the times for each subtree.
5953 Puts the resulting times in minutes as a text property on each headline."
5954 (interactive)
5955 (let* ((bmp (buffer-modified-p))
5956 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
5957 org-clock-string
5958 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
5959 (lmax 30)
5960 (ltimes (make-vector lmax 0))
5961 (t1 0)
5962 (level 0)
5963 ts te dt
5964 time)
5965 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
5966 (save-excursion
5967 (goto-char (point-max))
5968 (while (re-search-backward re nil t)
5969 (if (match-end 2)
5970 ;; A time
5971 (setq ts (match-string 2)
5972 te (match-string 3)
5973 ts (time-to-seconds
5974 (apply 'encode-time (org-parse-time-string ts)))
5975 te (time-to-seconds
5976 (apply 'encode-time (org-parse-time-string te)))
5977 ts (if tstart (max ts tstart) ts)
5978 te (if tend (min te tend) te)
5979 dt (- te ts)
5980 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
5981 ;; A headline
5982 (setq level (- (match-end 1) (match-beginning 1)))
5983 (when (or (> t1 0) (> (aref ltimes level) 0))
5984 (loop for l from 0 to level do
5985 (aset ltimes l (+ (aref ltimes l) t1)))
5986 (setq t1 0 time (aref ltimes level))
5987 (loop for l from level to (1- lmax) do
5988 (aset ltimes l 0))
5989 (goto-char (match-beginning 0))
5990 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
5991 (setq org-clock-file-total-minutes (aref ltimes 0)))
5992 (set-buffer-modified-p bmp)))
5994 (defun org-clock-display (&optional total-only)
5995 "Show subtree times in the entire buffer.
5996 If TOTAL-ONLY is non-nil, only show the total time for the entire file
5997 in the echo area."
5998 (interactive)
5999 (org-remove-clock-overlays)
6000 (let (time h m p)
6001 (org-clock-sum)
6002 (unless total-only
6003 (save-excursion
6004 (goto-char (point-min))
6005 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6006 (goto-char p)
6007 (when (setq time (get-text-property p :org-clock-minutes))
6008 (org-put-clock-overlay time (funcall outline-level))))
6009 (setq h (/ org-clock-file-total-minutes 60)
6010 m (- org-clock-file-total-minutes (* 60 h)))
6011 ;; Arrange to remove the overlays upon next change.
6012 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
6013 nil 'local)))
6014 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
6016 (defvar org-clock-overlays nil)
6017 (make-variable-buffer-local 'org-clock-overlays)
6019 (defun org-put-clock-overlay (time &optional level)
6020 "Put an overlays on the current line, displaying TIME.
6021 If LEVEL is given, prefix time with a corresponding number of stars.
6022 This creates a new overlay and stores it in `org-clock-overlays', so that it
6023 will be easy to remove."
6024 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
6025 (l (if level (org-get-legal-level level 0) 0))
6026 (off 0)
6027 ov tx)
6028 (move-to-column c)
6029 (unless (eolp) (skip-chars-backward "^ \t"))
6030 (skip-chars-backward " \t")
6031 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6032 tx (concat (buffer-substring (1- (point)) (point))
6033 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6034 (org-add-props (format "%s %2d:%02d%s"
6035 (make-string l ?*) h m
6036 (make-string (- 10 l) ?\ ))
6037 '(face secondary-selection))
6038 ""))
6039 (org-overlay-put ov 'display tx)
6040 (push ov org-clock-overlays)))
6042 (defun org-remove-clock-overlays (&optional beg end noremove)
6043 "Remove the occur highlights from the buffer.
6044 BEG and END are ignored. If NOREMOVE is nil, remove this function
6045 from the `before-change-functions' in the current buffer."
6046 (interactive)
6047 (unless org-inhibit-highlight-removal
6048 (mapc 'org-delete-overlay org-clock-overlays)
6049 (setq org-clock-overlays nil)
6050 (unless noremove
6051 (remove-hook 'before-change-functions
6052 'org-remove-clock-overlays 'local))))
6054 (defun org-clock-out-if-current ()
6055 "Clock out if the current entry contains the running clock.
6056 This is used to stop the clock after a TODO entry is marked DONE."
6057 (when (and (equal state org-done-string)
6058 (equal (marker-buffer org-clock-marker) (current-buffer))
6059 (< (point) org-clock-marker)
6060 (> (save-excursion (outline-next-heading) (point))
6061 org-clock-marker))
6062 (org-clock-out)))
6064 (add-hook 'org-after-todo-state-change-hook
6065 'org-clock-out-if-current)
6067 (defun org-check-running-clock ()
6068 "Check if the current buffer contains the running clock.
6069 If yes, offer to stop it and to save the buffer with the changes."
6070 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6071 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6072 (buffer-name))))
6073 (org-clock-out)
6074 (when (y-or-n-p "Save changed buffer?")
6075 (save-buffer))))
6077 (defun org-clock-report ()
6078 "Create a table containing a report about clocked time.
6079 If the buffer contains lines
6080 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6082 #+END: clocktable
6083 then the table will be inserted between these lines, replacing whatever
6084 is was there before. If these lines are not in the buffer, the table
6085 is inserted at point, surrounded by the special lines.
6086 The BEGIN line can contain parameters. Allowed are:
6087 :maxlevel The maximum level to be included in the table. Default is 3.
6088 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6089 (interactive)
6090 (org-remove-clock-overlays)
6091 (unless (org-find-dblock "clocktable")
6092 (org-create-dblock (list :name "clocktable"
6093 :maxlevel 2 :emphasize nil)))
6094 (org-update-dblock))
6096 (defun org-clock-update-time-maybe ()
6097 "If this is a CLOCK line, update it and return t.
6098 Otherwise, return nil."
6099 (interactive)
6100 (save-excursion
6101 (beginning-of-line 1)
6102 (skip-chars-forward " \t")
6103 (when (looking-at org-clock-string)
6104 (let ((re (concat "[ \t]*" org-clock-string
6105 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
6106 "\\([ \t]*=>.*\\)?"))
6107 ts te h m s)
6108 (if (not (looking-at re))
6110 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
6111 (end-of-line 1)
6112 (setq ts (match-string 1)
6113 te (match-string 2))
6114 (setq s (- (time-to-seconds
6115 (apply 'encode-time (org-parse-time-string te)))
6116 (time-to-seconds
6117 (apply 'encode-time (org-parse-time-string ts))))
6118 h (floor (/ s 3600))
6119 s (- s (* 3600 h))
6120 m (floor (/ s 60))
6121 s (- s (* 60 s)))
6122 (insert " => " (format "%2d:%02d" h m))
6123 t)))))
6125 (defun org-clock-special-range (key &optional time as-strings)
6126 "Return two times bordering a special time range.
6127 Key is a symbol specifying the range and can be one of `today', `yesterday',
6128 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
6129 A week starts Monday 0:00 and ends Sunday 24:00.
6130 The range is determined relative to TIME. TIME defaults to the current time.
6131 The return value is a cons cell with two internal times like the ones
6132 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
6133 the returned times will be formatted strings."
6134 (let* ((tm (decode-time (or time (current-time))))
6135 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
6136 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
6137 (dow (nth 6 tm))
6138 s1 m1 h1 d1 month1 y1 diff ts te fm)
6139 (cond
6140 ((eq key 'today)
6141 (setq h 0 m 0 h1 24 m1 0))
6142 ((eq key 'yesterday)
6143 (setq d (1- d) h 0 m 0 h1 24 m1 0))
6144 ((eq key 'thisweek)
6145 (setq diff (if (= dow 0) 6 (1- dow))
6146 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6147 ((eq key 'lastweek)
6148 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
6149 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6150 ((eq key 'thismonth)
6151 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
6152 ((eq key 'lastmonth)
6153 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
6154 ((eq key 'thisyear)
6155 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
6156 ((eq key 'lastyear)
6157 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
6158 (t (error "No such time block %s" key)))
6159 (setq ts (encode-time s m h d month y)
6160 te (encode-time (or s1 s) (or m1 m) (or h1 h)
6161 (or d1 d) (or month1 month) (or y1 y)))
6162 (setq fm (cdr org-time-stamp-formats))
6163 (if as-strings
6164 (cons (format-time-string fm ts) (format-time-string fm te))
6165 (cons ts te))))
6167 (defun org-dblock-write:clocktable (params)
6168 "Write the standard clocktable."
6169 (let ((hlchars '((1 . "*") (2 . ?/)))
6170 (emph nil)
6171 (ins (make-marker))
6172 ipos time h m p level hlc hdl maxlevel
6173 ts te cc block)
6174 (setq maxlevel (or (plist-get params :maxlevel) 3)
6175 emph (plist-get params :emphasize)
6176 ts (plist-get params :tstart)
6177 te (plist-get params :tend)
6178 block (plist-get params :block))
6179 (when block
6180 (setq cc (org-clock-special-range block nil t)
6181 ts (car cc) te (cdr cc)))
6182 (if ts (setq ts (time-to-seconds
6183 (apply 'encode-time (org-parse-time-string ts)))))
6184 (if te (setq te (time-to-seconds
6185 (apply 'encode-time (org-parse-time-string te)))))
6186 (move-marker ins (point))
6187 (setq ipos (point))
6188 (insert-before-markers "Clock summary at ["
6189 (substring
6190 (format-time-string (cdr org-time-stamp-formats))
6191 1 -1)
6192 "]."
6193 (if block
6194 (format " Considered range is /%s/." block)
6196 "\n\n|L|Headline|Time|\n")
6197 (org-clock-sum ts te)
6198 (setq h (/ org-clock-file-total-minutes 60)
6199 m (- org-clock-file-total-minutes (* 60 h)))
6200 (insert-before-markers "|-\n|0|" "*Total file time*| "
6201 (format "*%d:%02d*" h m)
6202 "|\n")
6203 (goto-char (point-min))
6204 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6205 (goto-char p)
6206 (when (setq time (get-text-property p :org-clock-minutes))
6207 (beginning-of-line 1)
6208 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6209 (setq level (- (match-end 1) (match-beginning 1)))
6210 (<= level maxlevel))
6211 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6212 hdl (match-string 2)
6213 h (/ time 60)
6214 m (- time (* 60 h)))
6215 (save-excursion
6216 (goto-char ins)
6217 (if (= level 1) (insert-before-markers "|-\n"))
6218 (insert-before-markers
6219 "| " (int-to-string level) "|" hlc hdl hlc " |"
6220 (make-string (1- level) ?|)
6222 (format "%d:%02d" h m)
6224 " |\n")))))
6225 (goto-char ins)
6226 (backward-delete-char 1)
6227 (goto-char ipos)
6228 (skip-chars-forward "^|")
6229 (org-table-align)))
6231 (defun org-collect-clock-time-entries ()
6232 "Return an internal list with clocking information.
6233 This list has one entry for each CLOCK interval.
6234 FIXME: describe the elements."
6235 (interactive)
6236 (let ((re (concat "^[ \t]*" org-clock-string
6237 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6238 rtn beg end next cont level title total closedp leafp
6239 clockpos titlepos h m donep)
6240 (save-excursion
6241 (org-clock-sum)
6242 (goto-char (point-min))
6243 (while (re-search-forward re nil t)
6244 (setq clockpos (match-beginning 0)
6245 beg (match-string 1) end (match-string 2)
6246 cont (match-end 0))
6247 (setq beg (apply 'encode-time (org-parse-time-string beg))
6248 end (apply 'encode-time (org-parse-time-string end)))
6249 (org-back-to-heading t)
6250 (setq donep (org-entry-is-done-p))
6251 (setq titlepos (point)
6252 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6253 h (/ total 60) m (- total (* 60 h))
6254 total (cons h m))
6255 (looking-at "\\(\\*+\\) +\\(.*\\)")
6256 (setq level (- (match-end 1) (match-beginning 1))
6257 title (org-match-string-no-properties 2))
6258 (save-excursion (outline-next-heading) (setq next (point)))
6259 (setq closedp (re-search-forward org-closed-time-regexp next t))
6260 (goto-char next)
6261 (setq leafp (and (looking-at "^\\*+ ")
6262 (<= (- (match-end 0) (point)) level)))
6263 (push (list beg end clockpos closedp donep
6264 total title titlepos level leafp)
6265 rtn)
6266 (goto-char cont)))
6267 (nreverse rtn)))
6269 ;;; Agenda, and Diary Integration
6271 ;;; Define the mode
6273 (defvar org-agenda-mode-map (make-sparse-keymap)
6274 "Keymap for `org-agenda-mode'.")
6276 (defvar org-agenda-menu) ; defined later in this file.
6277 (defvar org-agenda-follow-mode nil)
6278 (defvar org-agenda-show-log nil)
6279 (defvar org-agenda-buffer-name "*Org Agenda*")
6280 (defvar org-agenda-redo-command nil)
6281 (defvar org-agenda-mode-hook nil)
6282 (defvar org-agenda-type nil)
6283 (defvar org-agenda-force-single-file nil)
6285 (defun org-agenda-mode ()
6286 "Mode for time-sorted view on action items in Org-mode files.
6288 The following commands are available:
6290 \\{org-agenda-mode-map}"
6291 (interactive)
6292 (kill-all-local-variables)
6293 (setq major-mode 'org-agenda-mode)
6294 (setq mode-name "Org-Agenda")
6295 (use-local-map org-agenda-mode-map)
6296 (easy-menu-add org-agenda-menu)
6297 (if org-startup-truncated (setq truncate-lines t))
6298 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6299 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6300 (unless org-agenda-keep-modes
6301 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6302 org-agenda-show-log nil))
6303 (easy-menu-change
6304 '("Agenda") "Agenda Files"
6305 (append
6306 (list
6307 (vector
6308 (if (get 'org-agenda-files 'org-restrict)
6309 "Restricted to single file"
6310 "Edit File List")
6311 '(org-edit-agenda-file-list)
6312 (not (get 'org-agenda-files 'org-restrict)))
6313 "--")
6314 (mapcar 'org-file-menu-entry (org-agenda-files))))
6315 (org-agenda-set-mode-name)
6316 (apply
6317 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6318 (list 'org-agenda-mode-hook)))
6320 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6321 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6322 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6323 (define-key org-agenda-mode-map " " 'org-agenda-show)
6324 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6325 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6326 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6327 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6328 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6329 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6330 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6331 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6332 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6333 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6334 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6335 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6336 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6338 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6339 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6340 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6341 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6342 (while l (define-key org-agenda-mode-map
6343 (int-to-string (pop l)) 'digit-argument)))
6345 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6346 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6347 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6348 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6349 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6350 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6351 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6352 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
6353 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6354 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6355 (define-key org-agenda-mode-map "n" 'next-line)
6356 (define-key org-agenda-mode-map "p" 'previous-line)
6357 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6358 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6359 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6360 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6361 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6362 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6363 (eval-after-load "calendar"
6364 '(define-key calendar-mode-map org-calendar-to-agenda-key
6365 'org-calendar-goto-agenda))
6366 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6367 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6368 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6369 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6370 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6371 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6372 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6373 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6374 (define-key org-agenda-mode-map "O" 'org-clock-out)
6375 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6376 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6377 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6378 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6379 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6380 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6381 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6382 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6383 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6384 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6385 "Local keymap for agenda entries from Org-mode.")
6387 (define-key org-agenda-keymap
6388 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6389 (define-key org-agenda-keymap
6390 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6391 (when org-agenda-mouse-1-follows-link
6392 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6393 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6394 '("Agenda"
6395 ("Agenda Files")
6396 "--"
6397 ["Show" org-agenda-show t]
6398 ["Go To (other window)" org-agenda-goto t]
6399 ["Go To (one window)" org-agenda-switch-to t]
6400 ["Follow Mode" org-agenda-follow-mode
6401 :style toggle :selected org-agenda-follow-mode :active t]
6402 "--"
6403 ["Cycle TODO" org-agenda-todo t]
6404 ("Tags"
6405 ["Show all Tags" org-agenda-show-tags t]
6406 ["Set Tags" org-agenda-set-tags t])
6407 ("Schedule"
6408 ["Schedule" org-agenda-schedule t]
6409 ["Set Deadline" org-agenda-deadline t]
6410 "--"
6411 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6412 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6413 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6414 ("Priority"
6415 ["Set Priority" org-agenda-priority t]
6416 ["Increase Priority" org-agenda-priority-up t]
6417 ["Decrease Priority" org-agenda-priority-down t]
6418 ["Show Priority" org-agenda-show-priority t])
6419 "--"
6420 ;; ["New agenda command" org-agenda t]
6421 ["Rebuild buffer" org-agenda-redo t]
6422 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
6423 "--"
6424 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6425 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6426 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6427 "--"
6428 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6429 :style radio :selected (equal org-agenda-ndays 1)]
6430 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6431 :style radio :selected (equal org-agenda-ndays 7)]
6432 "--"
6433 ["Show Logbook entries" org-agenda-log-mode
6434 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6435 ["Include Diary" org-agenda-toggle-diary
6436 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6437 ["Use Time Grid" org-agenda-toggle-time-grid
6438 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6439 "--"
6440 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6441 ("Calendar Commands"
6442 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6443 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6444 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6445 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6446 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6447 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6448 "--"
6449 ["Quit" org-agenda-quit t]
6450 ["Exit and Release Buffers" org-agenda-exit t]
6453 ;;;###autoload
6454 (defun org-agenda (arg)
6455 "Dispatch agenda commands to collect entries to the agenda buffer.
6456 Prompts for a character to select a command. Any prefix arg will be passed
6457 on to the selected command. The default selections are:
6459 a Call `org-agenda' to display the agenda for the current day or week.
6460 t Call `org-todo-list' to display the global todo list.
6461 T Call `org-todo-list' to display the global todo list, select only
6462 entries with a specific TODO keyword (the user gets a prompt).
6463 m Call `org-tags-view' to display headlines with tags matching
6464 a condition (the user is prompted for the condition).
6465 M Like `m', but select only TODO entries, no ordinary headlines.
6467 More commands can be added by configuring the variable
6468 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
6469 searches can be pre-defined in this way.
6471 If the current buffer is in Org-mode and visiting a file, you can also
6472 first press `1' to indicate that the agenda should be temporarily (until the
6473 next use of \\[org-agenda]) restricted to the current file."
6474 (interactive "P")
6475 (catch 'exit
6476 (let ((restrict-ok (and buffer-file-name (org-mode-p)))
6477 (bfn buffer-file-name)
6478 (custom org-agenda-custom-commands)
6479 c entry key type string)
6480 (put 'org-agenda-files 'org-restrict nil)
6481 (save-window-excursion
6482 (delete-other-windows)
6483 (switch-to-buffer-other-window " *Agenda Commands*")
6484 (erase-buffer)
6485 (insert
6486 "Press key for an agenda command:
6487 --------------------------------
6488 a Agenda for current week or day
6489 t List of all TODO entries T Entries with special TODO kwd
6490 m Match a TAGS query M Like m, but only TODO entries
6491 C Configure your own agenda commands")
6492 (while (setq entry (pop custom))
6493 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
6494 (insert (format "\n%-4s%-14s: %s"
6496 (cond
6497 ((eq type 'tags) "Tags query")
6498 ((eq type 'todo) "TODO keyword")
6499 ((eq type 'tags-tree) "Tags tree")
6500 ((eq type 'todo-tree) "TODO kwd tree")
6501 ((eq type 'occur-tree) "Occur tree")
6502 (t "???"))
6503 (org-add-props string nil 'face 'org-warning))))
6504 (goto-char (point-min))
6505 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
6506 (message "Press key for agenda command%s"
6507 (if restrict-ok ", or [1] to restrict to current file" ""))
6508 (setq c (read-char-exclusive))
6509 (message "")
6510 (when (equal c ?1)
6511 (if restrict-ok
6512 (put 'org-agenda-files 'org-restrict (list bfn))
6513 (error "Cannot restrict agenda to current buffer"))
6514 (message "Press key for agenda command%s"
6515 (if restrict-ok " (restricted to current file)" ""))
6516 (setq c (read-char-exclusive))
6517 (message "")))
6518 (require 'calendar) ; FIXME: can we avoid this for some commands?
6519 ;; For example the todo list should not need it (but does...)
6520 (cond
6521 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
6522 ((equal c ?a) (call-interactively 'org-agenda-list))
6523 ((equal c ?t) (call-interactively 'org-todo-list))
6524 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
6525 ((equal c ?m) (call-interactively 'org-tags-view))
6526 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
6527 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
6528 (setq type (nth 1 entry) string (nth 2 entry))
6529 (cond
6530 ((eq type 'tags)
6531 (org-tags-view current-prefix-arg string))
6532 ((eq type 'tags-todo)
6533 (org-tags-view '(4) string))
6534 ((eq type 'todo)
6535 (org-todo-list string))
6536 ((eq type 'tags-tree)
6537 (org-check-for-org-mode)
6538 (org-tags-sparse-tree current-prefix-arg string))
6539 ((eq type 'todo-tree)
6540 (org-check-for-org-mode)
6541 (org-occur (concat "^" outline-regexp "[ \t]*"
6542 (regexp-quote string) "\\>")))
6543 ((eq type 'occur-tree)
6544 (org-check-for-org-mode)
6545 (org-occur string))
6546 (t (error "Invalid custom agenda command type %s" type))))
6547 (t (error "Invalid key"))))))
6549 (defun org-check-for-org-mode ()
6550 "Make sure current buffer is in org-mode. Error if not."
6551 (or (org-mode-p)
6552 (error "Cannot execute org-mode agenda command on buffer in %s."
6553 major-mode)))
6555 (defun org-fit-agenda-window ()
6556 "Fit the window to the buffer size."
6557 (and org-fit-agenda-window
6558 (fboundp 'fit-window-to-buffer)
6559 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
6560 (/ (frame-height) 2))))
6562 (defun org-agenda-files (&optional unrestricted)
6563 "Get the list of agenda files.
6564 Optional UNRESTRICTED means return the full list even if a restriction
6565 is currently in place."
6566 (cond
6567 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
6568 ((stringp org-agenda-files) (org-read-agenda-file-list))
6569 ((listp org-agenda-files) org-agenda-files)
6570 (t (error "Invalid value of `org-agenda-files'"))))
6572 (defvar org-window-configuration)
6574 (defun org-edit-agenda-file-list ()
6575 "Edit the list of agenda files.
6576 Depending on setup, this either uses customize to edit the variable
6577 `org-agenda-files', or it visits the file that is holding the list. In the
6578 latter case, the buffer is set up in a way that saving it automatically kills
6579 the buffer and restores the previous window configuration."
6580 (interactive)
6581 (if (stringp org-agenda-files)
6582 (let ((cw (current-window-configuration)))
6583 (find-file org-agenda-files)
6584 (org-set-local 'org-window-configuration cw)
6585 (org-add-hook 'after-save-hook
6586 (lambda ()
6587 (set-window-configuration
6588 (prog1 org-window-configuration
6589 (kill-buffer (current-buffer))))
6590 (org-install-agenda-files-menu)
6591 (message "New agenda file list installed"))
6592 nil 'local)
6593 (message (substitute-command-keys
6594 "Edit list and finish with \\[save-buffer]")))
6595 (customize-variable 'org-agenda-files)))
6597 (defun org-store-new-agenda-file-list (list)
6598 "Set new value for the agenda file list and save it correcly."
6599 (if (stringp org-agenda-files)
6600 (let ((f org-agenda-files) b)
6601 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
6602 (with-temp-file f
6603 (insert (mapconcat 'identity list "\n") "\n")))
6604 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
6605 (setq org-agenda-files list)
6606 (customize-save-variable 'org-agenda-files org-agenda-files))))
6608 (defun org-read-agenda-file-list ()
6609 "Read the list of agenda files from a file."
6610 (when (stringp org-agenda-files)
6611 (with-temp-buffer
6612 (insert-file-contents org-agenda-files)
6613 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
6615 (defvar org-agenda-markers nil
6616 "List of all currently active markers created by `org-agenda'.")
6617 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
6618 "Creation time of the last agenda marker.")
6620 (defun org-agenda-new-marker (&optional pos)
6621 "Return a new agenda marker.
6622 Org-mode keeps a list of these markers and resets them when they are
6623 no longer in use."
6624 (let ((m (copy-marker (or pos (point)))))
6625 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
6626 (push m org-agenda-markers)
6629 (defun org-agenda-maybe-reset-markers (&optional force)
6630 "Reset markers created by `org-agenda'. But only if they are old enough."
6631 (if (or force
6632 (> (- (time-to-seconds (current-time))
6633 org-agenda-last-marker-time)
6635 (while org-agenda-markers
6636 (move-marker (pop org-agenda-markers) nil))))
6638 (defvar org-agenda-new-buffers nil
6639 "Buffers created to visit agenda files.")
6641 (defun org-get-agenda-file-buffer (file)
6642 "Get a buffer visiting FILE. If the buffer needs to be created, add
6643 it to the list of buffers which might be released later."
6644 (let ((buf (find-buffer-visiting file)))
6645 (if buf
6646 buf ; just return it
6647 ;; Make a new buffer and remember it
6648 (setq buf (find-file-noselect file))
6649 (if buf (push buf org-agenda-new-buffers))
6650 buf)))
6652 (defun org-release-buffers (blist)
6653 "Release all buffers in list, asking the user for confirmation when needed.
6654 When a buffer is unmodified, it is just killed. When modified, it is saved
6655 \(if the user agrees) and then killed."
6656 (let (buf file)
6657 (while (setq buf (pop blist))
6658 (setq file (buffer-file-name buf))
6659 (when (and (buffer-modified-p buf)
6660 file
6661 (y-or-n-p (format "Save file %s? " file)))
6662 (with-current-buffer buf (save-buffer)))
6663 (kill-buffer buf))))
6665 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
6667 (defun org-timeline (&optional include-all keep-modes)
6668 "Show a time-sorted view of the entries in the current org file.
6669 Only entries with a time stamp of today or later will be listed. With
6670 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
6671 under the current date.
6672 If the buffer contains an active region, only check the region for
6673 dates."
6674 (interactive "P")
6675 (require 'calendar)
6676 (org-agenda-maybe-reset-markers 'force)
6677 (org-compile-prefix-format org-timeline-prefix-format)
6678 (let* ((dopast t)
6679 (dotodo include-all)
6680 (doclosed org-agenda-show-log)
6681 (org-agenda-keep-modes keep-modes)
6682 (entry buffer-file-name)
6683 (org-agenda-files (list buffer-file-name))
6684 (date (calendar-current-date))
6685 (win (selected-window))
6686 (pos1 (point))
6687 (beg (if (org-region-active-p) (region-beginning) (point-min)))
6688 (end (if (org-region-active-p) (region-end) (point-max)))
6689 (day-numbers (org-get-all-dates beg end 'no-ranges
6690 t doclosed ; always include today
6691 org-timeline-show-empty-dates))
6692 (today (time-to-days (current-time)))
6693 (org-respect-restriction t)
6694 (past t)
6695 args
6696 s e rtn d emptyp)
6697 (org-prepare-agenda-buffers org-agenda-files)
6698 (setq org-agenda-redo-command
6699 (list 'progn
6700 (list 'switch-to-buffer-other-window (current-buffer))
6701 (list 'org-timeline (list 'quote include-all) t)))
6702 (if (not dopast)
6703 ;; Remove past dates from the list of dates.
6704 (setq day-numbers (delq nil (mapcar (lambda(x)
6705 (if (>= x today) x nil))
6706 day-numbers))))
6707 (switch-to-buffer-other-window
6708 (get-buffer-create org-agenda-buffer-name))
6709 (setq buffer-read-only nil)
6710 (erase-buffer)
6711 (org-agenda-mode) (setq buffer-read-only nil)
6712 (org-set-local 'org-agenda-type 'timeline)
6713 (if doclosed (push :closed args))
6714 (push :timestamp args)
6715 (if dotodo (push :todo args))
6716 (while (setq d (pop day-numbers))
6717 (if (and (listp d) (eq (car d) :omitted))
6718 (progn
6719 (setq s (point))
6720 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
6721 (put-text-property s (1- (point)) 'face 'org-level-3))
6722 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
6723 (if (and (>= d today)
6724 dopast
6725 past)
6726 (progn
6727 (setq past nil)
6728 (insert (make-string 79 ?-) "\n")))
6729 (setq date (calendar-gregorian-from-absolute d))
6730 (setq s (point))
6731 (setq rtn (and (not emptyp)
6732 (apply 'org-agenda-get-day-entries
6733 entry date args)))
6734 (if (or rtn (equal d today) org-timeline-show-empty-dates)
6735 (progn
6736 (insert (calendar-day-name date) " "
6737 (number-to-string (extract-calendar-day date)) " "
6738 (calendar-month-name (extract-calendar-month date)) " "
6739 (number-to-string (extract-calendar-year date)) "\n")
6740 (put-text-property s (1- (point)) 'face
6741 'org-level-3)
6742 (if (equal d today)
6743 (put-text-property s (1- (point)) 'org-today t))
6744 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
6745 (put-text-property s (1- (point)) 'day d)))))
6746 (goto-char (point-min))
6747 (setq buffer-read-only t)
6748 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6749 (point-min)))
6750 (when (not org-select-timeline-window)
6751 (select-window win)
6752 (goto-char pos1))))
6754 ;;;###autoload
6755 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
6756 "Produce a weekly view from all files in variable `org-agenda-files'.
6757 The view will be for the current week, but from the overview buffer you
6758 will be able to go to other weeks.
6759 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
6760 also be shown, under the current date.
6761 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
6762 on the days are also shown. See the variable `org-log-done' for how
6763 to turn on logging.
6764 START-DAY defaults to TODAY, or to the most recent match for the weekday
6765 given in `org-agenda-start-on-weekday'.
6766 NDAYS defaults to `org-agenda-ndays'."
6767 (interactive "P")
6768 (org-agenda-maybe-reset-markers 'force)
6769 (org-compile-prefix-format org-agenda-prefix-format)
6770 (require 'calendar)
6771 (let* ((org-agenda-start-on-weekday
6772 (if (or (equal ndays 1)
6773 (and (null ndays) (equal 1 org-agenda-ndays)))
6774 nil org-agenda-start-on-weekday))
6775 (org-agenda-keep-modes keep-modes)
6776 (thefiles (org-agenda-files))
6777 (files thefiles)
6778 (win (selected-window))
6779 (today (time-to-days (current-time)))
6780 (sd (or start-day today))
6781 (start (if (or (null org-agenda-start-on-weekday)
6782 (< org-agenda-ndays 7))
6784 (let* ((nt (calendar-day-of-week
6785 (calendar-gregorian-from-absolute sd)))
6786 (n1 org-agenda-start-on-weekday)
6787 (d (- nt n1)))
6788 (- sd (+ (if (< d 0) 7 0) d)))))
6789 (day-numbers (list start))
6790 (inhibit-redisplay t)
6791 s e rtn rtnall file date d start-pos end-pos todayp nd)
6792 (org-prepare-agenda-buffers files)
6793 (setq org-agenda-redo-command
6794 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
6795 ;; Make the list of days
6796 (setq ndays (or ndays org-agenda-ndays)
6797 nd ndays)
6798 (while (> ndays 1)
6799 (push (1+ (car day-numbers)) day-numbers)
6800 (setq ndays (1- ndays)))
6801 (setq day-numbers (nreverse day-numbers))
6802 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6803 (progn
6804 (delete-other-windows)
6805 (switch-to-buffer-other-window
6806 (get-buffer-create org-agenda-buffer-name))))
6807 (setq buffer-read-only nil)
6808 (erase-buffer)
6809 (org-agenda-mode) (setq buffer-read-only nil)
6810 (org-set-local 'org-agenda-type 'agenda)
6811 (org-set-local 'starting-day (car day-numbers))
6812 (org-set-local 'include-all-loc include-all)
6813 (when (and (or include-all org-agenda-include-all-todo)
6814 (member today day-numbers))
6815 (setq files thefiles
6816 rtnall nil)
6817 (while (setq file (pop files))
6818 (catch 'nextfile
6819 (org-check-agenda-file file)
6820 (setq date (calendar-gregorian-from-absolute today)
6821 rtn (org-agenda-get-day-entries
6822 file date :todo))
6823 (setq rtnall (append rtnall rtn))))
6824 (when rtnall
6825 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
6826 (add-text-properties (point-min) (1- (point))
6827 (list 'face 'org-level-3))
6828 (insert (org-finalize-agenda-entries rtnall) "\n")))
6829 (while (setq d (pop day-numbers))
6830 (setq date (calendar-gregorian-from-absolute d)
6831 s (point))
6832 (if (or (setq todayp (= d today))
6833 (and (not start-pos) (= d sd)))
6834 (setq start-pos (point))
6835 (if (and start-pos (not end-pos))
6836 (setq end-pos (point))))
6837 (setq files thefiles
6838 rtnall nil)
6839 (while (setq file (pop files))
6840 (catch 'nextfile
6841 (org-check-agenda-file file)
6842 (if org-agenda-show-log
6843 (setq rtn (org-agenda-get-day-entries
6844 file date
6845 :deadline :scheduled :timestamp :closed))
6846 (setq rtn (org-agenda-get-day-entries
6847 file date
6848 :deadline :scheduled :timestamp)))
6849 (setq rtnall (append rtnall rtn))))
6850 (if org-agenda-include-diary
6851 (progn
6852 (require 'diary-lib)
6853 (setq rtn (org-get-entries-from-diary date))
6854 (setq rtnall (append rtnall rtn))))
6855 (if (or rtnall org-agenda-show-all-dates)
6856 (progn
6857 (insert (format "%-9s %2d %s %4d\n"
6858 (calendar-day-name date)
6859 (extract-calendar-day date)
6860 (calendar-month-name (extract-calendar-month date))
6861 (extract-calendar-year date)))
6862 (put-text-property s (1- (point)) 'face
6863 'org-level-3)
6864 (if rtnall (insert
6865 (org-finalize-agenda-entries
6866 (org-agenda-add-time-grid-maybe
6867 rtnall nd todayp))
6868 "\n"))
6869 (put-text-property s (1- (point)) 'day d))))
6870 (goto-char (point-min))
6871 (setq buffer-read-only t)
6872 (org-fit-agenda-window)
6873 (unless (and (pos-visible-in-window-p (point-min))
6874 (pos-visible-in-window-p (point-max)))
6875 (goto-char (1- (point-max)))
6876 (recenter -1)
6877 (if (not (pos-visible-in-window-p (or start-pos 1)))
6878 (progn
6879 (goto-char (or start-pos 1))
6880 (recenter 1))))
6881 (goto-char (or start-pos 1))
6882 (if (not org-select-agenda-window) (select-window win))
6883 (message "")))
6885 (defvar org-select-this-todo-keyword nil)
6887 ;;;###autoload
6888 (defun org-todo-list (arg &optional keep-modes)
6889 "Show all TODO entries from all agenda file in a single list.
6890 The prefix arg can be used to select a specific TODO keyword and limit
6891 the list to these. When using \\[universal-argument], you will be prompted
6892 for a keyword. A numeric prefix directly selects the Nth keyword in
6893 `org-todo-keywords'."
6894 (interactive "P")
6895 (org-agenda-maybe-reset-markers 'force)
6896 (org-compile-prefix-format org-agenda-prefix-format)
6897 (let* ((org-agenda-keep-modes keep-modes)
6898 (today (time-to-days (current-time)))
6899 (date (calendar-gregorian-from-absolute today))
6900 (win (selected-window))
6901 (kwds org-todo-keywords)
6902 (completion-ignore-case t)
6903 (org-select-this-todo-keyword
6904 (if (stringp arg) arg
6905 (and arg (integerp arg) (> arg 0)
6906 (nth (1- arg) org-todo-keywords))))
6907 rtn rtnall files file pos)
6908 (when (equal arg '(4))
6909 (setq org-select-this-todo-keyword
6910 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
6911 nil t)))
6912 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
6913 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6914 (progn
6915 (delete-other-windows)
6916 (switch-to-buffer-other-window
6917 (get-buffer-create org-agenda-buffer-name))))
6918 (setq buffer-read-only nil)
6919 (erase-buffer)
6920 (org-agenda-mode) (setq buffer-read-only nil)
6921 (org-set-local 'org-agenda-type 'todo)
6922 (org-set-local 'last-arg arg)
6923 (org-set-local 'org-todo-keywords kwds)
6924 (org-set-local 'org-agenda-redo-command
6925 '(org-todo-list (or current-prefix-arg last-arg) t))
6926 (setq files (org-agenda-files)
6927 rtnall nil)
6928 (org-prepare-agenda-buffers files)
6929 (while (setq file (pop files))
6930 (catch 'nextfile
6931 (org-check-agenda-file file)
6932 (setq rtn (org-agenda-get-day-entries file date :todo))
6933 (setq rtnall (append rtnall rtn))))
6934 (insert "Global list of TODO items of type: ")
6935 (add-text-properties (point-min) (1- (point))
6936 (list 'face 'org-level-3))
6937 (setq pos (point))
6938 (insert (or org-select-this-todo-keyword "ALL") "\n")
6939 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6940 (setq pos (point))
6941 (insert
6942 "Available with `N r': (0)ALL "
6943 (let ((n 0))
6944 (mapconcat (lambda (x)
6945 (format "(%d)%s" (setq n (1+ n)) x))
6946 org-todo-keywords " "))
6947 "\n")
6948 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
6949 (when rtnall
6950 (insert (org-finalize-agenda-entries rtnall) "\n"))
6951 (goto-char (point-min))
6952 (setq buffer-read-only t)
6953 (org-fit-agenda-window)
6954 (if (not org-select-agenda-window) (select-window win))))
6956 (defun org-check-agenda-file (file)
6957 "Make sure FILE exists. If not, ask user what to do."
6958 (when (not (file-exists-p file))
6959 (message "non-existent file %s. [R]emove from list or [A]bort?"
6960 (abbreviate-file-name file))
6961 (let ((r (downcase (read-char-exclusive))))
6962 (cond
6963 ((equal r ?r)
6964 (org-remove-file file)
6965 (throw 'nextfile t))
6966 (t (error "Abort"))))))
6968 (defun org-agenda-check-type (error &rest types)
6969 "Check if agenda buffer is of allowed type.
6970 If ERROR is non-nil, throw an error, otherwise just return nil."
6971 (if (memq org-agenda-type types)
6973 (if error
6974 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
6975 nil)))
6977 (defun org-agenda-quit ()
6978 "Exit agenda by removing the window or the buffer."
6979 (interactive)
6980 (let ((buf (current-buffer)))
6981 (if (not (one-window-p)) (delete-window))
6982 (kill-buffer buf)
6983 (org-agenda-maybe-reset-markers 'force)))
6985 (defun org-agenda-exit ()
6986 "Exit agenda by removing the window or the buffer.
6987 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
6988 Org-mode buffers visited directly by the user will not be touched."
6989 (interactive)
6990 (org-release-buffers org-agenda-new-buffers)
6991 (setq org-agenda-new-buffers nil)
6992 (org-agenda-quit))
6994 ;; FIXME: move this function.
6995 (defun org-save-all-org-buffers ()
6996 "Save all Org-mode buffers without user confirmation."
6997 (interactive)
6998 (message "Saving all Org-mode buffers...")
6999 (save-some-buffers t 'org-mode-p)
7000 (message "Saving all Org-mode buffers... done"))
7002 (defun org-agenda-redo ()
7003 "Rebuild Agenda.
7004 When this is the global TODO list, a prefix argument will be interpreted."
7005 (interactive)
7006 (message "Rebuilding agenda buffer...")
7007 (eval org-agenda-redo-command)
7008 (message "Rebuilding agenda buffer...done"))
7010 (defun org-agenda-goto-today ()
7011 "Go to today."
7012 (interactive)
7013 (org-agenda-check-type t 'timeline 'agenda)
7014 (if (boundp 'starting-day)
7015 (let ((cmd (car org-agenda-redo-command))
7016 (iall (nth 1 org-agenda-redo-command))
7017 (nday (nth 3 org-agenda-redo-command))
7018 (keep (nth 4 org-agenda-redo-command)))
7019 (eval (list cmd iall nil nday keep)))
7020 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
7021 (point-min)))))
7023 (defun org-agenda-later (arg)
7024 "Go forward in time by `org-agenda-ndays' days.
7025 With prefix ARG, go forward that many times `org-agenda-ndays'."
7026 (interactive "p")
7027 (org-agenda-check-type t 'agenda)
7028 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
7029 (+ starting-day (* arg org-agenda-ndays)) nil t))
7031 (defun org-agenda-earlier (arg)
7032 "Go back in time by `org-agenda-ndays' days.
7033 With prefix ARG, go back that many times `org-agenda-ndays'."
7034 (interactive "p")
7035 (org-agenda-check-type t 'agenda)
7036 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
7037 (- starting-day (* arg org-agenda-ndays)) nil t))
7039 (defun org-agenda-week-view ()
7040 "Switch to weekly view for agenda."
7041 (interactive)
7042 (org-agenda-check-type t 'agenda)
7043 (setq org-agenda-ndays 7)
7044 (org-agenda-list include-all-loc
7045 (or (get-text-property (point) 'day)
7046 starting-day)
7047 nil t)
7048 (org-agenda-set-mode-name)
7049 (message "Switched to week view"))
7051 (defun org-agenda-day-view ()
7052 "Switch to daily view for agenda."
7053 (interactive)
7054 (org-agenda-check-type t 'agenda)
7055 (setq org-agenda-ndays 1)
7056 (org-agenda-list include-all-loc
7057 (or (get-text-property (point) 'day)
7058 starting-day)
7059 nil t)
7060 (org-agenda-set-mode-name)
7061 (message "Switched to day view"))
7063 (defun org-agenda-next-date-line (&optional arg)
7064 "Jump to the next line indicating a date in agenda buffer."
7065 (interactive "p")
7066 (org-agenda-check-type t 'agenda 'timeline)
7067 (beginning-of-line 1)
7068 (if (looking-at "^\\S-") (forward-char 1))
7069 (if (not (re-search-forward "^\\S-" nil t arg))
7070 (progn
7071 (backward-char 1)
7072 (error "No next date after this line in this buffer")))
7073 (goto-char (match-beginning 0)))
7075 (defun org-agenda-previous-date-line (&optional arg)
7076 "Jump to the previous line indicating a date in agenda buffer."
7077 (interactive "p")
7078 (org-agenda-check-type t 'agenda 'timeline)
7079 (beginning-of-line 1)
7080 (if (not (re-search-backward "^\\S-" nil t arg))
7081 (error "No previous date before this line in this buffer")))
7083 ;; Initialize the highlight
7084 (defvar org-hl (org-make-overlay 1 1))
7085 (org-overlay-put org-hl 'face 'highlight)
7087 (defun org-highlight (begin end &optional buffer)
7088 "Highlight a region with overlay."
7089 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
7090 org-hl begin end (or buffer (current-buffer))))
7092 (defun org-unhighlight ()
7093 "Detach overlay INDEX."
7094 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
7097 (defun org-agenda-follow-mode ()
7098 "Toggle follow mode in an agenda buffer."
7099 (interactive)
7100 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
7101 (org-agenda-set-mode-name)
7102 (message "Follow mode is %s"
7103 (if org-agenda-follow-mode "on" "off")))
7105 (defun org-agenda-log-mode ()
7106 "Toggle log mode in an agenda buffer."
7107 (interactive)
7108 (org-agenda-check-type t 'agenda 'timeline)
7109 (setq org-agenda-show-log (not org-agenda-show-log))
7110 (org-agenda-set-mode-name)
7111 (org-agenda-redo)
7112 (message "Log mode is %s"
7113 (if org-agenda-show-log "on" "off")))
7115 (defun org-agenda-toggle-diary ()
7116 "Toggle diary inclusion in an agenda buffer."
7117 (interactive)
7118 (org-agenda-check-type t 'agenda)
7119 (setq org-agenda-include-diary (not org-agenda-include-diary))
7120 (org-agenda-redo)
7121 (org-agenda-set-mode-name)
7122 (message "Diary inclusion turned %s"
7123 (if org-agenda-include-diary "on" "off")))
7125 (defun org-agenda-toggle-time-grid ()
7126 "Toggle time grid in an agenda buffer."
7127 (interactive)
7128 (org-agenda-check-type t 'agenda)
7129 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
7130 (org-agenda-redo)
7131 (org-agenda-set-mode-name)
7132 (message "Time-grid turned %s"
7133 (if org-agenda-use-time-grid "on" "off")))
7135 (defun org-agenda-set-mode-name ()
7136 "Set the mode name to indicate all the small mode settings."
7137 (setq mode-name
7138 (concat "Org-Agenda"
7139 (if (equal org-agenda-ndays 1) " Day" "")
7140 (if (equal org-agenda-ndays 7) " Week" "")
7141 (if org-agenda-follow-mode " Follow" "")
7142 (if org-agenda-include-diary " Diary" "")
7143 (if org-agenda-use-time-grid " Grid" "")
7144 (if org-agenda-show-log " Log" "")))
7145 (force-mode-line-update))
7147 (defun org-agenda-post-command-hook ()
7148 (and (eolp) (not (bolp)) (backward-char 1))
7149 (if (and org-agenda-follow-mode
7150 (get-text-property (point) 'org-marker))
7151 (org-agenda-show)))
7153 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
7155 (defun org-get-entries-from-diary (date)
7156 "Get the (Emacs Calendar) diary entries for DATE."
7157 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
7158 (diary-display-hook '(fancy-diary-display))
7159 (list-diary-entries-hook
7160 (cons 'org-diary-default-entry list-diary-entries-hook))
7161 (diary-file-name-prefix-function nil) ; turn this feature off
7162 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7163 entries
7164 (org-disable-agenda-to-diary t))
7165 (save-excursion
7166 (save-window-excursion
7167 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7168 (if (not (get-buffer fancy-diary-buffer))
7169 (setq entries nil)
7170 (with-current-buffer fancy-diary-buffer
7171 (setq buffer-read-only nil)
7172 (if (= (point-max) 1)
7173 ;; No entries
7174 (setq entries nil)
7175 ;; Omit the date and other unnecessary stuff
7176 (org-agenda-cleanup-fancy-diary)
7177 ;; Add prefix to each line and extend the text properties
7178 (if (= (point-max) 1)
7179 (setq entries nil)
7180 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7181 (set-buffer-modified-p nil)
7182 (kill-buffer fancy-diary-buffer)))
7183 (when entries
7184 (setq entries (org-split-string entries "\n"))
7185 (setq entries
7186 (mapcar
7187 (lambda (x)
7188 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7189 ;; Extend the text properties to the beginning of the line
7190 (org-add-props x (text-properties-at (1- (length x)) x)))
7191 entries)))))
7193 (defun org-agenda-cleanup-fancy-diary ()
7194 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7195 This gets rid of the date, the underline under the date, and
7196 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7197 date. It also removes lines that contain only whitespace."
7198 (goto-char (point-min))
7199 (if (looking-at ".*?:[ \t]*")
7200 (progn
7201 (replace-match "")
7202 (re-search-forward "\n=+$" nil t)
7203 (replace-match "")
7204 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7205 (re-search-forward "\n=+$" nil t)
7206 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7207 (goto-char (point-min))
7208 (while (re-search-forward "^ +\n" nil t)
7209 (replace-match ""))
7210 (goto-char (point-min))
7211 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7212 (replace-match "")))
7214 ;; Make sure entries from the diary have the right text properties.
7215 (eval-after-load "diary-lib"
7216 '(if (boundp 'diary-modify-entry-list-string-function)
7217 ;; We can rely on the hook, nothing to do
7219 ;; Hook not avaiable, must use advice to make this work
7220 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7221 "Make the position visible."
7222 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7223 (stringp string)
7224 buffer-file-name)
7225 (setq string (org-modify-diary-entry-string string))))))
7227 (defun org-modify-diary-entry-string (string)
7228 "Add text properties to string, allowing org-mode to act on it."
7229 (org-add-props string nil
7230 'mouse-face 'highlight
7231 'keymap org-agenda-keymap
7232 'help-echo (format "mouse-2 or RET jump to diary file %s"
7233 (abbreviate-file-name buffer-file-name))
7234 'org-agenda-diary-link t
7235 'org-marker (org-agenda-new-marker (point-at-bol))))
7237 (defun org-diary-default-entry ()
7238 "Add a dummy entry to the diary.
7239 Needed to avoid empty dates which mess up holiday display."
7240 ;; Catch the error if dealing with the new add-to-diary-alist
7241 (when org-disable-agenda-to-diary
7242 (condition-case nil
7243 (add-to-diary-list original-date "Org-mode dummy" "")
7244 (error
7245 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7247 (defun org-cycle-agenda-files ()
7248 "Cycle through the files in `org-agenda-files'.
7249 If the current buffer visits an agenda file, find the next one in the list.
7250 If the current buffer does not, find the first agenda file."
7251 (interactive)
7252 (let* ((fs (org-agenda-files t))
7253 (files (append fs (list (car fs))))
7254 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7255 file)
7256 (unless files (error "No agenda files"))
7257 (catch 'exit
7258 (while (setq file (pop files))
7259 (if (equal (file-truename file) tcf)
7260 (when (car files)
7261 (find-file (car files))
7262 (throw 'exit t))))
7263 (find-file (car fs)))))
7265 (defun org-agenda-file-to-end ()
7266 "Move/add the current file to the end of the agenda file list.
7267 If the file is not present in the list, it is appended to the list. If it is
7268 present, it is moved there."
7269 (interactive)
7270 (org-agenda-file-to-front 'to-end))
7272 (defun org-agenda-file-to-front (&optional to-end)
7273 "Move/add the current file to the top of the agenda file list.
7274 If the file is not present in the list, it is added to the front. If it is
7275 present, it is moved there. With optional argument TO-END, add/move to the
7276 end of the list."
7277 (interactive "P")
7278 (let ((file-alist (mapcar (lambda (x)
7279 (cons (file-truename x) x))
7280 (org-agenda-files t)))
7281 (ctf (file-truename buffer-file-name))
7282 x had)
7283 (setq x (assoc ctf file-alist) had x)
7285 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7286 (if to-end
7287 (setq file-alist (append (delq x file-alist) (list x)))
7288 (setq file-alist (cons x (delq x file-alist))))
7289 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7290 (org-install-agenda-files-menu)
7291 (message "File %s to %s of agenda file list"
7292 (if had "moved" "added") (if to-end "end" "front"))))
7294 (defun org-remove-file (&optional file)
7295 "Remove current file from the list of files in variable `org-agenda-files'.
7296 These are the files which are being checked for agenda entries.
7297 Optional argument FILE means, use this file instead of the current."
7298 (interactive)
7299 (let* ((file (or file buffer-file-name))
7300 (true-file (file-truename file))
7301 (afile (abbreviate-file-name file))
7302 (files (delq nil (mapcar
7303 (lambda (x)
7304 (if (equal true-file
7305 (file-truename x))
7306 nil x))
7307 (org-agenda-files t)))))
7308 (if (not (= (length files) (length (org-agenda-files t))))
7309 (progn
7310 (org-store-new-agenda-file-list files)
7311 (org-install-agenda-files-menu)
7312 (message "Removed file: %s" afile))
7313 (message "File was not in list: %s" afile))))
7315 (defun org-file-menu-entry (file)
7316 (vector file (list 'find-file file) t))
7318 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7319 "Return a list of all relevant day numbers from BEG to END buffer positions.
7320 If NO-RANGES is non-nil, include only the start and end dates of a range,
7321 not every single day in the range. If FORCE-TODAY is non-nil, make
7322 sure that TODAY is included in the list. If INACTIVE is non-nil, also
7323 inactive time stamps (those in square brackets) are included.
7324 When EMPTY is non-nil, also include days without any entries."
7325 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
7326 dates dates1 date day day1 day2 ts1 ts2)
7327 (if force-today
7328 (setq dates (list (time-to-days (current-time)))))
7329 (save-excursion
7330 (goto-char beg)
7331 (while (re-search-forward re end t)
7332 (setq day (time-to-days (org-time-string-to-time
7333 (substring (match-string 1) 0 10))))
7334 (or (memq day dates) (push day dates)))
7335 (unless no-ranges
7336 (goto-char beg)
7337 (while (re-search-forward org-tr-regexp end t)
7338 (setq ts1 (substring (match-string 1) 0 10)
7339 ts2 (substring (match-string 2) 0 10)
7340 day1 (time-to-days (org-time-string-to-time ts1))
7341 day2 (time-to-days (org-time-string-to-time ts2)))
7342 (while (< (setq day1 (1+ day1)) day2)
7343 (or (memq day1 dates) (push day1 dates)))))
7344 (setq dates (sort dates '<))
7345 (when empty
7346 (while (setq day (pop dates))
7347 (setq day2 (car dates))
7348 (push day dates1)
7349 (when (and day2 empty)
7350 (if (or (eq empty t)
7351 (and (numberp empty) (<= (- day2 day) empty)))
7352 (while (< (setq day (1+ day)) day2)
7353 (push (list day) dates1))
7354 (push (cons :omitted (- day2 day)) dates1))))
7355 (setq dates (nreverse dates1)))
7356 dates)))
7358 ;;;###autoload
7359 (defun org-diary (&rest args)
7360 "Return diary information from org-files.
7361 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
7362 It accesses org files and extracts information from those files to be
7363 listed in the diary. The function accepts arguments specifying what
7364 items should be listed. The following arguments are allowed:
7366 :timestamp List the headlines of items containing a date stamp or
7367 date range matching the selected date. Deadlines will
7368 also be listed, on the expiration day.
7370 :deadline List any deadlines past due, or due within
7371 `org-deadline-warning-days'. The listing occurs only
7372 in the diary for *today*, not at any other date. If
7373 an entry is marked DONE, it is no longer listed.
7375 :scheduled List all items which are scheduled for the given date.
7376 The diary for *today* also contains items which were
7377 scheduled earlier and are not yet marked DONE.
7379 :todo List all TODO items from the org-file. This may be a
7380 long list - so this is not turned on by default.
7381 Like deadlines, these entries only show up in the
7382 diary for *today*, not at any other date.
7384 The call in the diary file should look like this:
7386 &%%(org-diary) ~/path/to/some/orgfile.org
7388 Use a separate line for each org file to check. Or, if you omit the file name,
7389 all files listed in `org-agenda-files' will be checked automatically:
7391 &%%(org-diary)
7393 If you don't give any arguments (as in the example above), the default
7394 arguments (:deadline :scheduled :timestamp) are used. So the example above may
7395 also be written as
7397 &%%(org-diary :deadline :timestamp :scheduled)
7399 The function expects the lisp variables `entry' and `date' to be provided
7400 by the caller, because this is how the calendar works. Don't use this
7401 function from a program - use `org-agenda-get-day-entries' instead."
7402 (org-agenda-maybe-reset-markers)
7403 (org-compile-prefix-format org-agenda-prefix-format)
7404 (setq args (or args '(:deadline :scheduled :timestamp)))
7405 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
7406 (list entry)
7407 (org-agenda-files t)))
7408 file rtn results)
7409 ;; If this is called during org-agenda, don't return any entries to
7410 ;; the calendar. Org Agenda will list these entries itself.
7411 (if org-disable-agenda-to-diary (setq files nil))
7412 (while (setq file (pop files))
7413 (setq rtn (apply 'org-agenda-get-day-entries file date args))
7414 (setq results (append results rtn)))
7415 (if results
7416 (concat (org-finalize-agenda-entries results) "\n"))))
7417 (defvar org-category-table nil)
7418 (defun org-get-category-table ()
7419 "Get the table of categories and positions in current buffer."
7420 (let (tbl)
7421 (save-excursion
7422 (goto-char (point-min))
7423 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
7424 (push (cons (point) (org-trim (match-string 2))) tbl)))
7425 tbl))
7426 (defun org-get-category (&optional pos)
7427 "Get the category applying to position POS."
7428 (if (not org-category-table)
7429 (cond
7430 ((null org-category)
7431 (setq org-category
7432 (if buffer-file-name
7433 (file-name-sans-extension
7434 (file-name-nondirectory buffer-file-name))
7435 "???")))
7436 ((symbolp org-category) (symbol-name org-category))
7437 (t org-category))
7438 (let ((tbl org-category-table)
7439 (pos (or pos (point))))
7440 (while (and tbl (> (caar tbl) pos))
7441 (pop tbl))
7442 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
7443 org-category-table))))))
7445 (defun org-agenda-get-day-entries (file date &rest args)
7446 "Does the work for `org-diary' and `org-agenda'.
7447 FILE is the path to a file to be checked for entries. DATE is date like
7448 the one returned by `calendar-current-date'. ARGS are symbols indicating
7449 which kind of entries should be extracted. For details about these, see
7450 the documentation of `org-diary'."
7451 (setq args (or args '(:deadline :scheduled :timestamp)))
7452 (let* ((org-startup-with-deadline-check nil)
7453 (org-startup-folded nil)
7454 (org-startup-align-all-tables nil)
7455 (buffer (if (file-exists-p file)
7456 (org-get-agenda-file-buffer file)
7457 (error "No such file %s" file)))
7458 arg results rtn)
7459 (if (not buffer)
7460 ;; If file does not exist, make sure an error message ends up in diary
7461 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7462 (with-current-buffer buffer
7463 (unless (org-mode-p)
7464 (error "Agenda file %s is not in `org-mode'" file))
7465 (setq org-category-table (org-get-category-table))
7466 (let ((case-fold-search nil))
7467 (save-excursion
7468 (save-restriction
7469 (if org-respect-restriction
7470 (if (org-region-active-p)
7471 ;; Respect a region to restrict search
7472 (narrow-to-region (region-beginning) (region-end)))
7473 ;; If we work for the calendar or many files,
7474 ;; get rid of any restriction
7475 (widen))
7476 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
7477 (while (setq arg (pop args))
7478 (cond
7479 ((and (eq arg :todo)
7480 (equal date (calendar-current-date)))
7481 (setq rtn (org-agenda-get-todos))
7482 (setq results (append results rtn)))
7483 ((eq arg :timestamp)
7484 (setq rtn (org-agenda-get-blocks))
7485 (setq results (append results rtn))
7486 (setq rtn (org-agenda-get-timestamps))
7487 (setq results (append results rtn)))
7488 ((eq arg :scheduled)
7489 (setq rtn (org-agenda-get-scheduled))
7490 (setq results (append results rtn)))
7491 ((eq arg :closed)
7492 (setq rtn (org-agenda-get-closed))
7493 (setq results (append results rtn)))
7494 ((and (eq arg :deadline)
7495 (equal date (calendar-current-date)))
7496 (setq rtn (org-agenda-get-deadlines))
7497 (setq results (append results rtn))))))))
7498 results))))
7500 (defun org-entry-is-done-p ()
7501 "Is the current entry marked DONE?"
7502 (save-excursion
7503 (and (re-search-backward "[\r\n]\\*" nil t)
7504 (looking-at org-nl-done-regexp))))
7506 (defun org-at-date-range-p ()
7507 "Is the cursor inside a date range?"
7508 (interactive)
7509 (save-excursion
7510 (catch 'exit
7511 (let ((pos (point)))
7512 (skip-chars-backward "^<\r\n")
7513 (skip-chars-backward "<")
7514 (and (looking-at org-tr-regexp)
7515 (>= (match-end 0) pos)
7516 (throw 'exit t))
7517 (skip-chars-backward "^<\r\n")
7518 (skip-chars-backward "<")
7519 (and (looking-at org-tr-regexp)
7520 (>= (match-end 0) pos)
7521 (throw 'exit t)))
7522 nil)))
7524 (defun org-agenda-get-todos ()
7525 "Return the TODO information for agenda display."
7526 (let* ((props (list 'face nil
7527 'done-face 'org-done
7528 'org-not-done-regexp org-not-done-regexp
7529 'mouse-face 'highlight
7530 'keymap org-agenda-keymap
7531 'help-echo
7532 (format "mouse-2 or RET jump to org file %s"
7533 (abbreviate-file-name buffer-file-name))))
7534 (regexp (concat "[\n\r]\\*+ *\\("
7535 (if org-select-this-todo-keyword
7536 (concat "\\<\\(" org-select-this-todo-keyword
7537 "\\)\\>")
7538 org-not-done-regexp)
7539 "[^\n\r]*\\)"))
7540 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
7541 marker priority category tags
7542 ee txt)
7543 (goto-char (point-min))
7544 (while (re-search-forward regexp nil t)
7545 (catch :skip
7546 (when (and org-agenda-todo-ignore-scheduled
7547 (looking-at sched-re))
7548 ;; FIXME: the following test also happens below, but we need it here
7549 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
7550 (throw :skip nil))
7551 (org-agenda-skip)
7552 (goto-char (match-beginning 1))
7553 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
7554 category (org-get-category)
7555 tags (org-get-tags-at (point))
7556 txt (org-format-agenda-item "" (match-string 1) category tags)
7557 priority
7558 (+ (org-get-priority txt)
7559 (if org-todo-kwd-priority-p
7560 (- org-todo-kwd-max-priority -2
7561 (length
7562 (member (match-string 2) org-todo-keywords)))
7563 1)))
7564 (org-add-props txt props
7565 'org-marker marker 'org-hd-marker marker
7566 'priority priority 'category category)
7567 (push txt ee)
7568 (if org-agenda-todo-list-sublevels
7569 (goto-char (match-end 1))
7570 (org-end-of-subtree 'invisible))))
7571 (nreverse ee)))
7573 (defconst org-agenda-no-heading-message
7574 "No heading for this item in buffer or region.")
7576 (defun org-agenda-get-timestamps ()
7577 "Return the date stamp information for agenda display."
7578 (let* ((props (list 'face nil
7579 'org-not-done-regexp org-not-done-regexp
7580 'mouse-face 'highlight
7581 'keymap org-agenda-keymap
7582 'help-echo
7583 (format "mouse-2 or RET jump to org file %s"
7584 (abbreviate-file-name buffer-file-name))))
7585 (regexp (regexp-quote
7586 (substring
7587 (format-time-string
7588 (car org-time-stamp-formats)
7589 (apply 'encode-time ; DATE bound by calendar
7590 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7591 0 11)))
7592 marker hdmarker deadlinep scheduledp donep tmp priority category
7593 ee txt timestr tags)
7594 (goto-char (point-min))
7595 (while (re-search-forward regexp nil t)
7596 (catch :skip
7597 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
7598 (org-agenda-skip)
7599 (setq marker (org-agenda-new-marker (match-beginning 0))
7600 category (org-get-category (match-beginning 0))
7601 tmp (buffer-substring (max (point-min)
7602 (- (match-beginning 0)
7603 org-ds-keyword-length))
7604 (match-beginning 0))
7605 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7606 deadlinep (string-match org-deadline-regexp tmp)
7607 scheduledp (string-match org-scheduled-regexp tmp)
7608 donep (org-entry-is-done-p))
7609 (if (string-match ">" timestr)
7610 ;; substring should only run to end of time stamp
7611 (setq timestr (substring timestr 0 (match-end 0))))
7612 (save-excursion
7613 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7614 (progn
7615 (goto-char (match-end 1))
7616 (setq hdmarker (org-agenda-new-marker)
7617 tags (org-get-tags-at))
7618 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7619 (setq txt (org-format-agenda-item
7620 (format "%s%s"
7621 (if deadlinep "Deadline: " "")
7622 (if scheduledp "Scheduled: " ""))
7623 (match-string 1) category tags timestr)))
7624 (setq txt org-agenda-no-heading-message))
7625 (setq priority (org-get-priority txt))
7626 (org-add-props txt props
7627 'org-marker marker 'org-hd-marker hdmarker)
7628 (if deadlinep
7629 (org-add-props txt nil
7630 'face (if donep 'org-done 'org-warning)
7631 'undone-face 'org-warning 'done-face 'org-done
7632 'category category 'priority (+ 100 priority))
7633 (if scheduledp
7634 (org-add-props txt nil
7635 'face 'org-scheduled-today
7636 'undone-face 'org-scheduled-today 'done-face 'org-done
7637 'category category 'priority (+ 99 priority))
7638 (org-add-props txt nil 'priority priority 'category category)))
7639 (push txt ee))
7640 (outline-next-heading)))
7641 (nreverse ee)))
7643 (defun org-agenda-get-closed ()
7644 "Return the logged TODO entries for agenda display."
7645 (let* ((props (list 'mouse-face 'highlight
7646 'org-not-done-regexp org-not-done-regexp
7647 'keymap org-agenda-keymap
7648 'help-echo
7649 (format "mouse-2 or RET jump to org file %s"
7650 (abbreviate-file-name buffer-file-name))))
7651 (regexp (concat
7652 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
7653 (regexp-quote
7654 (substring
7655 (format-time-string
7656 (car org-time-stamp-formats)
7657 (apply 'encode-time ; DATE bound by calendar
7658 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7659 1 11))))
7660 marker hdmarker priority category tags closedp
7661 ee txt timestr)
7662 (goto-char (point-min))
7663 (while (re-search-forward regexp nil t)
7664 (catch :skip
7665 (org-agenda-skip)
7666 (setq marker (org-agenda-new-marker (match-beginning 0))
7667 closedp (equal (match-string 1) org-closed-string)
7668 category (org-get-category (match-beginning 0))
7669 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7670 ;; donep (org-entry-is-done-p)
7672 (if (string-match "\\]" timestr)
7673 ;; substring should only run to end of time stamp
7674 (setq timestr (substring timestr 0 (match-end 0))))
7675 (save-excursion
7676 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7677 (progn
7678 (goto-char (match-end 1))
7679 (setq hdmarker (org-agenda-new-marker)
7680 tags (org-get-tags-at))
7681 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7682 (setq txt (org-format-agenda-item
7683 (if closedp "Closed: " "Clocked: ")
7684 (match-string 1) category tags timestr)))
7685 (setq txt org-agenda-no-heading-message))
7686 (setq priority 100000)
7687 (org-add-props txt props
7688 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
7689 'priority priority 'category category
7690 'undone-face 'org-warning 'done-face 'org-done)
7691 (push txt ee))
7692 (outline-next-heading)))
7693 (nreverse ee)))
7695 (defun org-agenda-get-deadlines ()
7696 "Return the deadline information for agenda display."
7697 (let* ((wdays org-deadline-warning-days)
7698 (props (list 'mouse-face 'highlight
7699 'org-not-done-regexp org-not-done-regexp
7700 'keymap org-agenda-keymap
7701 'help-echo
7702 (format "mouse-2 or RET jump to org file %s"
7703 (abbreviate-file-name buffer-file-name))))
7704 (regexp org-deadline-time-regexp)
7705 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7706 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7707 d2 diff pos pos1 category tags
7708 ee txt head face)
7709 (goto-char (point-min))
7710 (while (re-search-forward regexp nil t)
7711 (catch :skip
7712 (org-agenda-skip)
7713 (setq pos (1- (match-beginning 1))
7714 d2 (time-to-days
7715 (org-time-string-to-time (match-string 1)))
7716 diff (- d2 d1))
7717 ;; When to show a deadline in the calendar:
7718 ;; If the expiration is within wdays warning time.
7719 ;; Past-due deadlines are only shown on the current date
7720 (if (and (< diff wdays) todayp (not (= diff 0)))
7721 (save-excursion
7722 (setq category (org-get-category))
7723 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7724 (progn
7725 (goto-char (match-end 0))
7726 (setq pos1 (match-end 1))
7727 (setq tags (org-get-tags-at pos1))
7728 (setq head (buffer-substring-no-properties
7729 (point)
7730 (progn (skip-chars-forward "^\r\n")
7731 (point))))
7732 (if (string-match org-looking-at-done-regexp head)
7733 (setq txt nil)
7734 (setq txt (org-format-agenda-item
7735 (format "In %3d d.: " diff) head category tags))))
7736 (setq txt org-agenda-no-heading-message))
7737 (when txt
7738 (setq face (cond ((<= diff 0) 'org-warning)
7739 ((<= diff 5) 'org-upcoming-deadline)
7740 (t nil)))
7741 (org-add-props txt props
7742 'org-marker (org-agenda-new-marker pos)
7743 'org-hd-marker (org-agenda-new-marker pos1)
7744 'priority (+ (- 10 diff) (org-get-priority txt))
7745 'category category
7746 'face face 'undone-face face 'done-face 'org-done)
7747 (push txt ee))))))
7748 ee))
7750 (defun org-agenda-get-scheduled ()
7751 "Return the scheduled information for agenda display."
7752 (let* ((props (list 'face 'org-scheduled-previously
7753 'org-not-done-regexp org-not-done-regexp
7754 'undone-face 'org-scheduled-previously
7755 'done-face 'org-done
7756 'mouse-face 'highlight
7757 'keymap org-agenda-keymap
7758 'help-echo
7759 (format "mouse-2 or RET jump to org file %s"
7760 (abbreviate-file-name buffer-file-name))))
7761 (regexp org-scheduled-time-regexp)
7762 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7763 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7764 d2 diff pos pos1 category tags
7765 ee txt head)
7766 (goto-char (point-min))
7767 (while (re-search-forward regexp nil t)
7768 (catch :skip
7769 (org-agenda-skip)
7770 (setq pos (1- (match-beginning 1))
7771 d2 (time-to-days
7772 (org-time-string-to-time (match-string 1)))
7773 diff (- d2 d1))
7774 ;; When to show a scheduled item in the calendar:
7775 ;; If it is on or past the date.
7776 (if (and (< diff 0) todayp)
7777 (save-excursion
7778 (setq category (org-get-category))
7779 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7780 (progn
7781 (goto-char (match-end 0))
7782 (setq pos1 (match-end 1))
7783 (setq tags (org-get-tags-at))
7784 (setq head (buffer-substring-no-properties
7785 (point)
7786 (progn (skip-chars-forward "^\r\n") (point))))
7787 (if (string-match org-looking-at-done-regexp head)
7788 (setq txt nil)
7789 (setq txt (org-format-agenda-item
7790 (format "Sched.%2dx: " (- 1 diff)) head
7791 category tags))))
7792 (setq txt org-agenda-no-heading-message))
7793 (when txt
7794 (org-add-props txt props
7795 'org-marker (org-agenda-new-marker pos)
7796 'org-hd-marker (org-agenda-new-marker pos1)
7797 'priority (+ (- 5 diff) (org-get-priority txt))
7798 'category category)
7799 (push txt ee))))))
7800 ee))
7802 (defun org-agenda-get-blocks ()
7803 "Return the date-range information for agenda display."
7804 (let* ((props (list 'face nil
7805 'org-not-done-regexp org-not-done-regexp
7806 'mouse-face 'highlight
7807 'keymap org-agenda-keymap
7808 'help-echo
7809 (format "mouse-2 or RET jump to org file %s"
7810 (abbreviate-file-name buffer-file-name))))
7811 (regexp org-tr-regexp)
7812 (d0 (calendar-absolute-from-gregorian date))
7813 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
7814 (goto-char (point-min))
7815 (while (re-search-forward regexp nil t)
7816 (catch :skip
7817 (org-agenda-skip)
7818 (setq pos (point))
7819 (setq timestr (match-string 0)
7820 s1 (match-string 1)
7821 s2 (match-string 2)
7822 d1 (time-to-days (org-time-string-to-time s1))
7823 d2 (time-to-days (org-time-string-to-time s2)))
7824 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
7825 ;; Only allow days between the limits, because the normal
7826 ;; date stamps will catch the limits.
7827 (save-excursion
7828 (setq marker (org-agenda-new-marker (point)))
7829 (setq category (org-get-category))
7830 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7831 (progn
7832 (setq hdmarker (org-agenda-new-marker (match-end 1)))
7833 (goto-char (match-end 1))
7834 (setq tags (org-get-tags-at))
7835 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7836 (setq txt (org-format-agenda-item
7837 (format (if (= d1 d2) "" "(%d/%d): ")
7838 (1+ (- d0 d1)) (1+ (- d2 d1)))
7839 (match-string 1) category tags
7840 (if (= d0 d1) timestr))))
7841 (setq txt org-agenda-no-heading-message))
7842 (org-add-props txt props
7843 'org-marker marker 'org-hd-marker hdmarker
7844 'priority (org-get-priority txt) 'category category)
7845 (push txt ee)))
7846 (goto-char pos)))
7847 ; (outline-next-heading))) ;FIXME: correct to be removed??????
7848 ;; Sort the entries by expiration date.
7849 (nreverse ee)))
7851 (defconst org-plain-time-of-day-regexp
7852 (concat
7853 "\\(\\<[012]?[0-9]"
7854 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7855 "\\(--?"
7856 "\\(\\<[012]?[0-9]"
7857 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7858 "\\)?")
7859 "Regular expression to match a plain time or time range.
7860 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
7861 groups carry important information:
7862 0 the full match
7863 1 the first time, range or not
7864 8 the second time, if it is a range.")
7866 (defconst org-stamp-time-of-day-regexp
7867 (concat
7868 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
7869 "\\([012][0-9]:[0-5][0-9]\\)>"
7870 "\\(--?"
7871 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
7872 "Regular expression to match a timestamp time or time range.
7873 After a match, the following groups carry important information:
7874 0 the full match
7875 1 date plus weekday, for backreferencing to make sure both times on same day
7876 2 the first time, range or not
7877 4 the second time, if it is a range.")
7879 (defvar org-prefix-has-time nil
7880 "A flag, set by `org-compile-prefix-format'.
7881 The flag is set if the currently compiled format contains a `%t'.")
7882 (defvar org-prefix-has-tag nil
7883 "A flag, set by `org-compile-prefix-format'.
7884 The flag is set if the currently compiled format contains a `%T'.")
7886 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
7887 "Format TXT to be inserted into the agenda buffer.
7888 In particular, it adds the prefix and corresponding text properties. EXTRA
7889 must be a string and replaces the `%s' specifier in the prefix format.
7890 CATEGORY (string, symbol or nil) may be used to overrule the default
7891 category taken from local variable or file name. It will replace the `%c'
7892 specifier in the format. DOTIME, when non-nil, indicates that a
7893 time-of-day should be extracted from TXT for sorting of this entry, and for
7894 the `%t' specifier in the format. When DOTIME is a string, this string is
7895 searched for a time before TXT is. NOPREFIX is a flag and indicates that
7896 only the correctly processes TXT should be returned - this is used by
7897 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
7898 (save-match-data
7899 ;; Diary entries sometimes have extra whitespace at the beginning
7900 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
7901 (let* ((category (or category
7902 org-category
7903 (if buffer-file-name
7904 (file-name-sans-extension
7905 (file-name-nondirectory buffer-file-name))
7906 "")))
7907 (tag (if tags (nth (1- (length tags)) tags) ""))
7908 time ;; needed for the eval of the prefix format
7909 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
7910 (time-of-day (and dotime (org-get-time-of-day ts)))
7911 stamp plain s0 s1 s2 rtn)
7912 (when (and dotime time-of-day org-prefix-has-time)
7913 ;; Extract starting and ending time and move them to prefix
7914 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
7915 (setq plain (string-match org-plain-time-of-day-regexp ts)))
7916 (setq s0 (match-string 0 ts)
7917 s1 (match-string (if plain 1 2) ts)
7918 s2 (match-string (if plain 8 4) ts))
7920 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
7921 ;; them, we might want to remove them there to avoid duplication.
7922 ;; The user can turn this off with a variable.
7923 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
7924 (string-match (concat (regexp-quote s0) " *") txt)
7925 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
7926 (= (match-beginning 0) 0)
7928 (setq txt (replace-match "" nil nil txt))))
7929 ;; Normalize the time(s) to 24 hour
7930 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
7931 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
7933 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
7934 ;; Tags are in the string
7935 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
7936 (and org-agenda-remove-tags-when-in-prefix
7937 org-prefix-has-tag))
7938 (setq txt (replace-match "" t t txt))
7939 (setq txt (replace-match
7940 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
7941 (match-string 2 txt))
7942 t t txt))))
7944 ;; Create the final string
7945 (if noprefix
7946 (setq rtn txt)
7947 ;; Prepare the variables needed in the eval of the compiled format
7948 (setq time (cond (s2 (concat s1 "-" s2))
7949 (s1 (concat s1 "......"))
7950 (t ""))
7951 extra (or extra "")
7952 category (if (symbolp category) (symbol-name category) category))
7953 ;; Evaluate the compiled format
7954 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
7956 ;; And finally add the text properties
7957 (org-add-props rtn nil
7958 'category (downcase category) 'tags tags
7959 'prefix-length (- (length rtn) (length txt))
7960 'time-of-day time-of-day
7961 'dotime dotime))))
7963 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
7964 (catch 'exit
7965 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
7966 ((and todayp (member 'today (car org-agenda-time-grid))))
7967 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
7968 ((member 'weekly (car org-agenda-time-grid)))
7969 (t (throw 'exit list)))
7970 (let* ((have (delq nil (mapcar
7971 (lambda (x) (get-text-property 1 'time-of-day x))
7972 list)))
7973 (string (nth 1 org-agenda-time-grid))
7974 (gridtimes (nth 2 org-agenda-time-grid))
7975 (req (car org-agenda-time-grid))
7976 (remove (member 'remove-match req))
7977 new time)
7978 (if (and (member 'require-timed req) (not have))
7979 ;; don't show empty grid
7980 (throw 'exit list))
7981 (while (setq time (pop gridtimes))
7982 (unless (and remove (member time have))
7983 (setq time (int-to-string time))
7984 (push (org-format-agenda-item
7985 nil string "" nil
7986 (concat (substring time 0 -2) ":" (substring time -2)))
7987 new)
7988 (put-text-property
7989 1 (length (car new)) 'face 'org-time-grid (car new))))
7990 (if (member 'time-up org-agenda-sorting-strategy)
7991 (append new list)
7992 (append list new)))))
7994 (defun org-compile-prefix-format (format)
7995 "Compile the prefix format into a Lisp form that can be evaluated.
7996 The resulting form is returned and stored in the variable
7997 `org-prefix-format-compiled'."
7998 (setq org-prefix-has-time nil org-prefix-has-tag nil)
7999 (let ((start 0) varform vars var (s format)e c f opt)
8000 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
8001 s start)
8002 (setq var (cdr (assoc (match-string 4 s)
8003 '(("c" . category) ("t" . time) ("s" . extra)
8004 ("T" . tag))))
8005 c (or (match-string 3 s) "")
8006 opt (match-beginning 1)
8007 start (1+ (match-beginning 0)))
8008 (if (equal var 'time) (setq org-prefix-has-time t))
8009 (if (equal var 'tag) (setq org-prefix-has-tag t))
8010 (setq f (concat "%" (match-string 2 s) "s"))
8011 (if opt
8012 (setq varform
8013 `(if (equal "" ,var)
8015 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
8016 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
8017 (setq s (replace-match "%s" t nil s))
8018 (push varform vars))
8019 (setq vars (nreverse vars))
8020 (setq org-prefix-format-compiled `(format ,s ,@vars))))
8022 (defun org-get-time-of-day (s &optional string mod24)
8023 "Check string S for a time of day.
8024 If found, return it as a military time number between 0 and 2400.
8025 If not found, return nil.
8026 The optional STRING argument forces conversion into a 5 character wide string
8027 HH:MM."
8028 (save-match-data
8029 (when
8031 (string-match
8032 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
8033 (string-match
8034 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
8035 (let* ((h (string-to-number (match-string 1 s)))
8036 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
8037 (ampm (if (match-end 4) (downcase (match-string 4 s))))
8038 (am-p (equal ampm "am"))
8039 (h1 (cond ((not ampm) h)
8040 ((= h 12) (if am-p 0 12))
8041 (t (+ h (if am-p 0 12)))))
8042 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
8043 (mod h1 24) h1))
8044 (t0 (+ (* 100 h2) m))
8045 (t1 (concat (if (>= h1 24) "+" " ")
8046 (if (< t0 100) "0" "")
8047 (if (< t0 10) "0" "")
8048 (int-to-string t0))))
8049 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
8051 (defun org-finalize-agenda-entries (list)
8052 "Sort and concatenate the agenda items."
8053 (setq list (mapcar 'org-agenda-highlight-todo list))
8054 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
8056 (defun org-agenda-highlight-todo (x)
8057 (let (re pl)
8058 (if (eq x 'line)
8059 (save-excursion
8060 (beginning-of-line 1)
8061 (setq re (get-text-property (point) 'org-not-done-regexp))
8062 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
8063 (and (looking-at (concat "[ \t]*" re))
8064 (add-text-properties (match-beginning 0) (match-end 0)
8065 '(face org-todo))))
8066 (setq re (get-text-property 0 'org-not-done-regexp x)
8067 pl (get-text-property 0 'prefix-length x))
8068 (and re (equal (string-match re x pl) pl)
8069 (add-text-properties (match-beginning 0) (match-end 0)
8070 '(face org-todo) x))
8071 x)))
8073 (defsubst org-cmp-priority (a b)
8074 "Compare the priorities of string A and B."
8075 (let ((pa (or (get-text-property 1 'priority a) 0))
8076 (pb (or (get-text-property 1 'priority b) 0)))
8077 (cond ((> pa pb) +1)
8078 ((< pa pb) -1)
8079 (t nil))))
8081 (defsubst org-cmp-category (a b)
8082 "Compare the string values of categories of strings A and B."
8083 (let ((ca (or (get-text-property 1 'category a) ""))
8084 (cb (or (get-text-property 1 'category b) "")))
8085 (cond ((string-lessp ca cb) -1)
8086 ((string-lessp cb ca) +1)
8087 (t nil))))
8089 (defsubst org-cmp-time (a b)
8090 "Compare the time-of-day values of strings A and B."
8091 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
8092 (ta (or (get-text-property 1 'time-of-day a) def))
8093 (tb (or (get-text-property 1 'time-of-day b) def)))
8094 (cond ((< ta tb) -1)
8095 ((< tb ta) +1)
8096 (t nil))))
8098 (defun org-entries-lessp (a b)
8099 "Predicate for sorting agenda entries."
8100 ;; The following variables will be used when the form is evaluated.
8101 (let* ((time-up (org-cmp-time a b))
8102 (time-down (if time-up (- time-up) nil))
8103 (priority-up (org-cmp-priority a b))
8104 (priority-down (if priority-up (- priority-up) nil))
8105 (category-up (org-cmp-category a b))
8106 (category-down (if category-up (- category-up) nil))
8107 (category-keep (if category-up +1 nil)))
8108 (cdr (assoc
8109 (eval (cons 'or org-agenda-sorting-strategy))
8110 '((-1 . t) (1 . nil) (nil . nil))))))
8112 (defun org-agenda-show-priority ()
8113 "Show the priority of the current item.
8114 This priority is composed of the main priority given with the [#A] cookies,
8115 and by additional input from the age of a schedules or deadline entry."
8116 (interactive)
8117 (let* ((pri (get-text-property (point-at-bol) 'priority)))
8118 (message "Priority is %d" (if pri pri -1000))))
8120 (defun org-agenda-show-tags ()
8121 "Show the tags applicable to the current item."
8122 (interactive)
8123 (let* ((tags (get-text-property (point-at-bol) 'tags)))
8124 (if tags
8125 (message "Tags are :%s:"
8126 (org-no-properties (mapconcat 'identity tags ":")))
8127 (message "No tags associated with this line"))))
8129 (defun org-agenda-goto (&optional highlight)
8130 "Go to the Org-mode file which contains the item at point."
8131 (interactive)
8132 (let* ((marker (or (get-text-property (point) 'org-marker)
8133 (org-agenda-error)))
8134 (buffer (marker-buffer marker))
8135 (pos (marker-position marker)))
8136 (switch-to-buffer-other-window buffer)
8137 (widen)
8138 (goto-char pos)
8139 (when (org-mode-p)
8140 (org-show-hidden-entry)
8141 (save-excursion
8142 (and (outline-next-heading)
8143 (org-flag-heading nil)))) ; show the next heading
8144 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
8146 (defun org-agenda-switch-to ()
8147 "Go to the Org-mode file which contains the item at point."
8148 (interactive)
8149 (let* ((marker (or (get-text-property (point) 'org-marker)
8150 (org-agenda-error)))
8151 (buffer (marker-buffer marker))
8152 (pos (marker-position marker)))
8153 (switch-to-buffer buffer)
8154 (delete-other-windows)
8155 (widen)
8156 (goto-char pos)
8157 (when (org-mode-p)
8158 (org-show-hidden-entry)
8159 (save-excursion
8160 (and (outline-next-heading)
8161 (org-flag-heading nil)))))) ; show the next heading
8163 (defun org-agenda-goto-mouse (ev)
8164 "Go to the Org-mode file which contains the item at the mouse click."
8165 (interactive "e")
8166 (mouse-set-point ev)
8167 (org-agenda-goto))
8169 (defun org-agenda-show ()
8170 "Display the Org-mode file which contains the item at point."
8171 (interactive)
8172 (let ((win (selected-window)))
8173 (org-agenda-goto t)
8174 (select-window win)))
8176 (defun org-agenda-recenter (arg)
8177 "Display the Org-mode file which contains the item at point and recenter."
8178 (interactive "P")
8179 (let ((win (selected-window)))
8180 (org-agenda-goto t)
8181 (recenter arg)
8182 (select-window win)))
8184 (defun org-agenda-show-mouse (ev)
8185 "Display the Org-mode file which contains the item at the mouse click."
8186 (interactive "e")
8187 (mouse-set-point ev)
8188 (org-agenda-show))
8190 (defun org-agenda-check-no-diary ()
8191 "Check if the entry is a diary link and abort if yes."
8192 (if (get-text-property (point) 'org-agenda-diary-link)
8193 (org-agenda-error)))
8195 (defun org-agenda-error ()
8196 (error "Command not allowed in this line"))
8198 (defvar org-last-heading-marker (make-marker)
8199 "Marker pointing to the headline that last changed its TODO state
8200 by a remote command from the agenda.")
8202 (defun org-agenda-todo (&optional arg)
8203 "Cycle TODO state of line at point, also in Org-mode file.
8204 This changes the line at point, all other lines in the agenda referring to
8205 the same tree node, and the headline of the tree node in the Org-mode file."
8206 (interactive "P")
8207 (org-agenda-check-no-diary)
8208 (let* ((col (current-column))
8209 (marker (or (get-text-property (point) 'org-marker)
8210 (org-agenda-error)))
8211 (buffer (marker-buffer marker))
8212 (pos (marker-position marker))
8213 (hdmarker (get-text-property (point) 'org-hd-marker))
8214 (buffer-read-only nil)
8215 newhead)
8216 (with-current-buffer buffer
8217 (widen)
8218 (goto-char pos)
8219 (org-show-hidden-entry)
8220 (save-excursion
8221 (and (outline-next-heading)
8222 (org-flag-heading nil))) ; show the next heading
8223 (org-todo arg)
8224 (and (bolp) (forward-char 1))
8225 (setq newhead (org-get-heading))
8226 (save-excursion
8227 (org-back-to-heading)
8228 (move-marker org-last-heading-marker (point))))
8229 (beginning-of-line 1)
8230 (save-excursion
8231 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8232 (move-to-column col)))
8234 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8235 "Change all lines in the agenda buffer which match HDMARKER.
8236 The new content of the line will be NEWHEAD (as modified by
8237 `org-format-agenda-item'). HDMARKER is checked with
8238 `equal' against all `org-hd-marker' text properties in the file.
8239 If FIXFACE is non-nil, the face of each item is modified acording to
8240 the new TODO state."
8241 (let* (props m pl undone-face done-face finish new dotime cat tags)
8242 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
8243 (save-excursion
8244 (goto-char (point-max))
8245 (beginning-of-line 1)
8246 (while (not finish)
8247 (setq finish (bobp))
8248 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8249 (equal m hdmarker))
8250 (setq props (text-properties-at (point))
8251 dotime (get-text-property (point) 'dotime)
8252 cat (get-text-property (point) 'category)
8253 tags (get-text-property (point) 'tags)
8254 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
8255 pl (get-text-property (point) 'prefix-length)
8256 undone-face (get-text-property (point) 'undone-face)
8257 done-face (get-text-property (point) 'done-face))
8258 (move-to-column pl)
8259 (if (looking-at ".*")
8260 (progn
8261 (replace-match new t t)
8262 (beginning-of-line 1)
8263 (add-text-properties (point-at-bol) (point-at-eol) props)
8264 (when fixface
8265 (add-text-properties
8266 (point-at-bol) (point-at-eol)
8267 (list 'face
8268 (if org-last-todo-state-is-todo
8269 undone-face done-face)))
8270 (org-agenda-highlight-todo 'line))
8271 (beginning-of-line 1))
8272 (error "Line update did not work")))
8273 (beginning-of-line 0)))))
8275 (defun org-agenda-priority-up ()
8276 "Increase the priority of line at point, also in Org-mode file."
8277 (interactive)
8278 (org-agenda-priority 'up))
8280 (defun org-agenda-priority-down ()
8281 "Decrease the priority of line at point, also in Org-mode file."
8282 (interactive)
8283 (org-agenda-priority 'down))
8285 (defun org-agenda-priority (&optional force-direction)
8286 "Set the priority of line at point, also in Org-mode file.
8287 This changes the line at point, all other lines in the agenda referring to
8288 the same tree node, and the headline of the tree node in the Org-mode file."
8289 (interactive)
8290 (org-agenda-check-no-diary)
8291 (let* ((marker (or (get-text-property (point) 'org-marker)
8292 (org-agenda-error)))
8293 (buffer (marker-buffer marker))
8294 (pos (marker-position marker))
8295 (hdmarker (get-text-property (point) 'org-hd-marker))
8296 (buffer-read-only nil)
8297 newhead)
8298 (with-current-buffer buffer
8299 (widen)
8300 (goto-char pos)
8301 (org-show-hidden-entry)
8302 (save-excursion
8303 (and (outline-next-heading)
8304 (org-flag-heading nil))) ; show the next heading
8305 (funcall 'org-priority force-direction)
8306 (end-of-line 1)
8307 (setq newhead (org-get-heading)))
8308 (org-agenda-change-all-lines newhead hdmarker)
8309 (beginning-of-line 1)))
8311 (defun org-get-tags-at (&optional pos)
8312 "Get a list of all headline tags applicable at POS.
8313 POS defaults to point. If tags are inherited, the list contains
8314 the targets in the same sequence as the headlines appear, i.e.
8315 the tags of the current headline come last."
8316 (interactive)
8317 (let (tags)
8318 (save-excursion
8319 (goto-char (or pos (point)))
8320 (save-match-data
8321 (org-back-to-heading t)
8322 (condition-case nil
8323 (while t
8324 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
8325 (setq tags (append (org-split-string
8326 (org-match-string-no-properties 1) ":")
8327 tags)))
8328 (or org-use-tag-inheritance (error ""))
8329 (org-up-heading-all 1))
8330 (error nil))))
8331 (message "%s" tags)
8332 tags))
8334 (defun org-agenda-set-tags ()
8335 "Set tags for the current headline."
8336 (interactive)
8337 (org-agenda-check-no-diary)
8338 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
8339 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
8340 (org-agenda-error)))
8341 (buffer (marker-buffer hdmarker))
8342 (pos (marker-position hdmarker))
8343 (buffer-read-only nil)
8344 newhead)
8345 (with-current-buffer buffer
8346 (widen)
8347 (goto-char pos)
8348 (org-show-hidden-entry)
8349 (save-excursion
8350 (and (outline-next-heading)
8351 (org-flag-heading nil))) ; show the next heading
8352 (call-interactively 'org-set-tags)
8353 (end-of-line 1)
8354 (setq newhead (org-get-heading)))
8355 (org-agenda-change-all-lines newhead hdmarker)
8356 (beginning-of-line 1)))
8358 (defun org-agenda-date-later (arg &optional what)
8359 "Change the date of this item to one day later."
8360 (interactive "p")
8361 (org-agenda-check-type t 'agenda 'timeline)
8362 (org-agenda-check-no-diary)
8363 (let* ((marker (or (get-text-property (point) 'org-marker)
8364 (org-agenda-error)))
8365 (buffer (marker-buffer marker))
8366 (pos (marker-position marker)))
8367 (with-current-buffer buffer
8368 (widen)
8369 (goto-char pos)
8370 (if (not (org-at-timestamp-p))
8371 (error "Cannot find time stamp"))
8372 (org-timestamp-change arg (or what 'day))
8373 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8375 (defun org-agenda-date-earlier (arg &optional what)
8376 "Change the date of this item to one day earlier."
8377 (interactive "p")
8378 (org-agenda-date-later (- arg) what))
8380 (defun org-agenda-date-prompt (arg)
8381 "Change the date of this item. Date is prompted for, with default today.
8382 The prefix ARG is passed to the `org-time-stamp' command and can therefore
8383 be used to request time specification in the time stamp."
8384 (interactive "P")
8385 (org-agenda-check-type t 'agenda 'timeline)
8386 (org-agenda-check-no-diary)
8387 (let* ((marker (or (get-text-property (point) 'org-marker)
8388 (org-agenda-error)))
8389 (buffer (marker-buffer marker))
8390 (pos (marker-position marker)))
8391 (with-current-buffer buffer
8392 (widen)
8393 (goto-char pos)
8394 (if (not (org-at-timestamp-p))
8395 (error "Cannot find time stamp"))
8396 (org-time-stamp arg)
8397 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8399 (defun org-agenda-schedule (arg)
8400 "Schedule the item at point."
8401 (interactive "P")
8402 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8403 (org-agenda-check-no-diary)
8404 (let* ((marker (or (get-text-property (point) 'org-marker)
8405 (org-agenda-error)))
8406 (buffer (marker-buffer marker))
8407 (pos (marker-position marker))
8408 (org-insert-labeled-timestamps-at-point nil)
8410 (with-current-buffer buffer
8411 (widen)
8412 (goto-char pos)
8413 (setq ts (org-schedule))
8414 (message "Item scheduled for %s" ts))))
8416 (defun org-agenda-deadline (arg)
8417 "Schedule the item at point."
8418 (interactive "P")
8419 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8420 (org-agenda-check-no-diary)
8421 (let* ((marker (or (get-text-property (point) 'org-marker)
8422 (org-agenda-error)))
8423 (buffer (marker-buffer marker))
8424 (pos (marker-position marker))
8425 (org-insert-labeled-timestamps-at-point nil)
8427 (with-current-buffer buffer
8428 (widen)
8429 (goto-char pos)
8430 (setq ts (org-deadline))
8431 (message "Deadline for this item set to %s" ts))))
8433 (defun org-get-heading ()
8434 "Return the heading of the current entry, without the stars."
8435 (save-excursion
8436 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
8437 (if (and (re-search-backward "[\r\n]\\*" nil t)
8438 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
8439 (match-string 1)
8440 "")))
8442 (defun org-agenda-clock-in (&optional arg)
8443 "Start the clock on the currently selected item."
8444 (interactive "P")
8445 (org-agenda-check-no-diary)
8446 (let* ((marker (or (get-text-property (point) 'org-marker)
8447 (org-agenda-error)))
8448 (pos (marker-position marker)))
8449 (with-current-buffer (marker-buffer marker)
8450 (widen)
8451 (goto-char pos)
8452 (org-clock-in))))
8454 (defun org-agenda-diary-entry ()
8455 "Make a diary entry, like the `i' command from the calendar.
8456 All the standard commands work: block, weekly etc."
8457 (interactive)
8458 (org-agenda-check-type t 'agenda 'timeline)
8459 (require 'diary-lib)
8460 (let* ((char (progn
8461 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
8462 (read-char-exclusive)))
8463 (cmd (cdr (assoc char
8464 '((?d . insert-diary-entry)
8465 (?w . insert-weekly-diary-entry)
8466 (?m . insert-monthly-diary-entry)
8467 (?y . insert-yearly-diary-entry)
8468 (?a . insert-anniversary-diary-entry)
8469 (?b . insert-block-diary-entry)
8470 (?c . insert-cyclic-diary-entry)))))
8471 (oldf (symbol-function 'calendar-cursor-to-date))
8472 (point (point))
8473 (mark (or (mark t) (point))))
8474 (unless cmd
8475 (error "No command associated with <%c>" char))
8476 (unless (and (get-text-property point 'day)
8477 (or (not (equal ?b char))
8478 (get-text-property mark 'day)))
8479 (error "Don't know which date to use for diary entry"))
8480 ;; We implement this by hacking the `calendar-cursor-to-date' function
8481 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
8482 (let ((calendar-mark-ring
8483 (list (calendar-gregorian-from-absolute
8484 (or (get-text-property mark 'day)
8485 (get-text-property point 'day))))))
8486 (unwind-protect
8487 (progn
8488 (fset 'calendar-cursor-to-date
8489 (lambda (&optional error)
8490 (calendar-gregorian-from-absolute
8491 (get-text-property point 'day))))
8492 (call-interactively cmd))
8493 (fset 'calendar-cursor-to-date oldf)))))
8496 (defun org-agenda-execute-calendar-command (cmd)
8497 "Execute a calendar command from the agenda, with the date associated to
8498 the cursor position."
8499 (org-agenda-check-type t 'agenda 'timeline)
8500 (require 'diary-lib)
8501 (unless (get-text-property (point) 'day)
8502 (error "Don't know which date to use for calendar command"))
8503 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
8504 (point (point))
8505 (date (calendar-gregorian-from-absolute
8506 (get-text-property point 'day)))
8507 (displayed-day (extract-calendar-day date))
8508 (displayed-month (extract-calendar-month date))
8509 (displayed-year (extract-calendar-year date)))
8510 (unwind-protect
8511 (progn
8512 (fset 'calendar-cursor-to-date
8513 (lambda (&optional error)
8514 (calendar-gregorian-from-absolute
8515 (get-text-property point 'day))))
8516 (call-interactively cmd))
8517 (fset 'calendar-cursor-to-date oldf))))
8519 (defun org-agenda-phases-of-moon ()
8520 "Display the phases of the moon for the 3 months around the cursor date."
8521 (interactive)
8522 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
8524 (defun org-agenda-holidays ()
8525 "Display the holidays for the 3 months around the cursor date."
8526 (interactive)
8527 (org-agenda-execute-calendar-command 'list-calendar-holidays))
8529 (defun org-agenda-sunrise-sunset (arg)
8530 "Display sunrise and sunset for the cursor date.
8531 Latitude and longitude can be specified with the variables
8532 `calendar-latitude' and `calendar-longitude'. When called with prefix
8533 argument, latitude and longitude will be prompted for."
8534 (interactive "P")
8535 (let ((calendar-longitude (if arg nil calendar-longitude))
8536 (calendar-latitude (if arg nil calendar-latitude))
8537 (calendar-location-name
8538 (if arg "the given coordinates" calendar-location-name)))
8539 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
8541 (defun org-agenda-goto-calendar ()
8542 "Open the Emacs calendar with the date at the cursor."
8543 (interactive)
8544 (org-agenda-check-type t 'agenda 'timeline)
8545 (let* ((day (or (get-text-property (point) 'day)
8546 (error "Don't know which date to open in calendar")))
8547 (date (calendar-gregorian-from-absolute day))
8548 (calendar-move-hook nil)
8549 (view-calendar-holidays-initially nil)
8550 (view-diary-entries-initially nil))
8551 (calendar)
8552 (calendar-goto-date date)))
8554 (defun org-calendar-goto-agenda ()
8555 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
8556 This is a command that has to be installed in `calendar-mode-map'."
8557 (interactive)
8558 (org-agenda-list nil (calendar-absolute-from-gregorian
8559 (calendar-cursor-to-date))
8560 nil t))
8562 (defun org-agenda-convert-date ()
8563 (interactive)
8564 (org-agenda-check-type t 'agenda 'timeline)
8565 (let ((day (get-text-property (point) 'day))
8566 date s)
8567 (unless day
8568 (error "Don't know which date to convert"))
8569 (setq date (calendar-gregorian-from-absolute day))
8570 (setq s (concat
8571 "Gregorian: " (calendar-date-string date) "\n"
8572 "ISO: " (calendar-iso-date-string date) "\n"
8573 "Day of Yr: " (calendar-day-of-year-string date) "\n"
8574 "Julian: " (calendar-julian-date-string date) "\n"
8575 "Astron. JD: " (calendar-astro-date-string date)
8576 " (Julian date number at noon UTC)\n"
8577 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
8578 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
8579 "French: " (calendar-french-date-string date) "\n"
8580 "Mayan: " (calendar-mayan-date-string date) "\n"
8581 "Coptic: " (calendar-coptic-date-string date) "\n"
8582 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
8583 "Persian: " (calendar-persian-date-string date) "\n"
8584 "Chinese: " (calendar-chinese-date-string date) "\n"))
8585 (with-output-to-temp-buffer "*Dates*"
8586 (princ s))
8587 (if (fboundp 'fit-window-to-buffer)
8588 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
8590 ;;; Tags
8592 (defun org-scan-tags (action matcher &optional todo-only)
8593 "Scan headline tags with inheritance and produce output ACTION.
8594 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8595 evaluated, testing if a given set of tags qualifies a headline for
8596 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8597 are included in the output."
8598 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8599 (mapconcat 'regexp-quote
8600 (nreverse (cdr (reverse org-todo-keywords)))
8601 "\\|")
8602 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
8603 (props (list 'face nil
8604 'done-face 'org-done
8605 'undone-face nil
8606 'mouse-face 'highlight
8607 'keymap org-agenda-keymap
8608 'help-echo
8609 (format "mouse-2 or RET jump to org file %s"
8610 (abbreviate-file-name buffer-file-name))))
8611 lspos
8612 tags tags-list tags-alist (llast 0) rtn level category i txt
8613 todo marker)
8614 (save-excursion
8615 (goto-char (point-min))
8616 (when (eq action 'sparse-tree) (org-overview))
8617 (while (re-search-forward re nil t)
8618 (catch :skip
8619 (and (eq action 'agenda) (org-agenda-skip))
8620 (setq todo (if (match-end 1) (match-string 2))
8621 tags (if (match-end 4) (match-string 4)))
8622 (goto-char (setq lspos (1+ (match-beginning 0))))
8623 (setq level (funcall outline-level)
8624 category (org-get-category))
8625 (setq i llast llast level)
8626 ;; remove tag lists from same and sublevels
8627 (while (>= i level)
8628 (when (setq entry (assoc i tags-alist))
8629 (setq tags-alist (delete entry tags-alist)))
8630 (setq i (1- i)))
8631 ;; add the nex tags
8632 (when tags
8633 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8634 tags-alist
8635 (cons (cons level tags) tags-alist)))
8636 ;; compile tags for current headline
8637 (setq tags-list
8638 (if org-use-tag-inheritance
8639 (apply 'append (mapcar 'cdr tags-alist))
8640 tags))
8641 (when (and (or (not todo-only) todo)
8642 (eval matcher)
8643 (or (not org-agenda-skip-archived-trees)
8644 (not (member org-archive-tag tags-list))))
8645 ;; list this headline
8646 (if (eq action 'sparse-tree)
8647 (progn
8648 (org-show-hierarchy-above))
8649 (setq txt (org-format-agenda-item
8651 (concat
8652 (if org-tags-match-list-sublevels
8653 (make-string (1- level) ?.) "")
8654 (org-get-heading))
8655 category tags-list))
8656 (goto-char lspos)
8657 (setq marker (org-agenda-new-marker))
8658 (org-add-props txt props
8659 'org-marker marker 'org-hd-marker marker 'category category)
8660 (push txt rtn))
8661 ;; if we are to skip sublevels, jump to end of subtree
8662 (point)
8663 (or org-tags-match-list-sublevels (org-end-of-subtree))))))
8664 (when (and (eq action 'sparse-tree)
8665 (not org-sparse-tree-open-archived-trees))
8666 (org-hide-archived-subtrees (point-min) (point-max)))
8667 (nreverse rtn)))
8669 (defun org-tags-sparse-tree (&optional arg match)
8670 "Create a sparse tree according to tags search string MATCH.
8671 MATCH can contain positive and negative selection of tags, like
8672 \"+WORK+URGENT-WITHBOSS\"."
8673 (interactive "P")
8674 (let ((org-show-following-heading nil)
8675 (org-show-hierarchy-above nil))
8676 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
8678 (defun org-make-tags-matcher (match)
8679 "Create the TAGS matcher form for the tags-selecting string MATCH."
8680 (unless match
8681 ;; Get a new match request, with completion
8682 (setq org-last-tags-completion-table
8683 (or (org-get-buffer-tags)
8684 org-last-tags-completion-table))
8685 (setq match (completing-read
8686 "Tags: " 'org-tags-completion-function nil nil nil
8687 'org-tags-history)))
8688 ;; parse the string and create a lisp form
8689 (let ((match0 match) minus tag mm matcher orterms term orlist)
8690 (setq orterms (org-split-string match "|"))
8691 (while (setq term (pop orterms))
8692 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
8693 (setq minus (and (match-end 1)
8694 (equal (match-string 1 term) "-"))
8695 tag (match-string 2 term)
8696 term (substring term (match-end 0))
8697 mm (list 'member (downcase tag) 'tags-list)
8698 mm (if minus (list 'not mm) mm))
8699 (push mm matcher))
8700 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
8701 orlist)
8702 (setq matcher nil))
8703 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8704 ;; Return the string and lisp forms of the matcher
8705 (cons match0 matcher)))
8707 ;;;###autoload
8708 (defun org-tags-view (&optional todo-only match keep-modes)
8709 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
8710 The prefix arg TODO-ONLY limits the search to TODO entries."
8711 (interactive "P")
8712 (org-agenda-maybe-reset-markers 'force)
8713 (org-compile-prefix-format org-agenda-prefix-format)
8714 (let* ((org-agenda-keep-modes keep-modes)
8715 (org-tags-match-list-sublevels
8716 (if todo-only t org-tags-match-list-sublevels))
8717 (win (selected-window))
8718 (completion-ignore-case t)
8719 rtn rtnall files file pos matcher
8720 buffer)
8721 (setq matcher (org-make-tags-matcher match)
8722 match (car matcher) matcher (cdr matcher))
8723 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
8724 (progn
8725 (delete-other-windows)
8726 (switch-to-buffer-other-window
8727 (get-buffer-create org-agenda-buffer-name))))
8728 (setq buffer-read-only nil)
8729 (erase-buffer)
8730 (org-agenda-mode) (setq buffer-read-only nil)
8731 (org-set-local 'org-agenda-type 'tags)
8732 (org-set-local 'org-agenda-redo-command
8733 (list 'org-tags-view (list 'quote todo-only)
8734 (list 'if 'current-prefix-arg nil match) t))
8735 (setq files (org-agenda-files)
8736 rtnall nil)
8737 (org-prepare-agenda-buffers files)
8738 (while (setq file (pop files))
8739 (catch 'nextfile
8740 (org-check-agenda-file file)
8741 (setq buffer (if (file-exists-p file)
8742 (org-get-agenda-file-buffer file)
8743 (error "No such file %s" file)))
8744 (if (not buffer)
8745 ;; If file does not exist, merror message to agenda
8746 (setq rtn (list
8747 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8748 rtnall (append rtnall rtn))
8749 (with-current-buffer buffer
8750 (unless (org-mode-p)
8751 (error "Agenda file %s is not in `org-mode'" file))
8752 (setq org-category-table (org-get-category-table))
8753 (save-excursion
8754 (save-restriction
8755 (if org-respect-restriction
8756 (if (org-region-active-p)
8757 ;; Respect a region to restrict search
8758 (narrow-to-region (region-beginning) (region-end)))
8759 ;; If we work for the calendar or many files,
8760 ;; get rid of any restriction
8761 (widen))
8762 (setq rtn (org-scan-tags 'agenda matcher todo-only))
8763 (setq rtnall (append rtnall rtn))))))))
8764 (insert "Headlines with TAGS match: ")
8765 (add-text-properties (point-min) (1- (point))
8766 (list 'face 'org-level-3))
8767 (setq pos (point))
8768 (insert match "\n")
8769 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
8770 (setq pos (point))
8771 (insert "Press `C-u r' to search again with new search string\n")
8772 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
8773 (when rtnall
8774 (insert (mapconcat 'identity rtnall "\n")))
8775 (goto-char (point-min))
8776 (setq buffer-read-only t)
8777 (org-fit-agenda-window)
8778 (if (not org-select-agenda-window) (select-window win))))
8780 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8781 (defun org-set-tags (&optional arg just-align)
8782 "Set the tags for the current headline.
8783 With prefix ARG, realign all tags in headings in the current buffer."
8784 (interactive "P")
8785 (let* ((re (concat "^" outline-regexp))
8786 (col (current-column))
8787 (current (org-get-tags))
8788 table current-tags inherited-tags ; computed below when needed
8789 tags hd empty invis)
8790 (if arg
8791 (save-excursion
8792 (goto-char (point-min))
8793 (while (re-search-forward re nil t)
8794 (org-set-tags nil t))
8795 (message "All tags realigned to column %d" org-tags-column))
8796 (if just-align
8797 (setq tags current)
8798 (setq table (or org-tag-alist (org-get-buffer-tags))
8799 org-last-tags-completion-table table
8800 current-tags (org-split-string current ":")
8801 inherited-tags (nreverse
8802 (nthcdr (length current-tags)
8803 (nreverse (org-get-tags-at))))
8804 tags
8805 (if (or (eq t org-use-fast-tag-selection)
8806 (and org-use-fast-tag-selection
8807 (delq nil (mapcar 'cdr table))))
8808 (org-fast-tag-selection current-tags inherited-tags table)
8809 (let ((org-add-colon-after-tag-completion t))
8810 (completing-read "Tags: " 'org-tags-completion-function
8811 nil nil current 'org-tags-history))))
8812 (while (string-match "[-+&]+" tags)
8813 (setq tags (replace-match ":" t t tags))))
8815 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
8816 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8817 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8818 (if (equal current "")
8819 (progn
8820 (end-of-line 1)
8821 (or empty (insert-before-markers " ")))
8822 (beginning-of-line 1)
8823 (setq invis (org-invisible-p))
8824 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
8825 (setq hd (match-string 1))
8826 (delete-region (match-beginning 0) (match-end 0))
8827 (insert-before-markers (org-trim hd) (if empty "" " ")))
8828 (if (equal tags "")
8829 (save-excursion
8830 (beginning-of-line 1)
8831 (skip-chars-forward "*")
8832 (if (= (char-after) ?\ ) (forward-char 1))
8833 (and (re-search-forward "[ \t]+$" (point-at-eol) t)
8834 (replace-match "")))
8835 (move-to-column (max (current-column)
8836 (if (> org-tags-column 0)
8837 org-tags-column
8838 (- (- org-tags-column) (length tags))))
8840 (insert-before-markers tags)
8841 (if (and (not invis) (org-invisible-p))
8842 (outline-flag-region (point-at-bol) (point) nil)))
8843 (move-to-column col))))
8845 (defun org-tags-completion-function (string predicate &optional flag)
8846 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8847 (confirm (lambda (x) (stringp (car x)))))
8848 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8849 (setq s1 (match-string 1 string)
8850 s2 (match-string 2 string))
8851 (setq s1 "" s2 string))
8852 (cond
8853 ((eq flag nil)
8854 ;; try completion
8855 (setq rtn (try-completion s2 ctable confirm))
8856 (if (stringp rtn)
8857 (concat s1 s2 (substring rtn (length s2))
8858 (if (and org-add-colon-after-tag-completion
8859 (assoc rtn ctable))
8860 ":" "")))
8862 ((eq flag t)
8863 ;; all-completions
8864 (all-completions s2 ctable confirm)
8866 ((eq flag 'lambda)
8867 ;; exact match?
8868 (assoc s2 ctable)))
8871 (defun org-fast-tag-insert (kwd tags face &optional end)
8872 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
8873 (insert (format "%-12s" (concat kwd ":"))
8874 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
8875 (or end "")))
8877 (defun org-fast-tag-selection (current inherited table)
8878 "Fast tag selection with single keys.
8879 CURRENT is the current list of tags in the headline, INHERITED is the
8880 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
8881 possibly with grouping information.
8882 If the keys are nil, a-z are automatically assigned.
8883 Returns the new tags string, or nil to not change the current settings."
8884 (let* ((maxlen (apply 'max (mapcar
8885 (lambda (x)
8886 (if (stringp (car x)) (string-width (car x)) 0))
8887 table)))
8888 (fwidth (+ maxlen 3 1 3))
8889 (ncol (/ (- (window-width) 4) fwidth))
8890 (i-face 'org-done)
8891 (c-face 'org-tag)
8892 tg cnt e c char c1 c2 ntable tbl rtn
8893 groups ingroup)
8894 (save-window-excursion
8895 (delete-other-windows)
8896 (split-window-vertically)
8897 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
8898 (erase-buffer)
8899 (org-fast-tag-insert "Inherited" inherited i-face "\n")
8900 (org-fast-tag-insert "Current" current c-face "\n\n")
8901 (setq tbl table char ?a cnt 0)
8902 (while (setq e (pop tbl))
8903 (cond
8904 ((equal e '(:startgroup))
8905 (push '() groups) (setq ingroup t)
8906 (when (not (= cnt 0))
8907 (setq cnt 0)
8908 (insert "\n"))
8909 (insert "{ "))
8910 ((equal e '(:endgroup))
8911 (setq ingroup nil cnt 0)
8912 (insert "}\n"))
8914 (setq tg (car e) c2 nil)
8915 (if (cdr e)
8916 (setq c (cdr e))
8917 ;; automatically assign a character.
8918 (setq c1 (string-to-char
8919 (downcase (substring
8920 tg (if (= (string-to-char tg) ?@) 1 0)))))
8921 (if (or (rassoc c1 ntable) (rassoc c1 table))
8922 (while (or (rassoc char ntable) (rassoc char table))
8923 (setq char (1+ char)))
8924 (setq c2 c1))
8925 (setq c (or c2 char)))
8926 (if ingroup (push tg (car groups)))
8927 (setq tg (org-add-props tg nil 'face
8928 (cond
8929 ((member tg current) c-face)
8930 ((member tg inherited) i-face)
8931 (t nil))))
8932 (if (and (= cnt 0) (not ingroup)) (insert " "))
8933 (insert "[" c "] " tg (make-string
8934 (- fwidth 4 (length tg)) ?\ ))
8935 (push (cons tg c) ntable)
8936 (when (= (setq cnt (1+ cnt)) ncol)
8937 (insert "\n")
8938 (if ingroup (insert " "))
8939 (setq cnt 0)))))
8940 (setq ntable (nreverse ntable))
8941 (insert "\n")
8942 (goto-char (point-min))
8943 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
8944 (setq rtn
8945 (catch 'exit
8946 (while t
8947 (message "[key]:Toggle SPC: clear current RET accept%s"
8948 (if groups " [!] ignore goups" ""))
8949 (setq c (read-char-exclusive))
8950 (cond
8951 ((= c ?\r) (throw 'exit t))
8952 ((= c ?!)
8953 (setq groups nil)
8954 (goto-char (point-min))
8955 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
8956 ((or (= c ?\C-g)
8957 (and (= c ?q) (not (rassoc c ntable))))
8958 (setq quit-flag t))
8959 ((= c ?\ ) (setq current nil))
8960 ((setq e (rassoc c ntable) tg (car e))
8961 (if (member tg current)
8962 (setq current (delete tg current))
8963 (loop for g in groups do
8964 (if (member tg g)
8965 (mapcar (lambda (x)
8966 (setq current (delete x current)))
8967 g)))
8968 (setq current (cons tg current)))))
8969 ;; Create a sorted list
8970 (setq current
8971 (sort current
8972 (lambda (a b)
8973 (assoc b (cdr (memq (assoc a ntable) ntable))))))
8974 (goto-char (point-min))
8975 (beginning-of-line 2)
8976 (delete-region (point) (point-at-eol))
8977 (org-fast-tag-insert "Current" current c-face)
8978 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
8979 (setq tg (match-string 1))
8980 (add-text-properties (match-beginning 1) (match-end 1)
8981 (list 'face
8982 (cond
8983 ((member tg current) c-face)
8984 ((member tg inherited) i-face)
8985 (t nil)))))
8986 (goto-char (point-min)))))
8987 (if rtn
8988 (mapconcat 'identity current ":")
8989 nil))))
8991 (defun org-get-tags ()
8992 "Get the TAGS string in the current headline."
8993 (unless (org-on-heading-p)
8994 (error "Not on a heading"))
8995 (save-excursion
8996 (beginning-of-line 1)
8997 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
8998 (org-match-string-no-properties 1)
8999 "")))
9001 (defun org-get-buffer-tags ()
9002 "Get a table of all tags used in the buffer, for completion."
9003 (let (tags)
9004 (save-excursion
9005 (goto-char (point-min))
9006 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
9007 (mapc (lambda (x) (add-to-list 'tags x))
9008 (org-split-string (org-match-string-no-properties 1) ":"))))
9009 (mapcar 'list tags)))
9011 ;;; Link Stuff
9013 (defvar org-create-file-search-functions nil
9014 "List of functions to construct the right search string for a file link.
9015 These functions are called in turn with point at the location to
9016 which the link should point.
9018 A function in the hook should first test if it would like to
9019 handle this file type, for example by checking the major-mode or
9020 the file extension. If it decides not to handle this file, it
9021 should just return nil to give other functions a chance. If it
9022 does handle the file, it must return the search string to be used
9023 when following the link. The search string will be part of the
9024 file link, given after a double colon, and `org-open-at-point'
9025 will automatically search for it. If special measures must be
9026 taken to make the search successful, another function should be
9027 added to the companion hook `org-execute-file-search-functions',
9028 which see.
9030 A function in this hook may also use `setq' to set the variable
9031 `description' to provide a suggestion for the descriptive text to
9032 be used for this link when it gets inserted into an Org-mode
9033 buffer with \\[org-insert-link].")
9035 (defvar org-execute-file-search-functions nil
9036 "List of functions to execute a file search triggered by a link.
9038 Functions added to this hook must accept a single argument, the
9039 search string that was part of the file link, the part after the
9040 double colon. The function must first check if it would like to
9041 handle this search, for example by checking the major-mode or the
9042 file extension. If it decides not to handle this search, it
9043 should just return nil to give other functions a chance. If it
9044 does handle the search, it must return a non-nil value to keep
9045 other functions from trying.
9047 Each function can access the current prefix argument through the
9048 variable `current-prefix-argument'. Note that a single prefix is
9049 used to force opening a link in Emacs, so it may be good to only
9050 use a numeric or double prefix to guide the search function.
9052 In case this is needed, a function in this hook can also restore
9053 the window configuration before `org-open-at-point' was called using:
9055 (set-window-configuration org-window-config-before-follow-link)")
9057 (defun org-find-file-at-mouse (ev)
9058 "Open file link or URL at mouse."
9059 (interactive "e")
9060 (mouse-set-point ev)
9061 (org-open-at-point 'in-emacs))
9063 (defun org-open-at-mouse (ev)
9064 "Open file link or URL at mouse."
9065 (interactive "e")
9066 (mouse-set-point ev)
9067 (org-open-at-point))
9069 (defvar org-window-config-before-follow-link nil
9070 "The window configuration before following a link.
9071 This is saved in case the need arises to restore it.")
9073 (defun org-open-at-point (&optional in-emacs)
9074 "Open link at or after point.
9075 If there is no link at point, this function will search forward up to
9076 the end of the current subtree.
9077 Normally, files will be opened by an appropriate application. If the
9078 optional argument IN-EMACS is non-nil, Emacs will visit the file."
9079 (interactive "P")
9080 (setq org-window-config-before-follow-link (current-window-configuration))
9081 (org-remove-occur-highlights nil nil t)
9082 (if (org-at-timestamp-p)
9083 (org-agenda-list nil (time-to-days (org-time-string-to-time
9084 (substring (match-string 1) 0 10)))
9086 (let (type path link line search (pos (point)))
9087 (catch 'match
9088 (save-excursion
9089 (skip-chars-forward "^]\n\r")
9090 (when (and (re-search-backward "\\[\\[" nil t)
9091 (looking-at org-bracket-link-regexp)
9092 (<= (match-beginning 0) pos)
9093 (>= (match-end 0) pos))
9094 (setq link (org-link-unescape (org-match-string-no-properties 1)))
9095 (while (string-match " *\n *" link)
9096 (setq link (replace-match " " t t link)))
9097 (if (string-match org-link-re-with-space2 link)
9098 (setq type (match-string 1 link)
9099 path (match-string 2 link))
9100 (setq type "thisfile"
9101 path link))
9102 (throw 'match t)))
9104 (when (get-text-property (point) 'org-linked-text)
9105 (setq type "thisfile"
9106 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9107 (1+ (point)) (point))
9108 path (buffer-substring
9109 (previous-single-property-change pos 'org-linked-text)
9110 (next-single-property-change pos 'org-linked-text)))
9111 (throw 'match t))
9113 (save-excursion
9114 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
9115 (if (equal (char-before) ?<) (backward-char 1))
9116 (when (or (looking-at org-angle-link-re)
9117 (looking-at org-plain-link-re)
9118 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
9119 (re-search-forward org-plain-link-re (point-at-eol) t))
9120 (<= (match-beginning 0) pos)
9121 (>= (match-end 0) pos)))
9122 (setq type (match-string 1)
9123 path (match-string 2))
9124 (throw 'match t)))
9125 (save-excursion
9126 (skip-chars-backward "^ \t\n\r")
9127 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9128 (setq type "tags"
9129 path (match-string 1))
9130 (while (string-match ":" path)
9131 (setq path (replace-match "+" t t path)))
9132 (throw 'match t)))
9133 (save-excursion
9134 (skip-chars-backward "a-zA-Z_")
9135 (when (and (memq 'camel org-activate-links)
9136 (looking-at org-camel-regexp))
9137 (setq type "camel" path (match-string 0))
9138 (if (equal (char-before) ?*)
9139 (setq path (concat "*" path))))
9140 (throw 'match t)))
9141 (unless path
9142 (error "No link found"))
9143 ;; Remove any trailing spaces in path
9144 (if (string-match " +\\'" path)
9145 (setq path (replace-match "" t t path)))
9147 (cond
9149 ((member type '("http" "https" "ftp" "mailto" "news"))
9150 (browse-url (concat type ":" path)))
9152 ((string= type "tags")
9153 (org-tags-view in-emacs path))
9154 ((or (string= type "camel")
9155 (string= type "thisfile"))
9156 (org-mark-ring-push)
9157 (org-link-search
9158 path
9159 (cond ((equal in-emacs '(4)) 'occur)
9160 ((equal in-emacs '(16)) 'org-occur)
9161 (t nil))))
9163 ((string= type "file")
9164 (if (string-match "::\\([0-9]+\\)\\'" path)
9165 (setq line (string-to-number (match-string 1 path))
9166 path (substring path 0 (match-beginning 0)))
9167 (if (string-match "::\\(.+\\)\\'" path)
9168 (setq search (match-string 1 path)
9169 path (substring path 0 (match-beginning 0)))))
9170 (org-open-file path in-emacs line search))
9172 ((string= type "news")
9173 (org-follow-gnus-link path))
9175 ((string= type "bbdb")
9176 (org-follow-bbdb-link path))
9178 ((string= type "info")
9179 (org-follow-info-link path))
9181 ((string= type "gnus")
9182 (let (group article)
9183 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9184 (error "Error in Gnus link"))
9185 (setq group (match-string 1 path)
9186 article (match-string 3 path))
9187 (org-follow-gnus-link group article)))
9189 ((string= type "vm")
9190 (let (folder article)
9191 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9192 (error "Error in VM link"))
9193 (setq folder (match-string 1 path)
9194 article (match-string 3 path))
9195 ;; in-emacs is the prefix arg, will be interpreted as read-only
9196 (org-follow-vm-link folder article in-emacs)))
9198 ((string= type "wl")
9199 (let (folder article)
9200 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9201 (error "Error in Wanderlust link"))
9202 (setq folder (match-string 1 path)
9203 article (match-string 3 path))
9204 (org-follow-wl-link folder article)))
9206 ((string= type "mhe")
9207 (let (folder article)
9208 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9209 (error "Error in MHE link"))
9210 (setq folder (match-string 1 path)
9211 article (match-string 3 path))
9212 (org-follow-mhe-link folder article)))
9214 ((string= type "rmail")
9215 (let (folder article)
9216 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9217 (error "Error in RMAIL link"))
9218 (setq folder (match-string 1 path)
9219 article (match-string 3 path))
9220 (org-follow-rmail-link folder article)))
9222 ((string= type "shell")
9223 (let ((cmd path))
9224 (while (string-match "@{" cmd)
9225 (setq cmd (replace-match "<" t t cmd)))
9226 (while (string-match "@}" cmd)
9227 (setq cmd (replace-match ">" t t cmd)))
9228 (if (or (not org-confirm-shell-link-function)
9229 (funcall org-confirm-shell-link-function
9230 (format "Execute \"%s\" in shell? "
9231 (org-add-props cmd nil
9232 'face 'org-warning))))
9233 (progn
9234 (message "Executing %s" cmd)
9235 (shell-command cmd))
9236 (error "Abort"))))
9238 ((string= type "elisp")
9239 (let ((cmd path))
9240 (if (or (not org-confirm-elisp-link-function)
9241 (funcall org-confirm-elisp-link-function
9242 (format "Execute \"%s\" as elisp? "
9243 (org-add-props cmd nil
9244 'face 'org-warning))))
9245 (message "%s => %s" cmd (eval (read cmd)))
9246 (error "Abort"))))
9249 (browse-url-at-point))))))
9251 (defun org-link-search (s &optional type)
9252 "Search for a link search option.
9253 When S is a CamelCaseWord, search for a target, or for a sentence containing
9254 the words. If S is surrounded by forward slashes, it is interpreted as a
9255 regular expression. In org-mode files, this will create an `org-occur'
9256 sparse tree. In ordinary files, `occur' will be used to list matches.
9257 If the current buffer is in `dired-mode', grep will be used to search
9258 in all files."
9259 (let ((case-fold-search t)
9260 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9261 (pos (point))
9262 (pre "") (post "")
9263 words re0 re1 re2 re3 re4 re5 re2a reall camel)
9264 (cond
9265 ;; First check if there are any special
9266 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9267 ;; Now try the builtin stuff
9268 ((save-excursion
9269 (goto-char (point-min))
9270 (and
9271 (re-search-forward
9272 (concat "<<" (regexp-quote s0) ">>") nil t)
9273 (setq pos (match-beginning 0))))
9274 ;; There is an exact target for this
9275 (goto-char pos))
9276 ((string-match "^/\\(.*\\)/$" s)
9277 ;; A regular expression
9278 (cond
9279 ((org-mode-p)
9280 (org-occur (match-string 1 s)))
9281 ;;((eq major-mode 'dired-mode)
9282 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9283 (t (org-do-occur (match-string 1 s)))))
9284 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
9286 ;; A camel or a normal search string
9287 (when (equal (string-to-char s) ?*)
9288 ;; Anchor on headlines, post may include tags.
9289 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9290 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9291 s (substring s 1)))
9292 (remove-text-properties
9293 0 (length s)
9294 '(face nil mouse-face nil keymap nil fontified nil) s)
9295 ;; Make a series of regular expressions to find a match
9296 (setq words
9297 (if camel
9298 (org-camel-to-words s)
9299 (org-split-string s "[ \n\r\t]+"))
9300 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9301 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9302 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9303 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9304 re1 (concat pre re2 post)
9305 re3 (concat pre re4 post)
9306 re5 (concat pre ".*" re4)
9307 re2 (concat pre re2)
9308 re2a (concat pre re2a)
9309 re4 (concat pre re4)
9310 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9311 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9312 re5 "\\)"
9314 (cond
9315 ((eq type 'org-occur) (org-occur reall))
9316 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9317 (t (goto-char (point-min))
9318 (if (or (org-search-not-link re0 nil t)
9319 (org-search-not-link re1 nil t)
9320 (org-search-not-link re2 nil t)
9321 (org-search-not-link re2a nil t)
9322 (org-search-not-link re3 nil t)
9323 (org-search-not-link re4 nil t)
9324 (org-search-not-link re5 nil t)
9326 (goto-char (match-beginning 1))
9327 (goto-char pos)
9328 (error "No match")))))
9330 ;; Normal string-search
9331 (goto-char (point-min))
9332 (if (search-forward s nil t)
9333 (goto-char (match-beginning 0))
9334 (error "No match"))))
9335 (and (org-mode-p) (org-show-hierarchy-above))))
9337 (defun org-search-not-link (&rest args)
9338 "Execute `re-search-forward', but only accept matches that are not a link."
9339 (catch 'exit
9340 (let (p1)
9341 (while (apply 're-search-forward args)
9342 (setq p1 (point))
9343 (if (not (save-match-data
9344 (and (re-search-backward "\\[\\[" nil t)
9345 (looking-at org-bracket-link-regexp)
9346 (<= (match-beginning 0) p1)
9347 (>= (match-end 0) p1))))
9348 (progn (goto-char (match-end 0))
9349 (throw 'exit (point)))
9350 (goto-char (match-end 0)))))))
9352 (defun org-do-occur (regexp &optional cleanup)
9353 "Call the Emacs command `occur'.
9354 If CLEANUP is non-nil, remove the printout of the regular expression
9355 in the *Occur* buffer. This is useful if the regex is long and not useful
9356 to read."
9357 (occur regexp)
9358 (when cleanup
9359 (let ((cwin (selected-window)) win beg end)
9360 (when (setq win (get-buffer-window "*Occur*"))
9361 (select-window win))
9362 (goto-char (point-min))
9363 (when (re-search-forward "match[a-z]+" nil t)
9364 (setq beg (match-end 0))
9365 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9366 (setq end (1- (match-beginning 0)))))
9367 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9368 (goto-char (point-min))
9369 (select-window cwin))))
9371 (defvar org-mark-ring nil
9372 "Mark ring for positions before jumps in Org-mode.")
9373 (defvar org-mark-ring-last-goto nil
9374 "Last position in the mark ring used to go back.")
9375 ;; Fill and close the ring
9376 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9377 (loop for i from 1 to org-mark-ring-length do
9378 (push (make-marker) org-mark-ring))
9379 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9380 org-mark-ring)
9382 (defun org-mark-ring-push (&optional pos buffer)
9383 "Put the current position or POS into the mark ring and rotate it."
9384 (interactive)
9385 (setq pos (or pos (point)))
9386 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9387 (move-marker (car org-mark-ring)
9388 (or pos (point))
9389 (or buffer (current-buffer)))
9390 (message
9391 (substitute-command-keys
9392 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9394 (defun org-mark-ring-goto (&optional n)
9395 "Jump to the previous position in the mark ring.
9396 With prefix arg N, jump back that many stored positions. When
9397 called several times in succession, walk through the entire ring.
9398 Org-mode commands jumping to a different position in the current file,
9399 or to another Org-mode file, automatically push the old position
9400 onto the ring."
9401 (interactive "p")
9402 (let (p m)
9403 (if (eq last-command this-command)
9404 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9405 (setq p org-mark-ring))
9406 (setq org-mark-ring-last-goto p)
9407 (setq m (car p))
9408 (switch-to-buffer (marker-buffer m))
9409 (goto-char m)
9410 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
9412 (defun org-camel-to-words (s)
9413 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
9414 (let ((case-fold-search nil)
9415 words)
9416 (while (string-match "[a-z][A-Z]" s)
9417 (push (substring s 0 (1+ (match-beginning 0))) words)
9418 (setq s (substring s (1+ (match-beginning 0)))))
9419 (nreverse (cons s words))))
9421 (defun org-remove-angle-brackets (s)
9422 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9423 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9425 (defun org-add-angle-brackets (s)
9426 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9427 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9430 (defun org-follow-bbdb-link (name)
9431 "Follow a BBDB link to NAME."
9432 (require 'bbdb)
9433 (let ((inhibit-redisplay t)
9434 (bbdb-electric-p nil))
9435 (catch 'exit
9436 ;; Exact match on name
9437 (bbdb-name (concat "\\`" name "\\'") nil)
9438 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9439 ;; Exact match on name
9440 (bbdb-company (concat "\\`" name "\\'") nil)
9441 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9442 ;; Partial match on name
9443 (bbdb-name name nil)
9444 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9445 ;; Partial match on company
9446 (bbdb-company name nil)
9447 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9448 ;; General match including network address and notes
9449 (bbdb name nil)
9450 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9451 (delete-window (get-buffer-window "*BBDB*"))
9452 (error "No matching BBDB record")))))
9455 (defun org-follow-info-link (name)
9456 "Follow an info file & node link to NAME."
9457 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9458 (string-match "\\(.*\\)" name))
9459 (progn
9460 (require 'info)
9461 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9462 (Info-find-node (match-string 1 name) (match-string 2 name))
9463 (Info-find-node (match-string 1 name) "Top")))
9464 (message (concat "Could not open: " name))))
9466 (defun org-follow-gnus-link (&optional group article)
9467 "Follow a Gnus link to GROUP and ARTICLE."
9468 (require 'gnus)
9469 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9470 (if group (gnus-fetch-group group))
9471 (if article
9472 (or (gnus-summary-goto-article article nil 'force)
9473 (if (fboundp 'gnus-summary-insert-cached-articles)
9474 (progn
9475 (gnus-summary-insert-cached-articles)
9476 (gnus-summary-goto-article article nil 'force))
9477 (message "Message could not be found.")))))
9479 (defun org-follow-vm-link (&optional folder article readonly)
9480 "Follow a VM link to FOLDER and ARTICLE."
9481 (require 'vm)
9482 (setq article (org-add-angle-brackets article))
9483 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9484 ;; ange-ftp or efs or tramp access
9485 (let ((user (or (match-string 1 folder) (user-login-name)))
9486 (host (match-string 2 folder))
9487 (file (match-string 3 folder)))
9488 (cond
9489 ((featurep 'tramp)
9490 ;; use tramp to access the file
9491 (if (featurep 'xemacs)
9492 (setq folder (format "[%s@%s]%s" user host file))
9493 (setq folder (format "/%s@%s:%s" user host file))))
9495 ;; use ange-ftp or efs
9496 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9497 (setq folder (format "/%s@%s:%s" user host file))))))
9498 (when folder
9499 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9500 (sit-for 0.1)
9501 (when article
9502 (vm-select-folder-buffer)
9503 (widen)
9504 (let ((case-fold-search t))
9505 (goto-char (point-min))
9506 (if (not (re-search-forward
9507 (concat "^" "message-id: *" (regexp-quote article))))
9508 (error "Could not find the specified message in this folder"))
9509 (vm-isearch-update)
9510 (vm-isearch-narrow)
9511 (vm-beginning-of-message)
9512 (vm-summarize)))))
9514 (defun org-follow-wl-link (folder article)
9515 "Follow a Wanderlust link to FOLDER and ARTICLE."
9516 (setq article (org-add-angle-brackets article))
9517 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
9518 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
9519 (wl-summary-redisplay))
9521 (defun org-follow-rmail-link (folder article)
9522 "Follow an RMAIL link to FOLDER and ARTICLE."
9523 (setq article (org-add-angle-brackets article))
9524 (let (message-number)
9525 (save-excursion
9526 (save-window-excursion
9527 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9528 (setq message-number
9529 (save-restriction
9530 (widen)
9531 (goto-char (point-max))
9532 (if (re-search-backward
9533 (concat "^Message-ID:\\s-+" (regexp-quote
9534 (or article "")))
9535 nil t)
9536 (rmail-what-message))))))
9537 (if message-number
9538 (progn
9539 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9540 (rmail-show-message message-number)
9541 message-number)
9542 (error "Message not found"))))
9544 ;; mh-e integration based on planner-mode
9545 (defun org-mhe-get-message-real-folder ()
9546 "Return the name of the current message real folder, so if you use
9547 sequences, it will now work."
9548 (save-excursion
9549 (let* ((folder
9550 (if (equal major-mode 'mh-folder-mode)
9551 mh-current-folder
9552 ;; Refer to the show buffer
9553 mh-show-folder-buffer))
9554 (end-index
9555 (if (boundp 'mh-index-folder)
9556 (min (length mh-index-folder) (length folder))))
9558 ;; a simple test on mh-index-data does not work, because
9559 ;; mh-index-data is always nil in a show buffer.
9560 (if (and (boundp 'mh-index-folder)
9561 (string= mh-index-folder (substring folder 0 end-index)))
9562 (if (equal major-mode 'mh-show-mode)
9563 (save-window-excursion
9564 (when (buffer-live-p (get-buffer folder))
9565 (progn
9566 (pop-to-buffer folder)
9567 (org-mhe-get-message-folder-from-index)
9570 (org-mhe-get-message-folder-from-index)
9572 folder
9576 (defun org-mhe-get-message-folder-from-index ()
9577 "Returns the name of the message folder in a index folder buffer."
9578 (save-excursion
9579 (mh-index-previous-folder)
9580 (re-search-forward "^\\(+.*\\)$" nil t)
9581 (message (match-string 1))))
9583 (defun org-mhe-get-message-folder ()
9584 "Return the name of the current message folder. Be careful if you
9585 use sequences."
9586 (save-excursion
9587 (if (equal major-mode 'mh-folder-mode)
9588 mh-current-folder
9589 ;; Refer to the show buffer
9590 mh-show-folder-buffer)))
9592 (defun org-mhe-get-message-num ()
9593 "Return the number of the current message. Be careful if you
9594 use sequences."
9595 (save-excursion
9596 (if (equal major-mode 'mh-folder-mode)
9597 (mh-get-msg-num nil)
9598 ;; Refer to the show buffer
9599 (mh-show-buffer-message-number))))
9601 (defun org-mhe-get-header (header)
9602 "Return a header of the message in folder mode. This will create a
9603 show buffer for the corresponding message. If you have a more clever
9604 idea..."
9605 (let* ((folder (org-mhe-get-message-folder))
9606 (num (org-mhe-get-message-num))
9607 (buffer (get-buffer-create (concat "show-" folder)))
9608 (header-field))
9609 (with-current-buffer buffer
9610 (mh-display-msg num folder)
9611 (if (equal major-mode 'mh-folder-mode)
9612 (mh-header-display)
9613 (mh-show-header-display))
9614 (set-buffer buffer)
9615 (setq header-field (mh-get-header-field header))
9616 (if (equal major-mode 'mh-folder-mode)
9617 (mh-show)
9618 (mh-show-show))
9619 header-field)))
9621 (defun org-follow-mhe-link (folder article)
9622 "Follow an MHE link to FOLDER and ARTICLE.
9623 If ARTICLE is nil FOLDER is shown. If the configuration variable
9624 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9625 ARTICLE is searched in all folders. Indexed searches (swish++,
9626 namazu, and others supported by MH-E) will always search in all
9627 folders."
9628 (require 'mh-e)
9629 (require 'mh-search)
9630 (require 'mh-utils)
9631 (mh-find-path)
9632 (if (not article)
9633 (mh-visit-folder (mh-normalize-folder-name folder))
9634 (setq article (org-add-angle-brackets article))
9635 (mh-search-choose)
9636 (if (equal mh-searcher 'pick)
9637 (progn
9638 (mh-search folder (list "--message-id" article))
9639 (when (and org-mhe-search-all-folders
9640 (not (org-mhe-get-message-real-folder)))
9641 (kill-this-buffer)
9642 (mh-search "+" (list "--message-id" article))))
9643 (mh-search "+" article))
9644 (if (org-mhe-get-message-real-folder)
9645 (mh-show-msg 1)
9646 (kill-this-buffer)
9647 (error "Message not found"))))
9649 ;; BibTeX links
9651 ;; Use the custom search meachnism to construct and use search strings for
9652 ;; file links to BibTeX database entries.
9654 (defun org-create-file-search-in-bibtex ()
9655 "Create the search string and description for a BibTeX database entry."
9656 (when (eq major-mode 'bibtex-mode)
9657 ;; yes, we want to construct this search string.
9658 ;; Make a good description for this entry, using names, year and the title
9659 ;; Put it into the `description' variable which is dynamically scoped.
9660 (let ((bibtex-autokey-names 1)
9661 (bibtex-autokey-names-stretch 1)
9662 (bibtex-autokey-name-case-convert-function 'identity)
9663 (bibtex-autokey-name-separator " & ")
9664 (bibtex-autokey-additional-names " et al.")
9665 (bibtex-autokey-year-length 4)
9666 (bibtex-autokey-name-year-separator " ")
9667 (bibtex-autokey-titlewords 3)
9668 (bibtex-autokey-titleword-separator " ")
9669 (bibtex-autokey-titleword-case-convert-function 'identity)
9670 (bibtex-autokey-titleword-length 'infty)
9671 (bibtex-autokey-year-title-separator ": "))
9672 (setq description (bibtex-generate-autokey)))
9673 ;; Now parse the entry, get the key and return it.
9674 (save-excursion
9675 (bibtex-beginning-of-entry)
9676 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9678 (defun org-execute-file-search-in-bibtex (s)
9679 "Find the link search string S as a key for a database entry."
9680 (when (eq major-mode 'bibtex-mode)
9681 ;; Yes, we want to do the search in this file.
9682 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9683 (goto-char (point-min))
9684 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9685 (regexp-quote s) "[ \t\n]*,") nil t)
9686 (goto-char (match-beginning 0)))
9687 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9688 ;; Use double prefix to indicate that any web link should be browsed
9689 (let ((b (current-buffer)) (p (point)))
9690 ;; Restore the window configuration because we just use the web link
9691 (set-window-configuration org-window-config-before-follow-link)
9692 (save-excursion (set-buffer b) (goto-char p)
9693 (bibtex-url)))
9694 (recenter 0)) ; Move entry start to beginning of window
9695 ;; return t to indicate that the search is done.
9698 ;; Finally add the functions to the right hooks.
9699 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9700 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9702 ;; end of Bibtex link setup
9704 (defun org-upgrade-old-links (&optional query-description)
9705 "Transfer old <...> style links to new [[...]] style links.
9706 With arg query-description, ask at each match for a description text to use
9707 for this link."
9708 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
9709 (save-excursion
9710 (goto-char (point-min))
9711 (let ((re (concat "\\([^[]\\)<\\("
9712 "\\(" (mapconcat 'identity org-link-types "\\|")
9713 "\\):"
9714 "[^" org-non-link-chars "]+\\)>"))
9715 l1 l2 (cnt 0))
9716 (while (re-search-forward re nil t)
9717 (setq cnt (1+ cnt)
9718 l1 (org-match-string-no-properties 2)
9719 l2 (save-match-data (org-link-escape l1)))
9720 (when query-description (setq l1 (read-string "Desc: " l1)))
9721 (if (equal l1 l2)
9722 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
9723 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
9724 (message "%d matches have beed treated" cnt))))
9726 (defun org-open-file (path &optional in-emacs line search)
9727 "Open the file at PATH.
9728 First, this expands any special file name abbreviations. Then the
9729 configuration variable `org-file-apps' is checked if it contains an
9730 entry for this file type, and if yes, the corresponding command is launched.
9731 If no application is found, Emacs simply visits the file.
9732 With optional argument IN-EMACS, Emacs will visit the file.
9733 Optional LINE specifies a line to go to, optional SEARCH a string to
9734 search for. If LINE or SEARCH is given, the file will always be
9735 opened in Emacs.
9736 If the file does not exist, an error is thrown."
9737 (setq in-emacs (or in-emacs line search))
9738 (let* ((file (if (equal path "")
9739 buffer-file-name
9740 path))
9741 (apps (append org-file-apps (org-default-apps)))
9742 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9743 (dirp (if remp nil (file-directory-p file)))
9744 (dfile (downcase file))
9745 (old-buffer (current-buffer))
9746 (old-pos (point))
9747 (old-mode major-mode)
9748 ext cmd)
9749 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9750 (setq ext (match-string 1 dfile))
9751 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9752 (setq ext (match-string 1 dfile))))
9753 (if in-emacs
9754 (setq cmd 'emacs)
9755 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9756 (and dirp (cdr (assoc 'directory apps)))
9757 (cdr (assoc ext apps))
9758 (cdr (assoc t apps)))))
9759 (when (eq cmd 'mailcap)
9760 (require 'mailcap)
9761 (mailcap-parse-mailcaps)
9762 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9763 (command (mailcap-mime-info mime-type)))
9764 (if (stringp command)
9765 (setq cmd command)
9766 (setq cmd 'emacs))))
9767 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
9768 (not (file-exists-p file))
9769 (not org-open-non-existing-files))
9770 (error "No such file: %s" file))
9771 (cond
9772 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9773 ;; Normalize use of quote, this can vary.
9774 (if (string-match "['\"]%s['\"]" cmd)
9775 (setq cmd (replace-match "'%s'" t t cmd)))
9776 (setq cmd (format cmd file))
9777 (save-window-excursion
9778 (shell-command (concat cmd " &"))))
9779 ((or (stringp cmd)
9780 (eq cmd 'emacs))
9781 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
9782 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
9783 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9784 (if line (goto-line line)
9785 (if search (org-link-search search))))
9786 ((consp cmd)
9787 (eval cmd))
9788 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9789 (and (org-mode-p) (eq old-mode 'org-mode)
9790 (or (not (equal old-buffer (current-buffer)))
9791 (not (equal old-pos (point))))
9792 (org-mark-ring-push old-pos old-buffer))))
9794 (defun org-default-apps ()
9795 "Return the default applications for this operating system."
9796 (cond
9797 ((eq system-type 'darwin)
9798 org-file-apps-defaults-macosx)
9799 ((eq system-type 'windows-nt)
9800 org-file-apps-defaults-windowsnt)
9801 (t org-file-apps-defaults-gnu)))
9803 (defun org-expand-file-name (path)
9804 "Replace special path abbreviations and expand the file name."
9805 (expand-file-name path))
9807 (defun org-file-remote-p (file)
9808 "Test whether FILE specifies a location on a remote system.
9809 Return non-nil if the location is indeed remote.
9811 For example, the filename \"/user@host:/foo\" specifies a location
9812 on the system \"/user@host:\"."
9813 (cond ((fboundp 'file-remote-p)
9814 (file-remote-p file))
9815 ((fboundp 'tramp-handle-file-remote-p)
9816 (tramp-handle-file-remote-p file))
9817 ((and (boundp 'ange-ftp-name-format)
9818 (string-match ange-ftp-name-format file))
9820 (t nil)))
9822 (defvar org-insert-link-history nil
9823 "Minibuffer history for links inserted with `org-insert-link'.")
9825 (defvar org-stored-links nil
9826 "Contains the links stored with `org-store-link'.")
9828 ;;;###autoload
9829 (defun org-store-link (arg)
9830 "\\<org-mode-map>Store an org-link to the current location.
9831 This link can later be inserted into an org-buffer with
9832 \\[org-insert-link].
9833 For some link types, a prefix arg is interpreted:
9834 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9835 For file links, arg negates `org-context-in-file-links'."
9836 (interactive "P")
9837 (let (link cpltxt desc description search txt (pos (point)))
9838 (cond
9840 ((eq major-mode 'bbdb-mode)
9841 (setq cpltxt (concat
9842 "bbdb:"
9843 (or (bbdb-record-name (bbdb-current-record))
9844 (bbdb-record-company (bbdb-current-record))))
9845 link (org-make-link cpltxt)))
9847 ((eq major-mode 'Info-mode)
9848 (setq link (org-make-link "info:"
9849 (file-name-nondirectory Info-current-file)
9850 ":" Info-current-node))
9851 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9852 ":" Info-current-node)))
9854 ((eq major-mode 'calendar-mode)
9855 (let ((cd (calendar-cursor-to-date)))
9856 (setq link
9857 (format-time-string
9858 (car org-time-stamp-formats)
9859 (apply 'encode-time
9860 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9861 nil nil nil))))))
9863 ((or (eq major-mode 'vm-summary-mode)
9864 (eq major-mode 'vm-presentation-mode))
9865 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9866 (vm-follow-summary-cursor)
9867 (save-excursion
9868 (vm-select-folder-buffer)
9869 (let* ((message (car vm-message-pointer))
9870 (folder buffer-file-name)
9871 (subject (vm-su-subject message))
9872 (author (vm-su-full-name message))
9873 (message-id (vm-su-message-id message)))
9874 (setq message-id (org-remove-angle-brackets message-id))
9875 (setq folder (abbreviate-file-name folder))
9876 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9877 folder)
9878 (setq folder (replace-match "" t t folder)))
9879 (setq cpltxt (concat author " on: " subject))
9880 (setq link (org-make-link "vm:" folder "#" message-id)))))
9882 ((eq major-mode 'wl-summary-mode)
9883 (let* ((msgnum (wl-summary-message-number))
9884 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9885 msgnum 'message-id))
9886 (wl-message-entity (elmo-msgdb-overview-get-entity
9887 msgnum (wl-summary-buffer-msgdb)))
9888 (author (wl-summary-line-from)) ; FIXME: correct?
9889 (subject "???")) ; FIXME:
9890 (setq message-id (org-remove-angle-brackets message-id))
9891 (setq cpltxt (concat author " on: " subject))
9892 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9893 "#" message-id))))
9895 ((or (equal major-mode 'mh-folder-mode)
9896 (equal major-mode 'mh-show-mode))
9897 (let ((from-header (org-mhe-get-header "From:"))
9898 (to-header (org-mhe-get-header "To:"))
9899 (subject (org-mhe-get-header "Subject:")))
9900 (setq cpltxt (concat from-header " on: " subject))
9901 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9902 (org-remove-angle-brackets
9903 (org-mhe-get-header "Message-Id:"))))))
9905 ((eq major-mode 'rmail-mode)
9906 (save-excursion
9907 (save-restriction
9908 (rmail-narrow-to-non-pruned-header)
9909 (let ((folder buffer-file-name)
9910 (message-id (mail-fetch-field "message-id"))
9911 (author (mail-fetch-field "from"))
9912 (subject (mail-fetch-field "subject")))
9913 (setq message-id (org-remove-angle-brackets message-id))
9914 (setq cpltxt (concat author " on: " subject))
9915 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9917 ((eq major-mode 'gnus-group-mode)
9918 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9919 (gnus-group-group-name)) ; version
9920 ((fboundp 'gnus-group-name)
9921 (gnus-group-name))
9922 (t "???"))))
9923 (setq cpltxt (concat
9924 (if (org-xor arg org-usenet-links-prefer-google)
9925 "http://groups.google.com/groups?group="
9926 "gnus:")
9927 group)
9928 link (org-make-link cpltxt))))
9930 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9931 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9932 (gnus-summary-beginning-of-article)
9933 (let* ((group (car gnus-article-current))
9934 (article (cdr gnus-article-current))
9935 (header (gnus-summary-article-header article))
9936 (author (mail-header-from header))
9937 (message-id (mail-header-id header))
9938 (date (mail-header-date header))
9939 (subject (gnus-summary-subject-string)))
9940 (setq cpltxt (concat author " on: " subject))
9941 (if (org-xor arg org-usenet-links-prefer-google)
9942 (setq link
9943 (concat
9944 cpltxt "\n "
9945 (format "http://groups.google.com/groups?as_umsgid=%s"
9946 (org-fixup-message-id-for-http message-id))))
9947 (setq link (org-make-link "gnus:" group
9948 "#" (number-to-string article))))))
9950 ((eq major-mode 'w3-mode)
9951 (setq cpltxt (url-view-url t)
9952 link (org-make-link cpltxt)))
9953 ((eq major-mode 'w3m-mode)
9954 (setq cpltxt (or w3m-current-title w3m-current-url)
9955 link (org-make-link w3m-current-url)))
9957 ((setq search (run-hook-with-args-until-success
9958 'org-create-file-search-functions))
9959 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9960 "::" search))
9961 (setq cpltxt (or description link)))
9963 ((eq major-mode 'image-mode)
9964 (setq cpltxt (concat "file:"
9965 (abbreviate-file-name buffer-file-name))
9966 link (org-make-link cpltxt)))
9968 ((org-mode-p)
9969 ;; Just link to current headline
9970 (setq cpltxt (concat "file:"
9971 (abbreviate-file-name buffer-file-name)))
9972 ;; Add a context search string
9973 (when (org-xor org-context-in-file-links arg)
9974 ;; Check if we are on a target
9975 (if (save-excursion
9976 (skip-chars-forward "^>\n\r")
9977 (and (re-search-backward "<<" nil t)
9978 (looking-at "<<\\(.*?\\)>>")
9979 (<= (match-beginning 0) pos)
9980 (>= (match-end 0) pos)))
9981 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9982 (setq txt (cond
9983 ((org-on-heading-p) nil)
9984 ((org-region-active-p)
9985 (buffer-substring (region-beginning) (region-end)))
9986 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9987 (when (or (null txt) (string-match "\\S-" txt))
9988 (setq cpltxt
9989 (concat cpltxt "::"
9990 (if org-file-link-context-use-camel-case
9991 (org-make-org-heading-camel txt)
9992 (org-make-org-heading-search-string txt)))
9993 desc "NONE"))))
9994 (if (string-match "::\\'" cpltxt)
9995 (setq cpltxt (substring cpltxt 0 -2)))
9996 (setq link (org-make-link cpltxt)))
9998 (buffer-file-name
9999 ;; Just link to this file here.
10000 (setq cpltxt (concat "file:"
10001 (abbreviate-file-name buffer-file-name)))
10002 ;; Add a context string
10003 (when (org-xor org-context-in-file-links arg)
10004 (setq txt (if (org-region-active-p)
10005 (buffer-substring (region-beginning) (region-end))
10006 (buffer-substring (point-at-bol) (point-at-eol))))
10007 ;; Only use search option if there is some text.
10008 (when (string-match "\\S-" txt)
10009 (setq cpltxt
10010 (concat cpltxt "::"
10011 (if org-file-link-context-use-camel-case
10012 (org-make-org-heading-camel txt)
10013 (org-make-org-heading-search-string txt)))
10014 desc "NONE")))
10015 (setq link (org-make-link cpltxt)))
10017 ((interactive-p)
10018 (error "Cannot link to a buffer which is not visiting a file"))
10020 (t (setq link nil)))
10022 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10023 (setq link (or link cpltxt)
10024 desc (or desc cpltxt))
10025 (if (equal desc "NONE") (setq desc nil))
10027 (if (and (interactive-p) link)
10028 (progn
10029 (setq org-stored-links
10030 (cons (list cpltxt link desc) org-stored-links))
10031 (message "Stored: %s" (or cpltxt link)))
10032 (org-make-link-string link desc))))
10034 (defun org-make-org-heading-search-string (&optional string heading)
10035 "Make search string for STRING or current headline."
10036 (interactive)
10037 (let ((s (or string (org-get-heading))))
10038 (unless (and string (not heading))
10039 ;; We are using a headline, clean up garbage in there.
10040 (if (string-match org-todo-regexp s)
10041 (setq s (replace-match "" t t s)))
10042 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10043 (setq s (replace-match "" t t s)))
10044 (setq s (org-trim s))
10045 (if (string-match (concat "^\\(" org-quote-string "\\|"
10046 org-comment-string "\\)") s)
10047 (setq s (replace-match "" t t s)))
10048 (while (string-match org-ts-regexp s)
10049 (setq s (replace-match "" t t s))))
10050 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10051 (setq s (replace-match " " t t s)))
10052 (or string (setq s (concat "*" s))) ; Add * for headlines
10053 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10055 (defun org-make-org-heading-camel (&optional string heading)
10056 "Make a CamelCase string for STRING or the current headline."
10057 (interactive)
10058 (let ((s (or string (org-get-heading))))
10059 (unless (and string (not heading))
10060 ;; We are using a headline, clean up garbage in there.
10061 (if (string-match org-todo-regexp s)
10062 (setq s (replace-match "" t t s)))
10063 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10064 (setq s (replace-match "" t t s)))
10065 (setq s (org-trim s))
10066 (if (string-match (concat "^\\(" org-quote-string "\\|"
10067 org-comment-string "\\)") s)
10068 (setq s (replace-match "" t t s)))
10069 (while (string-match org-ts-regexp s)
10070 (setq s (replace-match "" t t s))))
10071 (while (string-match "[^a-zA-Z_ \t]+" s)
10072 (setq s (replace-match " " t t s)))
10073 (or string (setq s (concat "*" s))) ; Add * for headlines
10074 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
10076 (defun org-make-link (&rest strings)
10077 "Concatenate STRINGS, format resulting string with `org-link-format'."
10078 (format org-link-format (apply 'concat strings)))
10080 (defun org-make-link-string (link &optional description)
10081 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10082 (if (eq org-link-style 'plain)
10083 (if (equal description link)
10084 link
10085 (concat description "\n" link))
10086 (when (stringp description)
10087 ;; Remove brackets from the description, they are fatal.
10088 (while (string-match "\\[\\|\\]" description)
10089 (setq description (replace-match "" t t description))))
10090 (when (equal (org-link-escape link) description)
10091 ;; No description needed, it is identical
10092 (setq description nil))
10093 (when (and (not description)
10094 (not (equal link (org-link-escape link))))
10095 (setq description link))
10096 (concat "[[" (org-link-escape link) "]"
10097 (if description (concat "[" description "]") "")
10098 "]")))
10100 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
10101 "Association list of escapes for some characters problematic in links.")
10103 (defun org-link-escape (text)
10104 "Escape charaters in TEXT that are problematic for links."
10105 (when text
10106 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10107 org-link-escape-chars "\\|")))
10108 (while (string-match re text)
10109 (setq text
10110 (replace-match
10111 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10112 t t text)))
10113 text)))
10115 (defun org-link-unescape (text)
10116 "Reverse the action of `org-link-escape'."
10117 (when text
10118 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10119 org-link-escape-chars "\\|")))
10120 (while (string-match re text)
10121 (setq text
10122 (replace-match
10123 (car (rassoc (match-string 0 text) org-link-escape-chars))
10124 t t text)))
10125 text)))
10127 (defun org-xor (a b)
10128 "Exclusive or."
10129 (if a (not b) b))
10131 (defun org-get-header (header)
10132 "Find a header field in the current buffer."
10133 (save-excursion
10134 (goto-char (point-min))
10135 (let ((case-fold-search t) s)
10136 (cond
10137 ((eq header 'from)
10138 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10139 (setq s (match-string 1)))
10140 (while (string-match "\"" s)
10141 (setq s (replace-match "" t t s)))
10142 (if (string-match "[<(].*" s)
10143 (setq s (replace-match "" t t s))))
10144 ((eq header 'message-id)
10145 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10146 (setq s (match-string 1))))
10147 ((eq header 'subject)
10148 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10149 (setq s (match-string 1)))))
10150 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10151 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10152 s)))
10155 (defun org-fixup-message-id-for-http (s)
10156 "Replace special characters in a message id, so it can be used in an http query."
10157 (while (string-match "<" s)
10158 (setq s (replace-match "%3C" t t s)))
10159 (while (string-match ">" s)
10160 (setq s (replace-match "%3E" t t s)))
10161 (while (string-match "@" s)
10162 (setq s (replace-match "%40" t t s)))
10165 (defun org-insert-link (&optional complete-file)
10166 "Insert a link. At the prompt, enter the link.
10168 Completion can be used to select a link previously stored with
10169 `org-store-link'. When the empty string is entered (i.e. if you just
10170 press RET at the prompt), the link defaults to the most recently
10171 stored link. As SPC triggers completion in the minibuffer, you need to
10172 use M-SPC or C-q SPC to force the insertion of a space character.
10174 You will also be prompted for a description, and if one is given, it will
10175 be displayed in the buffer instead of the link.
10177 If there is already a link at point, this command will allow you to edit link
10178 and description parts.
10180 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10181 selected using completion. The path to the file will be relative to
10182 the current directory if the file is in the current directory or a
10183 subdirectory. Otherwise, the link will be the absolute path as
10184 completed in the minibuffer (i.e. normally ~/path/to/file).
10186 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10187 is in the current directory or below.
10188 With three \\[universal-argument] prefixes, negate the meaning of
10189 `org-keep-stored-link-after-insertion'."
10190 (interactive "P")
10191 (let (link desc entry remove file (pos (point)))
10192 (cond
10193 ((save-excursion
10194 (skip-chars-forward "^]\n\r")
10195 (and (re-search-backward "\\[\\[" nil t)
10196 (looking-at org-bracket-link-regexp)
10197 (<= (match-beginning 0) pos)
10198 (>= (match-end 0) pos)))
10199 ;; We do have a link at point, and we are going to edit it.
10200 (setq remove (list (match-beginning 0) (match-end 0)))
10201 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10202 (setq link (read-string "Link: "
10203 (org-link-unescape
10204 (org-match-string-no-properties 1)))))
10205 ((equal complete-file '(4))
10206 ;; Completing read for file names.
10207 (setq file (read-file-name "File: "))
10208 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10209 (pwd1 (file-name-as-directory (abbreviate-file-name
10210 (expand-file-name ".")))))
10211 (cond
10212 ((equal complete-file '(16))
10213 (setq link (org-make-link
10214 "file:"
10215 (abbreviate-file-name (expand-file-name file)))))
10216 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10217 (setq link (org-make-link "file:" (match-string 1 file))))
10218 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10219 (expand-file-name file))
10220 (setq link (org-make-link
10221 "file:" (match-string 1 (expand-file-name file)))))
10222 (t (setq link (org-make-link "file:" file))))))
10224 ;; Read link, with completion for stored links.
10225 (setq link (org-completing-read
10226 "Link: " org-stored-links nil nil nil
10227 org-insert-link-history
10228 (or (car (car org-stored-links)))))
10229 (setq entry (assoc link org-stored-links))
10230 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10231 (not org-keep-stored-link-after-insertion))
10232 (setq org-stored-links (delq (assoc link org-stored-links)
10233 org-stored-links)))
10234 (setq link (if entry (nth 1 entry) link)
10235 desc (or desc (nth 2 entry)))))
10237 (if (string-match org-plain-link-re link)
10238 ;; URL-like link, normalize the use of angular brackets.
10239 (setq link (org-make-link (org-remove-angle-brackets link))))
10241 ;; Check if we are linking to the current file with a search option
10242 ;; If yes, simplify the link by using only the search option.
10243 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
10244 (let* ((path (match-string 1 link))
10245 (case-fold-search nil)
10246 (search (match-string 2 link)))
10247 (save-match-data
10248 (if (equal (file-truename buffer-file-name) (file-truename path))
10249 ;; We are linking to this same file, with a search option
10250 (setq link search)))))
10252 ;; Check if we can/should use a relative path. If yes, simplify the link
10253 (when (string-match "\\<file:\\(.*\\)" link)
10254 (let* ((path (match-string 1 link))
10255 (case-fold-search nil))
10256 (cond
10257 ((eq org-link-file-path-type 'absolute)
10258 (setq path (abbreviate-file-name (expand-file-name path))))
10259 ((eq org-link-file-path-type 'noabbrev)
10260 (setq path (expand-file-name path)))
10261 ((eq org-link-file-path-type 'relative)
10262 (setq path (file-relative-name path)))
10264 (save-match-data
10265 (if (string-match (concat "^" (regexp-quote
10266 (file-name-as-directory
10267 (expand-file-name "."))))
10268 (expand-file-name path))
10269 ;; We are linking a file with relative path name.
10270 (setq path (substring (expand-file-name path)
10271 (match-end 0)))))))
10272 (setq link (concat "file:" path))))
10274 (setq desc (read-string "Description: " desc))
10275 (unless (string-match "\\S-" desc) (setq desc nil))
10276 (if remove (apply 'delete-region remove))
10277 (insert (org-make-link-string link desc))))
10279 (defun org-completing-read (&rest args)
10280 (let ((minibuffer-local-completion-map
10281 (copy-keymap minibuffer-local-completion-map)))
10282 (define-key minibuffer-local-completion-map " " 'self-insert-command)
10283 (apply 'completing-read args)))
10285 ;;; Hooks for remember.el
10287 (defvar org-finish-function nil)
10289 ;;;###autoload
10290 (defun org-remember-annotation ()
10291 "Return a link to the current location as an annotation for remember.el.
10292 If you are using Org-mode files as target for data storage with
10293 remember.el, then the annotations should include a link compatible with the
10294 conventions in Org-mode. This function returns such a link."
10295 (org-store-link nil))
10297 (defconst org-remember-help
10298 "Select a destination location for the note.
10299 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10300 RET at beg-of-buf -> Append to file as level 2 headline
10301 RET on headline -> Store as sublevel entry to current headline
10302 <left>/<right> -> before/after current headline, same headings level")
10304 ;;;###autoload
10305 (defun org-remember-apply-template ()
10306 "Initialize *remember* buffer with template, invoke `org-mode'.
10307 This function should be placed into `remember-mode-hook' and in fact requires
10308 to be run from that hook to fucntion properly."
10309 (if org-remember-templates
10311 (let* ((entry (if (= (length org-remember-templates) 1)
10312 (cdar org-remember-templates)
10313 (message "Select template: %s"
10314 (mapconcat
10315 (lambda (x) (char-to-string (car x)))
10316 org-remember-templates " "))
10317 (cdr (assoc (read-char-exclusive) org-remember-templates))))
10318 (tpl (car entry))
10319 (file (if (consp (cdr entry)) (nth 1 entry)))
10320 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10321 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10322 (v-u (concat "[" (substring v-t 1 -1) "]"))
10323 (v-U (concat "[" (substring v-T 1 -1) "]"))
10324 (v-a annotation) ; defined in `remember-mode'
10325 (v-i initial) ; defined in `remember-mode'
10326 (v-n user-full-name)
10328 (unless tpl (setq tpl "") (message "No template") (ding))
10329 (insert tpl) (goto-char (point-min))
10330 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
10331 (when (and initial (equal (match-string 0) "%i"))
10332 (save-match-data
10333 (let* ((lead (buffer-substring
10334 (point-at-bol) (match-beginning 0))))
10335 (setq v-i (mapconcat 'identity
10336 (org-split-string initial "\n")
10337 (concat "\n" lead))))))
10338 (replace-match
10339 (or (eval (intern (concat "v-" (match-string 1)))) "")
10340 t t))
10341 (let ((org-startup-folded nil)
10342 (org-startup-with-deadline-check nil))
10343 (org-mode))
10344 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10345 (org-set-local 'org-default-notes-file file))
10346 (goto-char (point-min))
10347 (if (re-search-forward "%\\?" nil t) (replace-match "")))
10348 (let ((org-startup-folded nil)
10349 (org-startup-with-deadline-check nil))
10350 (org-mode)))
10351 (org-set-local 'org-finish-function 'remember-buffer))
10353 ;;;###autoload
10354 (defun org-remember-handler ()
10355 "Store stuff from remember.el into an org file.
10356 First prompts for an org file. If the user just presses return, the value
10357 of `org-default-notes-file' is used.
10358 Then the command offers the headings tree of the selected file in order to
10359 file the text at a specific location.
10360 You can either immediately press RET to get the note appended to the
10361 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10362 find a better place. Then press RET or <left> or <right> in insert the note.
10364 Key Cursor position Note gets inserted
10365 -----------------------------------------------------------------------------
10366 RET buffer-start as level 2 heading at end of file
10367 RET on headline as sublevel of the heading at cursor
10368 RET no heading at cursor position, level taken from context.
10369 Or use prefix arg to specify level manually.
10370 <left> on headline as same level, before current heading
10371 <right> on headline as same level, after current heading
10373 So the fastest way to store the note is to press RET RET to append it to
10374 the default file. This way your current train of thought is not
10375 interrupted, in accordance with the principles of remember.el. But with
10376 little extra effort, you can push it directly to the correct location.
10378 Before being stored away, the function ensures that the text has a
10379 headline, i.e. a first line that starts with a \"*\". If not, a headline
10380 is constructed from the current date and some additional data.
10382 If the variable `org-adapt-indentation' is non-nil, the entire text is
10383 also indented so that it starts in the same column as the headline
10384 \(i.e. after the stars).
10386 See also the variable `org-reverse-note-order'."
10387 (catch 'quit
10388 (let* ((txt (buffer-substring (point-min) (point-max)))
10389 (fastp current-prefix-arg)
10390 (file (if fastp org-default-notes-file (org-get-org-file)))
10391 (visiting (find-buffer-visiting file))
10392 (org-startup-with-deadline-check nil)
10393 (org-startup-folded nil)
10394 (org-startup-align-all-tables nil)
10395 spos level indent reversed)
10396 ;; Modify text so that it becomes a nice subtree which can be inserted
10397 ;; into an org tree.
10398 (let* ((lines (split-string txt "\n"))
10399 first)
10400 ;; remove empty lines at the beginning
10401 (while (and lines (string-match "^[ \t]*\n" (car lines)))
10402 (setq lines (cdr lines)))
10403 (setq first (car lines) lines (cdr lines))
10404 (if (string-match "^\\*+" first)
10405 ;; Is already a headline
10406 (setq indent nil)
10407 ;; We need to add a headline: Use time and first buffer line
10408 (setq lines (cons first lines)
10409 first (concat "* " (current-time-string)
10410 " (" (remember-buffer-desc) ")")
10411 indent " "))
10412 (if (and org-adapt-indentation indent)
10413 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10414 (setq txt (concat first "\n"
10415 (mapconcat 'identity lines "\n"))))
10416 ;; Find the file
10417 (if (not visiting)
10418 (find-file-noselect file))
10419 (with-current-buffer (get-file-buffer file)
10420 (save-excursion (and (goto-char (point-min))
10421 (not (re-search-forward "^\\* " nil t))
10422 (insert "\n* Notes\n")))
10423 (setq reversed (org-notes-order-reversed-p))
10424 (save-excursion
10425 (save-restriction
10426 (widen)
10427 ;; Ask the User for a location
10428 (setq spos (if fastp 1 (org-get-location
10429 (current-buffer)
10430 org-remember-help)))
10431 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10432 ; not handle this note
10433 (goto-char spos)
10434 (cond ((bobp)
10435 ;; Put it at the start or end, as level 2
10436 (save-restriction
10437 (widen)
10438 (goto-char (if reversed (point-min) (point-max)))
10439 (if (not (bolp)) (newline))
10440 (org-paste-subtree 2 txt)))
10441 ((and (org-on-heading-p nil) (not current-prefix-arg))
10442 ;; Put it below this entry, at the beg/end of the subtree
10443 (org-back-to-heading)
10444 (setq level (funcall outline-level))
10445 (if reversed
10446 (outline-end-of-heading)
10447 (outline-end-of-subtree))
10448 (if (not (bolp)) (newline))
10449 (beginning-of-line 1)
10450 (org-paste-subtree (1+ level) txt))
10452 ;; Put it right there, with automatic level determined by
10453 ;; org-paste-subtree or from prefix arg
10454 (org-paste-subtree current-prefix-arg txt)))
10455 (when remember-save-after-remembering
10456 (save-buffer)
10457 (if (not visiting) (kill-buffer (current-buffer)))))))))
10458 t) ;; return t to indicate that we took care of this note.
10460 (defun org-get-org-file ()
10461 "Read a filename, with default directory `org-directory'."
10462 (let ((default (or org-default-notes-file remember-data-file)))
10463 (read-file-name (format "File name [%s]: " default)
10464 (file-name-as-directory org-directory)
10465 default)))
10467 (defun org-notes-order-reversed-p ()
10468 "Check if the current file should receive notes in reversed order."
10469 (cond
10470 ((not org-reverse-note-order) nil)
10471 ((eq t org-reverse-note-order) t)
10472 ((not (listp org-reverse-note-order)) nil)
10473 (t (catch 'exit
10474 (let ((all org-reverse-note-order)
10475 entry)
10476 (while (setq entry (pop all))
10477 (if (string-match (car entry) buffer-file-name)
10478 (throw 'exit (cdr entry))))
10479 nil)))))
10481 ;;; Tables
10483 ;; Watch out: Here we are talking about two different kind of tables.
10484 ;; Most of the code is for the tables created with the Org-mode table editor.
10485 ;; Sometimes, we talk about tables created and edited with the table.el
10486 ;; Emacs package. We call the former org-type tables, and the latter
10487 ;; table.el-type tables.
10490 (defun org-before-change-function (beg end)
10491 "Every change indicates that a table might need an update."
10492 (setq org-table-may-need-update t))
10494 (defconst org-table-line-regexp "^[ \t]*|"
10495 "Detects an org-type table line.")
10496 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
10497 "Detects an org-type table line.")
10498 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
10499 "Detects a table line marked for automatic recalculation.")
10500 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
10501 "Detects a table line marked for automatic recalculation.")
10502 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
10503 "Detects a table line marked for automatic recalculation.")
10504 (defconst org-table-hline-regexp "^[ \t]*|-"
10505 "Detects an org-type table hline.")
10506 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
10507 "Detects a table-type table hline.")
10508 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
10509 "Detects an org-type or table-type table.")
10510 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
10511 "Searching from within a table (any type) this finds the first line
10512 outside the table.")
10513 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
10514 "Searching from within a table (any type) this finds the first line
10515 outside the table.")
10517 (defun org-table-create-with-table.el ()
10518 "Use the table.el package to insert a new table.
10519 If there is already a table at point, convert between Org-mode tables
10520 and table.el tables."
10521 (interactive)
10522 (require 'table)
10523 (cond
10524 ((org-at-table.el-p)
10525 (if (y-or-n-p "Convert table to Org-mode table? ")
10526 (org-table-convert)))
10527 ((org-at-table-p)
10528 (if (y-or-n-p "Convert table to table.el table? ")
10529 (org-table-convert)))
10530 (t (call-interactively 'table-insert))))
10532 (defun org-table-create-or-convert-from-region (arg)
10533 "Convert region to table, or create an empty table.
10534 If there is an active region, convert it to a table. If there is no such
10535 region, create an empty table."
10536 (interactive "P")
10537 (if (org-region-active-p)
10538 (org-table-convert-region (region-beginning) (region-end) arg)
10539 (org-table-create arg)))
10541 (defun org-table-create (&optional size)
10542 "Query for a size and insert a table skeleton.
10543 SIZE is a string Columns x Rows like for example \"3x2\"."
10544 (interactive "P")
10545 (unless size
10546 (setq size (read-string
10547 (concat "Table size Columns x Rows [e.g. "
10548 org-table-default-size "]: ")
10549 "" nil org-table-default-size)))
10551 (let* ((pos (point))
10552 (indent (make-string (current-column) ?\ ))
10553 (split (org-split-string size " *x *"))
10554 (rows (string-to-number (nth 1 split)))
10555 (columns (string-to-number (car split)))
10556 (line (concat (apply 'concat indent "|" (make-list columns " |"))
10557 "\n")))
10558 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
10559 (point-at-bol) (point)))
10560 (beginning-of-line 1)
10561 (newline))
10562 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
10563 (dotimes (i rows) (insert line))
10564 (goto-char pos)
10565 (if (> rows 1)
10566 ;; Insert a hline after the first row.
10567 (progn
10568 (end-of-line 1)
10569 (insert "\n|-")
10570 (goto-char pos)))
10571 (org-table-align)))
10573 (defun org-table-convert-region (beg0 end0 &optional nspace)
10574 "Convert region to a table.
10575 The region goes from BEG0 to END0, but these borders will be moved
10576 slightly, to make sure a beginning of line in the first line is included.
10577 When NSPACE is non-nil, it indicates the minimum number of spaces that
10578 separate columns (default: just one space)."
10579 (interactive "rP")
10580 (let* ((beg (min beg0 end0))
10581 (end (max beg0 end0))
10582 (tabsep t)
10584 (goto-char beg)
10585 (beginning-of-line 1)
10586 (setq beg (move-marker (make-marker) (point)))
10587 (goto-char end)
10588 (if (bolp) (backward-char 1) (end-of-line 1))
10589 (setq end (move-marker (make-marker) (point)))
10590 ;; Lets see if this is tab-separated material. If every nonempty line
10591 ;; contains a tab, we will assume that it is tab-separated material
10592 (if nspace
10593 (setq tabsep nil)
10594 (goto-char beg)
10595 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
10596 (if nspace (setq tabsep nil))
10597 (if tabsep
10598 (setq re "^\\|\t")
10599 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
10600 (max 1 (prefix-numeric-value nspace)))))
10601 (goto-char beg)
10602 (while (re-search-forward re end t)
10603 (replace-match "|" t t))
10604 (goto-char beg)
10605 (insert " ")
10606 (org-table-align)))
10608 (defun org-table-import (file arg)
10609 "Import FILE as a table.
10610 The file is assumed to be tab-separated. Such files can be produced by most
10611 spreadsheet and database applications. If no tabs (at least one per line)
10612 are found, lines will be split on whitespace into fields."
10613 (interactive "f\nP")
10614 (or (bolp) (newline))
10615 (let ((beg (point))
10616 (pm (point-max)))
10617 (insert-file-contents file)
10618 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
10620 (defun org-table-export ()
10621 "Export table as a tab-separated file.
10622 Such a file can be imported into a spreadsheet program like Excel."
10623 (interactive)
10624 (let* ((beg (org-table-begin))
10625 (end (org-table-end))
10626 (table (buffer-substring beg end))
10627 (file (read-file-name "Export table to: "))
10628 buf)
10629 (unless (or (not (file-exists-p file))
10630 (y-or-n-p (format "Overwrite file %s? " file)))
10631 (error "Abort"))
10632 (with-current-buffer (find-file-noselect file)
10633 (setq buf (current-buffer))
10634 (erase-buffer)
10635 (fundamental-mode)
10636 (insert table)
10637 (goto-char (point-min))
10638 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
10639 (replace-match "" t t)
10640 (end-of-line 1))
10641 (goto-char (point-min))
10642 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
10643 (replace-match "" t t)
10644 (goto-char (min (1+ (point)) (point-max))))
10645 (goto-char (point-min))
10646 (while (re-search-forward "^-[-+]*$" nil t)
10647 (replace-match "")
10648 (if (looking-at "\n")
10649 (delete-char 1)))
10650 (goto-char (point-min))
10651 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
10652 (replace-match "\t" t t))
10653 (save-buffer))
10654 (kill-buffer buf)))
10656 (defvar org-table-aligned-begin-marker (make-marker)
10657 "Marker at the beginning of the table last aligned.
10658 Used to check if cursor still is in that table, to minimize realignment.")
10659 (defvar org-table-aligned-end-marker (make-marker)
10660 "Marker at the end of the table last aligned.
10661 Used to check if cursor still is in that table, to minimize realignment.")
10662 (defvar org-table-last-alignment nil
10663 "List of flags for flushright alignment, from the last re-alignment.
10664 This is being used to correctly align a single field after TAB or RET.")
10665 (defvar org-table-last-column-widths nil
10666 "List of max width of fields in each column.
10667 This is being used to correctly align a single field after TAB or RET.")
10669 (defvar org-last-recalc-line nil)
10670 (defconst org-narrow-column-arrow "=>"
10671 "Used as display property in narrowed table columns.")
10673 (defun org-table-align ()
10674 "Align the table at point by aligning all vertical bars."
10675 (interactive)
10676 (let* (
10677 ;; Limits of table
10678 (beg (org-table-begin))
10679 (end (org-table-end))
10680 ;; Current cursor position
10681 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10682 (colpos (org-table-current-column))
10683 (winstart (window-start))
10684 lines (new "") lengths l typenums ty fields maxfields i
10685 column
10686 (indent "") cnt frac
10687 rfmt hfmt
10688 (spaces '(1 . 1))
10689 (sp1 (car spaces))
10690 (sp2 (cdr spaces))
10691 (rfmt1 (concat
10692 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
10693 (hfmt1 (concat
10694 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
10695 emptystrings links narrow fmax f1 len c e)
10696 (untabify beg end)
10697 (remove-text-properties beg end '(org-cwidth t display t))
10698 ;; Check if we have links
10699 (goto-char beg)
10700 (setq links (re-search-forward org-bracket-link-regexp end t))
10701 ;; Make sure the link properties are right
10702 (when links (goto-char beg) (while (org-activate-bracket-links end)))
10703 ;; Check if we are narrowing any columns
10704 (goto-char beg)
10705 (setq narrow (and org-format-transports-properties-p
10706 (re-search-forward "<[0-9]+>" end t)))
10707 ;; Get the rows
10708 (setq lines (org-split-string
10709 (buffer-substring beg end) "\n"))
10710 ;; Store the indentation of the first line
10711 (if (string-match "^ *" (car lines))
10712 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
10713 ;; Mark the hlines by setting the corresponding element to nil
10714 ;; At the same time, we remove trailing space.
10715 (setq lines (mapcar (lambda (l)
10716 (if (string-match "^ *|-" l)
10718 (if (string-match "[ \t]+$" l)
10719 (substring l 0 (match-beginning 0))
10720 l)))
10721 lines))
10722 ;; Get the data fields by splitting the lines.
10723 (setq fields (mapcar
10724 (lambda (l)
10725 (org-split-string l " *| *"))
10726 (delq nil (copy-sequence lines))))
10727 ;; How many fields in the longest line?
10728 (condition-case nil
10729 (setq maxfields (apply 'max (mapcar 'length fields)))
10730 (error
10731 (kill-region beg end)
10732 (org-table-create org-table-default-size)
10733 (error "Empty table - created default table")))
10734 ;; A list of empty string to fill any short rows on output
10735 (setq emptystrings (make-list maxfields ""))
10736 ;; Check for special formatting.
10737 (setq i -1)
10738 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
10739 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
10740 ;; Check if there is an explicit width specified
10741 (when (and org-table-limit-column-width narrow)
10742 (setq c column fmax nil)
10743 (while c
10744 (setq e (pop c))
10745 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
10746 (setq fmax (string-to-number (match-string 1 e)) c nil)))
10747 ;; Find fields that are wider than fmax, and shorten them
10748 (when fmax
10749 (loop for xx in column do
10750 (when (and (stringp xx)
10751 (> (org-string-width xx) fmax))
10752 (org-add-props xx nil
10753 'help-echo
10754 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
10755 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
10756 (unless (> f1 1)
10757 (error "Cannot narrow field starting with wide link \"%s\""
10758 (match-string 0 xx)))
10759 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
10760 (add-text-properties (- f1 2) f1
10761 (list 'display org-narrow-column-arrow)
10762 xx)))))
10763 ;; Get the maximum width for each column
10764 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
10765 ;; Get the fraction of numbers, to decide about alignment of the column
10766 (setq cnt 0 frac 0.0)
10767 (loop for x in column do
10768 (if (equal x "")
10770 (setq frac ( / (+ (* frac cnt)
10771 (if (string-match org-table-number-regexp x) 1 0))
10772 (setq cnt (1+ cnt))))))
10773 (push (>= frac org-table-number-fraction) typenums))
10774 (setq lengths (nreverse lengths) typenums (nreverse typenums))
10776 ;; Store the alignment of this table, for later editing of single fields
10777 (setq org-table-last-alignment typenums
10778 org-table-last-column-widths lengths)
10780 ;; With invisible characters, `format' does not get the field width right
10781 ;; So we need to make these fields wide by hand.
10782 (when links
10783 (loop for i from 0 upto (1- maxfields) do
10784 (setq len (nth i lengths))
10785 (loop for j from 0 upto (1- (length fields)) do
10786 (setq c (nthcdr i (car (nthcdr j fields))))
10787 (if (and (stringp (car c))
10788 (string-match org-bracket-link-regexp (car c))
10789 (< (org-string-width (car c)) len))
10790 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
10792 ;; Compute the formats needed for output of the table
10793 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
10794 (while (setq l (pop lengths))
10795 (setq ty (if (pop typenums) "" "-")) ; number types flushright
10796 (setq rfmt (concat rfmt (format rfmt1 ty l))
10797 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
10798 (setq rfmt (concat rfmt "\n")
10799 hfmt (concat (substring hfmt 0 -1) "|\n"))
10801 (setq new (mapconcat
10802 (lambda (l)
10803 (if l (apply 'format rfmt
10804 (append (pop fields) emptystrings))
10805 hfmt))
10806 lines ""))
10807 ;; Replace the old one
10808 (delete-region beg end)
10809 (move-marker end nil)
10810 (move-marker org-table-aligned-begin-marker (point))
10811 (insert new)
10812 (move-marker org-table-aligned-end-marker (point))
10813 (when (and orgtbl-mode (not (org-mode-p)))
10814 (goto-char org-table-aligned-begin-marker)
10815 (while (org-hide-wide-columns org-table-aligned-end-marker)))
10816 ;; Try to move to the old location (approximately)
10817 (goto-line linepos)
10818 (set-window-start (selected-window) winstart 'noforce)
10819 (org-table-goto-column colpos)
10820 (setq org-table-may-need-update nil)
10823 (defun org-string-width (s)
10824 "Compute width of string, ignoring invisible characters.
10825 This ignores character with invisibility property `org-link', and also
10826 characters with property `org-cwidth', because these will become invisible
10827 upon the next fontification round."
10828 (let (b)
10829 (when (or (eq t buffer-invisibility-spec)
10830 (assq 'org-link buffer-invisibility-spec))
10831 (while (setq b (text-property-any 0 (length s)
10832 'invisible 'org-link s))
10833 (setq s (concat (substring s 0 b)
10834 (substring s (or (next-single-property-change
10835 b 'invisible s) (length s)))))))
10836 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
10837 (setq s (concat (substring s 0 b)
10838 (substring s (or (next-single-property-change
10839 b 'org-cwidth s) (length s))))))
10840 (string-width s)))
10842 (defun org-table-begin (&optional table-type)
10843 "Find the beginning of the table and return its position.
10844 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
10845 (save-excursion
10846 (if (not (re-search-backward
10847 (if table-type org-table-any-border-regexp
10848 org-table-border-regexp)
10849 nil t))
10850 (progn (goto-char (point-min)) (point))
10851 (goto-char (match-beginning 0))
10852 (beginning-of-line 2)
10853 (point))))
10855 (defun org-table-end (&optional table-type)
10856 "Find the end of the table and return its position.
10857 With argument TABLE-TYPE, go to the end of a table.el-type table."
10858 (save-excursion
10859 (if (not (re-search-forward
10860 (if table-type org-table-any-border-regexp
10861 org-table-border-regexp)
10862 nil t))
10863 (goto-char (point-max))
10864 (goto-char (match-beginning 0)))
10865 (point-marker)))
10867 (defun org-table-justify-field-maybe (&optional new)
10868 "Justify the current field, text to left, number to right.
10869 Optional argument NEW may specify text to replace the current field content."
10870 (cond
10871 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
10872 ((org-at-table-hline-p))
10873 ((and (not new)
10874 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
10875 (current-buffer)))
10876 (< (point) org-table-aligned-begin-marker)
10877 (>= (point) org-table-aligned-end-marker)))
10878 ;; This is not the same table, force a full re-align
10879 (setq org-table-may-need-update t))
10880 (t ;; realign the current field, based on previous full realign
10881 (let* ((pos (point)) s
10882 (col (org-table-current-column))
10883 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
10884 l f n o e)
10885 (when (> col 0)
10886 (skip-chars-backward "^|\n")
10887 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
10888 (progn
10889 (setq s (match-string 1)
10890 o (match-string 0)
10891 l (max 1 (- (match-end 0) (match-beginning 0) 3))
10892 e (not (= (match-beginning 2) (match-end 2))))
10893 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
10894 l (if e "|" (setq org-table-may-need-update t) ""))
10895 n (format f s))
10896 (if new
10897 (if (<= (length new) l) ;; FIXME: length -> str-width?
10898 (setq n (format f new))
10899 (setq n (concat new "|") org-table-may-need-update t)))
10900 (or (equal n o)
10901 (let (org-table-may-need-update)
10902 (replace-match n))))
10903 (setq org-table-may-need-update t))
10904 (goto-char pos))))))
10906 (defun org-table-next-field ()
10907 "Go to the next field in the current table, creating new lines as needed.
10908 Before doing so, re-align the table if necessary."
10909 (interactive)
10910 (org-table-maybe-eval-formula)
10911 (org-table-maybe-recalculate-line)
10912 (if (and org-table-automatic-realign
10913 org-table-may-need-update)
10914 (org-table-align))
10915 (let ((end (org-table-end)))
10916 (if (org-at-table-hline-p)
10917 (end-of-line 1))
10918 (condition-case nil
10919 (progn
10920 (re-search-forward "|" end)
10921 (if (looking-at "[ \t]*$")
10922 (re-search-forward "|" end))
10923 (if (and (looking-at "-")
10924 org-table-tab-jumps-over-hlines
10925 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
10926 (goto-char (match-beginning 1)))
10927 (if (looking-at "-")
10928 (progn
10929 (beginning-of-line 0)
10930 (org-table-insert-row 'below))
10931 (if (looking-at " ") (forward-char 1))))
10932 (error
10933 (org-table-insert-row 'below)))))
10935 (defun org-table-previous-field ()
10936 "Go to the previous field in the table.
10937 Before doing so, re-align the table if necessary."
10938 (interactive)
10939 (org-table-justify-field-maybe)
10940 (org-table-maybe-recalculate-line)
10941 (if (and org-table-automatic-realign
10942 org-table-may-need-update)
10943 (org-table-align))
10944 (if (org-at-table-hline-p)
10945 (end-of-line 1))
10946 (re-search-backward "|" (org-table-begin))
10947 (re-search-backward "|" (org-table-begin))
10948 (while (looking-at "|\\(-\\|[ \t]*$\\)")
10949 (re-search-backward "|" (org-table-begin)))
10950 (if (looking-at "| ?")
10951 (goto-char (match-end 0))))
10953 (defun org-table-next-row ()
10954 "Go to the next row (same column) in the current table.
10955 Before doing so, re-align the table if necessary."
10956 (interactive)
10957 (org-table-maybe-eval-formula)
10958 (org-table-maybe-recalculate-line)
10959 (if (or (looking-at "[ \t]*$")
10960 (save-excursion (skip-chars-backward " \t") (bolp)))
10961 (newline)
10962 (if (and org-table-automatic-realign
10963 org-table-may-need-update)
10964 (org-table-align))
10965 (let ((col (org-table-current-column)))
10966 (beginning-of-line 2)
10967 (if (or (not (org-at-table-p))
10968 (org-at-table-hline-p))
10969 (progn
10970 (beginning-of-line 0)
10971 (org-table-insert-row 'below)))
10972 (org-table-goto-column col)
10973 (skip-chars-backward "^|\n\r")
10974 (if (looking-at " ") (forward-char 1)))))
10976 (defun org-table-copy-down (n)
10977 "Copy a field down in the current column.
10978 If the field at the cursor is empty, copy into it the content of the nearest
10979 non-empty field above. With argument N, use the Nth non-empty field.
10980 If the current field is not empty, it is copied down to the next row, and
10981 the cursor is moved with it. Therefore, repeating this command causes the
10982 column to be filled row-by-row.
10983 If the variable `org-table-copy-increment' is non-nil and the field is an
10984 integer, it will be incremented while copying."
10985 (interactive "p")
10986 (let* ((colpos (org-table-current-column))
10987 (field (org-table-get-field))
10988 (non-empty (string-match "[^ \t]" field))
10989 (beg (org-table-begin))
10990 txt)
10991 (org-table-check-inside-data-field)
10992 (if non-empty
10993 (progn
10994 (setq txt (org-trim field))
10995 (org-table-next-row)
10996 (org-table-blank-field))
10997 (save-excursion
10998 (setq txt
10999 (catch 'exit
11000 (while (progn (beginning-of-line 1)
11001 (re-search-backward org-table-dataline-regexp
11002 beg t))
11003 (org-table-goto-column colpos t)
11004 (if (and (looking-at
11005 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
11006 (= (setq n (1- n)) 0))
11007 (throw 'exit (match-string 1))))))))
11008 (if txt
11009 (progn
11010 (if (and org-table-copy-increment
11011 (string-match "^[0-9]+$" txt))
11012 (setq txt (format "%d" (+ (string-to-number txt) 1))))
11013 (insert txt)
11014 (org-table-maybe-recalculate-line)
11015 (org-table-align))
11016 (error "No non-empty field found"))))
11018 (defun org-table-check-inside-data-field ()
11019 "Is point inside a table data field?
11020 I.e. not on a hline or before the first or after the last column?
11021 This actually throws an error, so it aborts the current command."
11022 (if (or (not (org-at-table-p))
11023 (= (org-table-current-column) 0)
11024 (org-at-table-hline-p)
11025 (looking-at "[ \t]*$"))
11026 (error "Not in table data field")))
11028 (defvar org-table-clip nil
11029 "Clipboard for table regions.")
11031 (defun org-table-blank-field ()
11032 "Blank the current table field or active region."
11033 (interactive)
11034 (org-table-check-inside-data-field)
11035 (if (and (interactive-p) (org-region-active-p))
11036 (let (org-table-clip)
11037 (org-table-cut-region (region-beginning) (region-end)))
11038 (skip-chars-backward "^|")
11039 (backward-char 1)
11040 (if (looking-at "|[^|\n]+")
11041 (let* ((pos (match-beginning 0))
11042 (match (match-string 0))
11043 (len (org-string-width match)))
11044 (replace-match (concat "|" (make-string (1- len) ?\ )))
11045 (goto-char (+ 2 pos))
11046 (substring match 1)))))
11048 (defun org-table-get-field (&optional n replace)
11049 "Return the value of the field in column N of current row.
11050 N defaults to current field.
11051 If REPLACE is a string, replace field with this value. The return value
11052 is always the old value."
11053 (and n (org-table-goto-column n))
11054 (skip-chars-backward "^|\n")
11055 (backward-char 1)
11056 (if (looking-at "|[^|\r\n]*")
11057 (let* ((pos (match-beginning 0))
11058 (val (buffer-substring (1+ pos) (match-end 0))))
11059 (if replace
11060 (replace-match (concat "|" replace)))
11061 (goto-char (min (point-at-eol) (+ 2 pos)))
11062 val)
11063 (forward-char 1) ""))
11065 (defun org-table-current-column ()
11066 "Find out which column we are in.
11067 When called interactively, column is also displayed in echo area."
11068 (interactive)
11069 (if (interactive-p) (org-table-check-inside-data-field))
11070 (save-excursion
11071 (let ((cnt 0) (pos (point)))
11072 (beginning-of-line 1)
11073 (while (search-forward "|" pos t)
11074 (setq cnt (1+ cnt)))
11075 (if (interactive-p) (message "This is table column %d" cnt))
11076 cnt)))
11078 (defun org-table-goto-column (n &optional on-delim force)
11079 "Move the cursor to the Nth column in the current table line.
11080 With optional argument ON-DELIM, stop with point before the left delimiter
11081 of the field.
11082 If there are less than N fields, just go to after the last delimiter.
11083 However, when FORCE is non-nil, create new columns if necessary."
11084 (interactive "p")
11085 (let ((pos (point-at-eol)))
11086 (beginning-of-line 1)
11087 (when (> n 0)
11088 (while (and (> (setq n (1- n)) -1)
11089 (or (search-forward "|" pos t)
11090 (and force
11091 (progn (end-of-line 1)
11092 (skip-chars-backward "^|")
11093 (insert " | "))))))
11094 ; (backward-char 2) t)))))
11095 (when (and force (not (looking-at ".*|")))
11096 (save-excursion (end-of-line 1) (insert " | ")))
11097 (if on-delim
11098 (backward-char 1)
11099 (if (looking-at " ") (forward-char 1))))))
11101 (defun org-at-table-p (&optional table-type)
11102 "Return t if the cursor is inside an org-type table.
11103 If TABLE-TYPE is non-nil, also check for table.el-type tables."
11104 (if org-enable-table-editor
11105 (save-excursion
11106 (beginning-of-line 1)
11107 (looking-at (if table-type org-table-any-line-regexp
11108 org-table-line-regexp)))
11109 nil))
11111 (defun org-at-table.el-p ()
11112 "Return t if and only if we are at a table.el table."
11113 (and (org-at-table-p 'any)
11114 (save-excursion
11115 (goto-char (org-table-begin 'any))
11116 (looking-at org-table1-hline-regexp))))
11118 (defun org-table-recognize-table.el ()
11119 "If there is a table.el table nearby, recognize it and move into it."
11120 (if org-table-tab-recognizes-table.el
11121 (if (org-at-table.el-p)
11122 (progn
11123 (beginning-of-line 1)
11124 (if (looking-at org-table-dataline-regexp)
11126 (if (looking-at org-table1-hline-regexp)
11127 (progn
11128 (beginning-of-line 2)
11129 (if (looking-at org-table-any-border-regexp)
11130 (beginning-of-line -1)))))
11131 (if (re-search-forward "|" (org-table-end t) t)
11132 (progn
11133 (require 'table)
11134 (if (table--at-cell-p (point))
11136 (message "recognizing table.el table...")
11137 (table-recognize-table)
11138 (message "recognizing table.el table...done")))
11139 (error "This should not happen..."))
11141 nil)
11142 nil))
11144 (defun org-at-table-hline-p ()
11145 "Return t if the cursor is inside a hline in a table."
11146 (if org-enable-table-editor
11147 (save-excursion
11148 (beginning-of-line 1)
11149 (looking-at org-table-hline-regexp))
11150 nil))
11152 (defun org-table-insert-column ()
11153 "Insert a new column into the table."
11154 (interactive)
11155 (if (not (org-at-table-p))
11156 (error "Not at a table"))
11157 (org-table-find-dataline)
11158 (let* ((col (max 1 (org-table-current-column)))
11159 (beg (org-table-begin))
11160 (end (org-table-end))
11161 ;; Current cursor position
11162 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11163 (colpos col))
11164 (goto-char beg)
11165 (while (< (point) end)
11166 (if (org-at-table-hline-p)
11168 (org-table-goto-column col t)
11169 (insert "| "))
11170 (beginning-of-line 2))
11171 (move-marker end nil)
11172 (goto-line linepos)
11173 (org-table-goto-column colpos)
11174 (org-table-align)
11175 (org-table-modify-formulas 'insert col)))
11177 (defun org-table-find-dataline ()
11178 "Find a dataline in the current table, which is needed for column commands."
11179 (if (and (org-at-table-p)
11180 (not (org-at-table-hline-p)))
11182 (let ((col (current-column))
11183 (end (org-table-end)))
11184 (move-to-column col)
11185 (while (and (< (point) end)
11186 (or (not (= (current-column) col))
11187 (org-at-table-hline-p)))
11188 (beginning-of-line 2)
11189 (move-to-column col))
11190 (if (and (org-at-table-p)
11191 (not (org-at-table-hline-p)))
11193 (error
11194 "Please position cursor in a data line for column operations")))))
11196 (defun org-table-delete-column ()
11197 "Delete a column from the table."
11198 (interactive)
11199 (if (not (org-at-table-p))
11200 (error "Not at a table"))
11201 (org-table-find-dataline)
11202 (org-table-check-inside-data-field)
11203 (let* ((col (org-table-current-column))
11204 (beg (org-table-begin))
11205 (end (org-table-end))
11206 ;; Current cursor position
11207 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11208 (colpos col))
11209 (goto-char beg)
11210 (while (< (point) end)
11211 (if (org-at-table-hline-p)
11213 (org-table-goto-column col t)
11214 (and (looking-at "|[^|\n]+|")
11215 (replace-match "|")))
11216 (beginning-of-line 2))
11217 (move-marker end nil)
11218 (goto-line linepos)
11219 (org-table-goto-column colpos)
11220 (org-table-align)
11221 (org-table-modify-formulas 'remove col)))
11223 (defun org-table-move-column-right ()
11224 "Move column to the right."
11225 (interactive)
11226 (org-table-move-column nil))
11227 (defun org-table-move-column-left ()
11228 "Move column to the left."
11229 (interactive)
11230 (org-table-move-column 'left))
11232 (defun org-table-move-column (&optional left)
11233 "Move the current column to the right. With arg LEFT, move to the left."
11234 (interactive "P")
11235 (if (not (org-at-table-p))
11236 (error "Not at a table"))
11237 (org-table-find-dataline)
11238 (org-table-check-inside-data-field)
11239 (let* ((col (org-table-current-column))
11240 (col1 (if left (1- col) col))
11241 (beg (org-table-begin))
11242 (end (org-table-end))
11243 ;; Current cursor position
11244 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11245 (colpos (if left (1- col) (1+ col))))
11246 (if (and left (= col 1))
11247 (error "Cannot move column further left"))
11248 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
11249 (error "Cannot move column further right"))
11250 (goto-char beg)
11251 (while (< (point) end)
11252 (if (org-at-table-hline-p)
11254 (org-table-goto-column col1 t)
11255 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
11256 (replace-match "|\\2|\\1|")))
11257 (beginning-of-line 2))
11258 (move-marker end nil)
11259 (goto-line linepos)
11260 (org-table-goto-column colpos)
11261 (org-table-align)
11262 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
11264 (defun org-table-move-row-down ()
11265 "Move table row down."
11266 (interactive)
11267 (org-table-move-row nil))
11268 (defun org-table-move-row-up ()
11269 "Move table row up."
11270 (interactive)
11271 (org-table-move-row 'up))
11273 (defun org-table-move-row (&optional up)
11274 "Move the current table line down. With arg UP, move it up."
11275 (interactive "P")
11276 (let ((col (current-column))
11277 (pos (point))
11278 (tonew (if up 0 2))
11279 txt)
11280 (beginning-of-line tonew)
11281 (if (not (org-at-table-p))
11282 (progn
11283 (goto-char pos)
11284 (error "Cannot move row further")))
11285 (goto-char pos)
11286 (beginning-of-line 1)
11287 (setq pos (point))
11288 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
11289 (delete-region (point) (1+ (point-at-eol)))
11290 (beginning-of-line tonew)
11291 (insert txt)
11292 (beginning-of-line 0)
11293 (move-to-column col)))
11295 (defun org-table-insert-row (&optional arg)
11296 "Insert a new row above the current line into the table.
11297 With prefix ARG, insert below the current line."
11298 (interactive "P")
11299 (if (not (org-at-table-p))
11300 (error "Not at a table"))
11301 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
11302 (new (org-table-clean-line line)))
11303 ;; Fix the first field if necessary
11304 (if (string-match "^[ \t]*| *[#$] *|" line)
11305 (setq new (replace-match (match-string 0 line) t t new)))
11306 (beginning-of-line (if arg 2 1))
11307 (let (org-table-may-need-update) (insert-before-markers new "\n"))
11308 (beginning-of-line 0)
11309 (re-search-forward "| ?" (point-at-eol) t)
11310 (and org-table-may-need-update (org-table-align))))
11312 (defun org-table-insert-hline (&optional arg)
11313 "Insert a horizontal-line below the current line into the table.
11314 With prefix ARG, insert above the current line."
11315 (interactive "P")
11316 (if (not (org-at-table-p))
11317 (error "Not at a table"))
11318 (let ((line (org-table-clean-line
11319 (buffer-substring (point-at-bol) (point-at-eol))))
11320 (col (current-column)))
11321 (while (string-match "|\\( +\\)|" line)
11322 (setq line (replace-match
11323 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
11324 ?-) "|") t t line)))
11325 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
11326 (beginning-of-line (if arg 1 2))
11327 (insert line "\n")
11328 (beginning-of-line (if arg 1 -1))
11329 (move-to-column col)))
11331 (defun org-table-clean-line (s)
11332 "Convert a table line S into a string with only \"|\" and space.
11333 In particular, this does handle wide and invisible characters."
11334 (if (string-match "^[ \t]*|-" s)
11335 ;; It's a hline, just map the characters
11336 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
11337 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
11338 (setq s (replace-match
11339 (concat "|" (make-string (org-string-width (match-string 1 s))
11340 ?\ ) "|")
11341 t t s)))
11344 (defun org-table-kill-row ()
11345 "Delete the current row or horizontal line from the table."
11346 (interactive)
11347 (if (not (org-at-table-p))
11348 (error "Not at a table"))
11349 (let ((col (current-column)))
11350 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
11351 (if (not (org-at-table-p)) (beginning-of-line 0))
11352 (move-to-column col)))
11354 (defun org-table-sort-lines (beg end numericp)
11355 "Sort table lines in region.
11356 Point and mark define the first and last line to include. Both point and
11357 mark should be in the column that is used for sorting. For example, to
11358 sort according to column 3, put the mark in the first line to sort, in
11359 table column 3. Put point into the last line to be included in the sorting,
11360 also in table column 3. The command will prompt for the sorting method
11361 \(n for numerical, a for alphanumeric)."
11362 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
11363 (setq numericp (string-match "[nN]" numericp))
11364 (org-table-align) ;; Just to be safe
11365 (let* (bcol ecol cmp column lns)
11366 (goto-char beg)
11367 (org-table-check-inside-data-field)
11368 (setq column (org-table-current-column)
11369 beg (move-marker (make-marker) (point-at-bol)))
11370 (goto-char end)
11371 (org-table-check-inside-data-field)
11372 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
11373 (untabify beg end)
11374 (goto-char beg)
11375 (org-table-goto-column column)
11376 (skip-chars-backward "^|")
11377 (setq bcol (current-column))
11378 (org-table-goto-column (1+ column))
11379 (skip-chars-backward "^|")
11380 (setq ecol (1- (current-column)))
11381 (setq cmp (if numericp
11382 (lambda (a b) (< (car a) (car b)))
11383 (lambda (a b) (string< (car a) (car b)))))
11384 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
11385 (org-split-string (buffer-substring beg end) "\n")))
11386 (if numericp
11387 (setq lns (mapcar (lambda(x)
11388 (cons (string-to-number (car x)) (cdr x)))
11389 lns)))
11390 (delete-region beg end)
11391 (move-marker beg nil)
11392 (move-marker end nil)
11393 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
11394 (message "%d lines sorted %s based on column %d"
11395 (length lns)
11396 (if numericp "numerically" "alphabetically") column)))
11398 (defun org-table-cut-region (beg end)
11399 "Copy region in table to the clipboard and blank all relevant fields."
11400 (interactive "r")
11401 (org-table-copy-region beg end 'cut))
11403 (defun org-table-copy-region (beg end &optional cut)
11404 "Copy rectangular region in table to clipboard.
11405 A special clipboard is used which can only be accessed
11406 with `org-table-paste-rectangle'."
11407 (interactive "rP")
11408 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
11409 region cols
11410 (rpl (if cut " " nil)))
11411 (goto-char beg)
11412 (org-table-check-inside-data-field)
11413 (setq l01 (count-lines (point-min) (point))
11414 c01 (org-table-current-column))
11415 (goto-char end)
11416 (org-table-check-inside-data-field)
11417 (setq l02 (count-lines (point-min) (point))
11418 c02 (org-table-current-column))
11419 (setq l1 (min l01 l02) l2 (max l01 l02)
11420 c1 (min c01 c02) c2 (max c01 c02))
11421 (catch 'exit
11422 (while t
11423 (catch 'nextline
11424 (if (> l1 l2) (throw 'exit t))
11425 (goto-line l1)
11426 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
11427 (setq cols nil ic1 c1 ic2 c2)
11428 (while (< ic1 (1+ ic2))
11429 (push (org-table-get-field ic1 rpl) cols)
11430 (setq ic1 (1+ ic1)))
11431 (push (nreverse cols) region)
11432 (setq l1 (1+ l1)))))
11433 (setq org-table-clip (nreverse region))
11434 (if cut (org-table-align))
11435 org-table-clip))
11437 (defun org-table-paste-rectangle ()
11438 "Paste a rectangular region into a table.
11439 The upper right corner ends up in the current field. All involved fields
11440 will be overwritten. If the rectangle does not fit into the present table,
11441 the table is enlarged as needed. The process ignores horizontal separator
11442 lines."
11443 (interactive)
11444 (unless (and org-table-clip (listp org-table-clip))
11445 (error "First cut/copy a region to paste!"))
11446 (org-table-check-inside-data-field)
11447 (let* ((clip org-table-clip)
11448 (line (count-lines (point-min) (point)))
11449 (col (org-table-current-column))
11450 (org-enable-table-editor t)
11451 (org-table-automatic-realign nil)
11452 c cols field)
11453 (while (setq cols (pop clip))
11454 (while (org-at-table-hline-p) (beginning-of-line 2))
11455 (if (not (org-at-table-p))
11456 (progn (end-of-line 0) (org-table-next-field)))
11457 (setq c col)
11458 (while (setq field (pop cols))
11459 (org-table-goto-column c nil 'force)
11460 (org-table-get-field nil field)
11461 (setq c (1+ c)))
11462 (beginning-of-line 2))
11463 (goto-line line)
11464 (org-table-goto-column col)
11465 (org-table-align)))
11467 (defun org-table-convert ()
11468 "Convert from `org-mode' table to table.el and back.
11469 Obviously, this only works within limits. When an Org-mode table is
11470 converted to table.el, all horizontal separator lines get lost, because
11471 table.el uses these as cell boundaries and has no notion of horizontal lines.
11472 A table.el table can be converted to an Org-mode table only if it does not
11473 do row or column spanning. Multiline cells will become multiple cells.
11474 Beware, Org-mode does not test if the table can be successfully converted - it
11475 blindly applies a recipe that works for simple tables."
11476 (interactive)
11477 (require 'table)
11478 (if (org-at-table.el-p)
11479 ;; convert to Org-mode table
11480 (let ((beg (move-marker (make-marker) (org-table-begin t)))
11481 (end (move-marker (make-marker) (org-table-end t))))
11482 (table-unrecognize-region beg end)
11483 (goto-char beg)
11484 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
11485 (replace-match ""))
11486 (goto-char beg))
11487 (if (org-at-table-p)
11488 ;; convert to table.el table
11489 (let ((beg (move-marker (make-marker) (org-table-begin)))
11490 (end (move-marker (make-marker) (org-table-end))))
11491 ;; first, get rid of all horizontal lines
11492 (goto-char beg)
11493 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
11494 (replace-match ""))
11495 ;; insert a hline before first
11496 (goto-char beg)
11497 (org-table-insert-hline 'above)
11498 (beginning-of-line -1)
11499 ;; insert a hline after each line
11500 (while (progn (beginning-of-line 3) (< (point) end))
11501 (org-table-insert-hline))
11502 (goto-char beg)
11503 (setq end (move-marker end (org-table-end)))
11504 ;; replace "+" at beginning and ending of hlines
11505 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
11506 (replace-match "\\1+-"))
11507 (goto-char beg)
11508 (while (re-search-forward "-|[ \t]*$" end t)
11509 (replace-match "-+"))
11510 (goto-char beg)))))
11512 (defun org-table-wrap-region (arg)
11513 "Wrap several fields in a column like a paragraph.
11514 This is useful if you'd like to spread the contents of a field over several
11515 lines, in order to keep the table compact.
11517 If there is an active region, and both point and mark are in the same column,
11518 the text in the column is wrapped to minimum width for the given number of
11519 lines. Generally, this makes the table more compact. A prefix ARG may be
11520 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
11521 formats the selected text to two lines. If the region was longer than two
11522 lines, the remaining lines remain empty. A negative prefix argument reduces
11523 the current number of lines by that amount. The wrapped text is pasted back
11524 into the table. If you formatted it to more lines than it was before, fields
11525 further down in the table get overwritten - so you might need to make space in
11526 the table first.
11528 If there is no region, the current field is split at the cursor position and
11529 the text fragment to the right of the cursor is prepended to the field one
11530 line down.
11532 If there is no region, but you specify a prefix ARG, the current field gets
11533 blank, and the content is appended to the field above."
11534 (interactive "P")
11535 (org-table-check-inside-data-field)
11536 (if (org-region-active-p)
11537 ;; There is a region: fill as a paragraph
11538 (let ((beg (region-beginning))
11539 nlines)
11540 (org-table-cut-region (region-beginning) (region-end))
11541 (if (> (length (car org-table-clip)) 1)
11542 (error "Region must be limited to single column"))
11543 (setq nlines (if arg
11544 (if (< arg 1)
11545 (+ (length org-table-clip) arg)
11546 arg)
11547 (length org-table-clip)))
11548 (setq org-table-clip
11549 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
11550 nil nlines)))
11551 (goto-char beg)
11552 (org-table-paste-rectangle))
11553 ;; No region, split the current field at point
11554 (if arg
11555 ;; combine with field above
11556 (let ((s (org-table-blank-field))
11557 (col (org-table-current-column)))
11558 (beginning-of-line 0)
11559 (while (org-at-table-hline-p) (beginning-of-line 0))
11560 (org-table-goto-column col)
11561 (skip-chars-forward "^|")
11562 (skip-chars-backward " ")
11563 (insert " " (org-trim s))
11564 (org-table-align))
11565 ;; split field
11566 (when (looking-at "\\([^|]+\\)+|")
11567 (let ((s (match-string 1)))
11568 (replace-match " |")
11569 (goto-char (match-beginning 0))
11570 (org-table-next-row)
11571 (insert (org-trim s) " ")
11572 (org-table-align))))))
11574 (defvar org-field-marker nil)
11576 (defun org-table-edit-field (arg)
11577 "Edit table field in a different window.
11578 This is mainly useful for fields that contain hidden parts.
11579 When called with a \\[universal-argument] prefix, just make the full field visible so that
11580 it can be edited in place."
11581 (interactive "P")
11582 (if arg
11583 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
11584 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
11585 (remove-text-properties b e '(org-cwidth t invisible t
11586 display t intangible t))
11587 (if (and (boundp 'font-lock-mode) font-lock-mode)
11588 (font-lock-fontify-block)))
11589 (let ((pos (move-marker (make-marker) (point)))
11590 (field (org-table-get-field))
11591 (cw (current-window-configuration))
11593 (switch-to-buffer-other-window "*Org tmp*")
11594 (erase-buffer)
11595 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
11596 (org-mode)
11597 (goto-char (setq p (point-max)))
11598 (insert (org-trim field))
11599 (remove-text-properties p (point-max)
11600 '(invisible t org-cwidth t display t
11601 intangible t))
11602 (goto-char p)
11603 (org-set-local 'org-finish-function
11604 'org-table-finish-edit-field)
11605 (org-set-local 'org-window-configuration cw)
11606 (org-set-local 'org-field-marker pos)
11607 (message "Edit and finish with C-c C-c"))))
11609 (defun org-table-finish-edit-field ()
11610 "Finish editing a table data field.
11611 Remove all newline characters, insert the result into the table, realign
11612 the table and kill the editing buffer."
11613 (let ((pos org-field-marker)
11614 (cw org-window-configuration)
11615 (cb (current-buffer))
11616 text)
11617 (goto-char (point-min))
11618 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
11619 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
11620 (replace-match " "))
11621 (setq text (org-trim (buffer-string)))
11622 (set-window-configuration cw)
11623 (kill-buffer cb)
11624 (select-window (get-buffer-window (marker-buffer pos)))
11625 (goto-char pos)
11626 (move-marker pos nil)
11627 (org-table-check-inside-data-field)
11628 (org-table-get-field nil text)
11629 (org-table-align)
11630 (message "New field value inserted")))
11632 (defun org-trim (s)
11633 "Remove whitespace at beginning and end of string."
11634 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
11635 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
11638 (defun org-wrap (string &optional width lines)
11639 "Wrap string to either a number of lines, or a width in characters.
11640 If WIDTH is non-nil, the string is wrapped to that width, however many lines
11641 that costs. If there is a word longer than WIDTH, the text is actually
11642 wrapped to the length of that word.
11643 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
11644 many lines, whatever width that takes.
11645 The return value is a list of lines, without newlines at the end."
11646 (let* ((words (org-split-string string "[ \t\n]+"))
11647 (maxword (apply 'max (mapcar 'org-string-width words)))
11648 w ll)
11649 (cond (width
11650 (org-do-wrap words (max maxword width)))
11651 (lines
11652 (setq w maxword)
11653 (setq ll (org-do-wrap words maxword))
11654 (if (<= (length ll) lines)
11656 (setq ll words)
11657 (while (> (length ll) lines)
11658 (setq w (1+ w))
11659 (setq ll (org-do-wrap words w)))
11660 ll))
11661 (t (error "Cannot wrap this")))))
11664 (defun org-do-wrap (words width)
11665 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
11666 (let (lines line)
11667 (while words
11668 (setq line (pop words))
11669 (while (and words (< (+ (length line) (length (car words))) width))
11670 (setq line (concat line " " (pop words))))
11671 (setq lines (push line lines)))
11672 (nreverse lines)))
11674 (defun org-split-string (string &optional separators)
11675 "Splits STRING into substrings at SEPARATORS.
11676 No empty strings are returned if there are matches at the beginning
11677 and end of string."
11678 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
11679 (start 0)
11680 notfirst
11681 (list nil))
11682 (while (and (string-match rexp string
11683 (if (and notfirst
11684 (= start (match-beginning 0))
11685 (< start (length string)))
11686 (1+ start) start))
11687 (< (match-beginning 0) (length string)))
11688 (setq notfirst t)
11689 (or (eq (match-beginning 0) 0)
11690 (and (eq (match-beginning 0) (match-end 0))
11691 (eq (match-beginning 0) start))
11692 (setq list
11693 (cons (substring string start (match-beginning 0))
11694 list)))
11695 (setq start (match-end 0)))
11696 (or (eq start (length string))
11697 (setq list
11698 (cons (substring string start)
11699 list)))
11700 (nreverse list)))
11702 (defun org-table-map-tables (function)
11703 "Apply FUNCTION to the start of all tables in the buffer."
11704 (save-excursion
11705 (save-restriction
11706 (widen)
11707 (goto-char (point-min))
11708 (while (re-search-forward org-table-any-line-regexp nil t)
11709 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
11710 (beginning-of-line 1)
11711 (if (looking-at org-table-line-regexp)
11712 (save-excursion (funcall function)))
11713 (re-search-forward org-table-any-border-regexp nil 1))))
11714 (message "Mapping tables: done"))
11716 (defun org-table-sum (&optional beg end nlast)
11717 "Sum numbers in region of current table column.
11718 The result will be displayed in the echo area, and will be available
11719 as kill to be inserted with \\[yank].
11721 If there is an active region, it is interpreted as a rectangle and all
11722 numbers in that rectangle will be summed. If there is no active
11723 region and point is located in a table column, sum all numbers in that
11724 column.
11726 If at least one number looks like a time HH:MM or HH:MM:SS, all other
11727 numbers are assumed to be times as well (in decimal hours) and the
11728 numbers are added as such.
11730 If NLAST is a number, only the NLAST fields will actually be summed."
11731 (interactive)
11732 (save-excursion
11733 (let (col (timecnt 0) diff h m s org-table-clip)
11734 (cond
11735 ((and beg end)) ; beg and end given explicitly
11736 ((org-region-active-p)
11737 (setq beg (region-beginning) end (region-end)))
11739 (setq col (org-table-current-column))
11740 (goto-char (org-table-begin))
11741 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
11742 (error "No table data"))
11743 (org-table-goto-column col)
11744 ;not needed? (skip-chars-backward "^|")
11745 (setq beg (point))
11746 (goto-char (org-table-end))
11747 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
11748 (error "No table data"))
11749 (org-table-goto-column col)
11750 ;not needed? (skip-chars-forward "^|")
11751 (setq end (point))))
11752 (let* ((items (apply 'append (org-table-copy-region beg end)))
11753 (items1 (cond ((not nlast) items)
11754 ((>= nlast (length items)) items)
11755 (t (setq items (reverse items))
11756 (setcdr (nthcdr (1- nlast) items) nil)
11757 (nreverse items))))
11758 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
11759 items1)))
11760 (res (apply '+ numbers))
11761 (sres (if (= timecnt 0)
11762 (format "%g" res)
11763 (setq diff (* 3600 res)
11764 h (floor (/ diff 3600)) diff (mod diff 3600)
11765 m (floor (/ diff 60)) diff (mod diff 60)
11766 s diff)
11767 (format "%d:%02d:%02d" h m s))))
11768 (kill-new sres)
11769 (if (interactive-p)
11770 (message "%s"
11771 (substitute-command-keys
11772 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
11773 (length numbers) sres))))
11774 sres))))
11776 (defun org-table-get-number-for-summing (s)
11777 (let (n)
11778 (if (string-match "^ *|? *" s)
11779 (setq s (replace-match "" nil nil s)))
11780 (if (string-match " *|? *$" s)
11781 (setq s (replace-match "" nil nil s)))
11782 (setq n (string-to-number s))
11783 (cond
11784 ((and (string-match "0" s)
11785 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
11786 ((string-match "\\`[ \t]+\\'" s) nil)
11787 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
11788 (let ((h (string-to-number (or (match-string 1 s) "0")))
11789 (m (string-to-number (or (match-string 2 s) "0")))
11790 (s (string-to-number (or (match-string 4 s) "0"))))
11791 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
11792 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
11793 ((equal n 0) nil)
11794 (t n))))
11796 (defun org-table-get-vertical-vector (desc &optional tbeg col)
11797 "Get a calc vector from a column, accorting to descriptor DESC.
11798 Optional arguments TBEG and COL can give the beginning of the table and
11799 the current column, to avoid unnecessary parsing."
11800 (save-excursion
11801 (or tbeg (setq tbeg (org-table-begin)))
11802 (or col (setq col (org-table-current-column)))
11803 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
11804 (cond
11805 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
11806 (setq n1 (- (match-end 1) (match-beginning 1)))
11807 (if (match-beginning 3)
11808 (setq n2 (- (match-end 2) (match-beginning 3))))
11809 (setq n (if n2 (max n1 n2) n1))
11810 (setq n1 (if n2 (min n1 n2)))
11811 (setq nn n)
11812 (while (and (> nn 0)
11813 (re-search-backward org-table-hline-regexp tbeg t))
11814 (push (org-current-line) hline-list)
11815 (setq nn (1- nn)))
11816 (setq hline-list (nreverse hline-list))
11817 (goto-line (nth (1- n) hline-list))
11818 (when (re-search-forward org-table-dataline-regexp)
11819 (org-table-goto-column col)
11820 (setq beg (point)))
11821 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
11822 (when (re-search-backward org-table-dataline-regexp)
11823 (org-table-goto-column col)
11824 (setq end (point)))
11825 (setq l (apply 'append (org-table-copy-region beg end)))
11826 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
11827 (if (equal x "") "0" x))
11828 l ",") "]"))
11829 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
11830 (setq n1 (string-to-number (match-string 1 desc))
11831 n2 (string-to-number (match-string 2 desc)))
11832 (beginning-of-line 1)
11833 (save-excursion
11834 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
11835 (org-table-goto-column col)
11836 (setq beg (point))))
11837 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
11838 (org-table-goto-column col)
11839 (setq end (point)))
11840 (setq l (apply 'append (org-table-copy-region beg end)))
11841 (concat "[" (mapconcat
11842 (lambda (x) (setq x (org-trim x))
11843 (if (equal x "") "0" x))
11844 l ",") "]"))
11845 ((string-match "\\([0-9]+\\)" desc)
11846 (beginning-of-line 1)
11847 (when (re-search-backward org-table-dataline-regexp tbeg t
11848 (string-to-number (match-string 0 desc)))
11849 (org-table-goto-column col)
11850 (org-trim (org-table-get-field))))))))
11852 (defvar org-table-formula-history nil)
11854 (defvar org-table-column-names nil
11855 "Alist with column names, derived from the `!' line.")
11856 (defvar org-table-column-name-regexp nil
11857 "Regular expression matching the current column names.")
11858 (defvar org-table-local-parameters nil
11859 "Alist with parameter names, derived from the `$' line.")
11860 (defvar org-table-named-field-locations nil
11861 "Alist with locations of named fields.")
11863 (defun org-table-get-formula (&optional equation named)
11864 "Read a formula from the minibuffer, offer stored formula as default."
11865 (let* ((name (car (rassoc (list (org-current-line)
11866 (org-table-current-column))
11867 org-table-named-field-locations)))
11868 (scol (if named
11869 (if name name
11870 (error "Not in a named field"))
11871 (int-to-string (org-table-current-column))))
11872 (dummy (and name (not named)
11873 (not (y-or-n-p "Replace named-field formula with column equation? " ))
11874 (error "Abort")))
11875 (org-table-may-need-update nil)
11876 (stored-list (org-table-get-stored-formulas))
11877 (stored (cdr (assoc scol stored-list)))
11878 (eq (cond
11879 ((and stored equation (string-match "^ *=? *$" equation))
11880 stored)
11881 ((stringp equation)
11882 equation)
11883 (t (read-string
11884 (format "%s formula $%s=" (if named "Field" "Column") scol)
11885 (or stored "") 'org-table-formula-history
11886 ;stored
11887 ))))
11888 mustsave)
11889 (when (not (string-match "\\S-" eq))
11890 ;; remove formula
11891 (setq stored-list (delq (assoc scol stored-list) stored-list))
11892 (org-table-store-formulas stored-list)
11893 (error "Formula removed"))
11894 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
11895 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
11896 (if (and name (not named))
11897 ;; We set the column equation, delete the named one.
11898 (setq stored-list (delq (assoc name stored-list) stored-list)
11899 mustsave t))
11900 (if stored
11901 (setcdr (assoc scol stored-list) eq)
11902 (setq stored-list (cons (cons scol eq) stored-list)))
11903 (if (or mustsave (not (equal stored eq)))
11904 (org-table-store-formulas stored-list))
11905 eq))
11907 (defun org-table-store-formulas (alist)
11908 "Store the list of formulas below the current table."
11909 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
11910 (save-excursion
11911 (goto-char (org-table-end))
11912 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
11913 (delete-region (point) (match-end 0)))
11914 (insert "#+TBLFM: "
11915 (mapconcat (lambda (x)
11916 (concat "$" (car x) "=" (cdr x)))
11917 alist "::")
11918 "\n")))
11920 (defun org-table-get-stored-formulas ()
11921 "Return an alist with the stored formulas directly after current table."
11922 (interactive)
11923 (let (scol eq eq-alist strings string seen)
11924 (save-excursion
11925 (goto-char (org-table-end))
11926 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
11927 (setq strings (org-split-string (match-string 2) " *:: *"))
11928 (while (setq string (pop strings))
11929 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
11930 (setq scol (match-string 1 string)
11931 eq (match-string 2 string)
11932 eq-alist (cons (cons scol eq) eq-alist))
11933 (if (member scol seen)
11934 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
11935 (push scol seen))))))
11936 (nreverse eq-alist)))
11938 (defun org-table-modify-formulas (action &rest columns)
11939 "Modify the formulas stored below the current table.
11940 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
11941 expected, for the other actions only a single column number is needed."
11942 (let ((list (org-table-get-stored-formulas))
11943 (nmax (length (org-split-string
11944 (buffer-substring (point-at-bol) (point-at-eol))
11945 "|")))
11946 col col1 col2 scol si sc1 sc2)
11947 (cond
11948 ((null list)) ; No action needed if there are no stored formulas
11949 ((eq action 'remove)
11950 (setq col (car columns)
11951 scol (int-to-string col))
11952 (org-table-replace-in-formulas list scol "INVALID")
11953 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
11954 (loop for i from (1+ col) upto nmax by 1 do
11955 (setq si (int-to-string i))
11956 (org-table-replace-in-formulas list si (int-to-string (1- i)))
11957 (if (assoc si list) (setcar (assoc si list)
11958 (int-to-string (1- i))))))
11959 ((eq action 'insert)
11960 (setq col (car columns))
11961 (loop for i from nmax downto col by 1 do
11962 (setq si (int-to-string i))
11963 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
11964 (if (assoc si list) (setcar (assoc si list)
11965 (int-to-string (1+ i))))))
11966 ((eq action 'swap)
11967 (setq col1 (car columns) col2 (nth 1 columns)
11968 sc1 (int-to-string col1) sc2 (int-to-string col2))
11969 ;; Hopefully, ZqZtZ will never be a name in a table
11970 (org-table-replace-in-formulas list sc1 "ZqZtZ")
11971 (org-table-replace-in-formulas list sc2 sc1)
11972 (org-table-replace-in-formulas list "ZqZtZ" sc2)
11973 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
11974 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
11975 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
11976 (t (error "Invalid action in `org-table-modify-formulas'")))
11977 (if list (org-table-store-formulas list))))
11979 (defun org-table-replace-in-formulas (list s1 s2)
11980 (let (elt re s)
11981 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
11982 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
11983 re (concat (regexp-quote s1) "\\>"))
11984 (while (setq elt (pop list))
11985 (setq s (cdr elt))
11986 (while (string-match re s)
11987 (setq s (replace-match s2 t t s)))
11988 (setcdr elt s))))
11990 (defun org-table-get-specials ()
11991 "Get the column names and local parameters for this table."
11992 (save-excursion
11993 (let ((beg (org-table-begin)) (end (org-table-end))
11994 names name fields fields1 field cnt c v line col)
11995 (setq org-table-column-names nil
11996 org-table-local-parameters nil
11997 org-table-named-field-locations nil)
11998 (goto-char beg)
11999 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
12000 (setq names (org-split-string (match-string 1) " *| *")
12001 cnt 1)
12002 (while (setq name (pop names))
12003 (setq cnt (1+ cnt))
12004 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
12005 (push (cons name (int-to-string cnt)) org-table-column-names))))
12006 (setq org-table-column-names (nreverse org-table-column-names))
12007 (setq org-table-column-name-regexp
12008 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
12009 (goto-char beg)
12010 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
12011 (setq fields (org-split-string (match-string 1) " *| *"))
12012 (while (setq field (pop fields))
12013 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
12014 (push (cons (match-string 1 field) (match-string 2 field))
12015 org-table-local-parameters))))
12016 (goto-char beg)
12017 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
12018 (setq c (match-string 1)
12019 fields (org-split-string (match-string 2) " *| *"))
12020 (save-excursion
12021 (beginning-of-line (if (equal c "_") 2 0))
12022 (setq line (org-current-line) col 1)
12023 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
12024 (setq fields1 (org-split-string (match-string 1) " *| *"))))
12025 (while (and fields1 (setq field (pop fields)))
12026 (setq v (pop fields1) col (1+ col))
12027 (when (and (stringp field) (stringp v)
12028 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
12029 (push (cons field v) org-table-local-parameters)
12030 (push (list field line col) org-table-named-field-locations)))))))
12032 (defun org-this-word ()
12033 ;; Get the current word
12034 (save-excursion
12035 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
12036 (end (progn (skip-chars-forward "^ \t\n") (point))))
12037 (buffer-substring-no-properties beg end))))
12039 (defun org-table-maybe-eval-formula ()
12040 "Check if the current field starts with \"=\" or \":=\".
12041 If yes, store the formula and apply it."
12042 ;; We already know we are in a table. Get field will only return a formula
12043 ;; when appropriate. It might return a separator line, but no problem.
12044 (when org-table-formula-evaluate-inline
12045 (let* ((field (org-trim (or (org-table-get-field) "")))
12046 named eq)
12047 (when (string-match "^:?=\\(.*\\)" field)
12048 (setq named (equal (string-to-char field) ?:)
12049 eq (match-string 1 field))
12050 (if (fboundp 'calc-eval)
12051 (org-table-eval-formula (if named '(4) nil) eq))))))
12053 (defvar org-recalc-commands nil
12054 "List of commands triggering the recalculation of a line.
12055 Will be filled automatically during use.")
12057 (defvar org-recalc-marks
12058 '((" " . "Unmarked: no special line, no automatic recalculation")
12059 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
12060 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
12061 ("!" . "Column name definition line. Reference in formula as $name.")
12062 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
12063 ("_" . "Names for values in row below this one.")
12064 ("^" . "Names for values in row above this one.")))
12066 (defun org-table-rotate-recalc-marks (&optional newchar)
12067 "Rotate the recalculation mark in the first column.
12068 If in any row, the first field is not consistent with a mark,
12069 insert a new column for the markers.
12070 When there is an active region, change all the lines in the region,
12071 after prompting for the marking character.
12072 After each change, a message will be displayed indicating the meaning
12073 of the new mark."
12074 (interactive)
12075 (unless (org-at-table-p) (error "Not at a table"))
12076 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
12077 (beg (org-table-begin))
12078 (end (org-table-end))
12079 (l (org-current-line))
12080 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
12081 (l2 (if (org-region-active-p) (org-current-line (region-end))))
12082 (have-col
12083 (save-excursion
12084 (goto-char beg)
12085 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
12086 (col (org-table-current-column))
12087 (forcenew (car (assoc newchar org-recalc-marks)))
12088 epos new)
12089 (when l1
12090 (message "Change region to what mark? Type # * ! $ or SPC: ")
12091 (setq newchar (char-to-string (read-char-exclusive))
12092 forcenew (car (assoc newchar org-recalc-marks))))
12093 (if (and newchar (not forcenew))
12094 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
12095 newchar))
12096 (if l1 (goto-line l1))
12097 (save-excursion
12098 (beginning-of-line 1)
12099 (unless (looking-at org-table-dataline-regexp)
12100 (error "Not at a table data line")))
12101 (unless have-col
12102 (org-table-goto-column 1)
12103 (org-table-insert-column)
12104 (org-table-goto-column (1+ col)))
12105 (setq epos (point-at-eol))
12106 (save-excursion
12107 (beginning-of-line 1)
12108 (org-table-get-field
12109 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
12110 (concat " "
12111 (setq new (or forcenew
12112 (cadr (member (match-string 1) marks))))
12113 " ")
12114 " # ")))
12115 (if (and l1 l2)
12116 (progn
12117 (goto-line l1)
12118 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
12119 (and (looking-at org-table-dataline-regexp)
12120 (org-table-get-field 1 (concat " " new " "))))
12121 (goto-line l1)))
12122 (if (not (= epos (point-at-eol))) (org-table-align))
12123 (goto-line l)
12124 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
12126 (defun org-table-maybe-recalculate-line ()
12127 "Recompute the current line if marked for it, and if we haven't just done it."
12128 (interactive)
12129 (and org-table-allow-automatic-line-recalculation
12130 (not (and (memq last-command org-recalc-commands)
12131 (equal org-last-recalc-line (org-current-line))))
12132 (save-excursion (beginning-of-line 1)
12133 (looking-at org-table-auto-recalculate-regexp))
12134 (fboundp 'calc-eval)
12135 (org-table-recalculate) t))
12137 (defvar org-table-formula-debug nil
12138 "Non-nil means, debug table formulas.
12139 When nil, simply write \"#ERROR\" in corrupted fields.")
12141 (defvar modes)
12142 (defsubst org-set-calc-mode (var &optional value)
12143 (if (stringp var)
12144 (setq var (assoc var '(("D" calc-angle-mode deg)
12145 ("R" calc-angle-mode rad)
12146 ("F" calc-prefer-frac t)
12147 ("S" calc-symbolic-mode t)))
12148 value (nth 2 var) var (nth 1 var)))
12149 (if (memq var modes)
12150 (setcar (cdr (memq var modes)) value)
12151 (cons var (cons value modes)))
12152 modes)
12154 (defun org-table-eval-formula (&optional arg equation
12155 suppress-align suppress-const
12156 suppress-store)
12157 "Replace the table field value at the cursor by the result of a calculation.
12159 This function makes use of Dave Gillespie's Calc package, in my view the
12160 most exciting program ever written for GNU Emacs. So you need to have Calc
12161 installed in order to use this function.
12163 In a table, this command replaces the value in the current field with the
12164 result of a formula. It also installs the formula as the \"current\" column
12165 formula, by storing it in a special line below the table. When called
12166 with a `C-u' prefix, the current field must ba a named field, and the
12167 formula is installed as valid in only this specific field.
12169 When called, the command first prompts for a formula, which is read in
12170 the minibuffer. Previously entered formulas are available through the
12171 history list, and the last used formula is offered as a default.
12172 These stored formulas are adapted correctly when moving, inserting, or
12173 deleting columns with the corresponding commands.
12175 The formula can be any algebraic expression understood by the Calc package.
12176 For details, see the Org-mode manual.
12178 This function can also be called from Lisp programs and offers
12179 additional arguments: EQUATION can be the formula to apply. If this
12180 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
12181 used to speed-up recursive calls by by-passing unnecessary aligns.
12182 SUPPRESS-CONST suppresses the interpretation of constants in the
12183 formula, assuming that this has been done already outside the function.
12184 SUPPRESS-STORE means the formula should not be stored, either because
12185 it is already stored, or because it is a modified equation that should
12186 not overwrite the stored one."
12187 (interactive "P")
12188 (require 'calc)
12189 (org-table-check-inside-data-field)
12190 (org-table-get-specials)
12191 (let* (fields
12192 (ndown (if (integerp arg) arg 1))
12193 (org-table-automatic-realign nil)
12194 (case-fold-search nil)
12195 (down (> ndown 1))
12196 (formula (if (and equation suppress-store)
12197 equation
12198 (org-table-get-formula equation (equal arg '(4)))))
12199 (n0 (org-table-current-column))
12200 (modes (copy-sequence org-calc-default-modes))
12201 n form fmt x ev orig c lispp)
12202 ;; Parse the format string. Since we have a lot of modes, this is
12203 ;; a lot of work. However, I think calc still uses most of the time.
12204 (if (string-match ";" formula)
12205 (let ((tmp (org-split-string formula ";")))
12206 (setq formula (car tmp)
12207 fmt (concat (cdr (assoc "%" org-table-local-parameters))
12208 (nth 1 tmp)))
12209 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
12210 (setq c (string-to-char (match-string 1 fmt))
12211 n (string-to-number (match-string 2 fmt)))
12212 (if (= c ?p)
12213 (setq modes (org-set-calc-mode 'calc-internal-prec n))
12214 (setq modes (org-set-calc-mode
12215 'calc-float-format
12216 (list (cdr (assoc c '((?n . float) (?f . fix)
12217 (?s . sci) (?e . eng))))
12218 n))))
12219 (setq fmt (replace-match "" t t fmt)))
12220 (while (string-match "[DRFS]" fmt)
12221 (setq modes (org-set-calc-mode (match-string 0 fmt)))
12222 (setq fmt (replace-match "" t t fmt)))
12223 (unless (string-match "\\S-" fmt)
12224 (setq fmt nil))))
12225 (if (and (not suppress-const) org-table-formula-use-constants)
12226 (setq formula (org-table-formula-substitute-names formula)))
12227 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
12228 (while (> ndown 0)
12229 (setq fields (org-split-string
12230 (buffer-substring
12231 (point-at-bol) (point-at-eol)) " *| *"))
12232 (if org-table-formula-numbers-only
12233 (setq fields (mapcar
12234 (lambda (x) (number-to-string (string-to-number x)))
12235 fields)))
12236 (setq ndown (1- ndown))
12237 (setq form (copy-sequence formula)
12238 lispp (equal (substring form 0 2) "'("))
12239 ;; Insert the references to fields in same row
12240 (while (string-match "\\$\\([0-9]+\\)?" form)
12241 (setq n (if (match-beginning 1)
12242 (string-to-number (match-string 1 form))
12244 x (nth (1- n) fields))
12245 (unless x (error "Invalid field specifier \"%s\""
12246 (match-string 0 form)))
12247 (if (equal x "") (setq x "0"))
12248 (setq form (replace-match
12249 (if lispp x (concat "(" x ")"))
12250 t t form)))
12251 ;; Insert ranges in current column
12252 (while (string-match "\\&[-I0-9]+" form)
12253 (setq form (replace-match
12254 (save-match-data
12255 (org-table-get-vertical-vector (match-string 0 form)
12256 nil n0))
12257 t t form)))
12258 (if lispp
12259 (setq ev (eval (eval (read form)))
12260 ev (if (numberp ev) (number-to-string ev) ev))
12261 (setq ev (calc-eval (cons form modes)
12262 (if org-table-formula-numbers-only 'num))))
12264 (when org-table-formula-debug
12265 (with-output-to-temp-buffer "*Help*"
12266 (princ (format "Substitution history of formula
12267 Orig: %s
12268 $xyz-> %s
12269 $1-> %s\n" orig formula form))
12270 (if (listp ev)
12271 (princ (format " %s^\nError: %s"
12272 (make-string (car ev) ?\-) (nth 1 ev)))
12273 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
12274 ev (or fmt "NONE")
12275 (if fmt (format fmt (string-to-number ev)) ev)))))
12276 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
12277 (unless (and (interactive-p) (not ndown))
12278 (unless (let (inhibit-redisplay)
12279 (y-or-n-p "Debugging Formula. Continue to next? "))
12280 (org-table-align)
12281 (error "Abort"))
12282 (delete-window (get-buffer-window "*Help*"))
12283 (message "")))
12284 (if (listp ev) (setq fmt nil ev "#ERROR"))
12285 (org-table-justify-field-maybe
12286 (if fmt (format fmt (string-to-number ev)) ev))
12287 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
12288 (call-interactively 'org-return)
12289 (setq ndown 0)))
12290 (and down (org-table-maybe-recalculate-line))
12291 (or suppress-align (and org-table-may-need-update
12292 (org-table-align)))))
12294 (defun org-table-recalculate (&optional all noalign)
12295 "Recalculate the current table line by applying all stored formulas.
12296 With prefix arg ALL, do this for all lines in the table."
12297 (interactive "P")
12298 (or (memq this-command org-recalc-commands)
12299 (setq org-recalc-commands (cons this-command org-recalc-commands)))
12300 (unless (org-at-table-p) (error "Not at a table"))
12301 (org-table-get-specials)
12302 (let* ((eqlist (sort (org-table-get-stored-formulas)
12303 (lambda (a b) (string< (car a) (car b)))))
12304 (inhibit-redisplay t)
12305 (line-re org-table-dataline-regexp)
12306 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
12307 (thiscol (org-table-current-column))
12308 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
12309 ;; Insert constants in all formulas
12310 (setq eqlist
12311 (mapcar (lambda (x)
12312 (setcdr x (org-table-formula-substitute-names (cdr x)))
12314 eqlist))
12315 ;; Split the equation list
12316 (while (setq eq (pop eqlist))
12317 (if (<= (string-to-char (car eq)) ?9)
12318 (push eq eqlnum)
12319 (push eq eqlname)))
12320 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
12321 (if all
12322 (progn
12323 (setq end (move-marker (make-marker) (1+ (org-table-end))))
12324 (goto-char (setq beg (org-table-begin)))
12325 (if (re-search-forward org-table-calculate-mark-regexp end t)
12326 ;; This is a table with marked lines, only compute selected lines
12327 (setq line-re org-table-recalculate-regexp)
12328 ;; Move forward to the first non-header line
12329 (if (and (re-search-forward org-table-dataline-regexp end t)
12330 (re-search-forward org-table-hline-regexp end t)
12331 (re-search-forward org-table-dataline-regexp end t))
12332 (setq beg (match-beginning 0))
12333 nil))) ;; just leave beg where it is
12334 (setq beg (point-at-bol)
12335 end (move-marker (make-marker) (1+ (point-at-eol)))))
12336 (goto-char beg)
12337 (and all (message "Re-applying formulas to full table..."))
12338 (while (re-search-forward line-re end t)
12339 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
12340 ;; Unprotected line, recalculate
12341 (and all (message "Re-applying formulas to full table...(line %d)"
12342 (setq cnt (1+ cnt))))
12343 (setq org-last-recalc-line (org-current-line))
12344 (setq eql eqlnum)
12345 (while (setq entry (pop eql))
12346 (goto-line org-last-recalc-line)
12347 (org-table-goto-column (string-to-number (car entry)) nil 'force)
12348 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
12349 (goto-line thisline)
12350 (org-table-goto-column thiscol)
12351 (or noalign (and org-table-may-need-update (org-table-align))
12352 (and all (message "Re-applying formulas to %d lines...done" cnt)))
12353 ;; Now do the names fields
12354 (while (setq eq (pop eqlname))
12355 (setq name (car eq)
12356 a (assoc name org-table-named-field-locations))
12357 (when a
12358 (message "Re-applying formula to named field: %s" name)
12359 (goto-line (nth 1 a))
12360 (org-table-goto-column (nth 2 a))
12361 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
12362 ;; back to initial position
12363 (goto-line thisline)
12364 (org-table-goto-column thiscol)
12365 (or noalign (and org-table-may-need-update (org-table-align))
12366 (and all (message "Re-applying formulas...done")))))
12368 (defun org-table-formula-substitute-names (f)
12369 "Replace $const with values in string F."
12370 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
12371 ;; First, check for column names
12372 (while (setq start (string-match org-table-column-name-regexp f start))
12373 (setq start (1+ start))
12374 (setq a (assoc (match-string 1 f) org-table-column-names))
12375 (setq f (replace-match (concat "$" (cdr a)) t t f)))
12376 ;; Expand ranges to vectors
12377 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
12378 (setq n1 (string-to-number (match-string 1 f))
12379 n2 (string-to-number (match-string 2 f))
12380 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
12381 s (concat "[($" (number-to-string (1- nn1)) ")"))
12382 (loop for i from nn1 upto nn2 do
12383 (setq s (concat s ",($" (int-to-string i) ")")))
12384 (setq s (concat s "]"))
12385 (if (< n2 n1) (setq s (concat "rev(" s ")")))
12386 (setq f (replace-match s t t f)))
12387 ;; Parameters and constants
12388 (setq start 0)
12389 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
12390 (setq start (1+ start))
12391 (if (setq a (save-match-data
12392 (org-table-get-constant (match-string 1 f))))
12393 (setq f (replace-match (concat "(" a ")") t t f))))
12394 (if org-table-formula-debug
12395 (put-text-property 0 (length f) :orig-formula f1 f))
12398 (defun org-table-get-constant (const)
12399 "Find the value for a parameter or constant in a formula.
12400 Parameters get priority."
12401 (or (cdr (assoc const org-table-local-parameters))
12402 (cdr (assoc const org-table-formula-constants))
12403 (and (fboundp 'constants-get) (constants-get const))
12404 "#UNDEFINED_NAME"))
12406 (defvar org-edit-formulas-map (make-sparse-keymap))
12407 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
12408 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
12409 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
12411 (defvar org-pos)
12413 (defun org-table-edit-formulas ()
12414 "Edit the formulas of the current table in a separate buffer."
12415 (interactive)
12416 (unless (org-at-table-p)
12417 (error "Not at a table"))
12418 (org-table-get-specials)
12419 (let ((eql (org-table-get-stored-formulas))
12420 (pos (move-marker (make-marker) (point)))
12421 (wc (current-window-configuration))
12422 entry loc s)
12423 (switch-to-buffer-other-window "*Edit Formulas*")
12424 (erase-buffer)
12425 (fundamental-mode)
12426 (org-set-local 'org-pos pos)
12427 (org-set-local 'org-window-configuration wc)
12428 (use-local-map org-edit-formulas-map)
12429 (setq s "# Edit formulas and finish with `C-c C-c'.
12430 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
12431 # Use `C-c ?' to get information about $name at point.
12432 # To cancel editing, press `C-c C-q'.\n")
12433 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12434 (insert s)
12435 (while (setq entry (pop eql))
12436 (when (setq loc (assoc (car entry) org-table-named-field-locations))
12437 (setq s (format "# Named formula, referring to column %d in line %d\n"
12438 (nth 2 loc) (nth 1 loc)))
12439 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12440 (insert s))
12441 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
12442 (remove-text-properties 0 (length s) '(face nil) s)
12443 (insert s))
12444 (goto-char (point-min))
12445 (message "Edit formulas and finish with `C-c C-c'.")))
12447 (defun org-show-variable ()
12448 "Show the location/value of the $ expression at point."
12449 (interactive)
12450 (let (var (pos org-pos) (win (selected-window)) e)
12451 (save-excursion
12452 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
12453 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
12454 (setq var (match-string 1))
12455 (error "No variable at point")))
12456 (cond
12457 ((setq e (assoc var org-table-named-field-locations))
12458 (switch-to-buffer-other-window (marker-buffer pos))
12459 (goto-line (nth 1 e))
12460 (org-table-goto-column (nth 2 e))
12461 (select-window win)
12462 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
12463 ((setq e (assoc var org-table-column-names))
12464 (switch-to-buffer-other-window (marker-buffer pos))
12465 (goto-char pos)
12466 (goto-char (org-table-begin))
12467 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
12468 (org-table-end) t)
12469 (progn
12470 (goto-char (match-beginning 1))
12471 (message "Named column (column %s)" (cdr e)))
12472 (error "Column name not found"))
12473 (select-window win))
12474 ((string-match "^[0-9]$" var)
12475 ;; column number
12476 (switch-to-buffer-other-window (marker-buffer pos))
12477 (goto-char pos)
12478 (goto-char (org-table-begin))
12479 (recenter 1)
12480 (if (re-search-forward org-table-dataline-regexp
12481 (org-table-end) t)
12482 (progn
12483 (goto-char (match-beginning 0))
12484 (org-table-goto-column (string-to-number var))
12485 (message "Column %s" var))
12486 (error "Column name not found"))
12487 (select-window win))
12488 ((setq e (assoc var org-table-local-parameters))
12489 (switch-to-buffer-other-window (marker-buffer pos))
12490 (goto-char pos)
12491 (goto-char (org-table-begin))
12492 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
12493 (progn
12494 (goto-char (match-beginning 1))
12495 (message "Local parameter."))
12496 (error "Parameter not found"))
12497 (select-window win))
12499 (cond
12500 ((setq e (assoc var org-table-formula-constants))
12501 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
12502 ((setq e (and (fboundp 'constants-get) (constants-get var)))
12503 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
12504 (t (error "Undefined name $%s" var)))))))
12506 (defun org-finish-edit-formulas (&optional arg)
12507 "Parse the buffer for formula definitions and install them.
12508 With prefix ARG, apply the new formulas to the table."
12509 (interactive "P")
12510 (let ((pos org-pos) eql)
12511 (goto-char (point-min))
12512 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
12513 (push (cons (match-string 1) (match-string 2)) eql))
12514 (set-window-configuration org-window-configuration)
12515 (select-window (get-buffer-window (marker-buffer pos)))
12516 (goto-char pos)
12517 (unless (org-at-table-p)
12518 (error "Lost table position - cannot install formulae"))
12519 (org-table-store-formulas eql)
12520 (move-marker pos nil)
12521 (kill-buffer "*Edit Formulas*")
12522 (if arg
12523 (org-table-recalculate 'all)
12524 (message "New formulas installed - press C-u C-c C-c to apply."))))
12526 (defun org-abort-edit-formulas ()
12527 "Abort editing formulas, without installing the changes."
12528 (interactive)
12529 (let ((pos org-pos))
12530 (set-window-configuration org-window-configuration)
12531 (select-window (get-buffer-window (marker-buffer pos)))
12532 (goto-char pos)
12533 (message "Formula editing aborted without installing changes")))
12535 ;;; The orgtbl minor mode
12537 ;; Define a minor mode which can be used in other modes in order to
12538 ;; integrate the org-mode table editor.
12540 ;; This is really a hack, because the org-mode table editor uses several
12541 ;; keys which normally belong to the major mode, for example the TAB and
12542 ;; RET keys. Here is how it works: The minor mode defines all the keys
12543 ;; necessary to operate the table editor, but wraps the commands into a
12544 ;; function which tests if the cursor is currently inside a table. If that
12545 ;; is the case, the table editor command is executed. However, when any of
12546 ;; those keys is used outside a table, the function uses `key-binding' to
12547 ;; look up if the key has an associated command in another currently active
12548 ;; keymap (minor modes, major mode, global), and executes that command.
12549 ;; There might be problems if any of the keys used by the table editor is
12550 ;; otherwise used as a prefix key.
12552 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
12553 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
12554 ;; addresses this by checking explicitly for both bindings.
12556 ;; The optimized version (see variable `orgtbl-optimized') takes over
12557 ;; all keys which are bound to `self-insert-command' in the *global map*.
12558 ;; Some modes bind other commands to simple characters, for example
12559 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
12560 ;; active, this binding is ignored inside tables and replaced with a
12561 ;; modified self-insert.
12563 (defvar orgtbl-mode nil
12564 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
12565 table editor in arbitrary modes.")
12566 (make-variable-buffer-local 'orgtbl-mode)
12568 (defvar orgtbl-mode-map (make-keymap)
12569 "Keymap for `orgtbl-mode'.")
12571 ;;;###autoload
12572 (defun turn-on-orgtbl ()
12573 "Unconditionally turn on `orgtbl-mode'."
12574 (orgtbl-mode 1))
12576 ;;;###autoload
12577 (defun orgtbl-mode (&optional arg)
12578 "The `org-mode' table editor as a minor mode for use in other modes."
12579 (interactive)
12580 (if (org-mode-p)
12581 ;; Exit without error, in case some hook functions calls this
12582 ;; by accident in org-mode.
12583 (message "Orgtbl-mode is not useful in org-mode, command ignored")
12584 (setq orgtbl-mode
12585 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
12586 (if orgtbl-mode
12587 (progn
12588 (and (orgtbl-setup) (defun orgtbl-setup () nil))
12589 ;; Make sure we are first in minor-mode-map-alist
12590 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
12591 (and c (setq minor-mode-map-alist
12592 (cons c (delq c minor-mode-map-alist)))))
12593 (org-set-local (quote org-table-may-need-update) t)
12594 (org-add-hook 'before-change-functions 'org-before-change-function
12595 nil 'local)
12596 (org-set-local 'org-old-auto-fill-inhibit-regexp
12597 auto-fill-inhibit-regexp)
12598 (org-set-local 'auto-fill-inhibit-regexp
12599 (if auto-fill-inhibit-regexp
12600 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
12601 "[ \t]*|"))
12602 (org-add-to-invisibility-spec '(org-cwidth))
12603 (easy-menu-add orgtbl-mode-menu)
12604 (run-hooks 'orgtbl-mode-hook))
12605 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
12606 (org-cleanup-narrow-column-properties)
12607 (org-remove-from-invisibility-spec '(org-cwidth))
12608 (remove-hook 'before-change-functions 'org-before-change-function t)
12609 (easy-menu-remove orgtbl-mode-menu)
12610 (force-mode-line-update 'all))))
12612 (defun org-cleanup-narrow-column-properties ()
12613 "Remove all properties related to narrow-column invisibility."
12614 (let ((s 1))
12615 (while (setq s (text-property-any s (point-max)
12616 'display org-narrow-column-arrow))
12617 (remove-text-properties s (1+ s) '(display t)))
12618 (setq s 1)
12619 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
12620 (remove-text-properties s (1+ s) '(org-cwidth t)))
12621 (setq s 1)
12622 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
12623 (remove-text-properties s (1+ s) '(invisible t)))))
12625 ;; Install it as a minor mode.
12626 (put 'orgtbl-mode :included t)
12627 (put 'orgtbl-mode :menu-tag "Org Table Mode")
12628 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
12630 (defun orgtbl-make-binding (fun n &rest keys)
12631 "Create a function for binding in the table minor mode.
12632 FUN is the command to call inside a table. N is used to create a unique
12633 command name. KEYS are keys that should be checked in for a command
12634 to execute outside of tables."
12635 (eval
12636 (list 'defun
12637 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
12638 '(arg)
12639 (concat "In tables, run `" (symbol-name fun) "'.\n"
12640 "Outside of tables, run the binding of `"
12641 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
12642 "'.")
12643 '(interactive "p")
12644 (list 'if
12645 '(org-at-table-p)
12646 (list 'call-interactively (list 'quote fun))
12647 (list 'let '(orgtbl-mode)
12648 (list 'call-interactively
12649 (append '(or)
12650 (mapcar (lambda (k)
12651 (list 'key-binding k))
12652 keys)
12653 '('orgtbl-error))))))))
12655 (defun orgtbl-error ()
12656 "Error when there is no default binding for a table key."
12657 (interactive)
12658 (error "This key is has no function outside tables"))
12660 (defun orgtbl-setup ()
12661 "Setup orgtbl keymaps."
12662 (let ((nfunc 0)
12663 (bindings
12664 (list
12665 '([(meta shift left)] org-table-delete-column)
12666 '([(meta left)] org-table-move-column-left)
12667 '([(meta right)] org-table-move-column-right)
12668 '([(meta shift right)] org-table-insert-column)
12669 '([(meta shift up)] org-table-kill-row)
12670 '([(meta shift down)] org-table-insert-row)
12671 '([(meta up)] org-table-move-row-up)
12672 '([(meta down)] org-table-move-row-down)
12673 '("\C-c\C-w" org-table-cut-region)
12674 '("\C-c\M-w" org-table-copy-region)
12675 '("\C-c\C-y" org-table-paste-rectangle)
12676 '("\C-c-" org-table-insert-hline)
12677 ; '([(shift tab)] org-table-previous-field)
12678 '("\C-m" org-table-next-row)
12679 (list (org-key 'S-return) 'org-table-copy-down)
12680 '([(meta return)] org-table-wrap-region)
12681 '("\C-c\C-q" org-table-wrap-region)
12682 '("\C-c?" org-table-current-column)
12683 '("\C-c " org-table-blank-field)
12684 '("\C-c+" org-table-sum)
12685 '("\C-c=" org-table-eval-formula)
12686 '("\C-c'" org-table-edit-formulas)
12687 '("\C-c`" org-table-edit-field)
12688 '("\C-c*" org-table-recalculate)
12689 '("\C-c|" org-table-create-or-convert-from-region)
12690 '("\C-c^" org-table-sort-lines)
12691 '([(control ?#)] org-table-rotate-recalc-marks)))
12692 elt key fun cmd)
12693 (while (setq elt (pop bindings))
12694 (setq nfunc (1+ nfunc))
12695 (setq key (car elt)
12696 fun (nth 1 elt)
12697 cmd (orgtbl-make-binding fun nfunc key))
12698 (define-key orgtbl-mode-map key cmd))
12699 ;; Special treatment needed for TAB and RET
12700 (define-key orgtbl-mode-map [(return)]
12701 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
12702 (define-key orgtbl-mode-map "\C-m"
12703 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
12704 (define-key orgtbl-mode-map [(tab)]
12705 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
12706 (define-key orgtbl-mode-map "\C-i"
12707 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
12708 (define-key orgtbl-mode-map "\C-i"
12709 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
12710 (define-key orgtbl-mode-map "\C-c\C-c"
12711 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
12712 (when orgtbl-optimized
12713 ;; If the user wants maximum table support, we need to hijack
12714 ;; some standard editing functions
12715 (org-remap orgtbl-mode-map
12716 'self-insert-command 'orgtbl-self-insert-command
12717 'delete-char 'org-delete-char
12718 'delete-backward-char 'org-delete-backward-char)
12719 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
12720 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
12721 '("OrgTbl"
12722 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
12723 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
12724 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
12725 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
12726 "--"
12727 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
12728 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
12729 ["Copy Field from Above"
12730 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
12731 "--"
12732 ("Column"
12733 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
12734 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
12735 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
12736 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
12737 "--"
12738 ["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])
12739 ("Row"
12740 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
12741 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
12742 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
12743 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
12744 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
12745 "--"
12746 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
12747 ("Rectangle"
12748 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
12749 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
12750 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
12751 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
12752 "--"
12753 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
12754 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12755 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
12756 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
12757 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
12758 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
12759 ["Sum Column/Rectangle" org-table-sum
12760 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
12761 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
12762 ["Debug Formulas"
12763 (setq org-table-formula-debug (not org-table-formula-debug))
12764 :style toggle :selected org-table-formula-debug]
12768 (defun orgtbl-tab (arg)
12769 "Justification and field motion for `orgtbl-mode'."
12770 (interactive "P")
12771 (if arg (org-table-edit-field t)
12772 (org-table-justify-field-maybe)
12773 (org-table-next-field)))
12775 (defun orgtbl-ret ()
12776 "Justification and field motion for `orgtbl-mode'."
12777 (interactive)
12778 (org-table-justify-field-maybe)
12779 (org-table-next-row))
12781 (defun orgtbl-self-insert-command (N)
12782 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12783 If the cursor is in a table looking at whitespace, the whitespace is
12784 overwritten, and the table is not marked as requiring realignment."
12785 (interactive "p")
12786 (if (and (org-at-table-p)
12788 (and org-table-auto-blank-field
12789 (member last-command
12790 '(orgtbl-hijacker-command-100
12791 orgtbl-hijacker-command-101
12792 orgtbl-hijacker-command-102
12793 orgtbl-hijacker-command-103
12794 orgtbl-hijacker-command-104
12795 orgtbl-hijacker-command-105))
12796 (org-table-blank-field))
12798 (eq N 1)
12799 (looking-at "[^|\n]* +|"))
12800 (let (org-table-may-need-update)
12801 (goto-char (1- (match-end 0)))
12802 (delete-backward-char 1)
12803 (goto-char (match-beginning 0))
12804 (self-insert-command N))
12805 (setq org-table-may-need-update t)
12806 (let (orgtbl-mode)
12807 (call-interactively (key-binding (vector last-input-event))))))
12809 (defun org-force-self-insert (N)
12810 "Needed to enforce self-insert under remapping."
12811 (interactive "p")
12812 (self-insert-command N))
12814 ;;; Exporting
12816 (defconst org-level-max 20)
12818 (defvar org-export-html-preamble nil
12819 "Preamble, to be inserted just after <body>. Set by publishing functions.")
12820 (defvar org-export-html-postamble nil
12821 "Preamble, to be inserted just before </body>. Set by publishing functions.")
12822 (defvar org-export-html-auto-preamble t
12823 "Should default preamble be inserted? Set by publishing functions.")
12824 (defvar org-export-html-auto-postamble t
12825 "Should default postamble be inserted? Set by publishing functions.")
12827 (defconst org-export-plist-vars
12828 '((:language . org-export-default-language)
12829 (:headline-levels . org-export-headline-levels)
12830 (:section-numbers . org-export-with-section-numbers)
12831 (:table-of-contents . org-export-with-toc)
12832 (:archived-trees . org-export-with-archived-trees)
12833 (:emphasize . org-export-with-emphasize)
12834 (:sub-superscript . org-export-with-sub-superscripts)
12835 (:TeX-macros . org-export-with-TeX-macros)
12836 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
12837 (:fixed-width . org-export-with-fixed-width)
12838 (:timestamps . org-export-with-timestamps)
12839 (:tables . org-export-with-tables)
12840 (:table-auto-headline . org-export-highlight-first-table-line)
12841 (:style . org-export-html-style)
12842 (:convert-org-links . org-export-html-link-org-files-as-html)
12843 (:inline-images . org-export-html-inline-images)
12844 (:expand-quoted-html . org-export-html-expand)
12845 (:timestamp . org-export-html-with-timestamp)
12846 (:publishing-directory . org-export-publishing-directory)
12847 (:preamble . org-export-html-preamble)
12848 (:postamble . org-export-html-postamble)
12849 (:auto-preamble . org-export-html-auto-preamble)
12850 (:auto-postamble . org-export-html-auto-postamble)
12851 (:author . user-full-name)
12852 (:email . user-mail-address)))
12854 (defun org-default-export-plist ()
12855 "Return the property list with default settings for the export variables."
12856 (let ((l org-export-plist-vars) rtn e)
12857 (while (setq e (pop l))
12858 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
12859 rtn))
12861 (defun org-infile-export-plist ()
12862 "Return the property list with file-local settings for export."
12863 (save-excursion
12864 (goto-char 0)
12865 (let ((re (org-make-options-regexp
12866 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12867 p key val text options)
12868 (while (re-search-forward re nil t)
12869 (setq key (org-match-string-no-properties 1)
12870 val (org-match-string-no-properties 2))
12871 (cond
12872 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
12873 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
12874 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
12875 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
12876 ((string-equal key "TEXT")
12877 (setq text (if text (concat text "\n" val) val)))
12878 ((string-equal key "OPTIONS") (setq options val))))
12879 (setq p (plist-put p :text text))
12880 (when options
12881 (let ((op '(("H" . :headline-levels)
12882 ("num" . :section-numbers)
12883 ("toc" . :table-of-contents)
12884 ("\\n" . :preserve-breaks)
12885 ("@" . :expand-quoted-html)
12886 (":" . :fixed-width)
12887 ("|" . :tables)
12888 ("^" . :sub-superscript)
12889 ("*" . :emphasize)
12890 ("TeX" . :TeX-macros)
12891 ("LaTeX" . :LaTeX-fragments)))
12893 (while (setq o (pop op))
12894 (if (string-match (concat (regexp-quote (car o))
12895 ":\\([^ \t\n\r;,.]*\\)")
12896 options)
12897 (setq p (plist-put p (cdr o)
12898 (car (read-from-string
12899 (match-string 1 options)))))))))
12900 p)))
12902 (defun org-combine-plists (&rest plists)
12903 "Create a single property list from all plists in PLISTS.
12904 The process starts by copying the last list, and then setting properties
12905 from the other lists. Settings in the first list are the most significant
12906 ones and overrule settings in the other lists."
12907 (let ((rtn (copy-sequence (pop plists)))
12908 p v ls)
12909 (while plists
12910 (setq ls (pop plists))
12911 (while ls
12912 (setq p (pop ls) v (pop ls))
12913 (setq rtn (plist-put rtn p v))))
12914 rtn))
12916 (defun org-export-directory (type plist)
12917 (let* ((val (plist-get plist :publishing-directory))
12918 (dir (if (listp val)
12919 (or (cdr (assoc type val)) ".")
12920 val)))
12921 dir))
12923 (defun org-export-find-first-heading-line (list)
12924 "Remove all lines from LIST which are before the first headline."
12925 (let ((orig-list list)
12926 (re (concat "^" outline-regexp)))
12927 (while (and list
12928 (not (string-match re (car list))))
12929 (pop list))
12930 (or list orig-list)))
12932 (defun org-skip-comments (lines)
12933 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
12934 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
12935 (re2 "^\\(\\*+\\)[ \t\n\r]")
12936 rtn line level)
12937 (while (setq line (pop lines))
12938 (cond
12939 ((and (string-match re1 line)
12940 (setq level (- (match-end 1) (match-beginning 1))))
12941 ;; Beginning of a COMMENT subtree. Skip it.
12942 (while (and (setq line (pop lines))
12943 (or (not (string-match re2 line))
12944 (> (- (match-end 1) (match-beginning 1)) level))))
12945 (setq lines (cons line lines)))
12946 ((string-match "^#" line)
12947 ;; an ordinary comment line
12949 ((and org-export-table-remove-special-lines
12950 (string-match "^[ \t]*|" line)
12951 (or (string-match "^[ \t]*| *[!_^] *|" line)
12952 (and (string-match "| *<[0-9]+> *|" line)
12953 (not (string-match "| *[^ <|]" line)))))
12954 ;; a special table line that should be removed
12956 (t (setq rtn (cons line rtn)))))
12957 (nreverse rtn)))
12959 (defun org-export (&optional arg)
12960 (interactive)
12961 (let ((help "[t] insert the export option template
12962 \[v] limit export to visible part of outline tree
12964 \[a] export as ASCII
12965 \[h] export as HTML
12966 \[b] export as HTML and browse immediately
12967 \[x] export as XOXO
12969 \[i] export current file as iCalendar file
12970 \[I] export all agenda files as iCalendar files
12971 \[c] export agenda files into combined iCalendar file
12973 \[F] publish current file
12974 \[P] publish current project
12975 \[X] publish... (project will be prompted for)
12976 \[A] publish all projects")
12977 (cmds
12978 '((?t . org-insert-export-options-template)
12979 (?v . org-export-visible)
12980 (?a . org-export-as-ascii)
12981 (?h . org-export-as-html)
12982 (?b . org-export-as-html-and-open)
12983 (?x . org-export-as-xoxo)
12984 (?i . org-export-icalendar-this-file)
12985 (?I . org-export-icalendar-all-agenda-files)
12986 (?c . org-export-icalendar-combine-agenda-files)
12987 (?F . org-publish-current-file)
12988 (?P . org-publish-current-project)
12989 (?X . org-publish)
12990 (?A . org-publish-all)))
12991 r1 r2 ass)
12992 (save-window-excursion
12993 (delete-other-windows)
12994 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
12995 (princ help))
12996 (message "Select command: ")
12997 (setq r1 (read-char-exclusive)))
12998 (setq r2 (if (< r1 27) (+ r1 96) r1))
12999 (if (setq ass (assq r2 cmds))
13000 (call-interactively (cdr ass))
13001 (error "No command associated with key %c" r1))))
13003 ;; ASCII
13005 (defconst org-html-entities
13006 '(("nbsp")
13007 ("iexcl")
13008 ("cent")
13009 ("pound")
13010 ("curren")
13011 ("yen")
13012 ("brvbar")
13013 ("sect")
13014 ("uml")
13015 ("copy")
13016 ("ordf")
13017 ("laquo")
13018 ("not")
13019 ("shy")
13020 ("reg")
13021 ("macr")
13022 ("deg")
13023 ("plusmn")
13024 ("sup2")
13025 ("sup3")
13026 ("acute")
13027 ("micro")
13028 ("para")
13029 ("middot")
13030 ("odot"."o")
13031 ("star"."*")
13032 ("cedil")
13033 ("sup1")
13034 ("ordm")
13035 ("raquo")
13036 ("frac14")
13037 ("frac12")
13038 ("frac34")
13039 ("iquest")
13040 ("Agrave")
13041 ("Aacute")
13042 ("Acirc")
13043 ("Atilde")
13044 ("Auml")
13045 ("Aring") ("AA"."&Aring;")
13046 ("AElig")
13047 ("Ccedil")
13048 ("Egrave")
13049 ("Eacute")
13050 ("Ecirc")
13051 ("Euml")
13052 ("Igrave")
13053 ("Iacute")
13054 ("Icirc")
13055 ("Iuml")
13056 ("ETH")
13057 ("Ntilde")
13058 ("Ograve")
13059 ("Oacute")
13060 ("Ocirc")
13061 ("Otilde")
13062 ("Ouml")
13063 ("times")
13064 ("Oslash")
13065 ("Ugrave")
13066 ("Uacute")
13067 ("Ucirc")
13068 ("Uuml")
13069 ("Yacute")
13070 ("THORN")
13071 ("szlig")
13072 ("agrave")
13073 ("aacute")
13074 ("acirc")
13075 ("atilde")
13076 ("auml")
13077 ("aring")
13078 ("aelig")
13079 ("ccedil")
13080 ("egrave")
13081 ("eacute")
13082 ("ecirc")
13083 ("euml")
13084 ("igrave")
13085 ("iacute")
13086 ("icirc")
13087 ("iuml")
13088 ("eth")
13089 ("ntilde")
13090 ("ograve")
13091 ("oacute")
13092 ("ocirc")
13093 ("otilde")
13094 ("ouml")
13095 ("divide")
13096 ("oslash")
13097 ("ugrave")
13098 ("uacute")
13099 ("ucirc")
13100 ("uuml")
13101 ("yacute")
13102 ("thorn")
13103 ("yuml")
13104 ("fnof")
13105 ("Alpha")
13106 ("Beta")
13107 ("Gamma")
13108 ("Delta")
13109 ("Epsilon")
13110 ("Zeta")
13111 ("Eta")
13112 ("Theta")
13113 ("Iota")
13114 ("Kappa")
13115 ("Lambda")
13116 ("Mu")
13117 ("Nu")
13118 ("Xi")
13119 ("Omicron")
13120 ("Pi")
13121 ("Rho")
13122 ("Sigma")
13123 ("Tau")
13124 ("Upsilon")
13125 ("Phi")
13126 ("Chi")
13127 ("Psi")
13128 ("Omega")
13129 ("alpha")
13130 ("beta")
13131 ("gamma")
13132 ("delta")
13133 ("epsilon")
13134 ("varepsilon"."&epsilon;")
13135 ("zeta")
13136 ("eta")
13137 ("theta")
13138 ("iota")
13139 ("kappa")
13140 ("lambda")
13141 ("mu")
13142 ("nu")
13143 ("xi")
13144 ("omicron")
13145 ("pi")
13146 ("rho")
13147 ("sigmaf") ("varsigma"."&sigmaf;")
13148 ("sigma")
13149 ("tau")
13150 ("upsilon")
13151 ("phi")
13152 ("chi")
13153 ("psi")
13154 ("omega")
13155 ("thetasym") ("vartheta"."&thetasym;")
13156 ("upsih")
13157 ("piv")
13158 ("bull") ("bullet"."&bull;")
13159 ("hellip") ("dots"."&hellip;")
13160 ("prime")
13161 ("Prime")
13162 ("oline")
13163 ("frasl")
13164 ("weierp")
13165 ("image")
13166 ("real")
13167 ("trade")
13168 ("alefsym")
13169 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
13170 ("uarr") ("uparrow"."&uarr;")
13171 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
13172 ("darr")("downarrow"."&darr;")
13173 ("harr") ("leftrightarrow"."&harr;")
13174 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
13175 ("lArr") ("Leftarrow"."&lArr;")
13176 ("uArr") ("Uparrow"."&uArr;")
13177 ("rArr") ("Rightarrow"."&rArr;")
13178 ("dArr") ("Downarrow"."&dArr;")
13179 ("hArr") ("Leftrightarrow"."&hArr;")
13180 ("forall")
13181 ("part") ("partial"."&part;")
13182 ("exist") ("exists"."&exist;")
13183 ("empty") ("emptyset"."&empty;")
13184 ("nabla")
13185 ("isin") ("in"."&isin;")
13186 ("notin")
13187 ("ni")
13188 ("prod")
13189 ("sum")
13190 ("minus")
13191 ("lowast") ("ast"."&lowast;")
13192 ("radic")
13193 ("prop") ("proptp"."&prop;")
13194 ("infin") ("infty"."&infin;")
13195 ("ang") ("angle"."&ang;")
13196 ("and") ("vee"."&and;")
13197 ("or") ("wedge"."&or;")
13198 ("cap")
13199 ("cup")
13200 ("int")
13201 ("there4")
13202 ("sim")
13203 ("cong") ("simeq"."&cong;")
13204 ("asymp")("approx"."&asymp;")
13205 ("ne") ("neq"."&ne;")
13206 ("equiv")
13207 ("le")
13208 ("ge")
13209 ("sub") ("subset"."&sub;")
13210 ("sup") ("supset"."&sup;")
13211 ("nsub")
13212 ("sube")
13213 ("supe")
13214 ("oplus")
13215 ("otimes")
13216 ("perp")
13217 ("sdot") ("cdot"."&sdot;")
13218 ("lceil")
13219 ("rceil")
13220 ("lfloor")
13221 ("rfloor")
13222 ("lang")
13223 ("rang")
13224 ("loz") ("Diamond"."&loz;")
13225 ("spades") ("spadesuit"."&spades;")
13226 ("clubs") ("clubsuit"."&clubs;")
13227 ("hearts") ("diamondsuit"."&hearts;")
13228 ("diams") ("diamondsuit"."&diams;")
13229 ("quot")
13230 ("amp")
13231 ("lt")
13232 ("gt")
13233 ("OElig")
13234 ("oelig")
13235 ("Scaron")
13236 ("scaron")
13237 ("Yuml")
13238 ("circ")
13239 ("tilde")
13240 ("ensp")
13241 ("emsp")
13242 ("thinsp")
13243 ("zwnj")
13244 ("zwj")
13245 ("lrm")
13246 ("rlm")
13247 ("ndash")
13248 ("mdash")
13249 ("lsquo")
13250 ("rsquo")
13251 ("sbquo")
13252 ("ldquo")
13253 ("rdquo")
13254 ("bdquo")
13255 ("dagger")
13256 ("Dagger")
13257 ("permil")
13258 ("lsaquo")
13259 ("rsaquo")
13260 ("euro")
13262 ("arccos"."arccos")
13263 ("arcsin"."arcsin")
13264 ("arctan"."arctan")
13265 ("arg"."arg")
13266 ("cos"."cos")
13267 ("cosh"."cosh")
13268 ("cot"."cot")
13269 ("coth"."coth")
13270 ("csc"."csc")
13271 ("deg"."deg")
13272 ("det"."det")
13273 ("dim"."dim")
13274 ("exp"."exp")
13275 ("gcd"."gcd")
13276 ("hom"."hom")
13277 ("inf"."inf")
13278 ("ker"."ker")
13279 ("lg"."lg")
13280 ("lim"."lim")
13281 ("liminf"."liminf")
13282 ("limsup"."limsup")
13283 ("ln"."ln")
13284 ("log"."log")
13285 ("max"."max")
13286 ("min"."min")
13287 ("Pr"."Pr")
13288 ("sec"."sec")
13289 ("sin"."sin")
13290 ("sinh"."sinh")
13291 ("sup"."sup")
13292 ("tan"."tan")
13293 ("tanh"."tanh")
13295 "Entities for TeX->HTML translation.
13296 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
13297 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
13298 In that case, \"\\ent\" will be translated to \"&other;\".
13299 The list contains HTML entities for Latin-1, Greek and other symbols.
13300 It is supplemented by a number of commonly used TeX macros with appropriate
13301 translations. There is currently no way for users to extend this.")
13303 (defun org-cleaned-string-for-export (string &rest parameters)
13304 "Cleanup a buffer substring so that links can be created safely."
13305 (interactive)
13306 (let* ((re-radio (and org-target-link-regexp
13307 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
13308 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
13309 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
13310 (re-archive (concat ":" org-archive-tag ":"))
13311 rtn)
13312 (save-excursion
13313 (set-buffer (get-buffer-create " org-mode-tmp"))
13314 (erase-buffer)
13315 (insert string)
13316 (let ((org-inhibit-startup t)) (org-mode))
13318 ;; Get rid of archived trees
13319 (when (not (eq org-export-with-archived-trees t))
13320 (goto-char (point-min))
13321 (while (re-search-forward re-archive nil t)
13322 (if (not (org-on-heading-p))
13323 (org-end-of-subtree t)
13324 (beginning-of-line 1)
13325 (delete-region
13326 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
13327 (org-end-of-subtree)))))
13329 ;; Find targets in comments and move them out of comments,
13330 ;; but mark them as targets that should be invisible
13331 (goto-char (point-min))
13332 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
13333 (replace-match "\\1(INVISIBLE)"))
13335 ;; Find matches for radio targets and turn them into internal links
13336 (goto-char (point-min))
13337 (when re-radio
13338 (while (re-search-forward re-radio nil t)
13339 (replace-match "\\1[[\\2]]")))
13341 ;; Find all links that contain a newline and put them into a single line
13342 (goto-char (point-min))
13343 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
13344 (replace-match "\\1 \\3")
13345 (goto-char (match-beginning 0)))
13347 ;; Convert LaTeX fragments to images
13348 (when (memq :LaTeX-fragments parameters)
13349 (org-format-latex
13350 (concat "ltxpng/" (file-name-sans-extension
13351 (file-name-nondirectory
13352 org-current-export-file)))
13353 org-current-export-dir nil "Creating LaTeX image %s"))
13354 (message "Exporting...")
13356 ;; Normalize links: Convert angle and plain links into bracket links
13357 (goto-char (point-min))
13358 (while (re-search-forward re-plain-link nil t)
13359 (replace-match
13360 (concat
13361 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13362 t t))
13363 (goto-char (point-min))
13364 (while (re-search-forward re-angle-link nil t)
13365 (replace-match
13366 (concat
13367 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13368 t t))
13370 ;; Find multiline emphasis and put them into single line
13371 (when (memq :emph-multiline parameters)
13372 (goto-char (point-min))
13373 (while (re-search-forward org-emph-re nil t)
13374 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
13375 (goto-char (1- (match-end 0)))))
13377 ;; Remove comments
13378 (goto-char (point-min))
13379 (while (re-search-forward "^#.*\n?" nil t)
13380 (replace-match ""))
13381 (setq rtn (buffer-string)))
13382 (kill-buffer " org-mode-tmp")
13383 rtn))
13385 (defun org-solidify-link-text (s &optional alist)
13386 "Take link text and make a safe target out of it."
13387 (save-match-data
13388 (let* ((rtn
13389 (mapconcat
13390 'identity
13391 (org-split-string s "[ \t\r\n]+") "--"))
13392 (a (assoc rtn alist)))
13393 (or (cdr a) rtn))))
13395 (defun org-convert-to-odd-levels ()
13396 "Convert an org-mode file with all levels allowed to one with odd levels.
13397 This will leave level 1 alone, convert level 2 to level 3, level 3 to
13398 level 5 etc."
13399 (interactive)
13400 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
13401 (let ((org-odd-levels-only nil) n)
13402 (save-excursion
13403 (goto-char (point-min))
13404 (while (re-search-forward "^\\*\\*+" nil t)
13405 (setq n (1- (length (match-string 0))))
13406 (while (>= (setq n (1- n)) 0)
13407 (org-demote))
13408 (end-of-line 1))))))
13411 (defun org-convert-to-oddeven-levels ()
13412 "Convert an org-mode file with only odd levels to one with odd and even levels.
13413 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
13414 section with an even level, conversion would destroy the structure of the file. An error
13415 is signaled in this case."
13416 (interactive)
13417 (goto-char (point-min))
13418 ;; First check if there are no even levels
13419 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
13420 (org-show-hierarchy-above)
13421 (error "Not all levels are odd in this file. Conversion not possible."))
13422 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
13423 (let ((org-odd-levels-only nil) n)
13424 (save-excursion
13425 (goto-char (point-min))
13426 (while (re-search-forward "^\\*\\*+" nil t)
13427 (setq n (/ (length (match-string 0)) 2))
13428 (while (>= (setq n (1- n)) 0)
13429 (org-promote))
13430 (end-of-line 1))))))
13432 (defun org-tr-level (n)
13433 "Make N odd if required."
13434 (if org-odd-levels-only (1+ (/ n 2)) n))
13436 (defvar org-last-level nil) ; dynamically scoped variable
13437 (defvar org-ascii-current-indentation nil) ; For communication
13439 (defun org-export-as-ascii (arg)
13440 "Export the outline as a pretty ASCII file.
13441 If there is an active region, export only the region.
13442 The prefix ARG specifies how many levels of the outline should become
13443 underlined headlines. The default is 3."
13444 (interactive "P")
13445 (setq-default org-todo-line-regexp org-todo-line-regexp)
13446 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13447 (org-infile-export-plist)))
13448 (region
13449 (buffer-substring
13450 (if (org-region-active-p) (region-beginning) (point-min))
13451 (if (org-region-active-p) (region-end) (point-max))))
13452 (lines (org-export-find-first-heading-line
13453 (org-skip-comments
13454 (org-split-string
13455 (org-cleaned-string-for-export region)
13456 "[\r\n]"))))
13457 (org-ascii-current-indentation '(0 . 0))
13458 (org-startup-with-deadline-check nil)
13459 (level 0) line txt
13460 (umax nil)
13461 (case-fold-search nil)
13462 (filename (concat (file-name-as-directory
13463 (org-export-directory :ascii opt-plist))
13464 (file-name-sans-extension
13465 (file-name-nondirectory buffer-file-name))
13466 ".txt"))
13467 (buffer (find-file-noselect filename))
13468 (levels-open (make-vector org-level-max nil))
13469 (odd org-odd-levels-only)
13470 (date (format-time-string "%Y/%m/%d" (current-time)))
13471 (time (format-time-string "%X" (org-current-time)))
13472 (author (plist-get opt-plist :author))
13473 (title (or (plist-get opt-plist :title)
13474 (file-name-sans-extension
13475 (file-name-nondirectory buffer-file-name))))
13476 (email (plist-get opt-plist :email))
13477 (language (plist-get opt-plist :language))
13478 (text nil)
13479 (todo nil)
13480 (lang-words nil))
13482 (setq org-last-level 1)
13483 (org-init-section-numbers)
13485 (find-file-noselect filename)
13487 (setq lang-words (or (assoc language org-export-language-setup)
13488 (assoc "en" org-export-language-setup)))
13489 (if org-export-ascii-show-new-buffer
13490 (switch-to-buffer-other-window buffer)
13491 (set-buffer buffer))
13492 (erase-buffer)
13493 (fundamental-mode)
13494 ;; create local variables for all options, to make sure all called
13495 ;; functions get the correct information
13496 (mapcar (lambda (x)
13497 (set (make-local-variable (cdr x))
13498 (plist-get opt-plist (car x))))
13499 org-export-plist-vars)
13500 (org-set-local 'org-odd-levels-only odd)
13501 (setq umax (if arg (prefix-numeric-value arg)
13502 org-export-headline-levels))
13504 ;; File header
13505 (if title (org-insert-centered title ?=))
13506 (insert "\n")
13507 (if (or author email)
13508 (insert (concat (nth 1 lang-words) ": " (or author "")
13509 (if email (concat " <" email ">") "")
13510 "\n")))
13511 (if (and date time)
13512 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
13513 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
13515 (insert "\n\n")
13517 (if org-export-with-toc
13518 (progn
13519 (insert (nth 3 lang-words) "\n"
13520 (make-string (length (nth 3 lang-words)) ?=) "\n")
13521 (mapcar '(lambda (line)
13522 (if (string-match org-todo-line-regexp
13523 line)
13524 ;; This is a headline
13525 (progn
13526 (setq level (- (match-end 1) (match-beginning 1))
13527 level (org-tr-level level)
13528 txt (match-string 3 line)
13529 todo
13530 (or (and org-export-mark-todo-in-toc
13531 (match-beginning 2)
13532 (not (equal (match-string 2 line)
13533 org-done-string)))
13534 ; TODO, not DONE
13535 (and org-export-mark-todo-in-toc
13536 (= level umax)
13537 (org-search-todo-below
13538 line lines level))))
13539 (setq txt (org-html-expand-for-ascii txt))
13541 (if org-export-with-section-numbers
13542 (setq txt (concat (org-section-number level)
13543 " " txt)))
13544 (if (<= level umax)
13545 (progn
13546 (insert
13547 (make-string (* (1- level) 4) ?\ )
13548 (format (if todo "%s (*)\n" "%s\n") txt))
13549 (setq org-last-level level))
13550 ))))
13551 lines)))
13553 (org-init-section-numbers)
13554 (while (setq line (pop lines))
13555 ;; Remove the quoted HTML tags.
13556 (setq line (org-html-expand-for-ascii line))
13557 ;; Remove targets
13558 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
13559 (setq line (replace-match "" t t line)))
13560 ;; Replace internal links
13561 (while (string-match org-bracket-link-regexp line)
13562 (setq line (replace-match
13563 (if (match-end 3) "[\\3]" "[\\1]")
13564 t nil line)))
13565 (cond
13566 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13567 ;; a Headline
13568 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13569 txt (match-string 2 line))
13570 (org-ascii-level-start level txt umax lines))
13572 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
13573 (normal-mode)
13574 (save-buffer)
13575 ;; remove display and invisible chars
13576 (let (beg end)
13577 (goto-char (point-min))
13578 (while (setq beg (next-single-property-change (point) 'display))
13579 (setq end (next-single-property-change beg 'display))
13580 (delete-region beg end)
13581 (goto-char beg)
13582 (insert "=>"))
13583 (goto-char (point-min))
13584 (while (setq beg (next-single-property-change (point) 'org-cwidth))
13585 (setq end (next-single-property-change beg 'org-cwidth))
13586 (delete-region beg end)
13587 (goto-char beg)))
13588 (goto-char (point-min))))
13590 (defun org-search-todo-below (line lines level)
13591 "Search the subtree below LINE for any TODO entries."
13592 (let ((rest (cdr (memq line lines)))
13593 (re org-todo-line-regexp)
13594 line lv todo)
13595 (catch 'exit
13596 (while (setq line (pop rest))
13597 (if (string-match re line)
13598 (progn
13599 (setq lv (- (match-end 1) (match-beginning 1))
13600 todo (and (match-beginning 2)
13601 (not (equal (match-string 2 line)
13602 org-done-string))))
13603 ; TODO, not DONE
13604 (if (<= lv level) (throw 'exit nil))
13605 (if todo (throw 'exit t))))))))
13607 (defun org-html-expand-for-ascii (line)
13608 "Handle quoted HTML for ASCII export."
13609 (if org-export-html-expand
13610 (while (string-match "@<[^<>\n]*>" line)
13611 ;; We just remove the tags for now.
13612 (setq line (replace-match "" nil nil line))))
13613 line)
13615 (defun org-insert-centered (s &optional underline)
13616 "Insert the string S centered and underline it with character UNDERLINE."
13617 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
13618 (insert (make-string ind ?\ ) s "\n")
13619 (if underline
13620 (insert (make-string ind ?\ )
13621 (make-string (string-width s) underline)
13622 "\n"))))
13624 (defun org-ascii-level-start (level title umax &optional lines)
13625 "Insert a new level in ASCII export."
13626 (let (char (n (- level umax 1)) (ind 0))
13627 (if (> level umax)
13628 (progn
13629 (insert (make-string (* 2 n) ?\ )
13630 (char-to-string (nth (% n (length org-export-ascii-bullets))
13631 org-export-ascii-bullets))
13632 " " title "\n")
13633 ;; find the indentation of the next non-empty line
13634 (catch 'stop
13635 (while lines
13636 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
13637 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
13638 (throw 'stop (setq ind (org-get-indentation (car lines)))))
13639 (pop lines)))
13640 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
13641 (if (or (not (equal (char-before) ?\n))
13642 (not (equal (char-before (1- (point))) ?\n)))
13643 (insert "\n"))
13644 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
13645 (if org-export-with-section-numbers
13646 (setq title (concat (org-section-number level) " " title)))
13647 (insert title "\n" (make-string (string-width title) char) "\n")
13648 (setq org-ascii-current-indentation '(0 . 0)))))
13650 (defun org-export-visible (type arg)
13651 "Create a copy of the visible part of the current buffer, and export it.
13652 The copy is created in a temporary buffer and removed after use.
13653 TYPE is the final key (as a string) that also select the export command in
13654 the `C-c C-e' export dispatcher.
13655 As a special case, if the you type SPC at the prompt, the temporary
13656 org-mode file will not be removed but presented to you so that you can
13657 continue to use it. The prefix arg ARG is passed through to the exporting
13658 command."
13659 (interactive
13660 (list (progn
13661 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
13662 (read-char-exclusive))
13663 current-prefix-arg))
13664 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
13665 (error "Invalid export key"))
13666 (let* ((binding (cdr (assoc type
13667 '((?a . org-export-as-ascii)
13668 (?\C-a . org-export-as-ascii)
13669 (?b . org-export-as-html-and-open)
13670 (?\C-b . org-export-as-html-and-open)
13671 (?h . org-export-as-html)
13672 (?x . org-export-as-xoxo)))))
13673 (keepp (equal type ?\ ))
13674 (file buffer-file-name)
13675 (buffer (get-buffer-create "*Org Export Visible*"))
13676 s e)
13677 (with-current-buffer buffer (erase-buffer))
13678 (save-excursion
13679 (setq s (goto-char (point-min)))
13680 (while (not (= (point) (point-max)))
13681 (goto-char (org-find-invisible))
13682 (append-to-buffer buffer s (point))
13683 (setq s (goto-char (org-find-visible))))
13684 (goto-char (point-min))
13685 (unless keepp
13686 ;; Copy all comment lines to the end, to make sure #+ settings are
13687 ;; still available for the second export step. Kind of a hack, but
13688 ;; does do the trick.
13689 (if (looking-at "#[^\r\n]*")
13690 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
13691 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
13692 (append-to-buffer buffer (1+ (match-beginning 0))
13693 (min (point-max) (1+ (match-end 0))))))
13694 (set-buffer buffer)
13695 (let ((buffer-file-name file)
13696 (org-inhibit-startup t))
13697 (org-mode)
13698 (show-all)
13699 (unless keepp (funcall binding arg))))
13700 (if (not keepp)
13701 (kill-buffer buffer)
13702 (switch-to-buffer-other-window buffer)
13703 (goto-char (point-min)))))
13705 (defun org-find-visible ()
13706 (let ((s (point)))
13707 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13708 (get-char-property s 'invisible)))
13710 (defun org-find-invisible ()
13711 (let ((s (point)))
13712 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13713 (not (get-char-property s 'invisible))))
13716 ;; HTML
13718 (defun org-get-current-options ()
13719 "Return a string with current options as keyword options.
13720 Does include HTML export options as well as TODO and CATEGORY stuff."
13721 (format
13722 "#+TITLE: %s
13723 #+AUTHOR: %s
13724 #+EMAIL: %s
13725 #+LANGUAGE: %s
13726 #+TEXT: Some descriptive text to be emitted. Several lines OK.
13727 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
13728 #+CATEGORY: %s
13729 #+SEQ_TODO: %s
13730 #+TYP_TODO: %s
13731 #+STARTUP: %s %s %s %s %s %s
13732 #+TAGS: %s
13733 #+ARCHIVE: %s
13735 (buffer-name) (user-full-name) user-mail-address org-export-default-language
13736 org-export-headline-levels
13737 org-export-with-section-numbers
13738 org-export-with-toc
13739 org-export-preserve-breaks
13740 org-export-html-expand
13741 org-export-with-fixed-width
13742 org-export-with-tables
13743 org-export-with-sub-superscripts
13744 org-export-with-emphasize
13745 org-export-with-TeX-macros
13746 org-export-with-LaTeX-fragments
13747 (file-name-nondirectory buffer-file-name)
13748 (if (equal org-todo-interpretation 'sequence)
13749 (mapconcat 'identity org-todo-keywords " ")
13750 "TODO FEEDBACK VERIFY DONE")
13751 (if (equal org-todo-interpretation 'type)
13752 (mapconcat 'identity org-todo-keywords " ")
13753 "Me Jason Marie DONE")
13754 (cdr (assoc org-startup-folded
13755 '((nil . "showall") (t . "overview") (content . "content"))))
13756 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
13757 (if org-odd-levels-only "odd" "oddeven")
13758 (if org-hide-leading-stars "hidestars" "showstars")
13759 (if org-startup-align-all-tables "align" "noalign")
13760 (if org-log-done "logging" "nologging")
13761 (if org-tag-alist (mapconcat 'car org-tag-alist " ") "")
13762 org-archive-location
13765 (defun org-insert-export-options-template ()
13766 "Insert into the buffer a template with information for exporting."
13767 (interactive)
13768 (if (not (bolp)) (newline))
13769 (let ((s (org-get-current-options)))
13770 (and (string-match "#\\+CATEGORY" s)
13771 (setq s (substring s 0 (match-beginning 0))))
13772 (insert s)))
13774 (defun org-toggle-fixed-width-section (arg)
13775 "Toggle the fixed-width export.
13776 If there is no active region, the QUOTE keyword at the current headline is
13777 inserted or removed. When present, it causes the text between this headline
13778 and the next to be exported as fixed-width text, and unmodified.
13779 If there is an active region, this command adds or removes a colon as the
13780 first character of this line. If the first character of a line is a colon,
13781 this line is also exported in fixed-width font."
13782 (interactive "P")
13783 (let* ((cc 0)
13784 (regionp (org-region-active-p))
13785 (beg (if regionp (region-beginning) (point)))
13786 (end (if regionp (region-end)))
13787 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13788 (re "[ \t]*\\(:\\)")
13789 off)
13790 (if regionp
13791 (save-excursion
13792 (goto-char beg)
13793 (setq cc (current-column))
13794 (beginning-of-line 1)
13795 (setq off (looking-at re))
13796 (while (> nlines 0)
13797 (setq nlines (1- nlines))
13798 (beginning-of-line 1)
13799 (cond
13800 (arg
13801 (move-to-column cc t)
13802 (insert ":\n")
13803 (forward-line -1))
13804 ((and off (looking-at re))
13805 (replace-match "" t t nil 1))
13806 ((not off) (move-to-column cc t) (insert ":")))
13807 (forward-line 1)))
13808 (save-excursion
13809 (org-back-to-heading)
13810 (if (looking-at (concat outline-regexp
13811 "\\( +\\<" org-quote-string "\\>\\)"))
13812 (replace-match "" t t nil 1)
13813 (if (looking-at outline-regexp)
13814 (progn
13815 (goto-char (match-end 0))
13816 (insert " " org-quote-string))))))))
13818 (defun org-export-as-html-and-open (arg)
13819 "Export the outline as HTML and immediately open it with a browser.
13820 If there is an active region, export only the region.
13821 The prefix ARG specifies how many levels of the outline should become
13822 headlines. The default is 3. Lower levels will become bulleted lists."
13823 (interactive "P")
13824 (org-export-as-html arg 'hidden)
13825 (org-open-file buffer-file-name))
13827 (defun org-export-as-html-batch ()
13828 "Call `org-export-as-html', may be used in batch processing as
13829 emacs --batch
13830 --load=$HOME/lib/emacs/org.el
13831 --eval \"(setq org-export-headline-levels 2)\"
13832 --visit=MyFile --funcall org-export-as-html-batch"
13833 (org-export-as-html org-export-headline-levels 'hidden))
13835 (defun org-export-as-html (arg &optional hidden ext-plist)
13836 "Export the outline as a pretty HTML file.
13837 If there is an active region, export only the region.
13838 The prefix ARG specifies how many levels of the outline should become
13839 headlines. The default is 3. Lower levels will become bulleted lists.
13840 When HIDDEN is non-nil, don't display the HTML buffer.
13841 EXT-PLIST is a property list with external parameters overriding
13842 org-mode's default settings, but still inferior to file-local settings."
13843 (interactive "P")
13844 (message "Exporting...")
13845 (setq-default org-todo-line-regexp org-todo-line-regexp)
13846 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
13847 (setq-default org-done-string org-done-string)
13848 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13849 ext-plist
13850 (org-infile-export-plist)))
13852 (style (plist-get opt-plist :style))
13853 (link-validate (plist-get opt-plist :link-validation-function))
13854 valid
13855 (odd org-odd-levels-only)
13856 (region-p (org-region-active-p))
13857 (region
13858 (buffer-substring
13859 (if region-p (region-beginning) (point-min))
13860 (if region-p (region-end) (point-max))))
13861 ;; The following two are dynamically scoped into other
13862 ;; routines below.
13863 (org-current-export-dir (org-export-directory :html opt-plist))
13864 (org-current-export-file buffer-file-name)
13865 (all_lines
13866 (org-skip-comments (org-split-string
13867 (org-cleaned-string-for-export
13868 region :emph-multiline
13869 (if (plist-get opt-plist :LaTeX-fragments)
13870 :LaTeX-fragments))
13871 "[\r\n]")))
13872 (lines (org-export-find-first-heading-line all_lines))
13873 (level 0) (line "") (origline "") txt todo
13874 (umax nil)
13875 (filename (concat (file-name-as-directory
13876 (org-export-directory :html opt-plist))
13877 (file-name-sans-extension
13878 (file-name-nondirectory buffer-file-name))
13879 ".html"))
13880 (current-dir (file-name-directory buffer-file-name))
13881 (buffer (find-file-noselect filename))
13882 (levels-open (make-vector org-level-max nil))
13883 (date (format-time-string "%Y/%m/%d" (current-time)))
13884 (time (format-time-string "%X" (org-current-time)))
13885 (author (plist-get opt-plist :author))
13886 (title (or (plist-get opt-plist :title)
13887 (file-name-sans-extension
13888 (file-name-nondirectory buffer-file-name))))
13889 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
13890 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
13891 (inquote nil)
13892 (infixed nil)
13893 (in-local-list nil)
13894 (local-list-num nil)
13895 (local-list-indent nil)
13896 (llt org-plain-list-ordered-item-terminator)
13897 (email (plist-get opt-plist :email))
13898 (language (plist-get opt-plist :language))
13899 (text (plist-get opt-plist :text))
13900 (lang-words nil)
13901 (target-alist nil) tg
13902 (head-count 0) cnt
13903 (start 0)
13904 (coding-system (and (fboundp 'coding-system-get)
13905 (boundp 'buffer-file-coding-system)
13906 buffer-file-coding-system))
13907 (coding-system-for-write (or coding-system coding-system-for-write))
13908 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
13909 (charset (and coding-system
13910 (coding-system-get coding-system 'mime-charset)))
13911 table-open type
13912 table-buffer table-orig-buffer
13913 ind start-is-num starter
13914 rpl path desc descp desc1 desc2 link
13916 (message "Exporting...")
13918 (setq org-last-level 1)
13919 (org-init-section-numbers)
13921 ;; Get the language-dependent settings
13922 (setq lang-words (or (assoc language org-export-language-setup)
13923 (assoc "en" org-export-language-setup)))
13925 ;; Switch to the output buffer
13926 (if (or hidden (not org-export-html-show-new-buffer))
13927 (set-buffer buffer)
13928 (switch-to-buffer-other-window buffer))
13929 (erase-buffer)
13930 (fundamental-mode)
13931 (let ((case-fold-search nil)
13932 (org-odd-levels-only odd))
13933 ;; create local variables for all options, to make sure all called
13934 ;; functions get the correct information
13935 (mapcar (lambda (x)
13936 (set (make-local-variable (cdr x))
13937 (plist-get opt-plist (car x))))
13938 org-export-plist-vars)
13939 (setq umax (if arg (prefix-numeric-value arg)
13940 org-export-headline-levels))
13942 ;; File header
13943 (insert (format
13944 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
13945 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
13946 <html xmlns=\"http://www.w3.org/1999/xhtml\"
13947 lang=\"%s\" xml:lang=\"%s\">
13948 <head>
13949 <title>%s</title>
13950 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
13951 <meta name=\"generator\" content=\"Org-mode\"/>
13952 <meta name=\"generated\" content=\"%s %s\"/>
13953 <meta name=\"author\" content=\"%s\"/>
13955 </head><body>
13957 language language (org-html-expand title) (or charset "iso-8859-1")
13958 date time author style))
13961 (insert (or (plist-get opt-plist :preamble) ""))
13963 (when (plist-get opt-plist :auto-preamble)
13964 (if title (insert (format org-export-html-title-format
13965 (org-html-expand title))))
13966 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
13968 (if org-export-with-toc
13969 (progn
13970 (insert (format "<h%d>%s</h%d>\n"
13971 org-export-html-toplevel-hlevel
13972 (nth 3 lang-words)
13973 org-export-html-toplevel-hlevel))
13974 (insert "<ul>\n<li>")
13975 (setq lines
13976 (mapcar '(lambda (line)
13977 (if (string-match org-todo-line-regexp line)
13978 ;; This is a headline
13979 (progn
13980 (setq level (- (match-end 1) (match-beginning 1))
13981 level (org-tr-level level)
13982 txt (save-match-data
13983 (org-html-expand
13984 (org-export-cleanup-toc-line
13985 (match-string 3 line))))
13986 todo
13987 (or (and org-export-mark-todo-in-toc
13988 (match-beginning 2)
13989 (not (equal (match-string 2 line)
13990 org-done-string)))
13991 ; TODO, not DONE
13992 (and org-export-mark-todo-in-toc
13993 (= level umax)
13994 (org-search-todo-below
13995 line lines level))))
13996 (if org-export-with-section-numbers
13997 (setq txt (concat (org-section-number level)
13998 " " txt)))
13999 (if (<= level umax)
14000 (progn
14001 (setq head-count (+ head-count 1))
14002 (if (> level org-last-level)
14003 (progn
14004 (setq cnt (- level org-last-level))
14005 (while (>= (setq cnt (1- cnt)) 0)
14006 (insert "\n<ul>\n<li>"))
14007 (insert "\n")))
14008 (if (< level org-last-level)
14009 (progn
14010 (setq cnt (- org-last-level level))
14011 (while (>= (setq cnt (1- cnt)) 0)
14012 (insert "</li>\n</ul>"))
14013 (insert "\n")))
14014 ;; Check for targets
14015 (while (string-match org-target-regexp line)
14016 (setq tg (match-string 1 line)
14017 line (replace-match
14018 (concat "@<span class=\"target\">" tg "@</span> ")
14019 t t line))
14020 (push (cons (org-solidify-link-text tg)
14021 (format "sec-%d" head-count))
14022 target-alist))
14023 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
14024 (setq txt (replace-match "" t t txt)))
14025 (insert
14026 (format
14027 (if todo
14028 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
14029 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
14030 head-count txt))
14032 (setq org-last-level level))
14034 line)
14035 lines))
14036 (while (> org-last-level 0)
14037 (setq org-last-level (1- org-last-level))
14038 (insert "</li>\n</ul>\n"))
14040 (setq head-count 0)
14041 (org-init-section-numbers)
14043 (while (setq line (pop lines) origline line)
14044 (catch 'nextline
14046 ;; end of quote section?
14047 (when (and inquote (string-match "^\\*+" line))
14048 (insert "</pre>\n")
14049 (setq inquote nil))
14050 ;; inside a quote section?
14051 (when inquote
14052 (insert (org-html-protect line) "\n")
14053 (throw 'nextline nil))
14055 ;; verbatim lines
14056 (when (and org-export-with-fixed-width
14057 (string-match "^[ \t]*:\\(.*\\)" line))
14058 (when (not infixed)
14059 (setq infixed t)
14060 (insert "<pre>\n"))
14061 (insert (org-html-protect (match-string 1 line)) "\n")
14062 (when (and lines
14063 (not (string-match "^[ \t]*\\(:.*\\)"
14064 (car lines))))
14065 (setq infixed nil)
14066 (insert "</pre>\n"))
14067 (throw 'nextline nil))
14070 ;; make targets to anchors
14071 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
14072 (cond
14073 ((match-end 2)
14074 (setq line (replace-match
14075 (concat "@<a name=\""
14076 (org-solidify-link-text (match-string 1 line))
14077 "\">\\nbsp@</a>")
14078 t t line)))
14079 ((and org-export-with-toc (equal (string-to-char line) ?*))
14080 (setq line (replace-match
14081 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
14082 ; (concat "@<i>" (match-string 1 line) "@</i> ")
14083 t t line)))
14085 (setq line (replace-match
14086 (concat "@<a name=\""
14087 (org-solidify-link-text (match-string 1 line))
14088 "\" class=\"target\">" (match-string 1 line) "@</a> ")
14089 t t line)))))
14091 (setq line (org-html-handle-time-stamps line))
14093 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
14094 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
14095 ;; Also handle sub_superscripts and checkboxes
14096 (setq line (org-html-expand line))
14098 ;; Format the links
14099 (setq start 0)
14100 (while (string-match org-bracket-link-analytic-regexp line start)
14101 (setq start (match-beginning 0))
14102 (setq type (if (match-end 2) (match-string 2 line) "internal"))
14103 (setq path (match-string 3 line))
14104 (setq desc1 (if (match-end 5) (match-string 5 line))
14105 desc2 (if (match-end 2) (concat type ":" path) path)
14106 descp (and desc1 (not (equal desc1 desc2)))
14107 desc (or desc1 desc2))
14108 ;; FIXME: do we need to unescape here somewhere?
14109 (cond
14110 ((equal type "internal")
14111 (setq rpl
14112 (concat
14113 "<a href=\"#"
14114 (org-solidify-link-text path target-alist)
14115 "\">" desc "</a>")))
14116 ((member type '("http" "https" "ftp" "mailto" "news"))
14117 ;; standard URL
14118 (setq link (concat type ":" path))
14119 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
14120 ((string= type "file")
14121 ;; FILE link
14122 (let* ((filename path)
14123 (abs-p (file-name-absolute-p filename))
14124 thefile file-is-image-p search)
14125 (save-match-data
14126 (if (string-match "::\\(.*\\)" filename)
14127 (setq search (match-string 1 filename)
14128 filename (replace-match "" t nil filename)))
14129 (setq valid
14130 (if (functionp link-validate)
14131 (funcall link-validate filename current-dir)
14132 t))
14133 (setq file-is-image-p
14134 (string-match (org-image-file-name-regexp) filename))
14135 (setq thefile (if abs-p (expand-file-name filename) filename))
14136 (when (and org-export-html-link-org-files-as-html
14137 (string-match "\\.org$" thefile))
14138 (setq thefile (concat (substring thefile 0
14139 (match-beginning 0))
14140 ".html"))
14141 (if (and search
14142 ;; make sure this is can be used as target search
14143 (not (string-match "^[0-9]*$" search))
14144 (not (string-match "^\\*" search))
14145 (not (string-match "^/.*/$" search)))
14146 (setq thefile (concat thefile "#"
14147 (org-solidify-link-text
14148 (org-link-unescape search)))))
14149 (when (string-match "^file:" desc)
14150 (setq desc (replace-match "" t t desc))
14151 (if (string-match "\\.org$" desc)
14152 (setq desc (replace-match "" t t desc))))))
14153 (setq rpl (if (and file-is-image-p
14154 (or (eq t org-export-html-inline-images)
14155 (and org-export-html-inline-images
14156 (not descp))))
14157 (concat "<img src=\"" thefile "\"/>")
14158 (concat "<a href=\"" thefile "\">" desc "</a>")))
14159 (if (not valid) (setq rpl desc))))
14160 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
14161 (setq rpl (concat "<i>&lt;" type ":"
14162 (save-match-data (org-link-unescape path))
14163 "&gt;</i>"))))
14164 (setq line (replace-match rpl t t line)
14165 start (+ start (length rpl))))
14166 ;; TODO items
14167 (if (and (string-match org-todo-line-regexp line)
14168 (match-beginning 2))
14169 (if (equal (match-string 2 line) org-done-string)
14170 (setq line (replace-match
14171 "<span class=\"done\">\\2</span>"
14172 t nil line 2))
14173 (setq line (replace-match "<span class=\"todo\">\\2</span>"
14174 t nil line 2))))
14176 (cond
14177 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14178 ;; This is a headline
14179 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14180 txt (match-string 2 line))
14181 (if (string-match quote-re0 txt)
14182 (setq txt (replace-match "" t t txt)))
14183 (if (<= level umax) (setq head-count (+ head-count 1)))
14184 (when in-local-list
14185 ;; Close any local lists before inserting a new header line
14186 (while local-list-num
14187 (org-close-li)
14188 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14189 (pop local-list-num))
14190 (setq local-list-indent nil
14191 in-local-list nil))
14192 (org-html-level-start level txt umax
14193 (and org-export-with-toc (<= level umax))
14194 head-count)
14195 ;; QUOTES
14196 (when (string-match quote-re line)
14197 (insert "<pre>")
14198 (setq inquote t)))
14200 ((and org-export-with-tables
14201 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
14202 (if (not table-open)
14203 ;; New table starts
14204 (setq table-open t table-buffer nil table-orig-buffer nil))
14205 ;; Accumulate lines
14206 (setq table-buffer (cons line table-buffer)
14207 table-orig-buffer (cons origline table-orig-buffer))
14208 (when (or (not lines)
14209 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
14210 (car lines))))
14211 (setq table-open nil
14212 table-buffer (nreverse table-buffer)
14213 table-orig-buffer (nreverse table-orig-buffer))
14214 (org-close-par-maybe)
14215 (insert (org-format-table-html table-buffer table-orig-buffer))))
14217 ;; Normal lines
14218 (when (string-match
14219 (cond
14220 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14221 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14222 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14223 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
14224 line)
14225 (setq ind (org-get-string-indentation line)
14226 start-is-num (match-beginning 4)
14227 starter (if (match-beginning 2)
14228 (substring (match-string 2 line) 0 -1))
14229 line (substring line (match-beginning 5)))
14230 (unless (string-match "[^ \t]" line)
14231 ;; empty line. Pretend indentation is large.
14232 (setq ind (1+ (or (car local-list-indent) 1))))
14233 (while (and in-local-list
14234 (or (and (= ind (car local-list-indent))
14235 (not starter))
14236 (< ind (car local-list-indent))))
14237 (org-close-li)
14238 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14239 (pop local-list-num) (pop local-list-indent)
14240 (setq in-local-list local-list-indent))
14241 (cond
14242 ((and starter
14243 (or (not in-local-list)
14244 (> ind (car local-list-indent))))
14245 ;; Start new (level of ) list
14246 (org-close-par-maybe)
14247 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
14248 (push start-is-num local-list-num)
14249 (push ind local-list-indent)
14250 (setq in-local-list t))
14251 (starter
14252 ;; continue current list
14253 (org-close-li)
14254 (insert "<li>\n")))
14255 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
14256 (setq line
14257 (replace-match
14258 (if (equal (match-string 1 line) "X")
14259 "<b>[X]</b>"
14260 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
14261 t t line))))
14263 ;; Empty lines start a new paragraph. If hand-formatted lists
14264 ;; are not fully interpreted, lines starting with "-", "+", "*"
14265 ;; also start a new paragraph.
14266 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
14268 ;; Check if the line break needs to be conserved
14269 (cond
14270 ((string-match "\\\\\\\\[ \t]*$" line)
14271 (setq line (replace-match "<br/>" t t line)))
14272 (org-export-preserve-breaks
14273 (setq line (concat line "<br/>"))))
14275 (insert line "\n")))))
14277 ;; Properly close all local lists and other lists
14278 (when inquote (insert "</pre>\n"))
14279 (when in-local-list
14280 ;; Close any local lists before inserting a new header line
14281 (while local-list-num
14282 (org-close-li)
14283 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
14284 (pop local-list-num))
14285 (setq local-list-indent nil
14286 in-local-list nil))
14287 (org-html-level-start 1 nil umax
14288 (and org-export-with-toc (<= level umax))
14289 head-count)
14291 (when (plist-get opt-plist :auto-postamble)
14292 (when author
14293 (insert "<p class=\"author\"> "
14294 (nth 1 lang-words) ": " author "\n")
14295 (when email
14296 (insert "<a href=\"mailto:" email "\">&lt;"
14297 email "&gt;</a>\n"))
14298 (insert "</p>\n"))
14299 (when (and date time)
14300 (insert "<p class=\"date\"> "
14301 (nth 2 lang-words) ": "
14302 date " " time "</p>\n")))
14304 (if org-export-html-with-timestamp
14305 (insert org-export-html-html-helper-timestamp))
14306 (insert (or (plist-get opt-plist :postamble) ""))
14307 (insert "</body>\n</html>\n")
14308 (normal-mode)
14309 ;; remove empty paragraphs and lists
14310 (goto-char (point-min))
14311 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
14312 (replace-match ""))
14313 (goto-char (point-min))
14314 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
14315 (replace-match ""))
14316 (save-buffer)
14317 (goto-char (point-min))
14318 (message "Exporting... done"))))
14321 (defun org-format-table-html (lines olines)
14322 "Find out which HTML converter to use and return the HTML code."
14323 (if (string-match "^[ \t]*|" (car lines))
14324 ;; A normal org table
14325 (org-format-org-table-html lines)
14326 ;; Table made by table.el - test for spanning
14327 (let* ((hlines (delq nil (mapcar
14328 (lambda (x)
14329 (if (string-match "^[ \t]*\\+-" x) x
14330 nil))
14331 lines)))
14332 (first (car hlines))
14333 (ll (and (string-match "\\S-+" first)
14334 (match-string 0 first)))
14335 (re (concat "^[ \t]*" (regexp-quote ll)))
14336 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
14337 hlines))))
14338 (if (and (not spanning)
14339 (not org-export-prefer-native-exporter-for-tables))
14340 ;; We can use my own converter with HTML conversions
14341 (org-format-table-table-html lines)
14342 ;; Need to use the code generator in table.el, with the original text.
14343 (org-format-table-table-html-using-table-generate-source olines)))))
14345 (defun org-format-org-table-html (lines)
14346 "Format a table into HTML."
14347 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14348 (setq lines (nreverse lines))
14349 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14350 (setq lines (nreverse lines))
14351 (when org-export-table-remove-special-lines
14352 ;; Check if the table has a marking column. If yes remove the
14353 ;; column and the special lines
14354 (let* ((special
14355 (not
14356 (memq nil
14357 (mapcar
14358 (lambda (x)
14359 (or (string-match "^[ \t]*|-" x)
14360 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
14361 lines)))))
14362 (if special
14363 (setq lines
14364 (delq nil
14365 (mapcar
14366 (lambda (x)
14367 (if (string-match "^[ \t]*| *[!_^] *|" x)
14368 nil ; ignore this line
14369 (and (or (string-match "^[ \t]*|-+\\+" x)
14370 (string-match "^[ \t]*|[^|]*|" x))
14371 (replace-match "|" t t x))))
14372 lines))))))
14374 (let ((head (and org-export-highlight-first-table-line
14375 (delq nil (mapcar
14376 (lambda (x) (string-match "^[ \t]*|-" x))
14377 (cdr lines)))))
14378 line fields html)
14379 (setq html (concat org-export-html-table-tag "\n"))
14380 (while (setq line (pop lines))
14381 (catch 'next-line
14382 (if (string-match "^[ \t]*|-" line)
14383 (progn
14384 (setq head nil) ;; head ends here, first time around
14385 ;; ignore this line
14386 (throw 'next-line t)))
14387 ;; Break the line into fields
14388 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14389 (setq html (concat
14390 html
14391 "<tr>"
14392 (mapconcat (lambda (x)
14393 (if head
14394 (concat "<th>" x "</th>")
14395 (concat "<td>" x "</td>")))
14396 fields "")
14397 "</tr>\n"))))
14398 (setq html (concat html "</table>\n"))
14399 html))
14401 (defun org-fake-empty-table-line (line)
14402 "Replace everything except \"|\" with spaces."
14403 (let ((i (length line))
14404 (newstr (copy-sequence line)))
14405 (while (> i 0)
14406 (setq i (1- i))
14407 (if (not (eq (aref newstr i) ?|))
14408 (aset newstr i ?\ )))
14409 newstr))
14411 (defun org-format-table-table-html (lines)
14412 "Format a table generated by table.el into HTML.
14413 This conversion does *not* use `table-generate-source' from table.el.
14414 This has the advantage that Org-mode's HTML conversions can be used.
14415 But it has the disadvantage, that no cell- or row-spanning is allowed."
14416 (let (line field-buffer
14417 (head org-export-highlight-first-table-line)
14418 fields html empty)
14419 (setq html (concat org-export-html-table-tag "\n"))
14420 (while (setq line (pop lines))
14421 (setq empty "&nbsp;")
14422 (catch 'next-line
14423 (if (string-match "^[ \t]*\\+-" line)
14424 (progn
14425 (if field-buffer
14426 (progn
14427 (setq html (concat
14428 html
14429 "<tr>"
14430 (mapconcat
14431 (lambda (x)
14432 (if (equal x "") (setq x empty))
14433 (if head
14434 (concat "<th>" x "</th>\n")
14435 (concat "<td>" x "</td>\n")))
14436 field-buffer "\n")
14437 "</tr>\n"))
14438 (setq head nil)
14439 (setq field-buffer nil)))
14440 ;; Ignore this line
14441 (throw 'next-line t)))
14442 ;; Break the line into fields and store the fields
14443 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14444 (if field-buffer
14445 (setq field-buffer (mapcar
14446 (lambda (x)
14447 (concat x "<br/>" (pop fields)))
14448 field-buffer))
14449 (setq field-buffer fields))))
14450 (setq html (concat html "</table>\n"))
14451 html))
14453 (defun org-format-table-table-html-using-table-generate-source (lines)
14454 "Format a table into html, using `table-generate-source' from table.el.
14455 This has the advantage that cell- or row-spanning is allowed.
14456 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
14457 (require 'table)
14458 (with-current-buffer (get-buffer-create " org-tmp1 ")
14459 (erase-buffer)
14460 (insert (mapconcat 'identity lines "\n"))
14461 (goto-char (point-min))
14462 (if (not (re-search-forward "|[^+]" nil t))
14463 (error "Error processing table"))
14464 (table-recognize-table)
14465 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
14466 (table-generate-source 'html " org-tmp2 ")
14467 (set-buffer " org-tmp2 ")
14468 (buffer-substring (point-min) (point-max))))
14470 (defun org-html-handle-time-stamps (s)
14471 "Format time stamps in string S, or remove them."
14472 (catch 'exit
14473 (let (r b)
14474 (while (string-match org-maybe-keyword-time-regexp s)
14475 ;; FIXME: is it good to never export CLOCK, or do we need control?
14476 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
14477 (throw 'exit ""))
14478 (or b (setq b (substring s 0 (match-beginning 0))))
14479 (if (not org-export-with-timestamps)
14480 (setq r (concat r (substring s 0 (match-beginning 0)))
14481 s (substring s (match-end 0)))
14482 (setq r (concat
14483 r (substring s 0 (match-beginning 0))
14484 (if (match-end 1)
14485 (format "@<span class=\"timestamp-kwd\">%s @</span>"
14486 (match-string 1 s)))
14487 (format " @<span class=\"timestamp\">%s@</span>"
14488 (substring (match-string 3 s) 1 -1)))
14489 s (substring s (match-end 0)))))
14490 ;; Line break if line started and ended with time stamp stuff
14491 (if (not r)
14493 (setq r (concat r s))
14494 (unless (string-match "\\S-" (concat b s))
14495 (setq r (concat r "@<br/>")))
14496 r))))
14498 (defun org-html-protect (s)
14499 ;; convert & to &amp;, < to &lt; and > to &gt;
14500 (let ((start 0))
14501 (while (string-match "&" s start)
14502 (setq s (replace-match "&amp;" t t s)
14503 start (1+ (match-beginning 0))))
14504 (while (string-match "<" s)
14505 (setq s (replace-match "&lt;" t t s)))
14506 (while (string-match ">" s)
14507 (setq s (replace-match "&gt;" t t s))))
14510 (defun org-export-cleanup-toc-line (s)
14511 "Remove tags and time staps from lines going into the toc."
14512 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
14513 (setq s (replace-match "" t t s)))
14514 (when org-export-remove-timestamps-from-toc
14515 (while (string-match org-maybe-keyword-time-regexp s)
14516 (setq s (replace-match "" t t s))))
14519 (defun org-html-expand (string)
14520 "Prepare STRING for HTML export. Applies all active conversions.
14521 If there are links in the string, don't modify these."
14522 (let* (m s l res)
14523 (while (setq m (string-match org-bracket-link-regexp string))
14524 (setq s (substring string 0 m)
14525 l (match-string 0 string)
14526 string (substring string (match-end 0)))
14527 (push (org-html-do-expand s) res)
14528 (push l res))
14529 (push (org-html-do-expand string) res)
14530 (apply 'concat (nreverse res))))
14532 (defun org-html-do-expand (s)
14533 "Apply all active conversions to translate special ASCII to HTML."
14534 (setq s (org-html-protect s))
14535 (if org-export-html-expand
14536 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
14537 (setq s (replace-match "<\\1>" t nil s))))
14538 (if org-export-with-emphasize
14539 (setq s (org-export-html-convert-emphasize s)))
14540 (if org-export-with-sub-superscripts
14541 (setq s (org-export-html-convert-sub-super s)))
14542 (if org-export-with-TeX-macros
14543 (let ((start 0) wd ass)
14544 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
14545 (setq wd (match-string 1 s))
14546 (if (setq ass (assoc wd org-html-entities))
14547 (setq s (replace-match (or (cdr ass)
14548 (concat "&" (car ass) ";"))
14549 t t s))
14550 (setq start (+ start (length wd)))))))
14553 (defun org-create-multibrace-regexp (left right n)
14554 "Create a regular expression which will match a balanced sexp.
14555 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
14556 as single character strings.
14557 The regexp returned will match the entire expression including the
14558 delimiters. It will also define a single group which contains the
14559 match except for the outermost delimiters. The maximum depth of
14560 stacked delimiters is N. Escaping delimiters is not possible."
14561 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
14562 (or "\\|")
14563 (re nothing)
14564 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
14565 (while (> n 1)
14566 (setq n (1- n)
14567 re (concat re or next)
14568 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
14569 (concat left "\\(" re "\\)" right)))
14571 (defvar org-match-substring-regexp
14572 (concat
14573 "\\([^\\]\\)\\([_^]\\)\\("
14574 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
14575 "\\|"
14576 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
14577 "\\|"
14578 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
14579 "The regular expression matching a sub- or superscript.")
14581 (defun org-export-html-convert-sub-super (string)
14582 "Convert sub- and superscripts in STRING to HTML."
14583 (let (key c)
14584 (while (string-match org-match-substring-regexp string)
14585 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
14586 (setq c (or (match-string 8 string)
14587 (match-string 6 string)
14588 (match-string 5 string)))
14589 (setq string (replace-match
14590 (concat (match-string 1 string)
14591 "<" key ">" c "</" key ">")
14592 t t string)))
14593 (while (string-match "\\\\\\([_^]\\)" string)
14594 (setq string (replace-match (match-string 1 string) t t string))))
14595 string)
14597 (defun org-export-html-convert-emphasize (string)
14598 "Apply emphasis."
14599 (while (string-match org-emph-re string)
14600 (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)))
14601 string)
14603 (defvar org-par-open nil)
14604 (defun org-open-par ()
14605 "Insert <p>, but first close previous paragraph if any."
14606 (org-close-par-maybe)
14607 (insert "\n<p>")
14608 (setq org-par-open t))
14609 (defun org-close-par-maybe ()
14610 "Close paragraph if there is one open."
14611 (when org-par-open
14612 (insert "</p>")
14613 (setq org-par-open nil)))
14614 (defun org-close-li ()
14615 "Close <li> if necessary."
14616 (org-close-par-maybe)
14617 (insert "</li>\n"))
14618 ; (when (save-excursion
14619 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
14620 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
14621 ; (insert "</li>"))))
14623 (defun org-html-level-start (level title umax with-toc head-count)
14624 "Insert a new level in HTML export.
14625 When TITLE is nil, just close all open levels."
14626 (org-close-par-maybe)
14627 (let ((l (1+ (max level umax))))
14628 (while (<= l org-level-max)
14629 (if (aref levels-open (1- l))
14630 (progn
14631 (org-html-level-close l)
14632 (aset levels-open (1- l) nil)))
14633 (setq l (1+ l)))
14634 (when title
14635 ;; If title is nil, this means this function is called to close
14636 ;; all levels, so the rest is done only if title is given
14637 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14638 (setq title (replace-match
14639 (if org-export-with-tags
14640 (save-match-data
14641 (concat
14642 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
14643 (mapconcat 'identity (org-split-string
14644 (match-string 1 title) ":")
14645 "&nbsp;")
14646 "</span>"))
14648 t t title)))
14649 (if (> level umax)
14650 (progn
14651 (if (aref levels-open (1- level))
14652 (progn
14653 (org-close-li)
14654 (insert "<li>" title "<br/>\n"))
14655 (aset levels-open (1- level) t)
14656 (org-close-par-maybe)
14657 (insert "<ul>\n<li>" title "<br/>\n")))
14658 (if org-export-with-section-numbers
14659 (setq title (concat (org-section-number level) " " title)))
14660 (setq level (+ level org-export-html-toplevel-hlevel -1))
14661 (if with-toc
14662 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
14663 level head-count title level))
14664 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
14665 (org-open-par)))))
14667 (defun org-html-level-close (&rest args)
14668 "Terminate one level in HTML export."
14669 (org-close-li)
14670 (insert "</ul>"))
14672 ;; Variable holding the vector with section numbers
14673 (defvar org-section-numbers (make-vector org-level-max 0))
14675 (defun org-init-section-numbers ()
14676 "Initialize the vector for the section numbers."
14677 (let* ((level -1)
14678 (numbers (nreverse (org-split-string "" "\\.")))
14679 (depth (1- (length org-section-numbers)))
14680 (i depth) number-string)
14681 (while (>= i 0)
14682 (if (> i level)
14683 (aset org-section-numbers i 0)
14684 (setq number-string (or (car numbers) "0"))
14685 (if (string-match "\\`[A-Z]\\'" number-string)
14686 (aset org-section-numbers i
14687 (- (string-to-char number-string) ?A -1))
14688 (aset org-section-numbers i (string-to-number number-string)))
14689 (pop numbers))
14690 (setq i (1- i)))))
14692 (defun org-section-number (&optional level)
14693 "Return a string with the current section number.
14694 When LEVEL is non-nil, increase section numbers on that level."
14695 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
14696 (when level
14697 (when (> level -1)
14698 (aset org-section-numbers
14699 level (1+ (aref org-section-numbers level))))
14700 (setq idx (1+ level))
14701 (while (<= idx depth)
14702 (if (not (= idx 1))
14703 (aset org-section-numbers idx 0))
14704 (setq idx (1+ idx))))
14705 (setq idx 0)
14706 (while (<= idx depth)
14707 (setq n (aref org-section-numbers idx))
14708 (setq string (concat string (if (not (string= string "")) "." "")
14709 (int-to-string n)))
14710 (setq idx (1+ idx)))
14711 (save-match-data
14712 (if (string-match "\\`\\([@0]\\.\\)+" string)
14713 (setq string (replace-match "" t nil string)))
14714 (if (string-match "\\(\\.0\\)+\\'" string)
14715 (setq string (replace-match "" t nil string))))
14716 string))
14719 ;;;###autoload
14720 (defun org-export-icalendar-this-file ()
14721 "Export current file as an iCalendar file.
14722 The iCalendar file will be located in the same directory as the Org-mode
14723 file, but with extension `.ics'."
14724 (interactive)
14725 (org-export-icalendar nil buffer-file-name))
14727 (defun org-export-as-xoxo-insert-into (buffer &rest output)
14728 (with-current-buffer buffer
14729 (apply 'insert output)))
14731 (defun org-export-as-xoxo (&optional buffer)
14732 "Export the org buffer as XOXO.
14733 The XOXO buffer is named *xoxo-<source buffer name>*"
14734 (interactive (list (current-buffer)))
14735 ;; A quickie abstraction
14737 ;; Output everything as XOXO
14738 (with-current-buffer (get-buffer buffer)
14739 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
14740 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14741 (org-infile-export-plist)))
14742 (filename (concat (file-name-as-directory
14743 (org-export-directory :xoxo opt-plist))
14744 (file-name-sans-extension
14745 (file-name-nondirectory buffer-file-name))
14746 ".html"))
14747 (out (find-file-noselect filename))
14748 (last-level 1)
14749 (hanging-li nil))
14750 ;; Check the output buffer is empty.
14751 (with-current-buffer out (erase-buffer))
14752 ;; Kick off the output
14753 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
14754 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
14755 (let* ((hd (match-string-no-properties 1))
14756 (level (length hd))
14757 (text (concat
14758 (match-string-no-properties 2)
14759 (save-excursion
14760 (goto-char (match-end 0))
14761 (let ((str ""))
14762 (catch 'loop
14763 (while 't
14764 (forward-line)
14765 (if (looking-at "^[ \t]\\(.*\\)")
14766 (setq str (concat str (match-string-no-properties 1)))
14767 (throw 'loop str)))))))))
14769 ;; Handle level rendering
14770 (cond
14771 ((> level last-level)
14772 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
14774 ((< level last-level)
14775 (dotimes (- (- last-level level) 1)
14776 (if hanging-li
14777 (org-export-as-xoxo-insert-into out "</li>\n"))
14778 (org-export-as-xoxo-insert-into out "</ol>\n"))
14779 (when hanging-li
14780 (org-export-as-xoxo-insert-into out "</li>\n")
14781 (setq hanging-li nil)))
14783 ((equal level last-level)
14784 (if hanging-li
14785 (org-export-as-xoxo-insert-into out "</li>\n")))
14788 (setq last-level level)
14790 ;; And output the new li
14791 (setq hanging-li 't)
14792 (if (equal ?+ (elt text 0))
14793 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
14794 (org-export-as-xoxo-insert-into out "<li>" text))))
14796 ;; Finally finish off the ol
14797 (dotimes (- last-level 1)
14798 (if hanging-li
14799 (org-export-as-xoxo-insert-into out "</li>\n"))
14800 (org-export-as-xoxo-insert-into out "</ol>\n"))
14802 ;; Finish the buffer off and clean it up.
14803 (switch-to-buffer-other-window out)
14804 (indent-region (point-min) (point-max) nil)
14805 (save-buffer)
14806 (goto-char (point-min))
14809 ;;;###autoload
14810 (defun org-export-icalendar-all-agenda-files ()
14811 "Export all files in `org-agenda-files' to iCalendar .ics files.
14812 Each iCalendar file will be located in the same directory as the Org-mode
14813 file, but with extension `.ics'."
14814 (interactive)
14815 (apply 'org-export-icalendar nil (org-agenda-files t)))
14817 ;;;###autoload
14818 (defun org-export-icalendar-combine-agenda-files ()
14819 "Export all files in `org-agenda-files' to a single combined iCalendar file.
14820 The file is stored under the name `org-combined-agenda-icalendar-file'."
14821 (interactive)
14822 (apply 'org-export-icalendar t (org-agenda-files t)))
14824 (defun org-export-icalendar (combine &rest files)
14825 "Create iCalendar files for all elements of FILES.
14826 If COMBINE is non-nil, combine all calendar entries into a single large
14827 file and store it under the name `org-combined-agenda-icalendar-file'."
14828 (save-excursion
14829 (let* ((dir (org-export-directory
14830 :ical (list :publishing-directory
14831 org-export-publishing-directory)))
14832 file ical-file ical-buffer category started org-agenda-new-buffers)
14834 (when combine
14835 (setq ical-file
14836 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
14837 org-combined-agenda-icalendar-file
14838 (expand-file-name org-combined-agenda-icalendar-file dir))
14839 ical-buffer (org-get-agenda-file-buffer ical-file))
14840 (set-buffer ical-buffer) (erase-buffer))
14841 (while (setq file (pop files))
14842 (catch 'nextfile
14843 (org-check-agenda-file file)
14844 (set-buffer (org-get-agenda-file-buffer file))
14845 (unless combine
14846 (setq ical-file (concat (file-name-as-directory dir)
14847 (file-name-sans-extension
14848 (file-name-nondirectory buffer-file-name))
14849 ".ics"))
14850 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
14851 (with-current-buffer ical-buffer (erase-buffer)))
14852 (setq category (or org-category
14853 (file-name-sans-extension
14854 (file-name-nondirectory buffer-file-name))))
14855 (if (symbolp category) (setq category (symbol-name category)))
14856 (let ((standard-output ical-buffer))
14857 (if combine
14858 (and (not started) (setq started t)
14859 (org-start-icalendar-file org-icalendar-combined-name))
14860 (org-start-icalendar-file category))
14861 (org-print-icalendar-entries combine category)
14862 (when (or (and combine (not files)) (not combine))
14863 (org-finish-icalendar-file)
14864 (set-buffer ical-buffer)
14865 (save-buffer)
14866 (run-hooks 'org-after-save-iCalendar-file-hook)))))
14867 (org-release-buffers org-agenda-new-buffers))))
14869 (defvar org-after-save-iCalendar-file-hook nil
14870 "Hook run after an iCalendar file has been saved.
14871 The iCalendar buffer is still current when this hook is run.
14872 A good way to use this is to tell a desktop calenndar application to re-read
14873 the iCalendar file.")
14875 (defun org-print-icalendar-entries (&optional combine category)
14876 "Print iCalendar entries for the current Org-mode file to `standard-output'.
14877 When COMBINE is non nil, add the category to each line."
14878 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
14879 (dts (org-ical-ts-to-string
14880 (format-time-string (cdr org-time-stamp-formats) (current-time))
14881 "DTSTART"))
14882 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
14883 (save-excursion
14884 (goto-char (point-min))
14885 (while (re-search-forward org-ts-regexp nil t)
14886 (setq pos (match-beginning 0)
14887 ts (match-string 0)
14888 inc t
14889 hd (org-get-heading))
14890 (if (looking-at re2)
14891 (progn
14892 (goto-char (match-end 0))
14893 (setq ts2 (match-string 1) inc nil))
14894 (setq ts2 ts
14895 tmp (buffer-substring (max (point-min)
14896 (- pos org-ds-keyword-length))
14897 pos)
14898 deadlinep (string-match org-deadline-regexp tmp)
14899 scheduledp (string-match org-scheduled-regexp tmp)
14900 ;; donep (org-entry-is-done-p)
14902 (if (or (string-match org-tr-regexp hd)
14903 (string-match org-ts-regexp hd))
14904 (setq hd (replace-match "" t t hd)))
14905 (if combine
14906 (setq hd (concat hd " (category " category ")")))
14907 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
14908 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
14909 (princ (format "BEGIN:VEVENT
14912 SUMMARY:%s
14913 END:VEVENT\n"
14914 (org-ical-ts-to-string ts "DTSTART")
14915 (org-ical-ts-to-string ts2 "DTEND" inc)
14916 hd)))
14917 (when org-icalendar-include-todo
14918 (goto-char (point-min))
14919 (while (re-search-forward org-todo-line-regexp nil t)
14920 (setq state (match-string 1))
14921 (unless (equal state org-done-string)
14922 (setq hd (match-string 3))
14923 (if (string-match org-priority-regexp hd)
14924 (setq pri (string-to-char (match-string 2 hd))
14925 hd (concat (substring hd 0 (match-beginning 1))
14926 (substring hd (- (match-end 1)))))
14927 (setq pri org-default-priority))
14928 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
14929 (- org-lowest-priority ?A))))))
14931 (princ (format "BEGIN:VTODO
14933 SUMMARY:%s
14934 SEQUENCE:1
14935 PRIORITY:%d
14936 END:VTODO\n"
14937 dts hd pri))))))))
14939 (defun org-start-icalendar-file (name)
14940 "Start an iCalendar file by inserting the header."
14941 (let ((user user-full-name)
14942 (name (or name "unknown"))
14943 (timezone (cadr (current-time-zone))))
14944 (princ
14945 (format "BEGIN:VCALENDAR
14946 VERSION:2.0
14947 X-WR-CALNAME:%s
14948 PRODID:-//%s//Emacs with Org-mode//EN
14949 X-WR-TIMEZONE:%s
14950 CALSCALE:GREGORIAN\n" name user timezone))))
14952 (defun org-finish-icalendar-file ()
14953 "Finish an iCalendar file by inserting the END statement."
14954 (princ "END:VCALENDAR\n"))
14956 (defun org-ical-ts-to-string (s keyword &optional inc)
14957 "Take a time string S and convert it to iCalendar format.
14958 KEYWORD is added in front, to make a complete line like DTSTART....
14959 When INC is non-nil, increase the hour by two (if time string contains
14960 a time), or the day by one (if it does not contain a time)."
14961 (let ((t1 (org-parse-time-string s 'nodefault))
14962 t2 fmt have-time time)
14963 (if (and (car t1) (nth 1 t1) (nth 2 t1))
14964 (setq t2 t1 have-time t)
14965 (setq t2 (org-parse-time-string s)))
14966 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
14967 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
14968 (when inc
14969 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
14970 (setq time (encode-time s mi h d m y)))
14971 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
14972 (concat keyword (format-time-string fmt time))))
14974 ;;; LaTeX stuff
14976 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14977 "Keymap for the minor `org-cdlatex-mode'.")
14979 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14980 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14981 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14982 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14983 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14985 (defvar org-cdlatex-texmathp-advice-is-done nil
14986 "Flag remembering if we have applied the advice to texmathp already.")
14988 (define-minor-mode org-cdlatex-mode
14989 "Toggle the minor `org-cdlatex-mode'.
14990 This mode supports entering LaTeX environment and math in LaTeX fragments
14991 in Org-mode.
14992 \\{org-cdlatex-mode-map}"
14993 nil " OCDL" nil
14994 (when org-cdlatex-mode (require 'cdlatex))
14995 (unless org-cdlatex-texmathp-advice-is-done
14996 (setq org-cdlatex-texmathp-advice-is-done t)
14997 (defadvice texmathp (around org-math-always-on activate)
14998 "Always return t in org-mode buffers.
14999 This is because we want to insert math symbols without dollars even outside
15000 the LaTeX math segments. If Orgmode thinks that point is actually inside
15001 en embedded LaTeX fragement, let texmathp do its job.
15002 \\[org-cdlatex-mode-map]"
15003 (interactive)
15004 (let (p)
15005 (cond
15006 ((not (org-mode-p)) ad-do-it)
15007 ((eq this-command 'cdlatex-math-symbol)
15008 (setq ad-return-value t
15009 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15011 (let ((p (org-inside-LaTeX-fragment-p)))
15012 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15013 (setq ad-return-value t
15014 texmathp-why '("Org-mode embedded math" . 0))
15015 (if p ad-do-it)))))))))
15017 (defun turn-on-org-cdlatex ()
15018 "Unconditionally turn on `org-cdlatex-mode'."
15019 (org-cdlatex-mode 1))
15021 (defun org-inside-LaTeX-fragment-p ()
15022 "Test if point is inside a LaTeX fragment.
15023 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15024 sequence appearing also before point.
15025 Even though the matchers for math are configurable, this function assumes
15026 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15027 delimiters are skipped when they have been removed by customization.
15028 The return value is nil, or a cons cell with the delimiter and
15029 and the position of this delimiter.
15031 This function does a reasonably good job, but can locally be fooled by
15032 for example currency specifications. For example it will assume being in
15033 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15034 fragments that are properly closed, but during editing, we have to live
15035 with the uncertainty caused by missing closing delimiters. This function
15036 looks only before point, not after."
15037 (catch 'exit
15038 (let ((pos (point))
15039 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15040 (lim (progn
15041 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15042 (point)))
15043 dd-on str (start 0) m re)
15044 (goto-char pos)
15045 (when dodollar
15046 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15047 re (nth 1 (assoc "$" org-latex-regexps)))
15048 (while (string-match re str start)
15049 (cond
15050 ((= (match-end 0) (length str))
15051 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
15052 ((= (match-end 0) (- (length str) 5))
15053 (throw 'exit nil))
15054 (t (setq start (match-end 0))))))
15055 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15056 (goto-char pos)
15057 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15058 (and (match-beginning 2) (throw 'exit nil))
15059 ;; count $$
15060 (while (re-search-backward "\\$\\$" lim t)
15061 (setq dd-on (not dd-on)))
15062 (goto-char pos)
15063 (if dd-on (cons "$$" m))))))
15066 (defun org-try-cdlatex-tab ()
15067 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15068 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15069 - inside a LaTeX fragment, or
15070 - after the first word in a line, where an abbreviation expansion could
15071 insert a LaTeX environment."
15072 ;; FIXME: This may still need refinement.
15073 (when org-cdlatex-mode
15074 (cond
15075 ((save-excursion
15076 (skip-chars-backward "a-zA-Z0-9*")
15077 (skip-chars-backward " \t")
15078 (bolp))
15079 (cdlatex-tab) t)
15080 ((org-inside-LaTeX-fragment-p)
15081 (cdlatex-tab) t)
15082 (t nil))))
15084 (defun org-cdlatex-underscore-caret (&optional arg)
15085 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15086 Revert to the normal definition outside of these fragments."
15087 (interactive "P")
15088 (if (org-inside-LaTeX-fragment-p)
15089 (call-interactively 'cdlatex-sub-superscript)
15090 (let (org-cdlatex-mode)
15091 (call-interactively (key-binding (vector last-input-event))))))
15093 (defun org-cdlatex-math-modify (&optional arg)
15094 "Execute `cdlatex-math-modify' in LaTeX fragments.
15095 Revert to the normal definition outside of these fragments."
15096 (interactive "P")
15097 (if (org-inside-LaTeX-fragment-p)
15098 (call-interactively 'cdlatex-math-modify)
15099 (let (org-cdlatex-mode)
15100 (call-interactively (key-binding (vector last-input-event))))))
15102 (defvar org-latex-fragment-image-overlays nil
15103 "List of overlays carrying the images of latex fragments.")
15104 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15106 (defun org-remove-latex-fragment-image-overlays ()
15107 "Remove all overlays with LaTeX fragment images in current buffer."
15108 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15109 (setq org-latex-fragment-image-overlays nil))
15111 (defun org-preview-latex-fragment (&optional subtree)
15112 "Preview the LaTeX fragment at point, or all locally or globally.
15113 If the cursor is in a LaTeX fragment, create the image and overlay
15114 it over the source code. If there is no fragment at point, display
15115 all fragments in the current text, from one headline to the next. With
15116 prefix SUBTREE, display all fragments in the current subtree. With a
15117 double prefix `C-u C-u', or when the cursor is before the first headline,
15118 display all fragments in the buffer.
15119 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15120 (interactive "P")
15121 (org-remove-latex-fragment-image-overlays)
15122 (save-excursion
15123 (save-restriction
15124 (let (beg end at msg)
15125 (cond
15126 ((or (equal subtree '(16))
15127 (not (save-excursion
15128 (re-search-backward (concat "^" outline-regexp) nil t))))
15129 (setq beg (point-min) end (point-max)
15130 msg "Creating images for buffer...%s"))
15131 ((equal subtree '(4))
15132 (org-back-to-heading)
15133 (setq beg (point) end (org-end-of-subtree)
15134 msg "Creating images for subtree...%s"))
15136 (if (setq at (org-inside-LaTeX-fragment-p))
15137 (goto-char (max (point-min) (- (cdr at) 2)))
15138 (org-back-to-heading))
15139 (setq beg (point) end (progn (outline-next-heading) (point))
15140 msg (if at "Creating image...%s"
15141 "Creating images for entry...%s"))))
15142 (message msg "")
15143 (narrow-to-region beg end)
15144 (org-format-latex
15145 (concat "ltxpng/" (file-name-sans-extension
15146 (file-name-nondirectory
15147 buffer-file-name)))
15148 default-directory 'overlays msg at)
15149 (message msg "done. Use `C-c C-c' to remove images.")))))
15151 (defvar org-latex-regexps
15152 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15153 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15154 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15155 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
15156 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15157 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
15158 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
15159 "Regular expressions for matching embedded LaTeX.")
15161 (defun org-format-latex (prefix &optional dir overlays msg at)
15162 "Replace LaTeX fragments with links to an image, and produce images."
15163 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15164 (let* ((prefixnodir (file-name-nondirectory prefix))
15165 (absprefix (expand-file-name prefix dir))
15166 (todir (file-name-directory absprefix))
15167 (opt org-format-latex-options)
15168 (matchers (plist-get opt :matchers))
15169 (re-list org-latex-regexps)
15170 (cnt 0) txt link beg end re e oldfiles
15171 m n block linkfile movefile ov)
15172 ;; Make sure the directory exists
15173 (or (file-directory-p todir) (make-directory todir))
15174 ;; Check if there are old images files with this prefix, and remove them
15175 (setq oldfiles (directory-files
15176 todir 'full
15177 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
15178 (while oldfiles (delete-file (pop oldfiles)))
15179 ;; Check the different regular expressions
15180 (while (setq e (pop re-list))
15181 (setq m (car e) re (nth 1 e) n (nth 2 e)
15182 block (if (nth 3 e) "\n\n" ""))
15183 (when (member m matchers)
15184 (goto-char (point-min))
15185 (while (re-search-forward re nil t)
15186 (when (or (not at) (equal (cdr at) (match-beginning n)))
15187 (setq txt (match-string n)
15188 beg (match-beginning n) end (match-end n)
15189 cnt (1+ cnt)
15190 linkfile (format "%s_%04d.png" prefix cnt)
15191 movefile (format "%s_%04d.png" absprefix cnt)
15192 link (concat block "[[file:" linkfile "]]" block))
15193 (if msg (message msg cnt))
15194 (goto-char beg)
15195 (org-create-formula-image
15196 txt movefile opt)
15197 (if overlays
15198 (progn
15199 (setq ov (org-make-overlay beg end))
15200 (if (featurep 'xemacs)
15201 (progn
15202 (org-overlay-put ov 'invisible t)
15203 (org-overlay-put
15204 ov 'end-glyph
15205 (make-glyph (vector 'png :file movefile))))
15206 (org-overlay-put
15207 ov 'display
15208 (list 'image :type 'png :file movefile :ascent 'center)))
15209 (push ov org-latex-fragment-image-overlays)
15210 (goto-char end))
15211 (delete-region beg end)
15212 (insert link))))))))
15214 ;; This function borrows from Ganesh Swami's latex2png.el
15215 (defun org-create-formula-image (string tofile options)
15216 (let* ((tmpdir (if (featurep 'xemacs)
15217 (temp-directory)
15218 temporary-file-directory))
15219 (texfilebase (make-temp-name
15220 (expand-file-name "orgtex" tmpdir)))
15222 ;(texfilebase (make-temp-file "orgtex"))
15223 ; (dummy (delete-file texfilebase))
15224 (texfile (concat texfilebase ".tex"))
15225 (dvifile (concat texfilebase ".dvi"))
15226 (pngfile (concat texfilebase ".png"))
15227 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15228 (fg (or (plist-get options :foreground) "Black"))
15229 (bg (or (plist-get options :background) "Transparent")))
15230 (with-temp-file texfile
15231 (insert "\\documentclass{article}
15232 \\usepackage{fullpage}
15233 \\usepackage{amssymb}
15234 \\usepackage[usenames]{color}
15235 \\usepackage{amsmath}
15236 \\usepackage{latexsym}
15237 \\usepackage[mathscr]{eucal}
15238 \\pagestyle{empty}
15239 \\begin{document}\n" string "\n\\end{document}\n"))
15240 (let ((dir default-directory))
15241 (condition-case nil
15242 (progn
15243 (cd tmpdir)
15244 (call-process "latex" nil nil nil texfile))
15245 (error nil))
15246 (cd dir))
15247 (if (not (file-exists-p dvifile))
15248 (progn (message "Failed to create dvi file from %s" texfile) nil)
15249 (call-process "dvipng" nil nil nil
15250 "-E" "-fg" fg "-bg" bg
15251 "-x" scale "-y" scale "-T" "tight"
15252 "-o" pngfile
15253 dvifile)
15254 (if (not (file-exists-p pngfile))
15255 (progn (message "Failed to create png file from %s" texfile) nil)
15256 ;; Use the requested file name and clean up
15257 (copy-file pngfile tofile 'replace)
15258 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15259 (delete-file (concat texfilebase e)))
15260 pngfile))))
15262 ;;; Key bindings
15264 ;; - Bindings in Org-mode map are currently
15265 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
15266 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
15267 ;; e (?) useful from outline-mode
15268 ;; i k @ expendable from outline-mode
15269 ;; 0123456789 % & ()_{} " ` free
15271 ;; Make `C-c C-x' a prefix key
15272 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
15274 ;; TAB key with modifiers
15275 (define-key org-mode-map "\C-i" 'org-cycle)
15276 (define-key org-mode-map [(tab)] 'org-cycle)
15277 (define-key org-mode-map [(meta tab)] 'org-complete)
15278 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
15279 ;; The following line is necessary under Suse GNU/Linux
15280 (unless (featurep 'xemacs)
15281 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
15282 (define-key org-mode-map [(shift tab)] 'org-shifttab)
15284 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
15285 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
15286 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15287 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
15288 (define-key org-mode-map [(meta return)] 'org-meta-return)
15289 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
15290 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
15292 ;; Cursor keys with modifiers
15293 (define-key org-mode-map [(meta left)] 'org-metaleft)
15294 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
15295 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
15296 (define-key org-mode-map [(meta right)] 'org-metaright)
15297 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
15298 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
15299 (define-key org-mode-map [(meta up)] 'org-metaup)
15300 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
15301 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
15302 (define-key org-mode-map [(meta down)] 'org-metadown)
15303 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
15304 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
15306 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15307 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
15308 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
15309 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
15310 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
15311 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
15312 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
15313 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
15314 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
15315 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
15316 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
15317 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
15318 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
15319 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
15320 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
15321 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
15323 ;; All the other keys
15325 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15326 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
15327 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
15328 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
15329 (define-key org-mode-map "\C-c\C-j" 'org-goto)
15330 (define-key org-mode-map "\C-c\C-t" 'org-todo)
15331 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
15332 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
15333 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
15334 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15335 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
15336 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
15337 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
15338 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
15339 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
15340 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
15341 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
15342 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
15343 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
15344 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
15345 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15346 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15347 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15348 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15349 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
15350 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
15351 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15352 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
15353 (define-key org-mode-map "\C-c]" 'org-remove-file)
15354 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
15355 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
15356 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
15357 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15358 (define-key org-mode-map "\C-m" 'org-return)
15359 (define-key org-mode-map "\C-c?" 'org-table-current-column)
15360 (define-key org-mode-map "\C-c " 'org-table-blank-field)
15361 (define-key org-mode-map "\C-c+" 'org-table-sum)
15362 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
15363 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
15364 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
15365 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15366 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
15367 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15368 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
15369 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
15370 (define-key org-mode-map "\C-c\C-e" 'org-export)
15371 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15373 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
15374 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15375 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15376 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15378 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15379 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15380 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15381 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15382 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15383 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15384 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15385 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15387 (when (featurep 'xemacs)
15388 (define-key org-mode-map 'button3 'popup-mode-menu))
15390 (defsubst org-table-p () (org-at-table-p))
15392 (defun org-self-insert-command (N)
15393 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15394 If the cursor is in a table looking at whitespace, the whitespace is
15395 overwritten, and the table is not marked as requiring realignment."
15396 (interactive "p")
15397 (if (and (org-table-p)
15398 (progn
15399 ;; check if we blank the field, and if that triggers align
15400 (and org-table-auto-blank-field
15401 (member last-command
15402 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
15403 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15404 ;; got extra space, this field does not determine column width
15405 (let (org-table-may-need-update) (org-table-blank-field))
15406 ;; no extra space, this field may determine column width
15407 (org-table-blank-field)))
15409 (eq N 1)
15410 (looking-at "[^|\n]* |"))
15411 (let (org-table-may-need-update)
15412 (goto-char (1- (match-end 0)))
15413 (delete-backward-char 1)
15414 (goto-char (match-beginning 0))
15415 (self-insert-command N))
15416 (setq org-table-may-need-update t)
15417 (self-insert-command N)))
15419 (defun org-delete-backward-char (N)
15420 "Like `delete-backward-char', insert whitespace at field end in tables.
15421 When deleting backwards, in tables this function will insert whitespace in
15422 front of the next \"|\" separator, to keep the table aligned. The table will
15423 still be marked for re-alignment if the field did fill the entire column,
15424 because, in this case the deletion might narrow the column."
15425 (interactive "p")
15426 (if (and (org-table-p)
15427 (eq N 1)
15428 (string-match "|" (buffer-substring (point-at-bol) (point)))
15429 (looking-at ".*?|"))
15430 (let ((pos (point))
15431 (noalign (looking-at "[^|\n\r]* |"))
15432 (c org-table-may-need-update))
15433 (backward-delete-char N)
15434 (skip-chars-forward "^|")
15435 (insert " ")
15436 (goto-char (1- pos))
15437 ;; noalign: if there were two spaces at the end, this field
15438 ;; does not determine the width of the column.
15439 (if noalign (setq org-table-may-need-update c)))
15440 (backward-delete-char N)))
15442 (defun org-delete-char (N)
15443 "Like `delete-char', but insert whitespace at field end in tables.
15444 When deleting characters, in tables this function will insert whitespace in
15445 front of the next \"|\" separator, to keep the table aligned. The table will
15446 still be marked for re-alignment if the field did fill the entire column,
15447 because, in this case the deletion might narrow the column."
15448 (interactive "p")
15449 (if (and (org-table-p)
15450 (not (bolp))
15451 (not (= (char-after) ?|))
15452 (eq N 1))
15453 (if (looking-at ".*?|")
15454 (let ((pos (point))
15455 (noalign (looking-at "[^|\n\r]* |"))
15456 (c org-table-may-need-update))
15457 (replace-match (concat
15458 (substring (match-string 0) 1 -1)
15459 " |"))
15460 (goto-char pos)
15461 ;; noalign: if there were two spaces at the end, this field
15462 ;; does not determine the width of the column.
15463 (if noalign (setq org-table-may-need-update c)))
15464 (delete-char N))
15465 (delete-char N)))
15467 ;; How to do this: Measure non-white length of current string
15468 ;; If equal to column width, we should realign.
15470 (defun org-remap (map &rest commands)
15471 "In MAP, remap the functions given in COMMANDS.
15472 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15473 (let (new old)
15474 (while commands
15475 (setq old (pop commands) new (pop commands))
15476 (if (fboundp 'command-remapping)
15477 (define-key map (vector 'remap old) new)
15478 (substitute-key-definition old new map global-map)))))
15480 (when (eq org-enable-table-editor 'optimized)
15481 ;; If the user wants maximum table support, we need to hijack
15482 ;; some standard editing functions
15483 (org-remap org-mode-map
15484 'self-insert-command 'org-self-insert-command
15485 'delete-char 'org-delete-char
15486 'delete-backward-char 'org-delete-backward-char)
15487 (define-key org-mode-map "|" 'org-force-self-insert))
15489 (defun org-shiftcursor-error ()
15490 "Throw an error because Shift-Cursor command was applied in wrong context."
15491 (error "This command is active in special context like tables, headlines or timestamps"))
15493 (defun org-shifttab (&optional arg)
15494 "Global visibility cycling or move to previous table field.
15495 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15496 on context.
15497 See the individual commands for more information."
15498 (interactive "P")
15499 (cond
15500 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15501 (t (call-interactively 'org-global-cycle))))
15503 (defun org-shiftmetaleft ()
15504 "Promote subtree or delete table column.
15505 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
15506 See the individual commands for more information."
15507 (interactive)
15508 (cond
15509 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15510 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15511 ((org-at-item-p) (call-interactively 'org-outdent-item))
15512 (t (org-shiftcursor-error))))
15514 (defun org-shiftmetaright ()
15515 "Demote subtree or insert table column.
15516 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
15517 See the individual commands for more information."
15518 (interactive)
15519 (cond
15520 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15521 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15522 ((org-at-item-p) (call-interactively 'org-indent-item))
15523 (t (org-shiftcursor-error))))
15525 (defun org-shiftmetaup (&optional arg)
15526 "Move subtree up or kill table row.
15527 Calls `org-move-subtree-up' or `org-table-kill-row' or
15528 `org-move-item-up' depending on context. See the individual commands
15529 for more information."
15530 (interactive "P")
15531 (cond
15532 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15533 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15534 ((org-at-item-p) (call-interactively 'org-move-item-up))
15535 (t (org-shiftcursor-error))))
15536 (defun org-shiftmetadown (&optional arg)
15537 "Move subtree down or insert table row.
15538 Calls `org-move-subtree-down' or `org-table-insert-row' or
15539 `org-move-item-down', depending on context. See the individual
15540 commands for more information."
15541 (interactive "P")
15542 (cond
15543 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15544 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15545 ((org-at-item-p) (call-interactively 'org-move-item-down))
15546 (t (org-shiftcursor-error))))
15548 (defun org-metaleft (&optional arg)
15549 "Promote heading or move table column to left.
15550 Calls `org-do-promote' or `org-table-move-column', depending on context.
15551 With no specific context, calls the Emacs default `backward-word'.
15552 See the individual commands for more information."
15553 (interactive "P")
15554 (cond
15555 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15556 ((or (org-on-heading-p) (org-region-active-p))
15557 (call-interactively 'org-do-promote))
15558 (t (call-interactively 'backward-word))))
15560 (defun org-metaright (&optional arg)
15561 "Demote subtree or move table column to right.
15562 Calls `org-do-demote' or `org-table-move-column', depending on context.
15563 With no specific context, calls the Emacs default `forward-word'.
15564 See the individual commands for more information."
15565 (interactive "P")
15566 (cond
15567 ((org-at-table-p) (call-interactively 'org-table-move-column))
15568 ((or (org-on-heading-p) (org-region-active-p))
15569 (call-interactively 'org-do-demote))
15570 (t (call-interactively 'forward-word))))
15572 (defun org-metaup (&optional arg)
15573 "Move subtree up or move table row up.
15574 Calls `org-move-subtree-up' or `org-table-move-row' or
15575 `org-move-item-up', depending on context. See the individual commands
15576 for more information."
15577 (interactive "P")
15578 (cond
15579 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15580 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15581 ((org-at-item-p) (call-interactively 'org-move-item-up))
15582 (t (org-shiftcursor-error))))
15584 (defun org-metadown (&optional arg)
15585 "Move subtree down or move table row down.
15586 Calls `org-move-subtree-down' or `org-table-move-row' or
15587 `org-move-item-down', depending on context. See the individual
15588 commands for more information."
15589 (interactive "P")
15590 (cond
15591 ((org-at-table-p) (call-interactively 'org-table-move-row))
15592 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15593 ((org-at-item-p) (call-interactively 'org-move-item-down))
15594 (t (org-shiftcursor-error))))
15596 (defun org-shiftup (&optional arg)
15597 "Increase item in timestamp or increase priority of current headline.
15598 Calls `org-timestamp-up' or `org-priority-up', depending on context.
15599 See the individual commands for more information."
15600 (interactive "P")
15601 (cond
15602 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
15603 ((org-on-heading-p) (call-interactively 'org-priority-up))
15604 ((org-at-item-p) (call-interactively 'org-previous-item))
15605 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
15607 (defun org-shiftdown (&optional arg)
15608 "Decrease item in timestamp or decrease priority of current headline.
15609 Calls `org-timestamp-down' or `org-priority-down', depending on context.
15610 See the individual commands for more information."
15611 (interactive "P")
15612 (cond
15613 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
15614 ((org-on-heading-p) (call-interactively 'org-priority-down))
15615 (t (call-interactively 'org-next-item))))
15617 (defun org-shiftright ()
15618 "Next TODO keyword or timestamp one day later, depending on context."
15619 (interactive)
15620 (cond
15621 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15622 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
15623 (t (org-shiftcursor-error))))
15625 (defun org-shiftleft ()
15626 "Previous TODO keyword or timestamp one day earlier, depending on context."
15627 (interactive)
15628 (cond
15629 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15630 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
15631 (t (org-shiftcursor-error))))
15633 (defun org-copy-special ()
15634 "Copy region in table or copy current subtree.
15635 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15636 See the individual commands for more information."
15637 (interactive)
15638 (call-interactively
15639 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15641 (defun org-cut-special ()
15642 "Cut region in table or cut current subtree.
15643 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15644 See the individual commands for more information."
15645 (interactive)
15646 (call-interactively
15647 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15649 (defun org-paste-special (arg)
15650 "Paste rectangular region into table, or past subtree relative to level.
15651 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15652 See the individual commands for more information."
15653 (interactive "P")
15654 (if (org-at-table-p)
15655 (org-table-paste-rectangle)
15656 (org-paste-subtree arg)))
15658 (defun org-ctrl-c-ctrl-c (&optional arg)
15659 "Set tags in headline, or update according to changed information at point.
15661 This command does many different things, depending on context:
15663 - If the cursor is in a headline, prompt for tags and insert them
15664 into the current line, aligned to `org-tags-column'. When called
15665 with prefix arg, realign all tags in the current buffer.
15667 - If the cursor is in one of the special #+KEYWORD lines, this
15668 triggers scanning the buffer for these lines and updating the
15669 information.
15671 - If the cursor is inside a table, realign the table. This command
15672 works even if the automatic table editor has been turned off.
15674 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15675 the entire table.
15677 - If the cursor is inside a table created by the table.el package,
15678 activate that table.
15680 - If the current buffer is a remember buffer, close note and file it.
15681 with a prefix argument, file it without further interaction to the default
15682 location.
15684 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15685 links in this buffer.
15687 - If the cursor is on a numbered item in a plain list, renumber the
15688 ordered list."
15689 (interactive "P")
15690 (let ((org-enable-table-editor t))
15691 (cond
15692 ((or org-clock-overlays org-occur-highlights
15693 org-latex-fragment-image-overlays)
15694 (org-remove-clock-overlays)
15695 (org-remove-occur-highlights)
15696 (org-remove-latex-fragment-image-overlays)
15697 (message "Temporary highlights/overlays removed from current buffer"))
15698 ((and (local-variable-p 'org-finish-function (current-buffer))
15699 (fboundp org-finish-function))
15700 (funcall org-finish-function))
15701 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15702 ((org-on-heading-p) (call-interactively 'org-set-tags))
15703 ((org-at-table.el-p)
15704 (require 'table)
15705 (beginning-of-line 1)
15706 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15707 (call-interactively 'table-recognize-table))
15708 ((org-at-table-p)
15709 (org-table-maybe-eval-formula)
15710 (if arg
15711 (call-interactively 'org-table-recalculate)
15712 (org-table-maybe-recalculate-line))
15713 (call-interactively 'org-table-align))
15714 ((org-at-item-checkbox-p)
15715 (call-interactively 'org-toggle-checkbox))
15716 ((org-at-item-p)
15717 (call-interactively 'org-renumber-ordered-list))
15718 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
15719 (cond
15720 ((equal (match-string 1) "TBLFM")
15721 ;; Recalculate the table before this line
15722 (save-excursion
15723 (beginning-of-line 1)
15724 (skip-chars-backward " \r\n\t")
15725 (if (org-at-table-p)
15726 (org-call-with-arg 'org-table-recalculate t))))
15728 (call-interactively 'org-mode-restart))))
15729 (t (error "C-c C-c can do nothing useful at this location.")))))
15731 (defun org-mode-restart ()
15732 "Restart Org-mode, to scan again for special lines.
15733 Also updates the keyword regular expressions."
15734 (interactive)
15735 (let ((org-inhibit-startup t)) (org-mode))
15736 (message "Org-mode restarted to refresh keyword and special line setup"))
15738 (defun org-return ()
15739 "Goto next table row or insert a newline.
15740 Calls `org-table-next-row' or `newline', depending on context.
15741 See the individual commands for more information."
15742 (interactive)
15743 (cond
15744 ((org-at-table-p)
15745 (org-table-justify-field-maybe)
15746 (call-interactively 'org-table-next-row))
15747 (t (newline))))
15749 (defun org-meta-return (&optional arg)
15750 "Insert a new heading or wrap a region in a table.
15751 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15752 See the individual commands for more information."
15753 (interactive "P")
15754 (cond
15755 ((org-at-table-p)
15756 (call-interactively 'org-table-wrap-region))
15757 (t (call-interactively 'org-insert-heading))))
15759 ;;; Menu entries
15761 ;; Define the Org-mode menus
15762 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15763 '("Tbl"
15764 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
15765 ["Next Field" org-cycle (org-at-table-p)]
15766 ["Previous Field" org-shifttab (org-at-table-p)]
15767 ["Next Row" org-return (org-at-table-p)]
15768 "--"
15769 ["Blank Field" org-table-blank-field (org-at-table-p)]
15770 ["Edit Field" org-table-edit-field (org-at-table-p)]
15771 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15772 "--"
15773 ("Column"
15774 ["Move Column Left" org-metaleft (org-at-table-p)]
15775 ["Move Column Right" org-metaright (org-at-table-p)]
15776 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15777 ["Insert Column" org-shiftmetaright (org-at-table-p)]
15778 "--"
15779 ["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])
15780 ("Row"
15781 ["Move Row Up" org-metaup (org-at-table-p)]
15782 ["Move Row Down" org-metadown (org-at-table-p)]
15783 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15784 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15785 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15786 "--"
15787 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
15788 ("Rectangle"
15789 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15790 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15791 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15792 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15793 "--"
15794 ("Calculate"
15795 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15796 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15797 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
15798 "--"
15799 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15800 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15801 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15802 "--"
15803 ["Sum Column/Rectangle" org-table-sum
15804 (or (org-at-table-p) (org-region-active-p))]
15805 ["Which Column?" org-table-current-column (org-at-table-p)])
15806 ["Debug Formulas"
15807 (setq org-table-formula-debug (not org-table-formula-debug))
15808 :style toggle :selected org-table-formula-debug]
15809 "--"
15810 ["Create" org-table-create (and (not (org-at-table-p))
15811 org-enable-table-editor)]
15812 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15813 ["Import from File" org-table-import (not (org-at-table-p))]
15814 ["Export to File" org-table-export (org-at-table-p)]
15815 "--"
15816 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15818 (easy-menu-define org-org-menu org-mode-map "Org menu"
15819 '("Org"
15820 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
15821 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
15822 ["Sparse Tree" org-occur t]
15823 ["Show All" show-all t]
15824 "--"
15825 ["New Heading" org-insert-heading t]
15826 ("Navigate Headings"
15827 ["Up" outline-up-heading t]
15828 ["Next" outline-next-visible-heading t]
15829 ["Previous" outline-previous-visible-heading t]
15830 ["Next Same Level" outline-forward-same-level t]
15831 ["Previous Same Level" outline-backward-same-level t]
15832 "--"
15833 ["Jump" org-goto t])
15834 ("Edit Structure"
15835 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15836 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15837 "--"
15838 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15839 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15840 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15841 "--"
15842 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15843 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15844 ["Demote Heading" org-metaright (not (org-at-table-p))]
15845 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15846 "--"
15847 ["Convert to odd levels" org-convert-to-odd-levels t]
15848 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15849 ("Archive"
15850 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15851 ["Check and Tag Children" (org-toggle-archive-tag (4))
15852 :active t :keys "C-u C-c C-x C-a"]
15853 ["Sparse trees open ARCHIVE trees"
15854 (setq org-sparse-tree-open-archived-trees
15855 (not org-sparse-tree-open-archived-trees))
15856 :style toggle :selected org-sparse-tree-open-archived-trees]
15857 ["Cycling opens ARCHIVE trees"
15858 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15859 :style toggle :selected org-cycle-open-archived-trees]
15860 ["Agenda includes ARCHIVE trees"
15861 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
15862 :style toggle :selected (not org-agenda-skip-archived-trees)]
15863 "--"
15864 ["Move Subtree to Archive" org-archive-subtree t]
15865 ["Check and Move Children" (org-archive-subtree '(4))
15866 :active t :keys "C-u C-c $"])
15867 "--"
15868 ("TODO Lists"
15869 ["TODO/DONE/-" org-todo t]
15870 ("Select keyword"
15871 ["Next keyword" org-shiftright (org-on-heading-p)]
15872 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15873 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
15874 ["Show TODO Tree" org-show-todo-tree t]
15875 ["Global TODO list" org-todo-list t]
15876 "--"
15877 ["Set Priority" org-priority t]
15878 ["Priority Up" org-shiftup t]
15879 ["Priority Down" org-shiftdown t])
15880 ("Dates and Scheduling"
15881 ["Timestamp" org-time-stamp t]
15882 ["Timestamp (inactive)" org-time-stamp-inactive t]
15883 ("Change Date"
15884 ["1 Day Later" org-timestamp-up-day t]
15885 ["1 Day Earlier" org-timestamp-down-day t]
15886 ["1 ... Later" org-shiftup t]
15887 ["1 ... Earlier" org-shiftdown t])
15888 ["Compute Time Range" org-evaluate-time-range t]
15889 ["Schedule Item" org-schedule t]
15890 ["Deadline" org-deadline t]
15891 "--"
15892 ["Goto Calendar" org-goto-calendar t]
15893 ["Date from Calendar" org-date-from-calendar t])
15894 ("Logging work"
15895 ["Clock in" org-clock-in t]
15896 ["Clock out" org-clock-out t]
15897 ["Clock cancel" org-clock-cancel t]
15898 ["Display times" org-clock-display t]
15899 ["Create clock table" org-clock-report t]
15900 "--"
15901 ["Record DONE time"
15902 (progn (setq org-log-done (not org-log-done))
15903 (message "Switching to %s will %s record a timestamp"
15904 org-done-string
15905 (if org-log-done "automatically" "not")))
15906 :style toggle :selected org-log-done])
15907 "--"
15908 ["Agenda Command" org-agenda t]
15909 ("File List for Agenda")
15910 ("Special views current file"
15911 ["TODO Tree" org-show-todo-tree t]
15912 ["Check Deadlines" org-check-deadlines t]
15913 ["Timeline" org-timeline t]
15914 ["Tags Tree" org-tags-sparse-tree t])
15915 "--"
15916 ("Hyperlinks"
15917 ["Store Link (Global)" org-store-link t]
15918 ["Insert Link" org-insert-link t]
15919 ["Follow Link" org-open-at-point t]
15920 "--"
15921 ["Descriptive Links"
15922 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15923 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
15924 ["Literal Links"
15925 (progn
15926 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15927 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
15928 "--"
15929 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
15930 (save-excursion (goto-char (point-min))
15931 (re-search-forward "<[a-z]+:" nil t))])
15932 "--"
15933 ["Export/Publish" org-export t]
15934 ("LaTeX"
15935 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15936 :selected org-cdlatex-mode]
15937 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15938 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15939 ["Modify math symbol" org-cdlatex-math-modify
15940 (org-inside-LaTeX-fragment-p)]
15941 ["Export LaTeX fragments as images"
15942 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
15943 :style toggle :selected org-export-with-LaTeX-fragments])
15944 "--"
15945 ("Documentation"
15946 ["Show Version" org-version t]
15947 ["Info Documentation" org-info t])
15948 ("Customize"
15949 ["Browse Org Group" org-customize t]
15950 "--"
15951 ["Expand This Menu" org-create-customize-menu
15952 (fboundp 'customize-menu-create)])
15953 "--"
15954 ["Refresh setup" org-mode-restart t]
15957 (defun org-info (&optional node)
15958 "Read documentation for Org-mode in the info system.
15959 With optional NODE, go directly to that node."
15960 (interactive)
15961 (require 'info)
15962 (Info-goto-node (format "(org)%s" (or node ""))))
15964 (defun org-install-agenda-files-menu ()
15965 (let ((bl (buffer-list)))
15966 (save-excursion
15967 (while bl
15968 (set-buffer (pop bl))
15969 (if (org-mode-p) (setq bl nil)))
15970 (when (org-mode-p)
15971 (easy-menu-change
15972 '("Org") "File List for Agenda"
15973 (append
15974 (list
15975 ["Edit File List" (org-edit-agenda-file-list) t]
15976 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15977 ["Remove Current File from List" org-remove-file t]
15978 ["Cycle through agenda files" org-cycle-agenda-files t]
15979 "--")
15980 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15982 ;;; Documentation
15984 (defun org-customize ()
15985 "Call the customize function with org as argument."
15986 (interactive)
15987 (customize-browse 'org))
15989 (defun org-create-customize-menu ()
15990 "Create a full customization menu for Org-mode, insert it into the menu."
15991 (interactive)
15992 (if (fboundp 'customize-menu-create)
15993 (progn
15994 (easy-menu-change
15995 '("Org") "Customize"
15996 `(["Browse Org group" org-customize t]
15997 "--"
15998 ,(customize-menu-create 'org)
15999 ["Set" Custom-set t]
16000 ["Save" Custom-save t]
16001 ["Reset to Current" Custom-reset-current t]
16002 ["Reset to Saved" Custom-reset-saved t]
16003 ["Reset to Standard Settings" Custom-reset-standard t]))
16004 (message "\"Org\"-menu now contains full customization menu"))
16005 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16007 ;;; Miscellaneous stuff
16009 (defun org-context ()
16010 "Return a list of contexts of the current cursor position.
16011 If several contexts apply, all are returned.
16012 Each context entry is a list with a symbol naming the context, and
16013 two positions indicating start and end of the context. Possible
16014 contexts are:
16016 :headline anywhere in a headline
16017 :headline-stars on the leading stars in a headline
16018 :todo-keyword on a TODO keyword (including DONE) in a headline
16019 :tags on the TAGS in a headline
16020 :priority on the priority cookie in a headline
16021 :item on the first line of a plain list item
16022 :item-bullet on the bullet/number of a plain list item
16023 :checkbox on the checkbox in a plain list item
16024 :table in an org-mode table
16025 :table-special on a special filed in a table
16026 :table-table in a table.el table
16027 :link on a hyperline
16028 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16029 :target on a <<target>>
16030 :radio-target on a <<<radio-target>>>
16031 :latex-fragment on a LaTeX fragment
16032 :latex-preview on a LaTeX fragment with overlayed preview image
16034 This function expects the position to be visible because it uses font-lock
16035 faces as a help to recognize the following contexts: :table-special, :link,
16036 and :keyword."
16037 (let* ((f (get-text-property (point) 'face))
16038 (faces (if (listp f) f (list f)))
16039 (p (point)) clist o)
16040 ;; First the large context
16041 (cond
16042 ((org-on-heading-p)
16043 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16044 (when (progn
16045 (beginning-of-line 1)
16046 (looking-at org-todo-line-tags-regexp))
16047 (push (org-point-in-group p 1 :headline-stars) clist)
16048 (push (org-point-in-group p 2 :todo-keyword) clist)
16049 (push (org-point-in-group p 4 :tags) clist))
16050 (goto-char p)
16051 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
16052 (if (looking-at "\\[#[A-Z]\\]")
16053 (push (org-point-in-group p 0 :priority) clist)))
16055 ((org-at-item-p)
16056 (push (org-point-in-group p 2 :item-bullet) clist)
16057 (push (list :item (point-at-bol)
16058 (save-excursion (org-end-of-item) (point)))
16059 clist)
16060 (and (org-at-item-checkbox-p)
16061 (push (org-point-in-group p 0 :checkbox) clist)))
16063 ((org-at-table-p)
16064 (push (list :table (org-table-begin) (org-table-end)) clist)
16065 (if (memq 'org-formula faces)
16066 (push (list :table-special
16067 (previous-single-property-change p 'face)
16068 (next-single-property-change p 'face)) clist)))
16069 ((org-at-table-p 'any)
16070 (push (list :table-table) clist)))
16071 (goto-char p)
16073 ;; Now the small context
16074 (cond
16075 ((org-at-timestamp-p)
16076 (push (org-point-in-group p 0 :timestamp) clist))
16077 ((memq 'org-link faces)
16078 (push (list :link
16079 (previous-single-property-change p 'face)
16080 (next-single-property-change p 'face)) clist))
16081 ((memq 'org-special-keyword faces)
16082 (push (list :keyword
16083 (previous-single-property-change p 'face)
16084 (next-single-property-change p 'face)) clist))
16085 ((org-on-target-p)
16086 (push (org-point-in-group p 0 :target) clist)
16087 (goto-char (1- (match-beginning 0)))
16088 (if (looking-at org-radio-target-regexp)
16089 (push (org-point-in-group p 0 :radio-target) clist))
16090 (goto-char p))
16091 ((setq o (car (delq nil
16092 (mapcar
16093 (lambda (x)
16094 (if (memq x org-latex-fragment-image-overlays) x))
16095 (org-overlays-at (point))))))
16096 (push (list :latex-fragment
16097 (org-overlay-start o) (org-overlay-end o)) clist)
16098 (push (list :latex-preview
16099 (org-overlay-start o) (org-overlay-end o)) clist))
16100 ((org-inside-LaTeX-fragment-p)
16101 ;; FIXME: positions wring.
16102 (push (list :latex-fragment (point) (point)) clist)))
16104 (setq clist (nreverse (delq nil clist)))
16105 clist))
16107 (defun org-point-in-group (point group &optional context)
16108 "Check if POINT is in match-group GROUP.
16109 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16110 match. If the match group does ot exist or point is not inside it,
16111 return nil."
16112 (and (match-beginning group)
16113 (>= point (match-beginning group))
16114 (<= point (match-end group))
16115 (if context
16116 (list context (match-beginning group) (match-end group))
16117 t)))
16119 (defun org-move-line-down (arg)
16120 "Move the current line down. With prefix argument, move it past ARG lines."
16121 (interactive "p")
16122 (let ((col (current-column))
16123 beg end pos)
16124 (beginning-of-line 1) (setq beg (point))
16125 (beginning-of-line 2) (setq end (point))
16126 (beginning-of-line (+ 1 arg))
16127 (setq pos (move-marker (make-marker) (point)))
16128 (insert (delete-and-extract-region beg end))
16129 (goto-char pos)
16130 (move-to-column col)))
16132 (defun org-move-line-up (arg)
16133 "Move the current line up. With prefix argument, move it past ARG lines."
16134 (interactive "p")
16135 (let ((col (current-column))
16136 beg end pos)
16137 (beginning-of-line 1) (setq beg (point))
16138 (beginning-of-line 2) (setq end (point))
16139 (beginning-of-line (- arg))
16140 (setq pos (move-marker (make-marker) (point)))
16141 (insert (delete-and-extract-region beg end))
16142 (goto-char pos)
16143 (move-to-column col)))
16145 ;; Paragraph filling stuff.
16146 ;; We want this to be just right, so use the full arsenal.
16148 (defun org-set-autofill-regexps ()
16149 (interactive)
16150 ;; In the paragraph separator we include headlines, because filling
16151 ;; text in a line directly attached to a headline would otherwise
16152 ;; fill the headline as well.
16153 (org-set-local 'comment-start-skip "^#+[ \t]*")
16154 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
16155 ;; The paragraph starter includes hand-formatted lists.
16156 (org-set-local 'paragraph-start
16157 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
16158 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16159 ;; But only if the user has not turned off tables or fixed-width regions
16160 (org-set-local
16161 'auto-fill-inhibit-regexp
16162 (concat "\\*\\|#"
16163 "\\|[ \t]*" org-keyword-time-regexp
16164 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16165 (concat
16166 "\\|[ \t]*["
16167 (if org-enable-table-editor "|" "")
16168 (if org-enable-fixed-width-editor ":" "")
16169 "]"))))
16170 ;; We use our own fill-paragraph function, to make sure that tables
16171 ;; and fixed-width regions are not wrapped. That function will pass
16172 ;; through to `fill-paragraph' when appropriate.
16173 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16174 ; Adaptive filling: To get full control, first make sure that
16175 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16176 (org-set-local 'adaptive-fill-regexp "\000")
16177 (org-set-local 'adaptive-fill-function
16178 'org-adaptive-fill-function))
16180 (defun org-fill-paragraph (&optional justify)
16181 "Re-align a table, pass through to fill-paragraph if no table."
16182 (let ((table-p (org-at-table-p))
16183 (table.el-p (org-at-table.el-p)))
16184 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
16185 (table.el-p t) ; skip table.el tables
16186 (table-p (org-table-align) t) ; align org-mode tables
16187 (t nil)))) ; call paragraph-fill
16189 ;; For reference, this is the default value of adaptive-fill-regexp
16190 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16192 (defun org-adaptive-fill-function ()
16193 "Return a fill prefix for org-mode files.
16194 In particular, this makes sure hanging paragraphs for hand-formatted lists
16195 work correctly."
16196 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
16197 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
16199 ;; Functions needed for Emacs/XEmacs region compatibility
16201 (defun org-add-hook (hook function &optional append local)
16202 "Add-hook, compatible with both Emacsen."
16203 (if (and local (featurep 'xemacs))
16204 (add-local-hook hook function append)
16205 (add-hook hook function append local)))
16207 (defun org-region-active-p ()
16208 "Is `transient-mark-mode' on and the region active?
16209 Works on both Emacs and XEmacs."
16210 (if org-ignore-region
16212 (if (featurep 'xemacs)
16213 (and zmacs-regions (region-active-p))
16214 (and transient-mark-mode mark-active))))
16216 (defun org-add-to-invisibility-spec (arg)
16217 "Add elements to `buffer-invisibility-spec'.
16218 See documentation for `buffer-invisibility-spec' for the kind of elements
16219 that can be added."
16220 (cond
16221 ((fboundp 'add-to-invisibility-spec)
16222 (add-to-invisibility-spec arg))
16223 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
16224 (setq buffer-invisibility-spec (list arg)))
16226 (setq buffer-invisibility-spec
16227 (cons arg buffer-invisibility-spec)))))
16229 (defun org-remove-from-invisibility-spec (arg)
16230 "Remove elements from `buffer-invisibility-spec'."
16231 (if (fboundp 'remove-from-invisibility-spec)
16232 (remove-from-invisibility-spec arg)
16233 (if (consp buffer-invisibility-spec)
16234 (setq buffer-invisibility-spec
16235 (delete arg buffer-invisibility-spec)))))
16237 (defun org-in-invisibility-spec-p (arg)
16238 "Is ARG a member of `buffer-invisibility-spec'?"
16239 (if (consp buffer-invisibility-spec)
16240 (member arg buffer-invisibility-spec)
16241 nil))
16243 (defun org-image-file-name-regexp ()
16244 "Return regexp matching the file names of images."
16245 (if (fboundp 'image-file-name-regexp)
16246 (image-file-name-regexp)
16247 (let ((image-file-name-extensions
16248 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16249 "xbm" "xpm" "pbm" "pgm" "ppm")))
16250 (concat "\\."
16251 (regexp-opt (nconc (mapcar 'upcase
16252 image-file-name-extensions)
16253 image-file-name-extensions)
16255 "\\'"))))
16257 ;; Functions extending outline functionality
16259 ;; C-a should go to the beginning of a *visible* line, also in the
16260 ;; new outline.el. I guess this should be patched into Emacs?
16261 (defun org-beginning-of-line ()
16262 "Go to the beginning of the current line. If that is invisible, continue
16263 to a visible line beginning. This makes the function of C-a more intuitive."
16264 (interactive)
16265 (beginning-of-line 1)
16266 (if (bobp)
16268 (backward-char 1)
16269 (if (org-invisible-p)
16270 (while (and (not (bobp)) (org-invisible-p))
16271 (backward-char 1)
16272 (beginning-of-line 1))
16273 (forward-char 1))))
16275 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16277 (defun org-invisible-p ()
16278 "Check if point is at a character currently not visible."
16279 ;; Early versions of noutline don't have `outline-invisible-p'.
16280 (if (fboundp 'outline-invisible-p)
16281 (outline-invisible-p)
16282 (get-char-property (point) 'invisible)))
16284 (defun org-invisible-p2 ()
16285 "Check if point is at a character currently not visible."
16286 (save-excursion
16287 (if (and (eolp) (not (bobp))) (backward-char 1))
16288 ;; Early versions of noutline don't have `outline-invisible-p'.
16289 (if (fboundp 'outline-invisible-p)
16290 (outline-invisible-p)
16291 (get-char-property (point) 'invisible))))
16293 (defalias 'org-back-to-heading 'outline-back-to-heading)
16294 (defalias 'org-on-heading-p 'outline-on-heading-p)
16296 (defun org-on-target-p ()
16297 (let ((pos (point)))
16298 (save-excursion
16299 (skip-chars-forward "<")
16300 (and (re-search-backward "<<" nil t)
16301 (or (looking-at org-radio-target-regexp)
16302 (looking-at org-target-regexp))
16303 (<= (match-beginning 0) pos)
16304 (>= (1+ (match-end 0)) pos)))))
16306 (defun org-up-heading-all (arg)
16307 "Move to the heading line of which the present line is a subheading.
16308 This function considers both visible and invisible heading lines.
16309 With argument, move up ARG levels."
16310 (if (fboundp 'outline-up-heading-all)
16311 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16312 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16314 (defun org-show-hidden-entry ()
16315 "Show an entry where even the heading is hidden."
16316 (save-excursion
16317 (org-show-entry)))
16319 (defun org-flag-heading (flag &optional entry)
16320 "Flag the current heading. FLAG non-nil means make invisible.
16321 When ENTRY is non-nil, show the entire entry."
16322 (save-excursion
16323 (org-back-to-heading t)
16324 ;; Check if we should show the entire entry
16325 (if entry
16326 (progn
16327 (org-show-entry)
16328 (save-excursion
16329 (and (outline-next-heading)
16330 (org-flag-heading nil))))
16331 (outline-flag-region (max 1 (1- (point)))
16332 (save-excursion (outline-end-of-heading) (point))
16333 flag))))
16335 (defun org-end-of-subtree (&optional invisible-OK)
16336 ;; This is an exact copy of the original function, but it uses
16337 ;; `org-back-to-heading', to make it work also in invisible
16338 ;; trees. And is uses an invisible-OK argument.
16339 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16340 (org-back-to-heading invisible-OK)
16341 (let ((first t)
16342 (level (funcall outline-level)))
16343 (while (and (not (eobp))
16344 (or first (> (funcall outline-level) level)))
16345 (setq first nil)
16346 (outline-next-heading))
16347 (if (memq (preceding-char) '(?\n ?\^M))
16348 (progn
16349 ;; Go to end of line before heading
16350 (forward-char -1)
16351 (if (memq (preceding-char) '(?\n ?\^M))
16352 ;; leave blank line before heading
16353 (forward-char -1)))))
16354 (point))
16356 (defun org-show-subtree ()
16357 "Show everything after this heading at deeper levels."
16358 (outline-flag-region
16359 (point)
16360 (save-excursion
16361 (outline-end-of-subtree) (outline-next-heading) (point))
16362 nil))
16364 (defun org-show-entry ()
16365 "Show the body directly following this heading.
16366 Show the heading too, if it is currently invisible."
16367 (interactive)
16368 (save-excursion
16369 (org-back-to-heading t)
16370 (outline-flag-region
16371 (max 1 (1- (point)))
16372 (save-excursion
16373 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
16374 (or (match-beginning 1) (point-max)))
16375 nil)))
16377 (defun org-make-options-regexp (kwds)
16378 "Make a regular expression for keyword lines."
16379 (concat
16381 "#?[ \t]*\\+\\("
16382 (mapconcat 'regexp-quote kwds "\\|")
16383 "\\):[ \t]*"
16384 "\\(.+\\)"))
16386 ;; Make `bookmark-jump' show the jump location if it was hidden.
16387 (eval-after-load "bookmark"
16388 '(if (boundp 'bookmark-after-jump-hook)
16389 ;; We can use the hook
16390 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16391 ;; Hook not available, use advice
16392 (defadvice bookmark-jump (after org-make-visible activate)
16393 "Make the position visible."
16394 (org-bookmark-jump-unhide))))
16396 (defun org-bookmark-jump-unhide ()
16397 "Unhide the current position, to show the bookmark location."
16398 (and (org-mode-p)
16399 (or (org-invisible-p)
16400 (save-excursion (goto-char (max (point-min) (1- (point))))
16401 (org-invisible-p)))
16402 (org-show-hierarchy-above)))
16404 ;;; Experimental code
16407 ;;; Finish up
16409 (provide 'org)
16411 (run-hooks 'org-load-hook)
16413 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16414 ;;; org.el ends here