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.
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/
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)
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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
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)
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
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.
94 ;; - Shift-curser keys can modify inactive time stamps (inactive time
95 ;; stamps are the ones in [...] brackets.
96 ;; - Toggle all checkboxes in a region/below a headline.
103 ;; - Special tag ARCHIVE keeps a subtree closed and away from agenda lists.
104 ;; - LaTeX code in Org-mode files can be converted to images for HTML.
106 ;; - CDLaTeX-mode features can be used in Org-mode to help inserting
107 ;; LaTeX environment and math.
110 ;; - noutline.el is now required (important for XEmacs users only).
112 ;; - Archiving of all level 1 trees without open TODO items.
113 ;; - Clock reports can be inserted into the file in a special section.
114 ;; - FAQ removed from the manual, now only on the web.
118 ;; - Clock-feature for measuring time spent on specific items.
119 ;; - Improved emphasizing allows configuration and stacking.
122 ;; - Improved indentation of ASCII export, when headlines become items.
123 ;; - Handling of 12am and 12pm fixed. Times beyond 24:00 can be used
124 ;; and will not lead to conflicts.
125 ;; - Support for mutually exclusive TAGS with the fast tags interface.
129 ;; - HTML export is now valid XHTML.
130 ;; - Timeline can also show dates without entries. See new option
131 ;; `org-timeline-show-empty-dates'.
132 ;; - The bullets created by the ASCII exporter can now be configured.
133 ;; See the new option `org-export-ascii-bullets'.
134 ;; - New face `org-upcoming-deadline' (was `org-scheduled-previously').
135 ;; - New function `org-context' to allow testing for local context.
141 ;; - New commands to move through plain lists: S-up and S-down.
142 ;; - Bug fixes and documentation update.
145 ;; - Fast (single-key-per-tag) interface for setting TAGS.
146 ;; - The list of legal tags can be configured globally and locally.
147 ;; - Elisp and Info links (thanks to Todd Neal).
148 ;; - `org-export-publishing-directory' can be an alist, with different
149 ;; directories for different export types.
150 ;; - All context-sensitive commands use `call-interactively' to dispatch.
151 ;; - `org-confirm-shell-links' renamed to `org-confirm-shell-link-function'.
158 ;; - Modified installation: Autoloads have been collected in org-install.el.
159 ;; - Logging (org-log-done) is now a #+STARTUP option.
160 ;; - Checkboxes in plain list items, following up on Frank Ruell's idea.
161 ;; - File links inserted with C-c C-l will use relative paths if the linked
162 ;; file is in the current directory or a subdirectory of it.
163 ;; - New variable `org-link-file-path-type' to specify preference for
164 ;; relative and absolute paths.
165 ;; - New CSS classes for tags, timestamps, timestamp keywords.
166 ;; - Bug and typo fixes.
169 ;; - Inlining images in HTML export now depends on wheather the link
170 ;; contains a description or not.
171 ;; - TODO items can be scheduled from the global TODO list using C-c C-s.
172 ;; - TODO items already scheduled can be made to disappear from the global
173 ;; todo list, see `org-agenda-todo-ignore-scheduled'.
174 ;; - In Tables, formulas may also be Lisp forms.
175 ;; - Exporting the visible part of an outline with `C-c C-x v' works now
176 ;; for all available exporters.
177 ;; - Bug fixes, lots of them :-(
183 ;; - HTML exporter generalized to receive external options.
184 ;; As part of the process, author, email and date have been moved to the
185 ;; end of the HTML file.
186 ;; - Support for customizable file search in file links.
187 ;; - BibTeX database links as first application of the above.
188 ;; - New option `org-agenda-todo-list-sublevels' to turn off listing TODO
189 ;; entries that are sublevels of another TODO entry.
197 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
198 ;; the file noutline.el being loaded.
199 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
200 ;; We require noutline, which might be provided in outline.el
201 (require 'outline) (require 'noutline)
202 ;; Other stuff we need.
206 ;;; Customization variables
208 (defvar org-version "4.41"
209 "The version number of the file org.el.")
210 (defun org-version ()
212 (message "Org-mode version %s" org-version))
214 ;; The following constant is for compatibility with different versions
216 (defconst org-noutline-p (featurep 'noutline)
217 "Are we using the new outline mode?")
218 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
219 (defconst org-format-transports-properties-p
221 (add-text-properties 0 1 '(test t) x)
222 (get-text-property 0 'test (format "%s" x)))
223 "Does format transport text properties?")
226 "Outline-based notes management and organizer."
232 (defgroup org-startup nil
233 "Options concerning startup of Org-mode."
237 (defcustom org-startup-folded t
238 "Non-nil means, entering Org-mode will switch to OVERVIEW.
239 This can also be configured on a per-file basis by adding one of
240 the following lines anywhere in the buffer:
247 (const :tag "nofold: show all" nil)
248 (const :tag "fold: overview" t)
249 (const :tag "content: all headlines" content)))
251 (defcustom org-startup-truncated t
252 "Non-nil means, entering Org-mode will set `truncate-lines'.
253 This is useful since some lines containing links can be very long and
254 uninteresting. Also tables look terrible when wrapped."
258 (defcustom org-startup-align-all-tables nil
259 "Non-nil means, align all tables when visiting a file.
260 This is useful when the column width in tables is forced with <N> cookies
261 in table fields. Such tables will look correct only after the first re-align.
262 This can also be configured on a per-file basis by adding one of
263 the following lines anywhere in the buffer:
269 (defcustom org-startup-with-deadline-check nil
270 "Non-nil means, entering Org-mode will run the deadline check.
271 This means, if you start editing an org file, you will get an
272 immediate reminder of any due deadlines.
273 This can also be configured on a per-file basis by adding one of
274 the following lines anywhere in the buffer:
276 #+STARTUP: nodlcheck"
280 (defcustom org-insert-mode-line-in-empty-file nil
281 "Non-nil means insert the first line setting Org-mode in empty files.
282 When the function `org-mode' is called interactively in an empty file, this
283 normally means that the file name does not automatically trigger Org-mode.
284 To ensure that the file will always be in Org-mode in the future, a
285 line enforcing Org-mode will be inserted into the buffer, if this option
290 (defcustom org-CUA-compatible nil
291 "Non-nil means use alternative key bindings for S-<cursor movement>.
292 Org-mode used S-<cursor movement> for changing timestamps and priorities.
293 S-<cursor movement> is also used for example by `CUA-mode' to select text.
294 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
295 alternative bindings. Setting this variable to t will replace the following
296 keys both in Org-mode and in the Org-agenda buffer.
304 If you do not like the alternative keys, take a look at the variable
307 This option is only relevant at load-time of Org-mode. Changing it requires
308 a restart of Emacs to become effective."
312 (defvar org-disputed-keys
313 '((S-up [(shift up)] [(meta ?p)])
314 (S-down [(shift down)] [(meta ?n)])
315 (S-left [(shift left)] [(meta ?-)])
316 (S-right [(shift right)] [(meta ?+)])
317 (S-return [(shift return)] [(control shift return)]))
318 "Keys for which Org-mode and other modes compete.
319 This is an alist, cars are symbols for lookup, 1st element is the default key,
320 second element will be used when `org-CUA-compatible' is t.")
323 "Select a key according to `org-CUA-compatible'."
324 (nth (if org-CUA-compatible 2 1)
325 (or (assq key org-disputed-keys)
326 (error "Invalid Key %s in `org-key'" key))))
328 (defcustom org-ellipsis nil
329 "The ellipsis to use in the Org-mode outline.
330 When nil, just use the standard three dots. When a string, use that instead,
331 and just in Org-mode (which will then use its own display table).
332 Changing this requires executing `M-x org-mode' in a buffer to become
335 :type '(choice (const :tag "Default" nil)
336 (string :tag "String" :value "...#")))
338 (defvar org-display-table nil
339 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
341 (defgroup org-keywords nil
342 "Keywords in Org-mode."
346 (defcustom org-deadline-string "DEADLINE:"
347 "String to mark deadline entries.
348 A deadline is this string, followed by a time stamp. Should be a word,
349 terminated by a colon. You can insert a schedule keyword and
350 a timestamp with \\[org-deadline].
351 Changes become only effective after restarting Emacs."
355 (defcustom org-scheduled-string "SCHEDULED:"
356 "String to mark scheduled TODO entries.
357 A schedule is this string, followed by a time stamp. Should be a word,
358 terminated by a colon. You can insert a schedule keyword and
359 a timestamp with \\[org-schedule].
360 Changes become only effective after restarting Emacs."
364 (defcustom org-closed-string "CLOSED:"
365 "String used as the prefix for timestamps logging closing a TODO entry."
369 (defcustom org-clock-string "CLOCK:"
370 "String used as prefix for timestamps clocking work hours on an item."
374 (defcustom org-comment-string "COMMENT"
375 "Entries starting with this keyword will never be exported.
376 An entry can be toggled between COMMENT and normal with
377 \\[org-toggle-comment].
378 Changes become only effective after restarting Emacs."
382 (defcustom org-quote-string "QUOTE"
383 "Entries starting with this keyword will be exported in fixed-width font.
384 Quoting applies only to the text in the entry following the headline, and does
385 not extend beyond the next headline, even if that is lower level.
386 An entry can be toggled between QUOTE and normal with
387 \\[org-toggle-fixed-width-section]."
391 (defgroup org-structure nil
392 "Options concerning the general structure of Org-mode files."
396 (defgroup org-cycle nil
397 "Options concerning visibility cycling in Org-mode."
399 :group 'org-structure)
401 (defcustom org-cycle-global-at-bob t
402 "Cycle globally if cursor is at beginning of buffer and not at a headline.
403 This makes it possible to do global cycling without having to use S-TAB or
404 C-u TAB. For this special case to work, the first line of the buffer
405 must not be a headline - it may be empty ot some other text. When used in
406 this way, `org-cycle-hook' is disables temporarily, to make sure the
407 cursor stays at the beginning of the buffer.
408 When this option is nil, don't do anything special at the beginning
413 (defcustom org-cycle-emulate-tab t
414 "Where should `org-cycle' emulate TAB.
416 white Only in completely white lines
417 whitestart Only at the beginning of lines, before the first non-white char.
418 t Everywhere except in headlines
419 If TAB is used in a place where it does not emulate TAB, the current subtree
420 visibility is cycled."
422 :type '(choice (const :tag "Never" nil)
423 (const :tag "Only in completely white lines" white)
424 (const :tag "Before first char in a line" whitestart)
425 (const :tag "Everywhere except in headlines" t)
428 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
429 org-optimize-window-after-visibility-change)
430 "Hook that is run after `org-cycle' has changed the buffer visibility.
431 The function(s) in this hook must accept a single argument which indicates
432 the new state that was set by the most recent `org-cycle' command. The
433 argument is a symbol. After a global state change, it can have the values
434 `overview', `content', or `all'. After a local state change, it can have
435 the values `folded', `children', or `subtree'."
439 (defgroup org-edit-structure nil
440 "Options concerning structure editing in Org-mode."
441 :tag "Org Edit Structure"
442 :group 'org-structure)
444 (defcustom org-odd-levels-only nil
445 "Non-nil means, skip even levels and only use odd levels for the outline.
446 This has the effect that two stars are being added/taken away in
447 promotion/demotion commands. It also influences how levels are
448 handled by the exporters.
449 Changing it requires restart of `font-lock-mode' to become effective
450 for fontification also in regions already fontified.
451 You may also set this on a per-file basis by adding one of the following
456 :group 'org-edit-structure
457 :group 'org-font-lock
460 (defcustom org-adapt-indentation t
461 "Non-nil means, adapt indentation when promoting and demoting.
462 When this is set and the *entire* text in an entry is indented, the
463 indentation is increased by one space in a demotion command, and
464 decreased by one in a promotion command. If any line in the entry
465 body starts at column 0, indentation is not changed at all."
466 :group 'org-edit-structure
469 (defcustom org-insert-heading-hook nil
470 "Hook being run after inserting a new heading."
471 :group 'org-edit-structure
474 (defcustom org-enable-fixed-width-editor t
475 "Non-nil means, lines starting with \":\" are treated as fixed-width.
476 This currently only means, they are never auto-wrapped.
477 When nil, such lines will be treated like ordinary lines.
478 See also the QUOTE keyword."
479 :group 'org-edit-structure
482 (defgroup org-sparse-trees nil
483 "Options concerning sparse trees in Org-mode."
484 :tag "Org Sparse Trees"
485 :group 'org-structure)
487 (defcustom org-highlight-sparse-tree-matches t
488 "Non-nil means, highlight all matches that define a sparse tree.
489 The highlights will automatically disappear the next time the buffer is
490 changed by an edit command."
491 :group 'org-sparse-trees
494 (defcustom org-show-hierarchy-above t
495 "Non-nil means, show full hierarchy when showing a spot in the tree.
496 Turning this off makes sparse trees more compact, but also less clear."
497 :group 'org-sparse-trees
500 (defcustom org-show-following-heading t
501 "Non-nil means, show heading following match in `org-occur'.
502 When doing an `org-occur' it is useful to show the headline which
503 follows the match, even if they do not match the regexp. This makes it
504 easier to edit directly inside the sparse tree. However, if you use
505 `org-occur' mainly as an overview, the following headlines are
506 unnecessary clutter."
507 :group 'org-sparse-trees
510 (defcustom org-occur-hook '(org-first-headline-recenter)
511 "Hook that is run after `org-occur' has constructed a sparse tree.
512 This can be used to recenter the window to show as much of the structure
514 :group 'org-sparse-trees
517 (defgroup org-plain-lists nil
518 "Options concerning plain lists in Org-mode."
519 :tag "Org Plain lists"
520 :group 'org-structure)
522 (defcustom org-cycle-include-plain-lists nil
523 "Non-nil means, include plain lists into visibility cycling.
524 This means that during cycling, plain list items will *temporarily* be
525 interpreted as outline headlines with a level given by 1000+i where i is the
526 indentation of the bullet. In all other operations, plain list items are
527 not seen as headlines. For example, you cannot assign a TODO keyword to
529 :group 'org-plain-lists
533 (defcustom org-plain-list-ordered-item-terminator t
534 "The character that makes a line with leading number an ordered list item.
535 Valid values are ?. and ?\). To get both terminators, use t. While
536 ?. may look nicer, it creates the danger that a line with leading
537 number may be incorrectly interpreted as an item. ?\) therefore is
539 :group 'org-plain-lists
540 :type '(choice (const :tag "dot like in \"2.\"" ?.)
541 (const :tag "paren like in \"2)\"" ?\))
542 (const :tab "both" t)))
544 (defcustom org-auto-renumber-ordered-lists t
545 "Non-nil means, automatically renumber ordered plain lists.
546 Renumbering happens when the sequence have been changed with
547 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
548 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
549 :group 'org-plain-lists
552 (defgroup org-archive nil
553 "Options concerning archiving in Org-mode."
555 :group 'org-structure)
557 (defcustom org-archive-tag "ARCHIVE"
558 "The tag that marks a subtree as archived.
559 An archived subtree does not open during visibility cycling, and does
560 not contribute to the agenda listings."
565 (defcustom org-agenda-skip-archived-trees t
566 "Non-nil means, the agenda will skip any items located in archived trees.
567 An archived tree is a tree marked with the tag ARCHIVE."
569 :group 'org-agenda-display
572 (defcustom org-cycle-open-archived-trees nil
573 "Non-nil means, `org-cycle' will open archived trees.
574 An archived tree is a tree marked with the tag ARCHIVE.
575 When nil, archived trees will stay folded. You can still open them with
576 normal outline commands like `show-all', but not with the cycling commands."
581 (defcustom org-sparse-tree-open-archived-trees nil
582 "Non-nil means sparse tree construction shows matches in archived trees.
583 When nil, matches in these trees are highlighted, but the trees are kept in
586 :group 'org-sparse-trees
589 (defcustom org-archive-location "%s_archive::"
590 "The location where subtrees should be archived.
591 This string consists of two parts, separated by a double-colon.
593 The first part is a file name - when omitted, archiving happens in the same
594 file. %s will be replaced by the current file name (without directory part).
595 Archiving to a different file is useful to keep archived entries from
596 contributing to the Org-mode Agenda.
598 The part after the double colon is a headline. The archived entries will be
599 filed under that headline. When omitted, the subtrees are simply filed away
600 at the end of the file, as top-level entries.
602 Here are a few examples:
604 If the current file is Projects.org, archive in file
605 Projects.org_archive, as top-level trees. This is the default.
607 \"::* Archived Tasks\"
608 Archive in the current file, under the top-level headline
609 \"* Archived Tasks\".
611 \"~/org/archive.org::\"
612 Archive in file ~/org/archive.org (absolute path), as top-level trees.
614 \"basement::** Finished Tasks\"
615 Archive in file ./basement (relative path), as level 3 trees
616 below the level 2 heading \"** Finished Tasks\".
618 You may set this option on a per-file basis by adding to the buffer a
621 #+ARCHIVE: basement::** Finished Tasks"
625 (defcustom org-archive-mark-done t
626 "Non-nil means, mark entries as DONE when they are moved to the archive file."
630 (defcustom org-archive-stamp-time t
631 "Non-nil means, add a time stamp to entries moved to an archive file.
632 The time stamp will be added directly after the TODO state keyword in the
633 first line, so it is probably best to use this in combinations with
634 `org-archive-mark-done'."
638 (defgroup org-table nil
639 "Options concerning tables in Org-mode."
643 (defcustom org-enable-table-editor 'optimized
644 "Non-nil means, lines starting with \"|\" are handled by the table editor.
645 When nil, such lines will be treated like ordinary lines.
647 When equal to the symbol `optimized', the table editor will be optimized to
649 - Use automatic overwrite mode in front of whitespace in table fields.
650 This make the structure of the table stay in tact as long as the edited
651 field does not exceed the column width.
652 - Minimize the number of realigns. Normally, the table is aligned each time
653 TAB or RET are pressed to move to another field. With optimization this
654 happens only if changes to a field might have changed the column width.
655 Optimization requires replacing the functions `self-insert-command',
656 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
657 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
658 very good at guessing when a re-align will be necessary, but you can always
659 force one with \\[org-ctrl-c-ctrl-c].
661 If you would like to use the optimized version in Org-mode, but the
662 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
664 This variable can be used to turn on and off the table editor during a session,
665 but in order to toggle optimization, a restart is required.
667 See also the variable `org-table-auto-blank-field'."
670 (const :tag "off" nil)
672 (const :tag "on, optimized" optimized)))
674 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
675 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
676 In the optimized version, the table editor takes over all simple keys that
677 normally just insert a character. In tables, the characters are inserted
678 in a way to minimize disturbing the table structure (i.e. in overwrite mode
679 for empty fields). Outside tables, the correct binding of the keys is
682 The default for this option is t if the optimized version is also used in
683 Org-mode. See the variable `org-enable-table-editor' for details. Changing
684 this variable requires a restart of Emacs to become effective."
688 (defgroup org-table-settings nil
689 "Settings for tables in Org-mode."
690 :tag "Org Table Settings"
693 (defcustom org-table-default-size "5x2"
694 "The default size for newly created tables, Columns x Rows."
695 :group 'org-table-settings
698 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
699 "Regular expression for recognizing numbers in table columns.
700 If a table column contains mostly numbers, it will be aligned to the
701 right. If not, it will be aligned to the left.
703 The default value of this option is a regular expression which allows
704 anything which looks remotely like a number as used in scientific
705 context. For example, all of the following will be considered a
707 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
709 Other options offered by the customize interface are more restrictive."
710 :group 'org-table-settings
712 (const :tag "Positive Integers"
714 (const :tag "Integers"
716 (const :tag "Floating Point Numbers"
717 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
718 (const :tag "Floating Point Number or Integer"
719 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
720 (const :tag "Exponential, Floating point, Integer"
721 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
722 (const :tag "Very General Number-Like"
723 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
724 (string :tag "Regexp:")))
726 (defcustom org-table-number-fraction 0.5
727 "Fraction of numbers in a column required to make the column align right.
728 In a column all non-white fields are considered. If at least this
729 fraction of fields is matched by `org-table-number-fraction',
730 alignment to the right border applies."
731 :group 'org-table-settings
734 (defgroup org-table-editing nil
735 "Bahavior of tables during editing in Org-mode."
736 :tag "Org Table Editing"
739 (defcustom org-table-automatic-realign t
740 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
741 When nil, aligning is only done with \\[org-table-align], or after column
743 :group 'org-table-editing
746 (defcustom org-table-limit-column-width t ;kw
747 "Non-nil means, allow to limit the width of table columns with <N> fields."
748 :group 'org-table-editing
751 (defcustom org-table-auto-blank-field t
752 "Non-nil means, automatically blank table field when starting to type into it.
753 This only happens when typing immediately after a field motion
754 command (TAB, S-TAB or RET).
755 Only relevant when `org-enable-table-editor' is equal to `optimized'."
756 :group 'org-table-editing
759 (defcustom org-table-tab-jumps-over-hlines t
760 "Non-nil means, tab in the last column of a table with jump over a hline.
761 If a horizontal separator line is following the current line,
762 `org-table-next-field' can either create a new row before that line, or jump
763 over the line. When this option is nil, a new line will be created before
765 :group 'org-table-editing
768 (defcustom org-table-tab-recognizes-table.el t
769 "Non-nil means, TAB will automatically notice a table.el table.
770 When it sees such a table, it moves point into it and - if necessary -
771 calls `table-recognize-table'."
772 :group 'org-table-editing
775 (defgroup org-table-calculation nil
776 "Options concerning tables in Org-mode."
777 :tag "Org Table Calculation"
780 (defcustom org-table-copy-increment t
781 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
782 :group 'org-table-calculation
785 (defcustom org-calc-default-modes
786 '(calc-internal-prec 12
787 calc-float-format (float 5)
790 calc-symbolic-mode nil
791 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
792 calc-display-working-message t
794 "List with Calc mode settings for use in calc-eval for table formulas.
795 The list must contain alternating symbols (Calc modes variables and values).
796 Don't remove any of the default settings, just change the values. Org-mode
797 relies on the variables to be present in the list."
798 :group 'org-table-calculation
801 (defcustom org-table-formula-evaluate-inline t
802 "Non-nil means, TAB and RET evaluate a formula in current table field.
803 If the current field starts with an equal sign, it is assumed to be a formula
804 which should be evaluated as described in the manual and in the documentation
805 string of the command `org-table-eval-formula'. This feature requires the
807 When this variable is nil, formula calculation is only available through
808 the command \\[org-table-eval-formula]."
809 :group 'org-table-calculation
813 (defcustom org-table-formula-use-constants t
814 "Non-nil means, interpret constants in formulas in tables.
815 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
816 by the value given in `org-table-formula-constants', or by a value obtained
817 from the `constants.el' package."
818 :group 'org-table-calculation
821 (defcustom org-table-formula-constants nil
822 "Alist with constant names and values, for use in table formulas.
823 The car of each element is a name of a constant, without the `$' before it.
824 The cdr is the value as a string. For example, if you'd like to use the
825 speed of light in a formula, you would configure
827 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
829 and then use it in an equation like `$1*$c'."
830 :group 'org-table-calculation
832 (cons (string :tag "name")
833 (string :tag "value"))))
835 (defcustom org-table-formula-numbers-only nil
836 "Non-nil means, calculate only with numbers in table formulas.
837 Then all input fields will be converted to a number, and the result
838 must also be a number. When nil, calc's full potential is available
839 in table calculations, including symbolics etc."
840 :group 'org-table-calculation
843 (defcustom org-table-allow-automatic-line-recalculation t
844 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
845 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
846 :group 'org-table-calculation
849 (defgroup org-link nil
850 "Options concerning links in Org-mode."
854 (defcustom org-descriptive-links t
855 "Non-nil means, hide link part and only show description of bracket links.
856 Bracket links are like [[link][descritpion]]. This variable sets the initial
857 state in new org-mode buffers. The setting can then be toggled on a
858 per-buffer basis from the Org->Hyperlinks menu."
862 (defcustom org-link-style 'bracket
863 "The style of links to be inserted with \\[org-insert-link].
865 bracket [[link][description]]. This is recommended
866 plain Description \\n link. The old way, no longer recommended."
869 (const :tag "Bracket (recommended)" bracket)
870 (const :tag "Plain (no longer recommended)" plain)))
872 (defcustom org-link-format "%s"
873 "Default format for external, URL-like linkes in the buffer.
874 This is a format string for printf, %s will be replaced by the link text.
875 The recommended value is just \"%s\", since links will be protected by
876 enclosing them in double brackets. If you prefer plain links (see variable
877 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
878 additional URL: prefix, so the format would be \"<URL:%s>\"."
881 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
882 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
883 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
884 (string :tag "Other" :value "<%s>")))
886 (defcustom org-link-file-path-type 'adaptive
887 "How the path name in file links should be stored.
890 relative relative to the current directory, i.e. the directory of the file
891 into which the link is being inserted.
892 absolute absolute path, if possible with ~ for home directory.
893 noabbrev absolute path, no abbreviation of home directory.
894 adaptive Use relative path for files in the current directory and sub-
895 directories of it. For other files, use an absolute path."
903 (defcustom org-activate-links '(bracket angle plain radio tag date)
904 "Types of links that should be activated in Org-mode files.
905 This is a list of symbols, each leading to the activation of a certain link
906 type. In principle, it does not hurt to turn on most link types - there may
907 be a small gain when turning off unused link types. The types are:
909 bracket The recommended [[link][description]] or [[link]] links with hiding.
910 angular Links in angular brackes that may contain whitespace like
911 <bbdb:Carsten Dominik>.
912 plain Plain links in normal text, no whitespace, like http://google.com.
913 radio Text that is matched by a radio target, see manual for details.
914 tag Tag settings in a headline (link to tag search).
915 date Time stamps (link to calendar).
916 camel CamelCase words defining text searches.
918 Changing this variable requires a restart of Emacs to become effective."
920 :type '(set (const :tag "Double bracket links (new style)" bracket)
921 (const :tag "Angular bracket links (old style)" angular)
922 (const :tag "plain text links" plain)
923 (const :tag "Radio target matches" radio)
924 (const :tag "Tags" tag)
925 (const :tag "Timestamps" date)
926 (const :tag "CamelCase words" camel)))
928 (defgroup org-link-store nil
929 "Options concerning storing links in Org-mode"
930 :tag "Org Store Link"
933 (defcustom org-context-in-file-links t
934 "Non-nil means, file links from `org-store-link' contain context.
935 A search string will be added to the file name with :: as separator and
936 used to find the context when the link is activated by the command
938 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
939 negates this setting for the duration of the command."
940 :group 'org-link-store
943 (defcustom org-file-link-context-use-camel-case nil
944 "Non-nil means, use CamelCase to store a search context in a file link.
945 When nil, the search string simply consists of the words of the string.
946 CamelCase is deprecated, and support for it may be dropped in the future."
947 :group 'org-link-store
950 (defcustom org-keep-stored-link-after-insertion nil
951 "Non-nil means, keep link in list for entire session.
953 The command `org-store-link' adds a link pointing to the current
954 location to an internal list. These links accumulate during a session.
955 The command `org-insert-link' can be used to insert links into any
956 Org-mode file (offering completion for all stored links). When this
957 option is nil, every link which has been inserted once using \\[org-insert-link]
958 will be removed from the list, to make completing the unused links
960 :group 'org-link-store
963 (defcustom org-usenet-links-prefer-google nil
964 "Non-nil means, `org-store-link' will create web links to Google groups.
965 When nil, Gnus will be used for such links.
966 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
967 negates this setting for the duration of the command."
968 :group 'org-link-store
971 (defgroup org-link-follow nil
972 "Options concerning following links in Org-mode"
973 :tag "Org Follow Link"
976 (defcustom org-tab-follows-link nil
977 "Non-nil means, on links TAB will follow the link.
978 Needs to be set before org.el is loaded."
979 :group 'org-link-follow
982 (defcustom org-return-follows-link nil
983 "Non-nil means, on links RET will follow the link.
984 Needs to be set before org.el is loaded."
985 :group 'org-link-follow
988 (defcustom org-mouse-1-follows-link t
989 "Non-nil means, mouse-1 on a link will follow the link.
990 A longer mouse click will still set point. Does not wortk on XEmacs.
991 Needs to be set before org.el is loaded."
992 :group 'org-link-follow
995 (defcustom org-mark-ring-length 4
996 "Number of different positions to be recorded in the ring
997 Changing this requires a restart of Emacs to work correctly."
998 :group 'org-link-follow
1001 (defcustom org-link-frame-setup
1002 '((vm . vm-visit-folder-other-frame)
1003 (gnus . gnus-other-frame)
1004 (file . find-file-other-window))
1005 "Setup the frame configuration for following links.
1006 When following a link with Emacs, it may often be useful to display
1007 this link in another window or frame. This variable can be used to
1008 set this up for the different types of links.
1011 `vm-visit-folder-other-frame'
1012 For Gnus, use any of
1015 For FILE, use any of
1017 `find-file-other-window'
1018 `find-file-other-frame'
1019 For the calendar, use the variable `calendar-setup'.
1020 For BBDB, it is currently only possible to display the matches in
1022 :group 'org-link-follow
1026 (const vm-visit-folder)
1027 (const vm-visit-folder-other-window)
1028 (const vm-visit-folder-other-frame)))
1032 (const gnus-other-frame)))
1036 (const find-file-other-window)
1037 (const find-file-other-frame)))))
1039 (defcustom org-open-non-existing-files nil
1040 "Non-nil means, `org-open-file' will open non-existing file.
1041 When nil, an error will be generated."
1042 :group 'org-link-follow
1045 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1046 "Non-nil means, ask for confirmation before executing shell links.
1047 Shell links can be dangerous, just thing about a link
1049 [[shell:rm -rf ~/*][Google Search]]
1051 This link would show up in your Org-mode document as \"Google Search\"
1052 but really it would remove your entire home directory.
1053 Therefore I *definitely* advise against setting this variable to nil.
1054 Just change it to `y-or-n-p' of you want to confirm with a single key press
1055 rather than having to type \"yes\"."
1056 :group 'org-link-follow
1058 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1059 (const :tag "with y-or-n (faster)" y-or-n-p)
1060 (const :tag "no confirmation (dangerous)" nil)))
1062 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1063 "Non-nil means, ask for confirmation before executing elisp links.
1064 Elisp links can be dangerous, just thing about a link
1066 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1068 This link would show up in your Org-mode document as \"Google Search\"
1069 but really it would remove your entire home directory.
1070 Therefore I *definitely* advise against setting this variable to nil.
1071 Just change it to `y-or-n-p' of you want to confirm with a single key press
1072 rather than having to type \"yes\"."
1073 :group 'org-link-follow
1075 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1076 (const :tag "with y-or-n (faster)" y-or-n-p)
1077 (const :tag "no confirmation (dangerous)" nil)))
1079 (defconst org-file-apps-defaults-gnu
1082 "Default file applications on a UNIX or GNU/Linux system.
1083 See `org-file-apps'.")
1085 (defconst org-file-apps-defaults-macosx
1091 ("eps.gz" . "gv %s")
1093 ("fig" . "xfig %s"))
1094 "Default file applications on a MacOS X system.
1095 The system \"open\" is known as a default, but we use X11 applications
1096 for some files for which the OS does not have a good default.
1097 See `org-file-apps'.")
1099 (defconst org-file-apps-defaults-windowsnt
1103 (list (if (featurep 'xemacs)
1104 'mswindows-shell-execute
1107 "Default file applications on a Windows NT system.
1108 The system \"open\" is used for most files.
1109 See `org-file-apps'.")
1111 (defcustom org-file-apps
1120 "External applications for opening `file:path' items in a document.
1121 Org-mode uses system defaults for different file types, but
1122 you can use this variable to set the application for a given file
1123 extension. The entries in this list are cons cells where the car identifies
1124 files and the cdr the corresponding command. Possible values for the
1126 \"ext\" A string identifying an extension
1127 `directory' Matches a directory
1128 `remote' Matches a remove file, accessible through tramp or efs.
1129 Remote files most likely should be visited through emacs
1130 because external applications cannot handle such paths.
1131 t Default for all remaining files
1133 Possible values for the command are:
1134 `emacs' The file will be visited by the current Emacs process.
1135 `default' Use the default application for this file type.
1136 string A command to be executed by a shell; %s will be replaced
1137 by the path to the file.
1138 sexp A Lisp form which will be evaluated. The file path will
1139 be available in the Lisp variable `file'.
1140 For more examples, see the system specific constants
1141 `org-file-apps-defaults-macosx'
1142 `org-file-apps-defaults-windowsnt'
1143 `org-file-apps-defaults-gnu'."
1144 :group 'org-link-follow
1146 (cons (choice :value ""
1147 (string :tag "Extension")
1148 (const :tag "Default for unrecognized files" t)
1149 (const :tag "Remote file" remote)
1150 (const :tag "Links to a directory" directory))
1152 (const :tag "Visit with Emacs" emacs)
1153 (const :tag "Use system default" default)
1154 (string :tag "Command")
1155 (sexp :tag "Lisp form")))))
1157 (defcustom org-mhe-search-all-folders nil
1158 "Non-nil means, that the search for the mh-message will be extended to
1159 all folders if the message cannot be found in the folder given in the link.
1160 Searching all folders is very effective with one of the search engines
1161 supported by MH-E, but will be slow with pick."
1162 :group 'org-link-follow
1165 (defgroup org-remember nil
1166 "Options concerning interaction with remember.el."
1170 (defcustom org-directory "~/org"
1171 "Directory with org files.
1172 This directory will be used as default to prompt for org files.
1173 Used by the hooks for remember.el."
1174 :group 'org-remember
1177 (defcustom org-default-notes-file "~/.notes"
1178 "Default target for storing notes.
1179 Used by the hooks for remember.el. This can be a string, or nil to mean
1180 the value of `remember-data-file'."
1181 :group 'org-remember
1183 (const :tag "Default from remember-data-file" nil)
1186 (defcustom org-remember-templates nil
1187 "Templates for the creation of remember buffers.
1188 When nil, just let remember make the buffer.
1189 When not nil, this is a list of 3-element lists. In each entry, the first
1190 element is a character, a unique key to select this template.
1191 The second element is the template. The third element is optional and can
1192 specify a destination file for remember items created with this template.
1193 The default file is given by `org-default-notes-file'.
1195 The template specifies the structure of the remember buffer. It should have
1196 a first line starting with a star, to act as the org-mode headline.
1197 Furthermore, the following %-escapes will be replaced with content:
1198 %t time stamp, date only
1199 %T time stamp with date and time
1200 %u inactive time stamp, date only
1201 %U inactive time stamp with date and time
1203 %a annotation, normally the link created with org-store-link
1204 %i initial content, the region when remember is called with C-u.
1205 If %i is indented, the entire inserted text will be indented as well.
1206 %? This will be removed, and the cursor placed at this position."
1207 :group 'org-remember
1208 :type '(repeat :tag "enabled"
1209 (list :value (?a "\n" nil)
1210 (character :tag "Selection Key")
1211 (string :tag "Template")
1212 (file :tag "Destination file (optional)"))))
1214 (defcustom org-reverse-note-order nil
1215 "Non-nil means, store new notes at the beginning of a file or entry.
1216 When nil, new notes will be filed to the end of a file or entry."
1217 :group 'org-remember
1219 (const :tag "Reverse always" t)
1220 (const :tag "Reverse never" nil)
1221 (repeat :tag "By file name regexp"
1222 (cons regexp boolean))))
1224 (defgroup org-todo nil
1225 "Options concerning TODO items in Org-mode."
1229 (defcustom org-todo-keywords '("TODO" "DONE")
1230 "List of TODO entry keywords.
1231 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1232 considered to mean that the entry is \"done\". All the other mean that
1233 action is required, and will make the entry show up in todo lists, diaries
1235 The command \\[org-todo] cycles an entry through these states, and an
1236 additional state where no keyword is present. For details about this
1237 cycling, see also the variable `org-todo-interpretation'
1238 Changes become only effective after restarting Emacs."
1240 :group 'org-keywords
1241 :type '(repeat (string :tag "Keyword")))
1243 (defcustom org-todo-interpretation 'sequence
1244 "Controls how TODO keywords are interpreted.
1245 This variable is only relevant if `org-todo-keywords' contains more than two
1246 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1248 When `sequence', \\[org-todo] will always switch to the next state in the
1249 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1250 to state when executed several times in direct succession. Otherwise, it
1251 switches directly to DONE from any state.
1252 See the manual for more information."
1254 :group 'org-keywords
1255 :type '(choice (const sequence)
1258 (defcustom org-after-todo-state-change-hook nil
1259 "Hook which is run after the state of a TODO item was changed.
1260 The new state (a string with a TODO keyword, or nil) is available in the
1261 Lisp variable `state'."
1265 (defcustom org-log-done nil
1266 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1267 When the state of an entry is changed from nothing to TODO, remove a previous
1269 This can also be configured on a per-file basis by adding one of
1270 the following lines anywhere in the buffer:
1273 #+STARTUP: nologging"
1277 (defgroup org-priorities nil
1278 "Priorities in Org-mode."
1279 :tag "Org Priorities"
1282 (defcustom org-default-priority ?B
1283 "The default priority of TODO items.
1284 This is the priority an item get if no explicit priority is given."
1285 :group 'org-priorities
1288 (defcustom org-lowest-priority ?C
1289 "The lowest priority of TODO items. A character like ?A, ?B etc."
1290 :group 'org-priorities
1293 (defgroup org-time nil
1294 "Options concerning time stamps and deadlines in Org-mode."
1298 (defcustom org-insert-labeled-timestamps-at-point nil
1299 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1300 When nil, these labeled time stamps are forces into the second line of an
1301 entry, just after the headline. When scheduling from the global TODO list,
1302 the time stamp will always be forced into the second line."
1306 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1307 "Formats for `format-time-string' which are used for time stamps.
1308 It is not recommended to change this constant.")
1310 (defcustom org-time-stamp-rounding-minutes 0
1311 "Number of minutes to round time stamps to upon insertion.
1312 When zero, insert the time unmodified. Useful rounding numbers
1313 should be factors of 60, so for example 5, 10, 15.
1314 When this is not zero, you can still force an exact time-stamp by using
1315 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1319 (defcustom org-deadline-warning-days 30
1320 "No. of days before expiration during which a deadline becomes active.
1321 This variable governs the display in the org file."
1325 (defcustom org-popup-calendar-for-date-prompt t
1326 "Non-nil means, pop up a calendar when prompting for a date.
1327 In the calendar, the date can be selected with mouse-1. However, the
1328 minibuffer will also be active, and you can simply enter the date as well.
1329 When nil, only the minibuffer will be available."
1333 (defcustom org-calendar-follow-timestamp-change t
1334 "Non-nil means, make the calendar window follow timestamp changes.
1335 When a timestamp is modified and the calendar window is visible, it will be
1336 moved to the new date."
1340 (defgroup org-tags nil
1341 "Options concerning tags in Org-mode."
1345 (defcustom org-tag-alist nil
1346 "List of tags allowed in Org-mode files.
1347 When this list is nil, Org-mode will base TAG input on what is already in the
1349 The value of this variable is an alist, the car may be (and should) be a
1350 character that is used to select that tag through the fast-tag-selection
1351 interface. See the manual for details."
1355 (cons (string :tag "Tag name")
1356 (character :tag "Access char"))
1357 (const :tag "Start radio group" (:startgroup))
1358 (const :tag "End radio group" (:endgroup)))))
1360 (defcustom org-use-fast-tag-selection 'auto
1361 "Non-nil means, use fast tag selection scheme.
1362 This is a special interface to select and deselect tags with single keys.
1363 When nil, fast selection is never used.
1364 When the symbol `auto', fast selection is used if and only if selection
1365 characters for tags have been configured, either through the variable
1366 `org-tag-alist' or through a #+TAGS line in the buffer.
1367 When t, fast selection is always used and selection keys are assigned
1368 automatically if necessary."
1371 (const :tag "Always" t)
1372 (const :tag "Never" nil)
1373 (const :tag "When selection characters are configured" 'auto)))
1375 (defcustom org-tags-column 48
1376 "The column to which tags should be indented in a headline.
1377 If this number is positive, it specifies the column. If it is negative,
1378 it means that the tags should be flushright to that column. For example,
1379 -79 works well for a normal 80 character screen."
1383 (defcustom org-auto-align-tags t
1384 "Non-nil means, realign tags after pro/demotion of TODO state change.
1385 These operations change the length of a headline and therefore shift
1386 the tags around. With this options turned on, after each such operation
1387 the tags are again aligned to `org-tags-column'."
1391 (defcustom org-use-tag-inheritance t
1392 "Non-nil means, tags in levels apply also for sublevels.
1393 When nil, only the tags directly given in a specific line apply there.
1394 If you turn off this option, you very likely want to turn on the
1395 companion option `org-tags-match-list-sublevels'."
1399 (defcustom org-tags-match-list-sublevels nil
1400 "Non-nil means list also sublevels of headlines matching tag search.
1401 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1402 the sublevels of a headline matching a tag search often also match
1403 the same search. Listing all of them can create very long lists.
1404 Setting this variable to nil causes subtrees of a match to be skipped.
1405 This option is off by default, because inheritance in on. If you turn
1406 inheritance off, you very likely want to turn this option on.
1408 As a special case, if the tag search is restricted to TODO items, the
1409 value of this variable is ignored and sublevels are always checked, to
1410 make sure all corresponding TODO items find their way into the list."
1414 (defvar org-tags-history nil
1415 "History of minibuffer reads for tags.")
1416 (defvar org-last-tags-completion-table nil
1417 "The last used completion table for tags.")
1419 (defgroup org-agenda nil
1420 "Options concerning agenda display Org-mode."
1424 (defvar org-category nil
1425 "Variable used by org files to set a category for agenda display.
1426 Such files should use a file variable to set it, for example
1428 -*- mode: org; org-category: \"ELisp\"
1430 or contain a special line
1434 If the file does not specify a category, then file's base name
1436 (make-variable-buffer-local 'org-category)
1438 (defcustom org-agenda-files nil
1439 "The files to be used for agenda display.
1440 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1441 \\[org-remove-file]. You can also use customize to edit the list.
1443 If the value of the variable is not a list but a single file name, then
1444 the list of agenda files is actually stored and maintained in that file, one
1445 agenda file per line."
1448 (repeat :tag "List of files" file)
1449 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1451 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1452 "Custom commands for the agenda.
1453 These commands will be offered on the splash screen displayed by the
1454 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1456 key The key (a single char as a string) to be associated with the command.
1457 type The command type, any of the following symbols:
1458 todo Entries with a specific TODO keyword, in all agenda files.
1459 tags Tags match in all agenda files.
1460 tags-todo Tags match in all agenda files, TODO entries only.
1461 todo-tree Sparse tree of specific TODO keyword in *current* file.
1462 tags-tree Sparse tree with all tags matches in *current* file.
1463 occur-tree Occur sparse tree for current file.
1464 match What to search for:
1465 - a single keyword for TODO keyword searches
1466 - a tags match expression for tags searches
1467 - a regular expression for occur searches"
1470 (list (string :tag "Key")
1472 (const :tag "Tags search in all agenda files" tags)
1473 (const :tag "Tags search of TODO entries, all agenda files" tags-todo)
1474 (const :tag "TODO keyword search in all agenda files" todo)
1475 (const :tag "Tags sparse tree in current buffer" tags-tree)
1476 (const :tag "TODO keyword tree in current buffer" todo-tree)
1477 (const :tag "Occur tree in current buffer" occur-tree))
1478 (string :tag "Match"))))
1480 (defcustom org-agenda-todo-list-sublevels t
1481 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1482 When nil, the sublevels of a TODO entry are not checked, resulting in
1483 potentially much shorter TODO lists."
1488 (defcustom org-agenda-todo-ignore-scheduled nil
1489 "Non-nil means, don't show scheduled entries in the global todo list.
1490 The idea behind this is that by scheduling it, you have already taken care
1496 (defcustom org-agenda-include-all-todo nil
1497 "Non-nil means, the agenda will always contain all TODO entries.
1498 When nil, date-less entries will only be shown if `org-agenda' is called
1499 with a prefix argument.
1500 When non-nil, the TODO entries will be listed at the top of the agenda, before
1501 the entries for specific days."
1505 (defcustom org-agenda-include-diary nil
1506 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1510 (defcustom org-calendar-to-agenda-key [?c]
1511 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1512 The command `org-calendar-goto-agenda' will be bound to this key. The
1513 default is the character `c' because then `c' can be used to switch back and
1514 forth between agenda and calendar."
1518 (defgroup org-agenda-setup nil
1519 "Options concerning setting up the Agenda window in Org Mode."
1520 :tag "Org Agenda Window Setup"
1523 (defcustom org-agenda-mouse-1-follows-link nil
1524 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1525 A longer mouse click will still set point. Does not wortk on XEmacs.
1526 Needs to be set before org.el is loaded."
1527 :group 'org-agenda-setup
1530 (defcustom org-agenda-start-with-follow-mode nil
1531 "The initial value of follwo-mode in a newly created agenda window."
1532 :group 'org-agenda-setup
1535 (defcustom org-select-agenda-window t
1536 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1537 When nil, cursor will remain in the current window."
1538 :group 'org-agenda-setup
1541 (defcustom org-fit-agenda-window t
1542 "Non-nil means, change window size of agenda to fit content."
1543 :group 'org-agenda-setup
1546 (defgroup org-agenda-display nil
1547 "Options concerning what to display initially in Agenda."
1548 :tag "Org Agenda Display"
1551 (defcustom org-agenda-show-all-dates t
1552 "Non-nil means, `org-agenda' shows every day in the selected range.
1553 When nil, only the days which actually have entries are shown."
1554 :group 'org-agenda-display
1557 (defcustom org-agenda-start-on-weekday 1
1558 "Non-nil means, start the overview always on the specified weekday.
1559 0 denotes Sunday, 1 denotes Monday etc.
1560 When nil, always start on the current day."
1561 :group 'org-agenda-display
1562 :type '(choice (const :tag "Today" nil)
1563 (number :tag "Weekday No.")))
1565 (defcustom org-agenda-ndays 7
1566 "Number of days to include in overview display.
1568 :group 'org-agenda-display
1571 (defcustom org-agenda-use-time-grid t
1572 "Non-nil means, show a time grid in the agenda schedule.
1573 A time grid is a set of lines for specific times (like every two hours between
1574 8:00 and 20:00). The items scheduled for a day at specific times are
1575 sorted in between these lines.
1576 For details about when the grid will be shown, and what it will look like, see
1577 the variable `org-agenda-time-grid'."
1578 :group 'org-agenda-display
1581 (defcustom org-agenda-time-grid
1582 '((daily today require-timed)
1584 (800 1000 1200 1400 1600 1800 2000))
1586 "The settings for time grid for agenda display.
1587 This is a list of three items. The first item is again a list. It contains
1588 symbols specifying conditions when the grid should be displayed:
1590 daily if the agenda shows a single day
1591 weekly if the agenda shows an entire week
1592 today show grid on current date, independent of daily/weekly display
1593 require-timed show grid only if at least on item has a time specification
1595 The second item is a string which will be places behing the grid time.
1597 The third item is a list of integers, indicating the times that should have
1599 :group 'org-agenda-display
1602 (set :greedy t :tag "Grid Display Options"
1603 (const :tag "Show grid in single day agenda display" daily)
1604 (const :tag "Show grid in weekly agenda display" weekly)
1605 (const :tag "Always show grid for today" today)
1606 (const :tag "Show grid only if any timed entries are present"
1608 (const :tag "Skip grid times already present in an entry"
1610 (string :tag "Grid String")
1611 (repeat :tag "Grid Times" (integer :tag "Time"))))
1613 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1614 "Sorting structure for the agenda items of a single day.
1615 This is a list of symbols which will be used in sequence to determine
1616 if an entry should be listed before another entry. The following
1617 symbols are recognized:
1619 time-up Put entries with time-of-day indications first, early first
1620 time-down Put entries with time-of-day indications first, late first
1621 category-keep Keep the default order of categories, corresponding to the
1622 sequence in `org-agenda-files'.
1623 category-up Sort alphabetically by category, A-Z.
1624 category-down Sort alphabetically by category, Z-A.
1625 priority-up Sort numerically by priority, high priority last.
1626 priority-down Sort numerically by priority, high priority first.
1628 The different possibilities will be tried in sequence, and testing stops
1629 if one comparison returns a \"not-equal\". For example, the default
1630 '(time-up category-keep priority-down)
1631 means: Pull out all entries having a specified time of day and sort them,
1632 in order to make a time schedule for the current day the first thing in the
1633 agenda listing for the day. Of the entries without a time indication, keep
1634 the grouped in categories, don't sort the categories, but keep them in
1635 the sequence given in `org-agenda-files'. Within each category sort by
1638 Leaving out `category-keep' would mean that items will be sorted across
1639 categories by priority."
1640 :group 'org-agenda-display
1645 (const category-keep)
1647 (const category-down)
1649 (const priority-down))))
1651 (defcustom org-sort-agenda-notime-is-late t
1652 "Non-nil means, items without time are considered late.
1653 This is only relevant for sorting. When t, items which have no explicit
1654 time like 15:30 will be considered as 99:01, i.e. later than any items which
1655 do have a time. When nil, the default time is before 0:00. You can use this
1656 option to decide if the schedule for today should come before or after timeless
1658 :group 'org-agenda-display
1662 (defgroup org-agenda-prefix nil
1663 "Options concerning the entry prefix in the Org-mode agenda display."
1664 :tag "Org Agenda Prefix"
1667 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1668 "Format specification for the prefix of items in the agenda buffer.
1669 This format works similar to a printf format, with the following meaning:
1671 %c the category of the item, \"Diary\" for entries from the diary, or
1672 as given by the CATEGORY keyword or derived from the file name.
1673 %T the first tag of the item.
1674 %t the time-of-day specification if one applies to the entry, in the
1676 %s Scheduling/Deadline information, a short string
1678 All specifiers work basically like the standard `%s' of printf, but may
1679 contain two additional characters: A question mark just after the `%' and
1680 a whitespace/punctuation character just before the final letter.
1682 If the first character after `%' is a question mark, the entire field
1683 will only be included if the corresponding value applies to the
1684 current entry. This is useful for fields which should have fixed
1685 width when present, but zero width when absent. For example,
1686 \"%?-12t\" will result in a 12 character time field if a time of the
1687 day is specified, but will completely disappear in entries which do
1690 If there is punctuation or whitespace character just before the final
1691 format letter, this character will be appended to the field value if
1692 the value is not empty. For example, the format \"%-12:c\" leads to
1693 \"Diary: \" if the category is \"Diary\". If the category were be
1694 empty, no additional colon would be interted.
1696 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1697 - Indent the line with two space characters
1698 - Give the category in a 12 chars wide field, padded with whitespace on
1699 the right (because of `-'). Append a colon if there is a category
1701 - If there is a time-of-day, put it into a 12 chars wide field. If no
1702 time, don't put in an empty field, just skip it (because of '?').
1703 - Finally, put the scheduling information and append a whitespace.
1705 As another example, if you don't want the time-of-day of entries in
1706 the prefix, you could use:
1708 (setq org-agenda-prefix-format \" %-11:c% s\")
1710 See also the variables `org-agenda-remove-times-when-in-prefix' and
1711 `org-agenda-remove-tags-when-in-prefix'."
1713 :group 'org-agenda-prefix)
1715 (defvar org-prefix-format-compiled nil
1716 "The compiled version of the most recently used prefix format.
1717 Depending on which command was used last, this may be the compiled version
1718 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1720 (defcustom org-agenda-remove-times-when-in-prefix t
1721 "Non-nil means, remove duplicate time specifications in agenda items.
1722 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1723 time-of-day specification in a headline or diary entry is extracted and
1724 placed into the prefix. If this option is non-nil, the original specification
1725 \(a timestamp or -range, or just a plain time(range) specification like
1726 11:30-4pm) will be removed for agenda display. This makes the agenda less
1728 The option can be t or nil. It may also be the symbol `beg', indicating
1729 that the time should only be removed what it is located at the beginning of
1730 the headline/diary entry."
1731 :group 'org-agenda-prefix
1733 (const :tag "Always" t)
1734 (const :tag "Never" nil)
1735 (const :tag "When at beginning of entry" beg)))
1737 (defcustom org-agenda-remove-tags-when-in-prefix nil
1738 "Non-nil means, remove the tags from the headline copy in the agenda.
1739 When this is the symbol `prefix', only remove tags when
1740 `org-agenda-prefix-format' contains a `%T' specifier."
1741 :group 'org-agenda-prefix
1743 (const :tag "Always" t)
1744 (const :tag "Never" nil)
1745 (const :tag "When prefix format contains %T" prefix)))
1747 (defgroup org-agenda-timeline nil
1748 "Options concerning the timeline buffer in Org Mode."
1749 :tag "Org Agenda Timeline"
1752 (defcustom org-timeline-prefix-format " % s"
1753 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1755 :group 'org-agenda-timeline)
1757 (defcustom org-select-timeline-window t
1758 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1759 When nil, cursor will remain in the current window."
1760 :group 'org-agenda-timeline
1763 (defcustom org-timeline-show-empty-dates 3
1764 "Non-nil means, `org-timeline' also shows dates without an entry.
1765 When nil, only the days which actually have entries are shown.
1766 When t, all days between the first and the last date are shown.
1767 When an integer, show also empty dates, but if there is a gap of more than
1768 N days, just insert a special line indicating the size of the gap."
1769 :group 'org-agenda-timeline
1771 (const :tag "None" nil)
1772 (const :tag "All" t)
1773 (number :tag "at most")))
1775 (defgroup org-latex nil
1776 "Options for embedding LaTeX code into Org-mode"
1780 (defcustom org-format-latex-options
1781 '(:foreground "Black" :background "Transparent" :scale 1.0
1782 :matchers ("begin" "$" "$$" "\\(" "\\["))
1783 "Options for creating images from LaTeX fragments.
1784 This is a property list with the following properties:
1785 :foreground the foreground color, for example \"Black\".
1786 :background the background color, or \"Transparent\".
1787 :scale a scaling factor for the size of the images
1788 :matchers a list indicating which matchers should be used to
1789 find LaTeX fragments. Valid members of this list are:
1790 \"begin\" find environments
1791 \"$\" find math expressions surrounded by $...$
1792 \"$$\" find math expressions surrounded by $$....$$
1793 \"\\(\" find math expressions surrounded by \\(...\\)
1794 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1798 (defgroup org-export nil
1799 "Options for exporting org-listings."
1803 (defgroup org-export-general nil
1804 "General options for exporting Org-mode files."
1805 :tag "Org Export General"
1808 (defcustom org-export-publishing-directory "."
1809 "Path to the location where exported files should be located.
1810 This path may be relative to the directory where the Org-mode file lives.
1811 The default is to put them into the same directory as the Org-mode file.
1812 The variable may also be an alist with export types `:html', `:ascii',
1813 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1814 is relative, it is interpreted relative to the directory where the exported
1815 Org-mode files lives."
1816 :group 'org-export-general
1822 (const :html) (const :ascii) (const :ical) (const :xoxo))
1825 (defcustom org-export-language-setup
1826 '(("en" "Author" "Date" "Table of Contents")
1827 ("da" "Ophavsmand" "Dato" "Indhold")
1828 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1829 ("es" "Autor" "Fecha" "\xccndice")
1830 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1831 ("it" "Autore" "Data" "Indice")
1832 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1833 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1834 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1835 "Terms used in export text, translated to different languages.
1836 Use the variable `org-export-default-language' to set the language,
1837 or use the +OPTION lines for a per-file setting."
1838 :group 'org-export-general
1841 (string :tag "HTML language tag")
1842 (string :tag "Author")
1843 (string :tag "Date")
1844 (string :tag "Table of Contents"))))
1846 (defcustom org-export-default-language "en"
1847 "The default language of HTML export, as a string.
1848 This should have an association in `org-export-language-setup'."
1849 :group 'org-export-general
1852 (defcustom org-export-headline-levels 3
1853 "The last level which is still exported as a headline.
1854 Inferior levels will produce itemize lists when exported.
1855 Note that a numeric prefix argument to an exporter function overrides
1858 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1859 :group 'org-export-general
1862 (defcustom org-export-with-section-numbers t
1863 "Non-nil means, add section numbers to headlines when exporting.
1865 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1866 :group 'org-export-general
1869 (defcustom org-export-with-toc t
1870 "Non-nil means, create a table of contents in exported files.
1871 The TOC contains headlines with levels up to`org-export-headline-levels'.
1873 Headlines which contain any TODO items will be marked with \"(*)\" in
1874 ASCII export, and with red color in HTML output.
1876 In HTML output, the TOC will be clickable.
1878 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1879 :group 'org-export-general
1882 (defcustom org-export-mark-todo-in-toc nil
1883 "Non-nil means, mark TOC lines that contain any open TODO items."
1884 :group 'org-export-general
1887 (defcustom org-export-preserve-breaks nil
1888 "Non-nil means, preserve all line breaks when exporting.
1889 Normally, in HTML output paragraphs will be reformatted. In ASCII
1890 export, line breaks will always be preserved, regardless of this variable.
1892 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1893 :group 'org-export-general
1896 (defcustom org-export-with-archived-trees 'headline
1897 "Whether subtrees with the ARCHIVE tag should be exported.
1898 This can have three different values
1899 nil Do not export, pretend this tree is not present
1900 t Do export the entire tree
1901 headline Only export the headline, but skip the tree below it."
1902 :group 'org-export-general
1905 (const :tag "not at all" nil)
1906 (const :tag "headline only" 'headline)
1907 (const :tag "entirely" t)))
1909 (defcustom org-export-with-timestamps t
1910 "Nil means, do not export time stamps and associated keywords."
1914 (defcustom org-export-remove-timestamps-from-toc t
1915 "Nil means, remove timestamps from the table of contents entries."
1919 (defcustom org-export-with-tags t
1920 "Nil means, do not export tags, just remove them from headlines."
1921 :group 'org-export-general
1924 (defcustom org-export-with-timestamps t
1925 "Nil means, do not export timestamps and associated keywords."
1926 :group 'org-export-general
1929 (defgroup org-export-translation nil
1930 "Options for translating special ascii sequences for the export backends."
1931 :tag "Org Export Translation"
1934 (defcustom org-export-with-emphasize t
1935 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1936 If the export target supports emphasizing text, the word will be
1937 typeset in bold, italic, or underlined, respectively. Works only for
1938 single words, but you can say: I *really* *mean* *this*.
1939 Not all export backends support this.
1941 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1942 :group 'org-export-translation
1945 (defcustom org-export-with-sub-superscripts t
1946 "Non-nil means, interpret \"_\" and \"^\" for export.
1947 When this option is turned on, you can use TeX-like syntax for sub- and
1948 superscripts. Several characters after \"_\" or \"^\" will be
1949 considered as a single item - so grouping with {} is normally not
1950 needed. For example, the following things will be parsed as single
1951 sub- or superscripts.
1953 10^24 or 10^tau several digits will be considered 1 item.
1954 10^-12 or 10^-tau a leading sign with digits or a word
1955 x^2-y^3 will be read as x^2 - y^3, because items are
1956 terminated by almost any nonword/nondigit char.
1957 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1959 Still, ambiguity is possible - so when in doubt use {} to enclose the
1961 Not all export backends support this, but HTML does.
1963 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1964 :group 'org-export-translation
1967 (defcustom org-export-with-TeX-macros t
1968 "Non-nil means, interpret simple TeX-like macros when exporting.
1969 For example, HTML export converts \\alpha to α and \\AA to Å.
1970 No only real TeX macros will work here, but the standard HTML entities
1971 for math can be used as macro names as well. For a list of supported
1972 names in HTML export, see the constant `org-html-entities'.
1973 Not all export backends support this.
1975 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1976 :group 'org-export-translation
1980 (defcustom org-export-with-LaTeX-fragments nil
1981 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
1982 When set, the exporter will find LaTeX environments if the \\begin line is
1983 the first non-white thing on a line. It will also find the math delimiters
1984 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
1987 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
1988 :group 'org-export-translation
1992 (defcustom org-export-with-fixed-width t
1993 "Non-nil means, lines starting with \":\" will be in fixed width font.
1994 This can be used to have pre-formatted text, fragments of code etc. For
1996 : ;; Some Lisp examples
1999 will be looking just like this in also HTML. See also the QUOTE keyword.
2000 Not all export backends support this.
2002 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2003 :group 'org-export-translation
2006 (defcustom org-match-sexp-depth 3
2007 "Number of stacked braces for sub/superscript matching.
2008 This has to be set before loading org.el to be effective."
2009 :group 'org-export-translation
2012 (defgroup org-export-tables nil
2013 "Options for exporting tables in Org-mode."
2014 :tag "Org Export Tables"
2017 (defcustom org-export-with-tables t
2018 "If non-nil, lines starting with \"|\" define a table.
2021 | Name | Address | Birthday |
2022 |-------------+----------+-----------|
2023 | Arthur Dent | England | 29.2.2100 |
2025 Not all export backends support this.
2027 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2028 :group 'org-export-tables
2031 (defcustom org-export-highlight-first-table-line t
2032 "Non-nil means, highlight the first table line.
2033 In HTML export, this means use <th> instead of <td>.
2034 In tables created with table.el, this applies to the first table line.
2035 In Org-mode tables, all lines before the first horizontal separator
2036 line will be formatted with <th> tags."
2037 :group 'org-export-tables
2040 (defcustom org-export-table-remove-special-lines t
2041 "Remove special lines and marking characters in calculating tables.
2042 This removes the special marking character column from tables that are set
2043 up for spreadsheet calculations. It also removes the entire lines
2044 marked with `!', `_', or `^'. The lines with `$' are kept, because
2045 the values of constants may be useful to have."
2046 :group 'org-export-tables
2049 (defcustom org-export-prefer-native-exporter-for-tables nil
2050 "Non-nil means, always export tables created with table.el natively.
2051 Natively means, use the HTML code generator in table.el.
2052 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2053 the table does not use row- or column-spanning). This has the
2054 advantage, that the automatic HTML conversions for math symbols and
2055 sub/superscripts can be applied. Org-mode's HTML generator is also
2057 :group 'org-export-tables
2060 (defgroup org-export-ascii nil
2061 "Options specific for ASCII export of Org-mode files."
2062 :tag "Org Export ASCII"
2065 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2066 "Characters for underlining headings in ASCII export.
2067 In the given sequence, these characters will be used for level 1, 2, ..."
2068 :group 'org-export-ascii
2069 :type '(repeat character))
2071 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2072 "Bullet characters for headlines converted to lists in ASCII export.
2073 The first character is is used for the first lest level generated in this
2074 way, and so on. If there are more levels than characters given here,
2075 the list will be repeated.
2076 Note that plain lists will keep the same bullets as the have in the
2078 :group 'org-export-ascii
2079 :type '(repeat character))
2081 (defcustom org-export-ascii-show-new-buffer t
2082 "Non-nil means, popup buffer containing the exported ASCII text.
2083 Otherwise the buffer will just be saved to a file and stay hidden."
2084 :group 'org-export-ascii
2087 (defgroup org-export-xml nil
2088 "Options specific for XML export of Org-mode files."
2089 :tag "Org Export XML"
2092 (defgroup org-export-html nil
2093 "Options specific for HTML export of Org-mode files."
2094 :tag "Org Export HTML"
2097 (defcustom org-export-html-style
2098 "<style type=\"text/css\">
2100 font-family: Times, serif;
2103 .title { text-align: center; }
2104 .todo { color: red; }
2105 .done { color: green; }
2106 .timestamp { color: grey }
2107 .timestamp-kwd { color: CadetBlue }
2108 .tag { background-color:lightblue; font-weight:normal }
2109 .target { background-color: lavender; }
2111 border: 1pt solid #AEBDCC;
2112 background-color: #F3F5F7;
2114 font-family: courier, monospace;
2116 table { border-collapse: collapse; }
2118 vertical-align: top;
2119 border: 1pt solid #ADB9CC;
2122 "The default style specification for exported HTML files.
2123 Since there are different ways of setting style information, this variable
2124 needs to contain the full HTML structure to provide a style, including the
2125 surrounding HTML tags. The style specifications should include definitions
2126 for new classes todo, done, title, and deadline. For example, legal values
2129 <style type=\"text/css\">
2130 p { font-weight: normal; color: gray; }
2131 h1 { color: black; }
2132 .title { text-align: center; }
2133 .todo, .deadline { color: red; }
2134 .done { color: green; }
2137 or, if you want to keep the style in a file,
2139 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2141 As the value of this option simply gets inserted into the HTML <head> header,
2142 you can \"misuse\" it to add arbitrary text to the header."
2143 :group 'org-export-html
2146 (defcustom org-export-html-link-org-files-as-html t
2147 "Non-nil means, make file links to `file.org' point to `file.html'.
2148 When org-mode is exporting an org-mode file to HTML, links to
2149 non-html files are directly put into a href tag in HTML.
2150 However, links to other Org-mode files (recognized by the
2151 extension `.org.) should become links to the corresponding html
2152 file, assuming that the linked org-mode file will also be
2154 When nil, the links still point to the plain `.org' file."
2155 :group 'org-export-html
2158 (defcustom org-export-html-inline-images 'maybe
2159 "Non-nil means, inline images into exported HTML pages.
2160 This is done using an <img> tag. When nil, an anchor with href is used to
2161 link to the image. If this option is `maybe', then images in links with
2162 an empty description will be inlined, while images with a description will
2164 :group 'org-export-html
2165 :type '(choice (const :tag "Never" nil)
2166 (const :tag "Always" t)
2167 (const :tag "When there is no description" maybe)))
2169 (defcustom org-export-html-expand t
2170 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2171 When nil, these tags will be exported as plain text and therefore
2172 not be interpreted by a browser.
2174 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2175 :group 'org-export-html
2178 (defcustom org-export-html-table-tag
2179 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2180 "The HTML tag used to start a table.
2181 This must be a <table> tag, but you may change the options like
2182 borders and spacing."
2183 :group 'org-export-html
2186 (defcustom org-export-html-with-timestamp nil
2187 "If non-nil, write `org-export-html-html-helper-timestamp'
2188 into the exported HTML text. Otherwise, the buffer will just be saved
2190 :group 'org-export-html
2193 (defcustom org-export-html-html-helper-timestamp
2194 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2195 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2196 :group 'org-export-html
2199 (defcustom org-export-html-show-new-buffer nil
2200 "Non-nil means, popup buffer containing the exported html text.
2201 Otherwise, the buffer will just be saved to a file and stay hidden."
2202 :group 'org-export-html
2205 (defgroup org-export-icalendar nil
2206 "Options specific for iCalendar export of Org-mode files."
2207 :tag "Org Export iCalendar"
2210 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2211 "The file name for the iCalendar file covering all agenda files.
2212 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2213 The file name should be absolute."
2214 :group 'org-export-icalendar
2217 (defcustom org-icalendar-include-todo nil
2218 "Non-nil means, export to iCalendar files should also cover TODO items."
2219 :group 'org-export-icalendar
2222 (defcustom org-icalendar-combined-name "OrgMode"
2223 "Calendar name for the combined iCalendar representing all agenda files."
2224 :group 'org-export-icalendar
2227 (defgroup org-font-lock nil
2228 "Font-lock settings for highlighting in Org-mode."
2229 :tag "Org Font Lock"
2232 (defcustom org-level-color-stars-only nil
2233 "Non-nil means fontify only the stars in each headline.
2234 When nil, the entire headline is fontified.
2235 Changing it requires restart of `font-lock-mode' to become effective
2236 also in regions already fontified."
2237 :group 'org-font-lock
2240 (defcustom org-hide-leading-stars nil
2241 "Non-nil means, hide the first N-1 stars in a headline.
2242 This works by using the face `org-hide' for these stars. This
2243 face is white for a light background, and black for a dark
2244 background. You may have to customize the face `org-hide' to
2246 Changing it requires restart of `font-lock-mode' to become effective
2247 also in regions already fontified.
2248 You may also set this on a per-file basis by adding one of the following
2249 lines to the buffer:
2251 #+STARTUP: hidestars
2252 #+STARTUP: showstars"
2253 :group 'org-font-lock
2256 (defcustom org-fontify-done-headline nil
2257 "Non-nil means, change the face of a headline if it is marked DONE.
2258 Normally, only the TODO/DONE keyword indicates the state of a headline.
2259 When this is non-nil, the headline after the keyword is set to the
2260 `org-headline-done' as an additional indication."
2261 :group 'org-font-lock
2264 (defcustom org-fontify-emphasized-text t
2265 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2266 Changing this variable requires a restart of Emacs to take effect."
2267 :group 'org-font-lock
2270 (defvar org-emph-re nil
2271 "Regular expression for matching emphasis.")
2272 (defvar org-emphasis-regexp-components) ; defined just below
2273 (defvar org-emphasis-alist) ; defined just below
2274 (defun org-set-emph-re (var val)
2275 "Set variable and compute the emphasis regular expression."
2277 (when (and (boundp 'org-emphasis-alist)
2278 (boundp 'org-emphasis-regexp-components)
2279 org-emphasis-alist org-emphasis-regexp-components)
2280 (let* ((e org-emphasis-regexp-components)
2287 (body1 (concat body "*?"))
2288 (markers (mapconcat 'car org-emphasis-alist "")))
2289 ;; make sure special characters appear at the right position in the class
2290 (if (string-match "\\^" markers)
2291 (setq markers (concat (replace-match "" t t markers) "^")))
2292 (if (string-match "-" markers)
2293 (setq markers (concat (replace-match "" t t markers) "-")))
2294 (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2297 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2299 "\\([" markers "]\\)"
2301 "[^" border markers "]"
2303 "[^" border markers "]"
2306 "\\([" post (if stacked markers) "]\\|$\\)")))))
2308 (defcustom org-emphasis-regexp-components
2309 '(" \t(" " \t.,?;:'\")" " \t\r\n,." "." 1 nil)
2310 "Components used to build the reqular expression for emphasis.
2311 This is a list with 6 entries. Terminology: In an emphasis string
2312 like \" *strong word* \", we call the initial space PREMATCH, the final
2313 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2314 and \"trong wor\" is the body. The different components in this variable
2315 specify what is allowed/forbidden in each part:
2317 pre Chars allowed as prematch. Beginning of line will be allowed too.
2318 post Chars allowed as postmatch. End of line will be allowed too.
2319 border The chars *forbidden* as border characters. In addition to the
2320 characters given here, all marker characters are forbidden too.
2321 body-regexp A regexp like \".\" to match a body character. Don't use
2322 non-shy groups here, and don't allow newline here.
2323 newline The maximum number of newlines allowed in an emphasis exp.
2324 stacked Non-nil means, allow stacked styles. This works only in HTML
2325 export. When this is set, all marker characters (as given in
2326 `org-emphasis-alist') will be allowed as pre/post, aiding
2327 inside-out matching.
2328 Use customize to modify this, or restart emacs after changing it."
2329 :group 'org-font-lock
2330 :set 'org-set-emph-re
2332 (sexp :tag "Allowed chars in pre ")
2333 (sexp :tag "Allowed chars in post ")
2334 (sexp :tag "Forbidden chars in border ")
2335 (sexp :tag "Regexp for body ")
2336 (integer :tag "number of newlines allowed")
2337 (boolean :tag "Stacking allowed ")))
2339 (defcustom org-emphasis-alist
2340 '(("*" bold "<b>" "</b>")
2341 ("/" italic "<i>" "</i>")
2342 ("_" underline "<u>" "</u>")
2343 ("=" shadow "<code>" "</code>")
2344 ("+" (:strike-through t) "<del>" "</del>")
2346 "Special syntax for emphasised text.
2347 Text starting and ending with a special character will be emphasized, for
2348 example *bold*, _underlined_ and /italic/. This variable sets the marker
2349 characters, the face to bbe used by font-lock for highlighting in Org-mode
2350 emacs buffers, and the HTML tags to be used for this.
2351 Use customize to modify this, or restart emacs after changing it."
2352 :group 'org-font-lock
2353 :set 'org-set-emph-re
2356 (string :tag "Marker character")
2358 (face :tag "Font-lock-face")
2359 (plist :tag "Face property list"))
2360 (string :tag "HTML start tag")
2361 (string :tag "HTML end tag"))))
2363 (defgroup org-faces nil
2364 "Faces in Org-mode."
2366 :group 'org-font-lock)
2368 (defun org-compatible-face (specs)
2369 "Make a compatible face specification.
2370 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2371 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2372 to the top of the list. The `min-colors' attribute will be removed from
2373 any other entries, and any resulting duplicates will be removed entirely."
2374 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2376 (while (setq e (pop specs))
2378 ((memq (car e) '(t default)) (push e r))
2379 ((setq a (member '(min-colors 8) (car e)))
2380 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2382 ((setq a (assq 'min-colors (car e)))
2383 (setq e (cons (delq a (car e)) (cdr e)))
2384 (or (assoc (car e) r) (push e r)))
2385 (t (or (assoc (car e) r) (push e r)))))
2390 '((((background light)) (:foreground "white"))
2391 (((background dark)) (:foreground "black")))
2392 "Face used to hide leading stars in headlines.
2393 The forground color of this face should be equal to the background
2394 color of the frame."
2397 (defface org-level-1 ;; font-lock-function-name-face
2398 (org-compatible-face
2399 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2400 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2401 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2402 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2403 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2405 "Face used for level 1 headlines."
2408 (defface org-level-2 ;; font-lock-variable-name-face
2409 (org-compatible-face
2410 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2411 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2412 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2413 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2415 "Face used for level 2 headlines."
2418 (defface org-level-3 ;; font-lock-keyword-face
2419 (org-compatible-face
2420 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2421 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2422 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2423 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2424 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2425 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2427 "Face used for level 3 headlines."
2430 (defface org-level-4 ;; font-lock-comment-face
2431 (org-compatible-face
2432 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2433 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2434 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2435 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2436 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2437 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2439 "Face used for level 4 headlines."
2442 (defface org-level-5 ;; font-lock-type-face
2443 (org-compatible-face
2444 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2445 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2446 (((class color) (min-colors 8)) (:foreground "green"))))
2447 "Face used for level 5 headlines."
2450 (defface org-level-6 ;; font-lock-constant-face
2451 (org-compatible-face
2452 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2453 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2454 (((class color) (min-colors 8)) (:foreground "magenta"))))
2455 "Face used for level 6 headlines."
2458 (defface org-level-7 ;; font-lock-builtin-face
2459 (org-compatible-face
2460 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2461 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2462 (((class color) (min-colors 8)) (:foreground "blue"))))
2463 "Face used for level 7 headlines."
2466 (defface org-level-8 ;; font-lock-string-face
2467 (org-compatible-face
2468 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2469 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2470 (((class color) (min-colors 8)) (:foreground "green"))))
2471 "Face used for level 8 headlines."
2474 (defface org-special-keyword ;; font-lock-string-face
2475 (org-compatible-face
2476 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2477 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2479 "Face used for special keywords."
2482 (defface org-warning ;; font-lock-warning-face
2483 (org-compatible-face
2484 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2485 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2486 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2487 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2489 "Face for deadlines and TODO keywords."
2492 (defface org-headline-done ;; font-lock-string-face
2493 (org-compatible-face
2494 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2495 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2496 (((class color) (min-colors 8) (background light)) (:bold nil))))
2497 "Face used to indicate that a headline is DONE.
2498 This face is only used if `org-fontify-done-headline' is set."
2501 (defface org-archived ; similar to shadow
2502 (org-compatible-face
2503 '((((class color grayscale) (min-colors 88) (background light))
2504 (:foreground "grey50"))
2505 (((class color grayscale) (min-colors 88) (background dark))
2506 (:foreground "grey70"))
2507 (((class color) (min-colors 8) (background light))
2508 (:foreground "green"))
2509 (((class color) (min-colors 8) (background dark))
2510 (:foreground "yellow"))))
2511 "Face for headline with the ARCHIVE tag."
2515 '((((class color) (background light)) (:foreground "Purple" :underline t))
2516 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2522 '((((class color) (background light)) (:foreground "Purple" :underline t))
2523 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2533 (defface org-todo ;; font-lock-warning-face
2534 (org-compatible-face
2535 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2536 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2537 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2538 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2539 (t (:inverse-video t :bold t))))
2540 "Face for TODO keywords."
2543 (defface org-done ;; font-lock-type-face
2544 (org-compatible-face
2545 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2546 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2547 (((class color) (min-colors 8)) (:foreground "green"))
2549 "Face used for DONE."
2552 (defface org-table ;; font-lock-function-name-face
2553 (org-compatible-face
2554 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2555 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2556 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2557 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2558 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2559 (((class color) (min-colors 8) (background dark)))))
2560 "Face used for tables."
2563 (defface org-formula
2564 (org-compatible-face
2565 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2566 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2567 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2568 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2569 (t (:bold t :italic t))))
2570 "Face for formulas."
2573 (defface org-scheduled-today
2574 (org-compatible-face
2575 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2576 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2577 (((class color) (min-colors 8)) (:foreground "green"))
2578 (t (:bold t :italic t))))
2579 "Face for items scheduled for a certain day."
2582 (defface org-scheduled-previously
2583 (org-compatible-face
2584 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2585 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2586 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2587 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2589 "Face for items scheduled previously, and not yet done."
2592 (defface org-upcoming-deadline
2593 (org-compatible-face
2594 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2595 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2596 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2597 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2599 "Face for items scheduled previously, and not yet done."
2602 (defface org-time-grid ;; font-lock-variable-name-face
2603 (org-compatible-face
2604 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2605 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2606 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2607 "Face used for time grids."
2610 (defconst org-level-faces
2611 '(org-level-1 org-level-2 org-level-3 org-level-4
2612 org-level-5 org-level-6 org-level-7 org-level-8
2614 (defconst org-n-levels (length org-level-faces))
2617 ;; Variables for pre-computed regular expressions, all buffer local
2618 (defvar org-done-string nil
2619 "The last string in `org-todo-keywords', indicating an item is DONE.")
2620 (make-variable-buffer-local 'org-done-string)
2621 (defvar org-todo-regexp nil
2622 "Matches any of the TODO state keywords.")
2623 (make-variable-buffer-local 'org-todo-regexp)
2624 (defvar org-not-done-regexp nil
2625 "Matches any of the TODO state keywords except the last one.")
2626 (make-variable-buffer-local 'org-not-done-regexp)
2627 (defvar org-todo-line-regexp nil
2628 "Matches a headline and puts TODO state into group 2 if present.")
2629 (make-variable-buffer-local 'org-todo-line-regexp)
2630 (defvar org-todo-line-tags-regexp nil
2631 "Matches a headline and puts TODO state into group 2 if present.
2632 Also put tags into group 4 if tags are present.")
2633 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2634 (defvar org-nl-done-regexp nil
2635 "Matches newline followed by a headline with the DONE keyword.")
2636 (make-variable-buffer-local 'org-nl-done-regexp)
2637 (defvar org-looking-at-done-regexp nil
2638 "Matches the DONE keyword a point.")
2639 (make-variable-buffer-local 'org-looking-at-done-regexp)
2640 (defvar org-todo-kwd-priority-p nil
2641 "Do TODO items have priorities?")
2642 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2643 (defvar org-todo-kwd-max-priority nil
2644 "Maximum priority of TODO items.")
2645 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2646 (defvar org-ds-keyword-length 12
2647 "Maximum length of the Deadline and SCHEDULED keywords.")
2648 (make-variable-buffer-local 'org-ds-keyword-length)
2649 (defvar org-deadline-regexp nil
2650 "Matches the DEADLINE keyword.")
2651 (make-variable-buffer-local 'org-deadline-regexp)
2652 (defvar org-deadline-time-regexp nil
2653 "Matches the DEADLINE keyword together with a time stamp.")
2654 (make-variable-buffer-local 'org-deadline-time-regexp)
2655 (defvar org-deadline-line-regexp nil
2656 "Matches the DEADLINE keyword and the rest of the line.")
2657 (make-variable-buffer-local 'org-deadline-line-regexp)
2658 (defvar org-scheduled-regexp nil
2659 "Matches the SCHEDULED keyword.")
2660 (make-variable-buffer-local 'org-scheduled-regexp)
2661 (defvar org-scheduled-time-regexp nil
2662 "Matches the SCHEDULED keyword together with a time stamp.")
2663 (make-variable-buffer-local 'org-scheduled-time-regexp)
2664 (defvar org-closed-time-regexp nil
2665 "Matches the CLOSED keyword together with a time stamp.")
2666 (make-variable-buffer-local 'org-closed-time-regexp)
2668 (defvar org-keyword-time-regexp nil
2669 "Matches any of the 3 keywords, together with the time stamp.")
2670 (make-variable-buffer-local 'org-keyword-time-regexp)
2671 (defvar org-maybe-keyword-time-regexp nil
2672 "Matches a timestamp, possibly preceeded by a keyword.")
2673 (make-variable-buffer-local 'org-keyword-time-regexp)
2675 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2677 "Properties to remove when a string without properties is wanted.")
2679 (defsubst org-match-string-no-properties (num &optional string)
2680 (if (featurep 'xemacs)
2681 (let ((s (match-string num string)))
2682 (remove-text-properties 0 (length s) org-rm-props s)
2684 (match-string-no-properties num string)))
2686 (defsubst org-no-properties (s)
2687 (remove-text-properties 0 (length s) org-rm-props s)
2690 (defun org-set-regexps-and-options ()
2691 "Precompute regular expressions for current buffer."
2692 (when (eq major-mode 'org-mode)
2693 (let ((re (org-make-options-regexp
2694 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2695 "STARTUP" "ARCHIVE" "TAGS")))
2697 kwds int key value cat arch tags)
2701 (goto-char (point-min))
2702 (while (re-search-forward re nil t)
2703 (setq key (match-string 1) value (org-match-string-no-properties 2))
2705 ((equal key "CATEGORY")
2706 (if (string-match "[ \t]+$" value)
2707 (setq value (replace-match "" t t value)))
2708 (setq cat (intern value)))
2709 ((equal key "SEQ_TODO")
2711 kwds (append kwds (org-split-string value splitre))))
2712 ((equal key "PRI_TODO")
2714 kwds (append kwds (org-split-string value splitre))))
2715 ((equal key "TYP_TODO")
2717 kwds (append kwds (org-split-string value splitre))))
2719 (setq tags (append tags (org-split-string value splitre))))
2720 ((equal key "STARTUP")
2721 (let ((opts (org-split-string value splitre))
2722 (set '(("fold" org-startup-folded t)
2723 ("overview" org-startup-folded t)
2724 ("nofold" org-startup-folded nil)
2725 ("showall" org-startup-folded nil)
2726 ("content" org-startup-folded content)
2727 ("hidestars" org-hide-leading-stars t)
2728 ("showstars" org-hide-leading-stars nil)
2729 ("odd" org-odd-levels-only t)
2730 ("oddeven" org-odd-levels-only nil)
2731 ("align" org-startup-align-all-tables t)
2732 ("noalign" org-startup-align-all-tables nil)
2733 ("logging" org-log-done t)
2734 ("nologging" org-log-done nil)
2735 ("dlcheck" org-startup-with-deadline-check t)
2736 ("nodlcheck" org-startup-with-deadline-check nil)))
2738 (while (setq l (assoc (pop opts) set))
2739 (setq var (nth 1 l) val (nth 2 l))
2740 (set (make-local-variable var) val))))
2741 ((equal key "ARCHIVE")
2742 (string-match " *$" value)
2743 (setq arch (replace-match "" t t value))
2744 (remove-text-properties 0 (length arch)
2745 '(face t fontified t) arch)))
2747 (and cat (set (make-local-variable 'org-category) cat))
2748 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2749 (and arch (set (make-local-variable 'org-archive-location) arch))
2750 (and int (set (make-local-variable 'org-todo-interpretation) int))
2753 (while (setq e (pop tags))
2755 ((equal e "{") (push '(:startgroup) tgs))
2756 ((equal e "}") (push '(:endgroup) tgs))
2757 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2758 (push (cons (match-string 1 e)
2759 (string-to-char (match-string 2 e)))
2761 (t (push (list e) tgs))))
2762 (set (make-local-variable 'org-tag-alist) nil)
2763 (while (setq e (pop tgs))
2764 (or (and (stringp (car e))
2765 (assoc (car e) org-tag-alist))
2766 (push e org-tag-alist))))))
2768 ;; Compute the regular expressions and other local variables
2769 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2770 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2771 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2772 (length org-scheduled-string)))
2774 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2776 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2780 (mapconcat 'regexp-quote
2781 (nreverse (cdr (reverse org-todo-keywords)))
2784 org-todo-line-regexp
2785 (concat "^\\(\\*+\\)[ \t]*\\("
2786 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2789 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2790 org-todo-line-tags-regexp
2791 (concat "^\\(\\*+\\)[ \t]*\\("
2792 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2793 "\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
2794 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2795 org-deadline-regexp (concat "\\<" org-deadline-string)
2796 org-deadline-time-regexp
2797 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2798 org-deadline-line-regexp
2799 (concat "\\<\\(" org-deadline-string "\\).*")
2800 org-scheduled-regexp
2801 (concat "\\<" org-scheduled-string)
2802 org-scheduled-time-regexp
2803 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2804 org-closed-time-regexp
2805 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2806 org-keyword-time-regexp
2807 (concat "\\<\\(" org-scheduled-string
2808 "\\|" org-deadline-string
2809 "\\|" org-closed-string
2810 "\\|" org-clock-string "\\)"
2811 " *[[<]\\([^]>]+\\)[]>]")
2812 org-maybe-keyword-time-regexp
2813 (concat "\\(\\<\\(" org-scheduled-string
2814 "\\|" org-deadline-string
2815 "\\|" org-closed-string
2816 "\\|" org-clock-string "\\)\\)?"
2817 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
2819 (org-set-font-lock-defaults)))
2821 ;; Tell the compiler about dynamically scoped variables,
2822 ;; and variables from other packages
2823 (defvar calc-embedded-close-formula) ; defined by the calc package
2824 (defvar calc-embedded-open-formula) ; defined by the calc package
2825 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
2826 (defvar zmacs-regions) ; XEmacs regions
2827 (defvar original-date) ; dynamically scoped in calendar
2828 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2829 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2830 (defvar org-html-entities) ; defined later in this file
2831 (defvar org-goto-start-pos) ; dynamically scoped parameter
2832 (defvar org-time-was-given) ; dynamically scoped parameter
2833 (defvar org-ts-what) ; dynamically scoped parameter
2834 (defvar org-current-export-file) ; dynamically scoped parameter
2835 (defvar org-current-export-dir) ; dynamically scoped parameter
2836 (defvar mark-active) ; Emacs only, not available in XEmacs.
2837 (defvar timecnt) ; dynamically scoped parameter
2838 (defvar levels-open) ; dynamically scoped parameter
2839 (defvar entry) ; dynamically scoped parameter
2840 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
2841 (defvar date) ; dynamically scoped parameter
2842 (defvar description) ; dynamically scoped parameter
2843 (defvar ans1) ; dynamically scoped parameter
2844 (defvar ans2) ; dynamically scoped parameter
2845 (defvar starting-day) ; local variable
2846 (defvar include-all-loc) ; local variable
2847 (defvar vm-message-pointer) ; from vm
2848 (defvar vm-folder-directory) ; from vm
2849 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2850 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2851 (defvar gnus-group-name) ; from gnus
2852 (defvar gnus-article-current) ; from gnus
2853 (defvar w3m-current-url) ; from w3m
2854 (defvar w3m-current-title) ; from w3m
2855 (defvar mh-progs) ; from MH-E
2856 (defvar mh-current-folder) ; from MH-E
2857 (defvar mh-show-folder-buffer) ; from MH-E
2858 (defvar mh-index-folder) ; from MH-E
2859 (defvar mh-searcher) ; from MH-E
2860 (defvar org-selected-point) ; dynamically scoped parameter
2861 (defvar calendar-mode-map) ; from calendar.el
2862 (defvar last-arg) ; local variable
2863 (defvar remember-save-after-remembering) ; from remember.el
2864 (defvar remember-data-file) ; from remember.el
2865 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2866 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2867 (defvar orgtbl-mode) ; defined later in this file
2868 (defvar Info-current-file) ; from info.el
2869 (defvar Info-current-node) ; from info.el
2870 (defvar texmathp-why) ; from texmathp.el
2871 (defvar org-latex-regexps)
2875 (defvar org-mode-map
2876 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2877 (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.")
2878 (copy-keymap outline-mode-map))
2879 "Keymap for Org-mode.")
2881 (defvar org-struct-menu) ; defined later in this file
2882 (defvar org-org-menu) ; defined later in this file
2883 (defvar org-tbl-menu) ; defined later in this file
2885 ;; We use a before-change function to check if a table might need
2887 (defvar org-table-may-need-update t
2888 "Indicates that a table might need an update.
2889 This variable is set by `org-before-change-function'.
2890 `org-table-align' sets it back to nil.")
2891 (defvar org-mode-hook nil)
2892 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2893 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2897 (define-derived-mode org-mode outline-mode "Org"
2898 "Outline-based notes management and organizer, alias
2899 \"Carsten's outline-mode for keeping track of everything.\"
2901 Org-mode develops organizational tasks around a NOTES file which
2902 contains information about projects as plain text. Org-mode is
2903 implemented on top of outline-mode, which is ideal to keep the content
2904 of large files well structured. It supports ToDo items, deadlines and
2905 time stamps, which magically appear in the diary listing of the Emacs
2906 calendar. Tables are easily created with a built-in table editor.
2907 Plain text URL-like links connect to websites, emails (VM), Usenet
2908 messages (Gnus), BBDB entries, and any files related to the project.
2909 For printing and sharing of notes, an Org-mode file (or a part of it)
2910 can be exported as a structured ASCII or HTML file.
2912 The following commands are available:
2916 ;; Get rid of Outline menus, they are not needed
2917 ;; Need to do this here because define-derived-mode sets up
2918 ;; the keymap so late.
2919 (if (featurep 'xemacs)
2922 (easy-menu-remove outline-mode-menu-heading)
2923 (easy-menu-remove outline-mode-menu-show)
2924 (easy-menu-remove outline-mode-menu-hide))
2925 (delete-menu-item '("Headings"))
2926 (delete-menu-item '("Show"))
2927 (delete-menu-item '("Hide"))
2928 (set-menubar-dirty-flag))
2929 (define-key org-mode-map [menu-bar headings] 'undefined)
2930 (define-key org-mode-map [menu-bar hide] 'undefined)
2931 (define-key org-mode-map [menu-bar show] 'undefined))
2933 (easy-menu-add org-org-menu)
2934 (easy-menu-add org-tbl-menu)
2935 (org-install-agenda-files-menu)
2936 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2937 (org-add-to-invisibility-spec '(org-cwidth))
2938 (when (featurep 'xemacs)
2939 (set (make-local-variable 'line-move-ignore-invisible) t))
2940 (setq outline-regexp "\\*+")
2941 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2942 (setq outline-level 'org-outline-level)
2943 (when (and org-ellipsis (stringp org-ellipsis))
2944 (unless org-display-table
2945 (setq org-display-table (make-display-table)))
2946 (set-display-table-slot org-display-table
2947 4 (string-to-vector org-ellipsis))
2948 (setq buffer-display-table org-display-table))
2949 (org-set-regexps-and-options)
2950 (modify-syntax-entry ?# "<")
2951 (if org-startup-truncated (setq truncate-lines t))
2952 (set (make-local-variable 'font-lock-unfontify-region-function)
2953 'org-unfontify-region)
2954 ;; Activate before-change-function
2955 (set (make-local-variable 'org-table-may-need-update) t)
2956 (org-add-hook 'before-change-functions 'org-before-change-function nil
2958 ;; Check for running clock before killing a buffer
2959 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
2960 ;; Paragraphs and auto-filling
2961 (org-set-autofill-regexps)
2962 (org-update-radio-target-regexp)
2963 ;; Settings for Calc embedded mode
2964 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2965 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2966 (if (and org-insert-mode-line-in-empty-file
2968 (= (point-min) (point-max)))
2969 (insert " -*- mode: org -*-\n\n"))
2971 (unless org-inhibit-startup
2972 (when org-startup-align-all-tables
2973 (let ((bmp (buffer-modified-p)))
2974 (org-table-map-tables 'org-table-align)
2975 (set-buffer-modified-p bmp)))
2976 (if org-startup-with-deadline-check
2977 (call-interactively 'org-check-deadlines)
2979 ((eq org-startup-folded t)
2981 ((eq org-startup-folded 'content)
2982 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2983 (org-cycle '(4)) (org-cycle '(4))))))))
2985 (defsubst org-call-with-arg (command arg)
2986 "Call COMMAND interactively, but pretend prefix are was ARG."
2987 (let ((current-prefix-arg arg)) (call-interactively command)))
2989 (defsubst org-current-line (&optional pos)
2990 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2992 (defun org-current-time ()
2993 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2994 (if (> org-time-stamp-rounding-minutes 0)
2995 (let ((r org-time-stamp-rounding-minutes)
2996 (time (decode-time)))
2998 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3002 (defun org-add-props (string plist &rest props)
3003 "Add text properties to entire string, from beginning to end.
3004 PLIST may be a list of properties, PROPS are individual properties and values
3005 that will be added to PLIST. Returns the string that was modified."
3006 (add-text-properties
3007 0 (length string) (if props (append plist props) plist) string)
3009 (put 'org-add-props 'lisp-indent-function 2)
3014 (defvar org-mouse-map (make-sparse-keymap))
3015 (define-key org-mouse-map
3016 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3017 (define-key org-mouse-map
3018 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3019 (when org-mouse-1-follows-link
3020 (define-key org-mouse-map [follow-link] 'mouse-face))
3021 (when org-tab-follows-link
3022 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3023 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3024 (when org-return-follows-link
3025 (define-key org-mouse-map [(return)] 'org-open-at-point)
3026 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3028 (require 'font-lock)
3030 (defconst org-non-link-chars "]\t\n\r<>")
3031 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3032 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3033 (defconst org-link-re-with-space
3035 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3036 "\\([^" org-non-link-chars " ]"
3037 "[^" org-non-link-chars "]*"
3038 "[^" org-non-link-chars " ]\\)>?")
3039 "Matches a link with spaces, optional angular brackets around it.")
3041 (defconst org-link-re-with-space2
3043 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3044 "\\([^" org-non-link-chars " ]"
3046 "[^" org-non-link-chars " ]\\)>?")
3047 "Matches a link with spaces, optional angular brackets around it.")
3049 (defconst org-angle-link-re
3051 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3052 "\\([^" org-non-link-chars " ]"
3053 "[^" org-non-link-chars "]*"
3055 "Matches link with angular brackets, spaces are allowed.")
3056 (defconst org-plain-link-re
3058 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3059 "\\([^]\t\n\r<>,;() ]+\\)")
3060 "Matches plain link, without spaces.")
3062 (defconst org-bracket-link-regexp
3063 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3064 "Matches a link in double brackets.")
3066 (defconst org-bracket-link-analytic-regexp
3069 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3072 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3081 (defconst org-ts-lengths
3082 (cons (length (format-time-string (car org-time-stamp-formats)))
3083 (length (format-time-string (cdr org-time-stamp-formats))))
3084 "This holds the lengths of the two different time formats.")
3085 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3086 "Regular expression for fast time stamp matching.")
3087 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3088 "Regular expression for fast time stamp matching.")
3089 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3090 "Regular expression matching time strings for analysis.")
3091 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3092 "Regular expression matching time stamps, with groups.")
3093 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3094 "Regular expression matching time stamps (also [..]), with groups.")
3095 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3096 "Regular expression matching a time stamp range.")
3097 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3098 org-ts-regexp "\\)?")
3099 "Regular expression matching a time stamp or time stamp range.")
3101 (defvar org-§emph-face nil)
3103 (defun org-do-emphasis-faces (limit)
3104 "Run through the buffer and add overlays to links."
3105 (if (re-search-forward org-emph-re limit t)
3107 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3109 (nth 1 (assoc (match-string 3)
3110 org-emphasis-alist)))
3111 (add-text-properties (match-beginning 2) (match-end 2)
3112 '(font-lock-multiline t))
3116 (defun org-activate-plain-links (limit)
3117 "Run through the buffer and add overlays to links."
3118 (if (re-search-forward org-plain-link-re limit t)
3120 (add-text-properties (match-beginning 0) (match-end 0)
3121 (list 'mouse-face 'highlight
3122 'keymap org-mouse-map
3126 (defun org-activate-angle-links (limit)
3127 "Run through the buffer and add overlays to links."
3128 (if (re-search-forward org-angle-link-re limit t)
3130 (add-text-properties (match-beginning 0) (match-end 0)
3131 (list 'mouse-face 'highlight
3132 'keymap org-mouse-map
3136 (defun org-activate-bracket-links (limit)
3137 "Run through the buffer and add overlays to bracketed links."
3138 (if (re-search-forward org-bracket-link-regexp limit t)
3139 (let* ((help (concat "LINK: "
3140 (org-match-string-no-properties 1)))
3141 ;; FIXME: above we should remove the escapes.
3142 ;; but that requires another match, protecting match data,
3143 ;; a lot of overhead for font-lock.
3144 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
3145 'keymap org-mouse-map 'mouse-face 'highlight
3147 (vp (list 'rear-nonsticky t
3148 'keymap org-mouse-map 'mouse-face 'highlight
3150 ;; We need to remove the invisible property here. Table narrowing
3151 ;; may have made some of this invisible.
3152 (remove-text-properties (match-beginning 0) (match-end 0)
3156 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3157 (add-text-properties (match-beginning 3) (match-end 3) vp)
3158 (add-text-properties (match-end 3) (match-end 0) ip))
3159 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3160 (add-text-properties (match-beginning 1) (match-end 1) vp)
3161 (add-text-properties (match-end 1) (match-end 0) ip))
3164 (defun org-activate-dates (limit)
3165 "Run through the buffer and add overlays to dates."
3166 (if (re-search-forward org-tsr-regexp limit t)
3168 (add-text-properties (match-beginning 0) (match-end 0)
3169 (list 'mouse-face 'highlight
3170 'keymap org-mouse-map))
3173 (defvar org-target-link-regexp nil
3174 "Regular expression matching radio targets in plain text.")
3175 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3176 "Regular expression matching a link target.")
3177 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3178 "Regular expression matching a link target.")
3180 (defun org-activate-target-links (limit)
3181 "Run through the buffer and add overlays to target matches."
3182 (when org-target-link-regexp
3183 (let ((case-fold-search t))
3184 (if (re-search-forward org-target-link-regexp limit t)
3186 (add-text-properties (match-beginning 0) (match-end 0)
3187 (list 'mouse-face 'highlight
3188 'keymap org-mouse-map
3189 'help-echo "Radio target link"
3190 'org-linked-text t))
3193 (defun org-update-radio-target-regexp ()
3194 "Find all radio targets in this file and update the regular expression."
3196 (when (memq 'radio org-activate-links)
3197 (setq org-target-link-regexp
3198 (org-make-target-link-regexp (org-all-targets 'radio)))
3199 (org-restart-font-lock)))
3201 (defun org-hide-wide-columns (limit)
3203 (setq s (text-property-any (point) (or limit (point-max))
3206 (setq e (next-single-property-change s 'org-cwidth))
3207 (add-text-properties s e '(invisible org-cwidth intangible t))
3211 (defun org-restart-font-lock ()
3212 "Restart font-lock-mode, to force refontification."
3213 (when (and (boundp 'font-lock-mode) font-lock-mode)
3215 (font-lock-mode 1)))
3217 (defun org-all-targets (&optional radio)
3218 "Return a list of all targets in this file.
3219 With optional argument RADIO, only find radio targets."
3220 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3223 (goto-char (point-min))
3224 (while (re-search-forward re nil t)
3225 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3228 (defun org-make-target-link-regexp (targets)
3229 "Make regular expression matching all strings in TARGETS.
3230 The regular expression finds the targets also if there is a line break
3237 (while (string-match " +" x)
3238 (setq x (replace-match "\\s-+" t t x)))
3244 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3245 "Matches CamelCase words, possibly with a star before it.")
3247 (defun org-activate-camels (limit)
3248 "Run through the buffer and add overlays to dates."
3249 (if (re-search-forward org-camel-regexp limit t)
3251 (add-text-properties (match-beginning 0) (match-end 0)
3252 (list 'mouse-face 'highlight
3253 'keymap org-mouse-map))
3256 (defun org-activate-tags (limit)
3257 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3259 (add-text-properties (match-beginning 1) (match-end 1)
3260 (list 'mouse-face 'highlight
3261 'keymap org-mouse-map))
3264 (defun org-font-lock-level ()
3266 (org-back-to-heading t)
3267 (- (match-end 0) (match-beginning 0))))
3269 (defun org-outline-level ()
3271 (looking-at outline-regexp)
3272 (if (match-beginning 1)
3273 (+ (org-get-string-indentation (match-string 1)) 1000)
3274 (- (match-end 0) (match-beginning 0)))))
3276 (defvar org-font-lock-keywords nil)
3278 (defun org-set-font-lock-defaults ()
3279 (let* ((em org-fontify-emphasized-text)
3280 (lk org-activate-links)
3281 (org-font-lock-extra-keywords
3284 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3285 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3286 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3289 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3290 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3291 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3292 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3293 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3294 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3295 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3296 (if org-table-limit-column-width
3297 '(org-hide-wide-columns (0 nil append)))
3299 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3302 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3304 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3305 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3306 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3307 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3309 (if em '(org-do-emphasis-faces))
3310 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3311 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3314 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3315 "\\|" org-quote-string "\\)\\>")
3316 '(1 'org-special-keyword t))
3317 '("^#.*" (0 'font-lock-comment-face t))
3319 (if org-fontify-done-headline
3320 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3321 '(1 'org-done t) '(2 'org-headline-done t))
3322 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3325 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3326 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3327 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3328 (if org-format-transports-properties-p
3329 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3330 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3332 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3333 ;; Now set the full font-lock-keywords
3334 (set (make-local-variable 'org-font-lock-keywords)
3335 org-font-lock-extra-keywords)
3336 (set (make-local-variable 'font-lock-defaults)
3337 '(org-font-lock-keywords t nil nil backward-paragraph))
3338 (kill-local-variable 'font-lock-keywords) nil))
3343 (defun org-get-level-face (n)
3344 "Get the right face for match N in font-lock matching of healdines."
3345 (setq org-l (- (match-end 2) (match-beginning 1)))
3346 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3347 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3348 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3350 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3352 (t (if org-level-color-stars-only nil org-f))))
3354 (defun org-unfontify-region (beg end &optional maybe_loudly)
3355 "Remove fontification and activation overlays from links."
3356 (font-lock-default-unfontify-region beg end)
3357 (let* ((buffer-undo-list t)
3358 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3359 (inhibit-modification-hooks t)
3360 deactivate-mark buffer-file-name buffer-file-truename)
3361 (remove-text-properties beg end
3362 '(mouse-face nil keymap nil org-linked-text nil
3363 invisible nil intangible nil))))
3364 ;;; Visibility cycling
3366 (defvar org-cycle-global-status nil)
3367 (make-variable-buffer-local 'org-cycle-global-status)
3368 (defvar org-cycle-subtree-status nil)
3369 (make-variable-buffer-local 'org-cycle-subtree-status)
3372 (defun org-cycle (&optional arg)
3373 "Visibility cycling for Org-mode.
3375 - When this function is called with a prefix argument, rotate the entire
3376 buffer through 3 states (global cycling)
3377 1. OVERVIEW: Show only top-level headlines.
3378 2. CONTENTS: Show all headlines of all levels, but no body text.
3379 3. SHOW ALL: Show everything.
3381 - When point is at the beginning of a headline, rotate the subtree started
3382 by this line through 3 different states (local cycling)
3383 1. FOLDED: Only the main headline is shown.
3384 2. CHILDREN: The main headline and the direct children are shown.
3385 From this state, you can move to one of the children
3386 and zoom in further.
3387 3. SUBTREE: Show the entire subtree, including body text.
3389 - When there is a numeric prefix, go up to a heading with level ARG, do
3390 a `show-subtree' and return to the previous cursor position. If ARG
3391 is negative, go up that many levels.
3393 - When point is not at the beginning of a headline, execute
3394 `indent-relative', like TAB normally does. See the option
3395 `org-cycle-emulate-tab' for details.
3397 - Special case: if point is the the beginning of the buffer and there is
3398 no headline in line 1, this function will act as if called with prefix arg."
3401 (let* ((outline-regexp
3402 (if org-cycle-include-plain-lists
3403 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
3405 (bob-special (and org-cycle-global-at-bob (bobp)
3406 (not (looking-at outline-regexp))))
3409 (delq 'org-optimize-window-after-visibility-change
3410 (copy-sequence org-cycle-hook))
3414 (if (or bob-special (equal arg '(4)))
3415 ;; special case: use global cycling
3420 ((org-at-table-p 'any)
3421 ;; Enter the table or move to the next field in the table
3422 (or (org-table-recognize-table.el)
3424 (if arg (org-table-edit-field t)
3425 (org-table-justify-field-maybe)
3426 (call-interactively 'org-table-next-field)))))
3428 ((eq arg t) ;; Global cycling
3431 ((and (eq last-command this-command)
3432 (eq org-cycle-global-status 'overview))
3433 ;; We just created the overview - now do table of contents
3434 ;; This can be slow in very large buffers, so indicate action
3435 (message "CONTENTS...")
3437 (message "CONTENTS...done")
3438 (setq org-cycle-global-status 'contents)
3439 (run-hook-with-args 'org-cycle-hook 'contents))
3441 ((and (eq last-command this-command)
3442 (eq org-cycle-global-status 'contents))
3443 ;; We just showed the table of contents - now show everything
3445 (message "SHOW ALL")
3446 (setq org-cycle-global-status 'all)
3447 (run-hook-with-args 'org-cycle-hook 'all))
3450 ;; Default action: go to overview
3452 (message "OVERVIEW")
3453 (setq org-cycle-global-status 'overview)
3454 (run-hook-with-args 'org-cycle-hook 'overview))))
3457 ;; Show-subtree, ARG levels up from here.
3459 (org-back-to-heading)
3460 (outline-up-heading (if (< arg 0) (- arg)
3461 (- (funcall outline-level) arg)))
3462 (org-show-subtree)))
3464 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3465 ;; At a heading: rotate between three different views
3466 (org-back-to-heading)
3467 (let ((goal-column 0) eoh eol eos)
3468 ;; First, some boundaries
3470 (org-back-to-heading)
3472 (beginning-of-line 2)
3473 (while (and (not (eobp)) ;; this is like `next-line'
3474 (get-char-property (1- (point)) 'invisible))
3475 (beginning-of-line 2)) (setq eol (point)))
3476 (outline-end-of-heading) (setq eoh (point))
3477 (org-end-of-subtree t) (setq eos (point))
3478 (outline-next-heading))
3479 ;; Find out what to do next and set `this-command'
3482 ;; Nothing is hidden behind this heading
3483 (message "EMPTY ENTRY")
3484 (setq org-cycle-subtree-status nil)))
3486 ;; Entire subtree is hidden in one line: open it
3489 (message "CHILDREN")
3490 (setq org-cycle-subtree-status 'children)
3491 (run-hook-with-args 'org-cycle-hook 'children))
3492 ((and (eq last-command this-command)
3493 (eq org-cycle-subtree-status 'children))
3494 ;; We just showed the children, now show everything.
3497 (setq org-cycle-subtree-status 'subtree)
3498 (run-hook-with-args 'org-cycle-hook 'subtree))
3500 ;; Default action: hide the subtree.
3503 (setq org-cycle-subtree-status 'folded)
3504 (run-hook-with-args 'org-cycle-hook 'folded)))))
3507 (buffer-read-only (org-back-to-heading))
3509 ((org-try-cdlatex-tab))
3511 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3512 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3513 (or (and (eq org-cycle-emulate-tab 'white)
3514 (= (match-end 0) (point-at-eol)))
3515 (and (eq org-cycle-emulate-tab 'whitestart)
3516 (>= (match-end 0) pos))))
3518 (eq org-cycle-emulate-tab t))
3519 (if (and (looking-at "[ \n\r\t]")
3520 (string-match "^[ \t]*$" (buffer-substring
3521 (point-at-bol) (point))))
3523 (beginning-of-line 1)
3524 (and (looking-at "[ \t]+") (replace-match ""))))
3528 (org-back-to-heading)
3532 (defun org-global-cycle (&optional arg)
3533 "Cycle the global visibility. For details see `org-cycle'."
3538 (hide-sublevels arg)
3539 (setq org-cycle-global-status 'contents))
3542 (defun org-overview ()
3543 "Switch to overview mode, shoing only top-level headlines.
3544 Really, this shows all headlines with level equal or greater than the level
3545 of the first headline in the buffer. This is important, because if the
3546 first headline is not level one, then (hide-sublevels 1) gives confusing
3549 (hide-sublevels (save-excursion
3550 (goto-char (point-min))
3551 (if (re-search-forward (concat "^" outline-regexp) nil t)
3553 (goto-char (match-beginning 0))
3554 (funcall outline-level))
3557 ;; FIXME: allow an argument to give a limiting level for this.
3558 (defun org-content ()
3559 "Show all headlines in the buffer, like a table of contents"
3562 ;; Visit all headings and show their offspring
3563 (goto-char (point-max))
3565 (while (and (progn (condition-case nil
3566 (outline-previous-visible-heading 1)
3567 (error (goto-char (point-min))))
3569 (looking-at outline-regexp))
3571 (if (bobp) (throw 'exit nil))))))
3574 (defun org-optimize-window-after-visibility-change (state)
3575 "Adjust the window after a change in outline visibility.
3576 This function is the default value of the hook `org-cycle-hook'."
3577 (when (get-buffer-window (current-buffer))
3579 ((eq state 'overview) (org-first-headline-recenter 1))
3580 ((eq state 'content) nil)
3581 ((eq state 'all) nil)
3582 ((eq state 'folded) nil)
3583 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3584 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3586 (defun org-subtree-end-visible-p ()
3587 "Is the end of the current subtree visible?"
3588 (pos-visible-in-window-p
3589 (save-excursion (org-end-of-subtree t) (point))))
3591 (defun org-first-headline-recenter (&optional N)
3592 "Move cursor to the first headline and recenter the headline.
3593 Optional argument N means, put the headline into the Nth line of the window."
3594 (goto-char (point-min))
3595 (when (re-search-forward (concat "^" outline-regexp) nil t)
3597 (recenter (prefix-numeric-value N))))
3599 (defvar org-goto-window-configuration nil)
3600 (defvar org-goto-marker nil)
3601 (defvar org-goto-map (make-sparse-keymap))
3602 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3603 (while (setq cmd (pop cmds))
3604 (substitute-key-definition cmd cmd org-goto-map global-map)))
3605 (define-key org-goto-map "\C-m" 'org-goto-ret)
3606 (define-key org-goto-map [(left)] 'org-goto-left)
3607 (define-key org-goto-map [(right)] 'org-goto-right)
3608 (define-key org-goto-map [(?q)] 'org-goto-quit)
3609 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3610 (define-key org-goto-map "\C-i" 'org-cycle)
3611 (define-key org-goto-map [(tab)] 'org-cycle)
3612 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3613 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3614 (define-key org-goto-map "n" 'outline-next-visible-heading)
3615 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3616 (define-key org-goto-map "f" 'outline-forward-same-level)
3617 (define-key org-goto-map "b" 'outline-backward-same-level)
3618 (define-key org-goto-map "u" 'outline-up-heading)
3619 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3620 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3621 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3622 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3623 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3624 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3625 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3627 (defconst org-goto-help
3628 "Select a location to jump to, press RET
3629 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3632 "Go to a different location of the document, keeping current visibility.
3634 When you want to go to a different location in a document, the fastest way
3635 is often to fold the entire buffer and then dive into the tree. This
3636 method has the disadvantage, that the previous location will be folded,
3637 which may not be what you want.
3639 This command works around this by showing a copy of the current buffer in
3640 overview mode. You can dive into the tree in that copy, to find the
3641 location you want to reach. When pressing RET, the command returns to the
3642 original buffer in which the visibility is still unchanged. It then jumps
3643 to the new location, making it and the headline hierarchy above it visible."
3645 (let* ((org-goto-start-pos (point))
3647 (org-get-location (current-buffer) org-goto-help)))
3650 (org-mark-ring-push org-goto-start-pos)
3651 (goto-char selected-point)
3652 (if (or (org-invisible-p) (org-invisible-p2))
3653 (org-show-hierarchy-above)))
3656 (defun org-get-location (buf help)
3657 "Let the user select a location in the Org-mode buffer BUF.
3658 This function uses a recursive edit. It returns the selected position
3660 (let (org-selected-point)
3662 (save-window-excursion
3663 (delete-other-windows)
3664 (switch-to-buffer (get-buffer-create "*org-goto*"))
3665 (with-output-to-temp-buffer "*Help*"
3667 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3668 (setq buffer-read-only nil)
3670 (insert-buffer-substring buf)
3671 (let ((org-startup-truncated t)
3672 (org-startup-folded t)
3673 (org-startup-align-all-tables nil)
3674 (org-startup-with-deadline-check nil))
3676 (setq buffer-read-only t)
3677 (if (boundp 'org-goto-start-pos)
3678 (goto-char org-goto-start-pos)
3679 (goto-char (point-min)))
3680 (org-beginning-of-line)
3681 (message "Select location and press RET")
3682 ;; now we make sure that during selection, ony very few keys work
3683 ;; and that it is impossible to switch to another window.
3684 (let ((gm (current-global-map))
3685 (overriding-local-map org-goto-map))
3688 (use-global-map org-goto-map)
3690 (use-global-map gm)))))
3691 (kill-buffer "*org-goto*")
3692 org-selected-point))
3694 (defun org-goto-ret (&optional arg)
3695 "Finish `org-goto' by going to the new location."
3697 (setq org-selected-point (point)
3698 current-prefix-arg arg)
3701 (defun org-goto-left ()
3702 "Finish `org-goto' by going to the new location."
3704 (if (org-on-heading-p)
3706 (beginning-of-line 1)
3707 (setq org-selected-point (point)
3708 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3710 (error "Not on a heading")))
3712 (defun org-goto-right ()
3713 "Finish `org-goto' by going to the new location."
3715 (if (org-on-heading-p)
3717 (outline-end-of-subtree)
3718 (or (eobp) (forward-char 1))
3719 (setq org-selected-point (point)
3720 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3722 (error "Not on a heading")))
3724 (defun org-goto-quit ()
3725 "Finish `org-goto' without cursor motion."
3727 (setq org-selected-point nil)
3730 ;;; Promotion, Demotion, Inserting new headlines
3732 (defvar org-ignore-region nil
3733 "To temporarily disable the active region.")
3735 (defun org-insert-heading (&optional force-heading)
3736 "Insert a new heading or item with same depth at point.
3737 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3738 If point is at the beginning of a headline, insert a sibling before the
3739 current headline. If point is in the middle of a headline, split the headline
3740 at that position and make the rest of the headline part of the sibling below
3741 the current headline."
3743 (if (= (buffer-size) 0)
3745 (when (or force-heading (not (org-insert-item)))
3746 (let* ((head (save-excursion
3749 (org-back-to-heading)
3754 ((and (org-on-heading-p) (bolp)
3755 (save-excursion (backward-char 1) (not (org-invisible-p))))
3757 ((and (bolp) (save-excursion
3758 (backward-char 1) (not (org-invisible-p))))
3761 (insert head) (just-one-space)
3764 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3765 (run-hooks 'org-insert-heading-hook)))))
3767 (defun org-insert-item (&optional checkbox)
3768 "Insert a new item at the current level.
3769 Return t when things worked, nil when we are not in an item."
3770 (when (save-excursion
3773 (org-beginning-of-item)
3777 (let* ((bul (match-string 0))
3778 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3782 ((and (org-at-item-p) (<= (point) eow))
3783 ;; before the bullet
3784 (beginning-of-line 1)
3787 (beginning-of-line 1))
3789 (insert bul (if checkbox "[ ]" ""))
3793 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3794 (org-maybe-renumber-ordered-list)
3797 (defun org-insert-todo-heading (arg)
3798 "Insert a new heading with the same level and TODO state as current heading.
3799 If the heading has no TODO state, or if the state is DONE, use the first
3800 state (TODO by default). Also with prefix arg, force first state."
3802 (when (not (org-insert-item 'checkbox))
3803 (org-insert-heading)
3805 (org-back-to-heading)
3807 (outline-previous-heading)
3808 (outline-previous-visible-heading t))
3809 (looking-at org-todo-line-regexp))
3811 (not (match-beginning 2))
3812 (equal (match-string 2) org-done-string))
3813 (insert (car org-todo-keywords) " ")
3814 (insert (match-string 2) " "))))
3816 (defun org-promote-subtree ()
3817 "Promote the entire subtree.
3818 See also `org-promote'."
3821 (org-map-tree 'org-promote)))
3823 (defun org-demote-subtree ()
3824 "Demote the entire subtree. See `org-demote'.
3825 See also `org-promote'."
3828 (org-map-tree 'org-demote)))
3830 (defun org-do-promote ()
3831 "Promote the current heading higher up the tree.
3832 If the region is active in `transient-mark-mode', promote all headings
3836 (if (org-region-active-p)
3837 (org-map-region 'org-promote (region-beginning) (region-end))
3839 (org-fix-position-after-promote))
3841 (defun org-do-demote ()
3842 "Demote the current heading lower down the tree.
3843 If the region is active in `transient-mark-mode', demote all headings
3847 (if (org-region-active-p)
3848 (org-map-region 'org-demote (region-beginning) (region-end))
3850 (org-fix-position-after-promote))
3852 (defun org-fix-position-after-promote ()
3853 "Make sure that after pro/demotion cursor position is right."
3854 (and (equal (char-after) ?\ )
3855 (equal (char-before) ?*)
3858 (defun org-get-legal-level (level change)
3859 "Rectify a level change under the influence of `org-odd-levels-only'
3860 LEVEL is a current level, CHANGE is by how much the level should be
3861 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3862 even level numbers will become the next higher odd number."
3863 (if org-odd-levels-only
3864 (cond ((not change) (1+ (* 2 (/ level 2))))
3865 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3866 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3867 (max 1 (+ level change))))
3869 (defun org-promote ()
3870 "Promote the current heading higher up the tree.
3871 If the region is active in `transient-mark-mode', promote all headings
3873 (org-back-to-heading t)
3874 (let* ((level (save-match-data (funcall outline-level)))
3875 (up-head (make-string (org-get-legal-level level -1) ?*))
3876 (diff (abs (- level (length up-head)))))
3877 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3878 (replace-match up-head nil t)
3879 ;; Fixup tag positioning
3880 (and org-auto-align-tags (org-set-tags nil t))
3881 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
3883 (defun org-demote ()
3884 "Demote the current heading lower down the tree.
3885 If the region is active in `transient-mark-mode', demote all headings
3887 (org-back-to-heading t)
3888 (let* ((level (save-match-data (funcall outline-level)))
3889 (down-head (make-string (org-get-legal-level level 1) ?*))
3890 (diff (abs (- level (length down-head)))))
3891 (replace-match down-head nil t)
3892 ;; Fixup tag positioning
3893 (and org-auto-align-tags (org-set-tags nil t))
3894 (if org-adapt-indentation (org-fixup-indentation diff))))
3896 (defun org-map-tree (fun)
3897 "Call FUN for every heading underneath the current one."
3898 (org-back-to-heading)
3899 (let ((level (funcall outline-level)))
3903 (outline-next-heading)
3904 (> (funcall outline-level) level))
3908 (defun org-map-region (fun beg end)
3909 "Call FUN for every heading between BEG and END."
3910 (let ((org-ignore-region t))
3912 (setq end (copy-marker end))
3914 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3918 (outline-next-heading)
3923 (defun org-fixup-indentation (diff)
3924 "Change the indentation in the current entry by DIFF
3925 However, if any line in the current entry has no indentation, or if it
3926 would end up with no indentation after the change, nothing at all is done."
3928 (let ((end (save-excursion (outline-next-heading)
3930 (prohibit (if (> diff 0)
3932 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
3934 (unless (save-excursion (re-search-forward prohibit end t))
3935 (while (re-search-forward "^[ \t]+" end t)
3936 (goto-char (match-end 0))
3937 (setq col (current-column))
3938 (if (< diff 0) (replace-match ""))
3939 (indent-to (+ diff col))))
3940 (move-marker end nil))))
3942 ;;; Vertical tree motion, cutting and pasting of subtrees
3944 (defun org-move-subtree-up (&optional arg)
3945 "Move the current subtree up past ARG headlines of the same level."
3947 (org-move-subtree-down (- (prefix-numeric-value arg))))
3949 (defun org-move-subtree-down (&optional arg)
3950 "Move the current subtree down past ARG headlines of the same level."
3952 (setq arg (prefix-numeric-value arg))
3953 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3954 'outline-get-last-sibling))
3955 (ins-point (make-marker))
3959 (org-back-to-heading)
3962 (save-excursion (outline-end-of-heading)
3963 (setq folded (org-invisible-p)))
3964 (outline-end-of-subtree))
3965 (outline-next-heading)
3967 ;; Find insertion point, with error handling
3970 (or (and (funcall movfunc) (looking-at outline-regexp))
3971 (progn (goto-char beg)
3972 (error "Cannot move past superior level or buffer limit")))
3973 (setq cnt (1- cnt)))
3975 ;; Moving forward - still need to move over subtree
3976 (progn (outline-end-of-subtree)
3977 (outline-next-heading)
3978 (if (not (or (looking-at (concat "^" outline-regexp))
3981 (move-marker ins-point (point))
3982 (setq txt (buffer-substring beg end))
3983 (delete-region beg end)
3985 (goto-char ins-point)
3986 (if folded (hide-subtree))
3987 (move-marker ins-point nil)))
3989 (defvar org-subtree-clip ""
3990 "Clipboard for cut and paste of subtrees.
3991 This is actually only a copy of the kill, because we use the normal kill
3992 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3994 (defvar org-subtree-clip-folded nil
3995 "Was the last copied subtree folded?
3996 This is used to fold the tree back after pasting.")
3998 (defun org-cut-subtree ()
3999 "Cut the current subtree into the clipboard.
4000 This is a short-hand for marking the subtree and then cutting it."
4002 (org-copy-subtree 'cut))
4004 (defun org-copy-subtree (&optional cut)
4005 "Cut the current subtree into the clipboard.
4006 This is a short-hand for marking the subtree and then copying it.
4007 If CUT is non nil, actually cut the subtree."
4009 (let (beg end folded)
4010 (org-back-to-heading)
4013 (save-excursion (outline-end-of-heading)
4014 (setq folded (org-invisible-p)))
4015 (outline-end-of-subtree))
4016 (if (equal (char-after) ?\n) (forward-char 1))
4020 (setq org-subtree-clip-folded folded)
4021 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4022 (setq org-subtree-clip (current-kill 0))
4023 (message "%s: Subtree with %d characters"
4024 (if cut "Cut" "Copied")
4025 (length org-subtree-clip)))))
4027 (defun org-paste-subtree (&optional level tree)
4028 "Paste the clipboard as a subtree, with modification of headline level.
4029 The entire subtree is promoted or demoted in order to match a new headline
4030 level. By default, the new level is derived from the visible headings
4031 before and after the insertion point, and taken to be the inferior headline
4032 level of the two. So if the previous visible heading is level 3 and the
4033 next is level 4 (or vice versa), level 4 will be used for insertion.
4034 This makes sure that the subtree remains an independent subtree and does
4035 not swallow low level entries.
4037 You can also force a different level, either by using a numeric prefix
4038 argument, or by inserting the heading marker by hand. For example, if the
4039 cursor is after \"*****\", then the tree will be shifted to level 5.
4041 If you want to insert the tree as is, just use \\[yank].
4043 If optional TREE is given, use this text instead of the kill ring."
4045 (unless (org-kill-is-subtree-p tree)
4047 (substitute-command-keys
4048 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4049 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4050 (^re (concat "^\\(" outline-regexp "\\)"))
4051 (re (concat "\\(" outline-regexp "\\)"))
4052 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4054 (old-level (if (string-match ^re txt)
4055 (- (match-end 0) (match-beginning 0))
4057 (force-level (cond (level (prefix-numeric-value level))
4059 ^re_ (buffer-substring (point-at-bol) (point)))
4060 (- (match-end 0) (match-beginning 0)))
4062 (previous-level (save-excursion
4065 (outline-previous-visible-heading 1)
4067 (- (match-end 0) (match-beginning 0))
4070 (next-level (save-excursion
4073 (outline-next-visible-heading 1)
4075 (- (match-end 0) (match-beginning 0))
4078 (new-level (or force-level (max previous-level next-level)))
4079 (shift (if (or (= old-level -1)
4081 (= old-level new-level))
4083 (- new-level old-level)))
4085 (delta (if (> shift 0) -1 1))
4086 (func (if (> shift 0) 'org-demote 'org-promote))
4087 (org-odd-levels-only nil)
4089 ;; Remove the forces level indicator
4091 (delete-region (point-at-bol) (point)))
4092 ;; Make sure we start at the beginning of an empty line
4093 (if (not (bolp)) (insert "\n"))
4094 (if (not (looking-at "[ \t]*$"))
4095 (progn (insert "\n") (backward-char 1)))
4098 (if (string-match "[ \t\r\n]+\\'" txt)
4099 (setq txt (replace-match "\n" t t txt)))
4102 (if (looking-at "[ \t\r\n]+")
4103 (replace-match "\n"))
4105 ;; Shift if necessary
4107 (message "Pasted at level %d, without shift" new-level)
4109 (narrow-to-region beg end)
4110 (while (not (= shift 0))
4111 (org-map-region func (point-min) (point-max))
4112 (setq shift (+ delta shift)))
4113 (goto-char (point-min))
4114 (message "Pasted at level %d, with shift by %d levels"
4117 (eq org-subtree-clip (current-kill 0))
4118 org-subtree-clip-folded)
4119 ;; The tree was folded before it was killed/copied
4122 (defun org-kill-is-subtree-p (&optional txt)
4123 "Check if the current kill is an outline subtree, or a set of trees.
4124 Returns nil if kill does not start with a headline, or if the first
4125 headline level is not the largest headline level in the tree.
4126 So this will actually accept several entries of equal levels as well,
4127 which is OK for `org-paste-subtree'.
4128 If optional TXT is given, check this string instead of the current kill."
4129 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4130 (start-level (and kill
4131 (string-match (concat "\\`" outline-regexp) kill)
4132 (- (match-end 0) (match-beginning 0))))
4133 (re (concat "^" outline-regexp))
4135 (if (not start-level)
4136 nil ;; does not even start with a heading
4138 (while (setq start (string-match re kill (1+ start)))
4139 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4143 (defun org-narrow-to-subtree ()
4144 "Narrow buffer to the current subtree."
4148 (progn (org-back-to-heading) (point))
4149 (progn (org-end-of-subtree t) (point)))))
4151 ;;; Plain list items
4153 (defun org-at-item-p ()
4154 "Is point in a line starting a hand-formatted item?"
4155 (let ((llt org-plain-list-ordered-item-terminator))
4157 (goto-char (point-at-bol))
4160 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4161 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4162 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4163 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4165 (defun org-at-item-checkbox-p ()
4166 "Is point at a line starting a plain-list item with a checklet?"
4167 (and (org-at-item-p)
4169 (goto-char (match-end 0))
4170 (skip-chars-forward " \t")
4171 (looking-at "\\[[ X]\\]"))))
4173 (defun org-toggle-checkbox (&optional arg)
4174 "Toggle the checkbox in the current line."
4177 (let (beg end status (firstnew 'unknown))
4179 ((org-region-active-p)
4180 (setq beg (region-beginning) end (region-end)))
4182 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4183 ((org-at-item-checkbox-p)
4185 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4187 (t (error "Not at a checkbox or heading, and no active region")))
4190 (while (< (point) end)
4191 (when (org-at-item-checkbox-p)
4192 (setq status (equal (match-string 0) "[X]"))
4193 (when (eq firstnew 'unknown)
4194 (setq firstnew (not status)))
4196 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4197 (beginning-of-line 2))))))
4199 (defun org-get-indentation (&optional line)
4200 "Get the indentation of the current line, interpreting tabs.
4201 When LINE is given, assume it represents a line and compute its indentation."
4203 (if (string-match "^ *" (org-remove-tabs line))
4206 (beginning-of-line 1)
4207 (skip-chars-forward " \t")
4210 (defun org-remove-tabs (s &optional width)
4211 "Replace tabulators in S with spaces.
4212 Assumes that s is a single line, starting in column 0."
4213 (setq width (or width tab-width))
4214 (while (string-match "\t" s)
4215 (setq s (replace-match
4217 (- (* width (/ (+ (match-beginning 0) width) width))
4218 (match-beginning 0)) ?\ )
4222 ;; FIXME: document properly.
4223 (defun org-fix-indentation (line ind)
4224 "If the current indenation is smaller than ind1, leave it alone.
4225 If it is larger than ind, reduce it by ind."
4226 (let* ((l (org-remove-tabs line))
4227 (i (org-get-indentation l))
4228 (i1 (car ind)) (i2 (cdr ind)))
4229 (if (>= i i2) (setq l (substring line i2)))
4231 (concat (make-string i1 ?\ ) l)
4234 (defun org-beginning-of-item ()
4235 "Go to the beginning of the current hand-formatted item.
4236 If the cursor is not in an item, throw an error."
4239 (limit (save-excursion (org-back-to-heading)
4240 (beginning-of-line 2) (point)))
4243 (beginning-of-line 1)
4244 (beginning-of-line 1)
4245 (skip-chars-forward " \t")
4246 (setq ind (current-column))
4249 (beginning-of-line 0)
4250 (if (< (point) limit) (throw 'exit nil))
4251 (unless (looking-at "[ \t]*$")
4252 (skip-chars-forward " \t")
4253 (setq ind1 (current-column))
4255 (throw 'exit (org-at-item-p))))))
4258 (error "Not in an item")))))
4260 (defun org-end-of-item ()
4261 "Go to the end of the current hand-formatted item.
4262 If the cursor is not in an item, throw an error."
4265 (limit (save-excursion (outline-next-heading) (point)))
4266 (ind (save-excursion
4267 (org-beginning-of-item)
4268 (skip-chars-forward " \t")
4273 (beginning-of-line 2)
4274 (if (>= (point) limit) (throw 'exit t))
4275 (unless (looking-at "[ \t]*$")
4276 (skip-chars-forward " \t")
4277 (setq ind1 (current-column))
4278 (if (<= ind1 ind) (throw 'exit t)))))
4279 (beginning-of-line 1)
4281 (error "Not in an item"))))
4283 (defun org-next-item ()
4284 "Move to the beginning of the next item in the current plain list.
4285 Error if not at a plain list, or if this is the last item in the list."
4287 (let (ind ind1 (pos (point)))
4288 (org-beginning-of-item)
4289 (setq ind (org-get-indentation))
4291 (setq ind1 (org-get-indentation))
4292 (unless (and (org-at-item-p) (= ind ind1))
4294 (error "On last item"))))
4296 (defun org-previous-item ()
4297 "Move to the beginning of the previous item in the current plain list.
4298 Error if not at a plain list, or if this is the last item in the list."
4300 (let (beg ind (pos (point)))
4301 (org-beginning-of-item)
4303 (setq ind (org-get-indentation))
4307 (beginning-of-line 0)
4308 (if (looking-at "[ \t]*$")
4310 (if (<= (org-get-indentation) ind)
4313 (org-beginning-of-item)
4314 (error (goto-char pos)
4315 (error "On first item")))))
4317 (defun org-move-item-down ()
4318 "Move the plain list item at point down, i.e. swap with following item.
4319 Subitems (items with larger indentation) are considered part of the item,
4320 so this really moves item trees."
4322 (let (beg end ind ind1 (pos (point)) txt)
4323 (org-beginning-of-item)
4325 (setq ind (org-get-indentation))
4328 (setq ind1 (org-get-indentation))
4329 (if (and (org-at-item-p) (= ind ind1))
4332 (setq txt (buffer-substring beg end))
4334 (delete-region beg end))
4338 (org-maybe-renumber-ordered-list))
4340 (error "Cannot move this item further down"))))
4342 (defun org-move-item-up (arg)
4343 "Move the plain list item at point up, i.e. swap with previous item.
4344 Subitems (items with larger indentation) are considered part of the item,
4345 so this really moves item trees."
4347 (let (beg end ind ind1 (pos (point)) txt)
4348 (org-beginning-of-item)
4350 (setq ind (org-get-indentation))
4356 (beginning-of-line 0)
4357 (if (looking-at "[ \t]*$")
4359 (if (<= (setq ind1 (org-get-indentation)) ind)
4362 (org-beginning-of-item)
4363 (error (goto-char beg)
4364 (error "Cannot move this item further up")))
4365 (setq ind1 (org-get-indentation))
4366 (if (and (org-at-item-p) (= ind ind1))
4368 (setq txt (buffer-substring beg end))
4370 (delete-region beg end))
4374 (org-maybe-renumber-ordered-list))
4376 (error "Cannot move this item further up"))))
4378 (defun org-maybe-renumber-ordered-list ()
4379 "Renumber the ordered list at point if setup allows it.
4380 This tests the user option `org-auto-renumber-ordered-lists' before
4381 doing the renumbering."
4382 (and org-auto-renumber-ordered-lists
4385 (org-renumber-ordered-list 1)))
4387 (defun org-get-string-indentation (s)
4388 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4389 (let ((n -1) (i 0) (w tab-width) c)
4391 (while (< (setq n (1+ n)) (length s))
4393 (cond ((= c ?\ ) (setq i (1+ i)))
4394 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4395 (t (throw 'exit t)))))
4398 (defun org-renumber-ordered-list (arg)
4399 "Renumber an ordered plain list.
4400 Cursor needs to be in the first line of an item, the line that starts
4401 with something like \"1.\" or \"2)\"."
4403 (unless (and (org-at-item-p)
4404 (match-beginning 3))
4405 (error "This is not an ordered list"))
4406 (let ((line (org-current-line))
4407 (col (current-column))
4408 (ind (org-get-string-indentation
4409 (buffer-substring (point-at-bol) (match-beginning 3))))
4410 ;; (term (substring (match-string 3) -1))
4412 ;; find where this list begins
4416 (beginning-of-line 0)
4417 (if (looking-at "[ \t]*$") (throw 'next t))
4418 (skip-chars-forward " \t") (setq ind1 (current-column))
4419 (if (or (< ind1 ind)
4421 (not (org-at-item-p))))
4423 ;; Walk forward and replace these numbers
4427 (beginning-of-line 2)
4428 (if (eobp) (throw 'exit nil))
4429 (if (looking-at "[ \t]*$") (throw 'next nil))
4430 (skip-chars-forward " \t") (setq ind1 (current-column))
4431 (if (> ind1 ind) (throw 'next t))
4432 (if (< ind1 ind) (throw 'exit t))
4433 (if (not (org-at-item-p)) (throw 'exit nil))
4434 (if (not (match-beginning 3))
4435 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4436 (delete-region (match-beginning 3) (1- (match-end 3)))
4437 (goto-char (match-beginning 3))
4438 (insert (format "%d" (setq n (1+ n)))))))
4440 (move-to-column col)))
4442 (defvar org-last-indent-begin-marker (make-marker))
4443 (defvar org-last-indent-end-marker (make-marker))
4445 (defun org-outdent-item (arg)
4446 "Outdent a local list item."
4448 (org-indent-item (- arg)))
4450 (defun org-indent-item (arg)
4451 "Indent a local list item."
4453 (unless (org-at-item-p)
4454 (error "Not on an item"))
4456 (let (beg end ind ind1)
4457 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4458 (setq beg org-last-indent-begin-marker
4459 end org-last-indent-end-marker)
4460 (org-beginning-of-item)
4461 (setq beg (move-marker org-last-indent-begin-marker (point)))
4463 (setq end (move-marker org-last-indent-end-marker (point))))
4465 (skip-chars-forward " \t") (setq ind (current-column))
4466 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4467 (while (< (point) end)
4468 (beginning-of-line 1)
4469 (skip-chars-forward " \t") (setq ind1 (current-column))
4470 (delete-region (point-at-bol) (point))
4471 (indent-to-column (+ ind1 arg))
4472 (beginning-of-line 2)))))
4476 (defun org-archive-subtree (&optional find-done)
4477 "Move the current subtree to the archive.
4478 The archive can be a certain top-level heading in the current file, or in
4479 a different file. The tree will be moved to that location, the subtree
4480 heading be marked DONE, and the current time will be added.
4482 When called with prefix argument FIND-DONE, find whole trees without any
4483 open TODO items and archive them (after getting confirmation from the user).
4484 If the cursor is not at a headline when this comand is called, try all level
4485 1 trees. If the cursor is on a headline, only try the direct children of
4489 (org-archive-all-done)
4490 ;; Save all relevant TODO keyword-relatex variables
4492 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4493 (tr-org-todo-keywords org-todo-keywords)
4494 (tr-org-todo-interpretation org-todo-interpretation)
4495 (tr-org-done-string org-done-string)
4496 (tr-org-todo-regexp org-todo-regexp)
4497 (tr-org-todo-line-regexp org-todo-line-regexp)
4498 (this-buffer (current-buffer))
4499 file heading buffer level newfile-p)
4500 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4502 (setq file (format (match-string 1 org-archive-location)
4503 (file-name-nondirectory buffer-file-name))
4504 heading (match-string 2 org-archive-location)))
4505 (error "Invalid `org-archive-location'"))
4506 (if (> (length file) 0)
4507 (setq newfile-p (not (file-exists-p file))
4508 buffer (find-file-noselect file))
4509 (setq buffer (current-buffer)))
4511 (error "Cannot access file \"%s\"" file))
4512 (if (and (> (length heading) 0)
4513 (string-match "^\\*+" heading))
4514 (setq level (match-end 0))
4515 (setq heading nil level 0))
4517 ;; We first only copy, in case something goes wrong
4518 ;; we need to protect this-command, to avoid kill-region sets it,
4519 ;; which would lead to duplication of subtrees
4520 (let (this-command) (org-copy-subtree))
4522 ;; Enforce org-mode for the archive buffer
4523 (if (not (eq major-mode 'org-mode))
4524 ;; Force the mode for future visits.
4525 (let ((org-insert-mode-line-in-empty-file t))
4526 (call-interactively 'org-mode)))
4528 (goto-char (point-max))
4529 (insert (format "\nArchived entries from file %s\n\n"
4530 (buffer-file-name this-buffer))))
4531 ;; Force the TODO keywords of the original buffer
4532 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4533 (org-todo-keywords tr-org-todo-keywords)
4534 (org-todo-interpretation tr-org-todo-interpretation)
4535 (org-done-string tr-org-done-string)
4536 (org-todo-regexp tr-org-todo-regexp)
4537 (org-todo-line-regexp tr-org-todo-line-regexp))
4538 (goto-char (point-min))
4541 (if (re-search-forward
4542 (concat "\\(^\\|\r\\)"
4543 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4545 (goto-char (match-end 0))
4546 ;; Heading not found, just insert it at the end
4547 (goto-char (point-max))
4548 (or (bolp) (insert "\n"))
4549 (insert "\n" heading "\n")
4551 ;; Make the subtree visible
4553 (org-end-of-subtree t)
4554 (skip-chars-backward " \t\r\n]")
4555 (and (looking-at "[ \t\r\n]*")
4556 (replace-match "\n\n")))
4557 ;; No specific heading, just go to end of file.
4558 (goto-char (point-max)) (insert "\n"))
4560 (org-paste-subtree (1+ level))
4561 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4562 (if org-archive-mark-done
4563 (org-todo (length org-todo-keywords)))
4564 ;; Move cursor to right after the TODO keyword
4565 (when org-archive-stamp-time
4566 (beginning-of-line 1)
4567 (looking-at org-todo-line-regexp)
4568 (goto-char (or (match-end 2) (match-beginning 3)))
4569 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4572 ;; Save the buffer, if it is not the same buffer.
4573 (if (not (eq this-buffer buffer)) (save-buffer))))
4574 ;; Here we are back in the original buffer. Everything seems to have
4575 ;; worked. So now cut the tree and finish up.
4576 (let (this-command) (org-cut-subtree))
4577 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4578 (message "Subtree archived %s"
4579 (if (eq this-buffer buffer)
4580 (concat "under heading: " heading)
4581 (concat "in file: " (abbreviate-file-name file)))))))
4583 (defun org-archive-all-done (&optional tag)
4584 "Archive sublevels of the current tree without open TODO items.
4585 If the cursor is not on a headline, try all level 1 trees. If
4586 it is on a headline, try all direct children.
4587 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4588 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4589 (rea (concat ".*:" org-archive-tag ":"))
4590 (begm (make-marker))
4591 (endm (make-marker))
4592 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4593 "Move subtree to archive (no open TODO items)? "))
4594 beg end (cntarch 0))
4595 (if (org-on-heading-p)
4597 (setq re1 (concat "^" (regexp-quote
4599 (1+ (- (match-end 0) (match-beginning 0)))
4602 (move-marker begm (point))
4603 (move-marker endm (org-end-of-subtree)))
4605 (move-marker begm (point-min))
4606 (move-marker endm (point-max)))
4609 (while (re-search-forward re1 endm t)
4610 (setq beg (match-beginning 0)
4611 end (save-excursion (org-end-of-subtree t) (point)))
4613 (if (re-search-forward re end t)
4616 (if (and (or (not tag) (not (looking-at rea)))
4617 (y-or-n-p question))
4620 (org-toggle-tag org-archive-tag 'on)
4621 (org-archive-subtree))
4622 (setq cntarch (1+ cntarch)))
4624 (message "%d trees archived" cntarch)))
4626 (defun org-cycle-hide-archived-subtrees (state)
4627 "Re-hide all archived subtrees after a visibility state change."
4628 (when (and (not org-cycle-open-archived-trees)
4629 (not (memq state '(overview folded))))
4631 (let* ((globalp (memq state '(contents all)))
4632 (beg (if globalp (point-min) (point)))
4633 (end (if globalp (point-max) (org-end-of-subtree))))
4634 (org-hide-archived-subtrees beg end)))))
4636 (defun org-hide-archived-subtrees (beg end)
4637 "Re-hide all archived subtrees after a visibility state change."
4639 (let* ((re (concat ":" org-archive-tag ":")))
4641 (while (re-search-forward re end t)
4642 (and (org-on-heading-p) (hide-subtree))
4643 (org-end-of-subtree)))))
4645 (defun org-toggle-tag (tag &optional onoff)
4646 "Toggle the tag TAG for the current line.
4647 If ONOFF is `on' or `off', don't toggle but set to this state."
4648 (unless (org-on-heading-p) (error "Not on headling"))
4652 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
4655 (setq current (match-string 1))
4658 (setq current (nreverse (org-split-string current ":")))
4662 (or (member tag current) (push tag current)))
4664 (or (not (member tag current)) (setq current (delete tag current))))
4665 (t (if (member tag current)
4666 (setq current (delete tag current))
4668 (push tag current))))
4671 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
4672 (org-set-tags nil t))
4675 (defun org-toggle-archive-tag (&optional arg)
4676 "Toggle the archive tag for the current headline.
4677 With prefix ARG, check all children of current headline and offer tagging
4678 the children that do not contain any open TODO items."
4681 (org-archive-all-done 'tag)
4684 (org-back-to-heading t)
4685 (setq set (org-toggle-tag org-archive-tag))
4686 (when set (hide-subtree)))
4687 (and set (beginning-of-line 1))
4688 (message "Subtree %s" (if set "archived" "unarchived")))))
4690 (defun org-prepare-agenda-buffers (files)
4691 "Create buffers for all agenda files, protect archived trees and comments."
4693 (let ((pa '(:org-archived t))
4694 (pc '(:org-comment t))
4695 (pall '(:org-archived t :org-comment t))
4696 (rea (concat ":" org-archive-tag ":"))
4699 (while (setq file (pop files))
4700 (org-check-agenda-file file)
4701 (set-buffer (org-get-agenda-file-buffer file))
4704 (remove-text-properties (point-min) (point-max) pall)
4705 (when org-agenda-skip-archived-trees
4706 (goto-char (point-min))
4707 (while (re-search-forward rea nil t)
4708 (if (org-on-heading-p)
4709 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
4710 (goto-char (point-min))
4711 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
4712 (while (re-search-forward re nil t)
4713 (add-text-properties
4714 (match-beginning 0) (org-end-of-subtree t) pc)))))))
4716 (defun org-agenda-skip ()
4717 "Throw to `:skip' in places that should be skipped."
4718 (let ((p (point-at-bol)))
4719 (and org-agenda-skip-archived-trees
4720 (get-text-property p :org-archived)
4721 (org-end-of-subtree)
4723 (and (get-text-property p :org-comment)
4724 (org-end-of-subtree)
4726 (if (equal (char-after p) ?#) (throw :skip t))))
4728 (defun org-agenda-toggle-archive-tag ()
4729 "Toggle the archive tag for the current entry."
4731 (org-agenda-check-no-diary)
4732 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
4733 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
4734 (org-agenda-error)))
4735 (buffer (marker-buffer hdmarker))
4736 (pos (marker-position hdmarker))
4737 (buffer-read-only nil)
4739 (with-current-buffer buffer
4742 (org-show-hidden-entry)
4744 (and (outline-next-heading)
4745 (org-flag-heading nil))) ; show the next heading
4746 (call-interactively 'org-toggle-archive-tag)
4748 (setq newhead (org-get-heading)))
4749 (org-agenda-change-all-lines newhead hdmarker)
4750 (beginning-of-line 1)))
4754 (defun org-find-dblock (name)
4755 "Find the first dynamic block with name NAME in the buffer.
4756 If not found, stay at current position and return nil."
4759 (goto-char (point-min))
4760 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
4762 (match-beginning 0))))
4763 (if pos (goto-char pos))
4766 (defconst org-dblock-start-re
4767 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)[ \t]+\\(.*\\)"
4768 "Matches the startline of a dynamic block, with parameters.")
4770 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
4771 "Matches the end of a dyhamic block.")
4773 (defun org-create-dblock (plist)
4774 "Create a dynamic block section, with parameters taken from PLIST.
4775 PLIST must containe a :name entry which is used as name of the block."
4776 (unless (bolp) (newline))
4777 (let ((name (plist-get plist :name)))
4778 (insert "#+BEGIN: " name)
4780 (if (eq (car plist) :name)
4781 (setq plist (cddr plist))
4782 (insert " " (prin1-to-string (pop plist)))))
4783 (insert "\n\n#+END:\n")
4784 (beginning-of-line -2)))
4786 (defun org-prepare-dblock ()
4787 "Prepare dynamic block for refresh.
4788 This empties the block, puts the cursor at the insert position and returns
4789 the property list including an extra property :name with the block name."
4790 (unless (looking-at org-dblock-start-re)
4791 (error "Not at a dynamic block"))
4792 (let* ((begdel (1+ (match-end 0)))
4793 (name (match-string 1))
4794 (params (append (list :name name)
4795 (read (concat "(" (match-string 2) ")")))))
4796 (unless (re-search-forward org-dblock-end-re nil t)
4797 (error "Dynamic block not terminated"))
4798 (delete-region begdel (match-beginning 0))
4803 (defun org-map-dblocks (&optional command)
4804 "Apply COMMAND to all dynamic blocks in the current buffer.
4805 If COMMAND is not given, use `org-update-dblock'."
4806 (let ((cmd (or command 'org-update-dblock))
4809 (goto-char (point-min))
4810 (while (re-search-forward org-dblock-start-re nil t)
4811 (goto-char (setq pos (match-beginning 0)))
4814 (error (message "Error during update of dynamic block")))
4816 (unless (re-search-forward org-dblock-end-re nil t)
4817 (error "Dynamic block not terminated"))))))
4819 (defun org-dblock-update (&optional arg)
4820 "User command for updating dynamic blocks.
4821 Update the dynamic block at point. With prefix ARG, update all dynamic
4822 blocks in the buffer."
4825 (org-update-all-dblocks)
4826 (or (looking-at org-dblock-start-re)
4827 (org-beginning-of-dblock))
4828 (org-update-dblock)))
4830 (defun org-update-dblock ()
4831 "Update the dynamic block at point
4832 This means to empty the block, parse for parameters and then call
4833 the correct writing function."
4834 (let* ((pos (point))
4835 (params (org-prepare-dblock))
4836 (name (plist-get params :name))
4837 (cmd (intern (concat "org-dblock-write:" name))))
4838 (funcall cmd params)
4841 (defun org-beginning-of-dblock ()
4842 "Find the beginning of the dynamic block at point.
4843 Error if there is no scuh block at point."
4847 (if (and (re-search-backward org-dblock-start-re nil t)
4848 (setq beg (match-beginning 0))
4849 (re-search-forward org-dblock-end-re nil t)
4850 (> (match-end 0) pos))
4853 (error "Not in a dynamic block"))))
4855 (defun org-update-all-dblocks ()
4856 "Update all dynamic blocks in the buffer.
4857 This function can be used in a hook."
4858 (when (eq major-mode 'org-mode)
4859 (org-map-dblocks 'org-update-dblock)))
4864 (defun org-complete (&optional arg)
4865 "Perform completion on word at point.
4866 At the beginning of a headline, this completes TODO keywords as given in
4867 `org-todo-keywords'.
4868 If the current word is preceded by a backslash, completes the TeX symbols
4869 that are supported for HTML support.
4870 If the current word is preceded by \"#+\", completes special words for
4871 setting file options.
4872 At all other locations, this simply calls `ispell-complete-word'."
4875 (let* ((end (point))
4876 (beg1 (save-excursion
4877 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4878 (skip-chars-backward "a-zA-Z_@0-9")
4880 (beg (save-excursion
4881 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4882 (skip-chars-backward "a-zA-Z0-9_:$")
4884 (confirm (lambda (x) (stringp (car x))))
4885 (camel (equal (char-before beg) ?*))
4886 (tag (equal (char-before beg1) ?:))
4887 (texp (equal (char-before beg) ?\\))
4888 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
4891 (completion-ignore-case opt)
4898 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
4899 (cons (match-string 2 x) (match-string 1 x)))
4900 (org-split-string (org-get-current-options) "\n")))
4904 ((string-match "\\`\\*+[ \t]*\\'"
4905 (buffer-substring (point-at-bol) beg))
4907 (mapcar 'list org-todo-keywords))
4911 (goto-char (point-min))
4912 (while (re-search-forward org-todo-line-regexp nil t)
4914 (if org-file-link-context-use-camel-case
4915 (org-make-org-heading-camel (match-string 3) t)
4916 (org-make-org-heading-search-string
4917 (match-string 3) t)))
4920 (tag (setq type :tag beg beg1)
4921 (or org-tag-alist (org-get-buffer-tags)))
4922 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
4923 (pattern (buffer-substring-no-properties beg end))
4924 (completion (try-completion pattern table confirm)))
4925 (cond ((eq completion t)
4926 (if (equal type :opt)
4927 (insert (substring (cdr (assoc (upcase pattern) table))
4928 (length pattern)))))
4930 (message "Can't find completion for \"%s\"" pattern)
4932 ((not (string= pattern completion))
4933 (delete-region beg end)
4934 (if (string-match " +$" completion)
4935 (setq completion (replace-match "" t t completion)))
4937 (if (get-buffer-window "*Completions*")
4938 (delete-window (get-buffer-window "*Completions*")))
4939 (if (assoc completion table)
4940 (if (eq type :todo) (insert " ")
4941 (if (eq type :tag) (insert ":"))))
4942 (if (and (equal type :opt) (assoc completion table))
4943 (message "%s" (substitute-command-keys
4944 "Press \\[org-complete] again to insert example settings"))))
4946 (message "Making completion list...")
4947 (let ((list (sort (all-completions pattern table confirm)
4949 (with-output-to-temp-buffer "*Completions*"
4951 ;; Protection needed for XEmacs and emacs 21
4952 (display-completion-list list pattern)
4953 (error (display-completion-list list)))))
4954 (message "Making completion list...%s" "done"))))))
4956 ;;; Comments, TODO and DEADLINE
4958 (defun org-toggle-comment ()
4959 "Change the COMMENT state of an entry."
4962 (org-back-to-heading)
4963 (if (looking-at (concat outline-regexp
4964 "\\( +\\<" org-comment-string "\\>\\)"))
4965 (replace-match "" t t nil 1)
4966 (if (looking-at outline-regexp)
4968 (goto-char (match-end 0))
4969 (insert " " org-comment-string))))))
4971 (defvar org-last-todo-state-is-todo nil
4972 "This is non-nil when the last TODO state change led to a TODO state.
4973 If the last change removed the TODO tag or switched to DONE, then
4976 (defun org-todo (&optional arg)
4977 "Change the TODO state of an item.
4978 The state of an item is given by a keyword at the start of the heading,
4980 *** TODO Write paper
4983 The different keywords are specified in the variable `org-todo-keywords'.
4984 By default the available states are \"TODO\" and \"DONE\".
4985 So for this example: when the item starts with TODO, it is changed to DONE.
4986 When it starts with DONE, the DONE is removed. And when neither TODO nor
4987 DONE are present, add TODO at the beginning of the heading.
4989 With prefix arg, use completion to determine the new state. With numeric
4990 prefix arg, switch to that state."
4993 (org-back-to-heading)
4994 (if (looking-at outline-regexp) (goto-char (match-end 0)))
4995 (or (looking-at (concat " +" org-todo-regexp " *"))
4997 (let* ((this (match-string 1))
4998 (completion-ignore-case t)
4999 (member (member this org-todo-keywords))
5003 ;; Read a state with completion
5004 (completing-read "State: " (mapcar (lambda(x) (list x))
5009 (if tail (car tail) nil)
5010 (car org-todo-keywords)))
5012 (if (equal member org-todo-keywords)
5015 (nth (- (length org-todo-keywords) (length tail) 2)
5019 ;; user requests a specific state
5020 (nth (1- (prefix-numeric-value arg))
5022 ((null member) (car org-todo-keywords))
5023 ((null tail) nil) ;; -> first entry
5024 ((eq org-todo-interpretation 'sequence)
5026 ((memq org-todo-interpretation '(type priority))
5027 (if (eq this-command last-command)
5029 (if (> (length tail) 0) org-done-string nil)))
5031 (next (if state (concat " " state " ") " ")))
5032 (replace-match next t t)
5033 (setq org-last-todo-state-is-todo
5034 (not (equal state org-done-string)))
5036 (if (equal state org-done-string)
5037 (org-add-planning-info 'closed (current-time) 'scheduled)
5039 (org-add-planning-info nil nil 'closed))))
5040 ;; Fixup tag positioning
5041 (and org-auto-align-tags (org-set-tags nil t))
5042 (run-hooks 'org-after-todo-state-change-hook)))
5043 ;; Fixup cursor location if close to the keyword
5044 (if (and (outline-on-heading-p)
5046 (save-excursion (beginning-of-line 1)
5047 (looking-at org-todo-line-regexp))
5048 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5050 (goto-char (or (match-end 2) (match-end 1)))
5053 (defun org-log-done (&optional undone)
5054 "Add a time stamp logging that a TODO entry has been closed.
5055 When UNDONE is non-nil, remove such a time stamp again."
5059 (org-back-to-heading t)
5061 (looking-at (concat outline-regexp " *"))
5062 (goto-char (match-end 0))
5063 (setq col (current-column))
5064 (outline-next-heading)
5067 (when (re-search-forward (concat
5069 (regexp-quote org-closed-string)
5070 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
5071 (delete-region (match-beginning 1) (match-end 1)))
5073 (org-back-to-heading t)
5074 (skip-chars-forward "^\n\r")
5075 (goto-char (min (1+ (point)) (point-max)))
5076 (when (not (member (char-before) '(?\r ?\n)))
5079 (insert org-closed-string " "
5081 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5085 (defun org-show-todo-tree (arg)
5086 "Make a compact tree which shows all headlines marked with TODO.
5087 The tree will show the lines where the regexp matches, and all higher
5088 headlines above the match.
5089 With \\[universal-argument] prefix, also show the DONE entries.
5090 With a numeric prefix N, construct a sparse tree for the Nth element
5091 of `org-todo-keywords'."
5093 (let ((case-fold-search nil)
5095 (cond ((null arg) org-not-done-regexp)
5096 ((equal arg '(4)) org-todo-regexp)
5097 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5098 (regexp-quote (nth (1- (prefix-numeric-value arg))
5099 org-todo-keywords)))
5100 (t (error "Invalid prefix argument: %s" arg)))))
5101 (message "%d TODO entries found"
5102 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5104 (defun org-deadline ()
5105 "Insert the DEADLINE: string to make a deadline.
5106 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5107 to modify it to the correct date."
5109 (org-add-planning-info 'deadline nil 'closed))
5111 (defun org-schedule ()
5112 "Insert the SCHEDULED: string to schedule a TODO item.
5113 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5114 to modify it to the correct date."
5116 (org-add-planning-info 'scheduled nil 'closed))
5118 (defun org-add-planning-info (what &optional time &rest remove)
5119 "Insert new timestamp with keyword in the line directly after the headline.
5120 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5121 If non is given, the user is prompted for a date.
5122 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5125 (when what (setq time (or time (org-read-date nil 'to-time))))
5126 (when (and org-insert-labeled-timestamps-at-point
5127 (member what '(scheduled deadline)))
5129 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
5131 (format-time-string (car org-time-stamp-formats) time))
5134 (let (col list elt (buffer-invisibility-spec nil) ts)
5135 (org-back-to-heading t)
5136 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5137 (goto-char (match-end 1))
5138 (setq col (current-column))
5139 (goto-char (1+ (match-end 0)))
5140 (if (and (not (looking-at outline-regexp))
5141 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5143 (not (equal (match-string 1) org-clock-string)))
5144 (narrow-to-region (match-beginning 0) (match-end 0))
5147 (narrow-to-region (point) (point))
5148 (indent-to-column col))
5149 ;; Check if we have to remove something.
5150 (setq list (cons what remove))
5152 (setq elt (pop list))
5153 (goto-char (point-min))
5154 (when (or (and (eq elt 'scheduled)
5155 (re-search-forward org-scheduled-time-regexp nil t))
5156 (and (eq elt 'deadline)
5157 (re-search-forward org-deadline-time-regexp nil t))
5158 (and (eq elt 'closed)
5159 (re-search-forward org-closed-time-regexp nil t)))
5161 (if (looking-at " +") (replace-match ""))))
5162 (goto-char (point-max))
5165 (if (not (equal (char-before) ?\ )) " " "")
5166 (cond ((eq what 'scheduled) org-scheduled-string)
5167 ((eq what 'deadline) org-deadline-string)
5168 ((eq what 'closed) org-closed-string))
5173 (if (eq what 'closed)
5174 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5175 (car org-time-stamp-formats))
5177 (goto-char (point-min))
5179 (if (looking-at "[ \t]+\r?\n")
5183 (defun org-occur (regexp &optional callback)
5184 "Make a compact tree which shows all matches of REGEXP.
5185 The tree will show the lines where the regexp matches, and all higher
5186 headlines above the match. It will also show the heading after the match,
5187 to make sure editing the matching entry is easy.
5188 If CALLBACK is non-nil, it is a function which is called to confirm
5189 that the match should indeed be shown."
5190 (interactive "sRegexp: ")
5191 (org-remove-occur-highlights nil nil t)
5192 (setq regexp (org-check-occur-regexp regexp))
5195 (goto-char (point-min))
5197 (while (re-search-forward regexp nil t)
5198 (when (or (not callback)
5199 (save-match-data (funcall callback)))
5201 (org-highlight-new-match (match-beginning 0) (match-end 0))
5202 (org-show-hierarchy-above))))
5203 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5205 (unless org-sparse-tree-open-archived-trees
5206 (org-hide-archived-subtrees (point-min) (point-max)))
5207 (run-hooks 'org-occur-hook)
5209 (message "%d match(es) for regexp %s" cnt regexp))
5212 (defun org-show-hierarchy-above ()
5213 "Make sure point and the headings hierarchy above is visible."
5215 (if (org-on-heading-p t)
5216 (org-flag-heading nil) ; only show the heading
5217 (and (or (org-invisible-p) (org-invisible-p2))
5218 (org-show-hidden-entry))) ; show entire entry
5220 (and org-show-following-heading
5221 (outline-next-heading)
5222 (org-flag-heading nil))) ; show the next heading
5223 (when org-show-hierarchy-above
5224 (save-excursion ; show all higher headings
5225 (while (and (condition-case nil
5226 (progn (org-up-heading-all 1) t)
5229 (org-flag-heading nil))))))
5231 ;; Overlay compatibility functions
5232 (defun org-make-overlay (beg end &optional buffer)
5233 (if (featurep 'xemacs)
5234 (make-extent beg end buffer)
5235 (make-overlay beg end buffer)))
5236 (defun org-delete-overlay (ovl)
5237 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5238 (defun org-detatch-overlay (ovl)
5239 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5240 (defun org-move-overlay (ovl beg end &optional buffer)
5241 (if (featurep 'xemacs)
5242 (set-extent-endpoints ovl beg end buffer)
5243 (move-overlay ovl beg end buffer)))
5244 (defun org-overlay-put (ovl prop value)
5245 (if (featurep 'xemacs)
5246 (set-extent-property ovl prop value)
5247 (overlay-put ovl prop value)))
5248 (defun org-overlays-at (pos)
5249 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5250 (defun org-overlay-start (o)
5251 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5252 (defun org-overlay-end (o)
5253 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5255 (defvar org-occur-highlights nil)
5256 (make-variable-buffer-local 'org-occur-highlights)
5257 (defun org-highlight-new-match (beg end)
5258 "Highlight from BEG to END and mark the highlight is an occur headline."
5259 (let ((ov (org-make-overlay beg end)))
5260 (org-overlay-put ov 'face 'secondary-selection)
5261 (push ov org-occur-highlights)))
5263 (defvar org-inhibit-highlight-removal nil)
5264 (defun org-remove-occur-highlights (&optional beg end noremove)
5265 "Remove the occur highlights from the buffer.
5266 BEG and END are ignored. If NOREMOVE is nil, remove this function
5267 from the `before-change-functions' in the current buffer."
5269 (unless org-inhibit-highlight-removal
5270 (mapc 'org-delete-overlay org-occur-highlights)
5271 (setq org-occur-highlights nil)
5273 (remove-hook 'before-change-functions
5274 'org-remove-occur-highlights 'local))))
5278 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5279 "Regular expression matching the priority indicator.")
5281 (defvar org-remove-priority-next-time nil)
5283 (defun org-priority-up ()
5284 "Increase the priority of the current item."
5288 (defun org-priority-down ()
5289 "Decrease the priority of the current item."
5291 (org-priority 'down))
5293 (defun org-priority (&optional action)
5294 "Change the priority of an item by ARG.
5295 ACTION can be set, up, or down."
5297 (setq action (or action 'set))
5298 (let (current new news have remove)
5300 (org-back-to-heading)
5301 (if (looking-at org-priority-regexp)
5302 (setq current (string-to-char (match-string 2))
5304 (setq current org-default-priority))
5307 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5308 (setq new (read-char-exclusive))
5309 (cond ((equal new ?\ ) (setq remove t))
5310 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5311 (error "Priority must be between `%c' and `%c'"
5312 ?A org-lowest-priority))))
5314 (setq new (1- current)))
5316 (setq new (1+ current)))
5317 (t (error "Invalid action")))
5318 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5319 (setq news (format "%c" new))
5322 (replace-match "" t t nil 1)
5323 (replace-match news t t nil 2))
5325 (error "No priority cookie found in line")
5326 (looking-at org-todo-line-regexp)
5329 (goto-char (match-end 2))
5330 (insert " [#" news "]"))
5331 (goto-char (match-beginning 3))
5332 (insert "[#" news "] ")))))
5334 (message "Priority removed")
5335 (message "Priority of current item set to %s" news))))
5338 (defun org-get-priority (s)
5339 "Find priority cookie and return priority."
5341 (if (not (string-match org-priority-regexp s))
5342 (* 1000 (- org-lowest-priority org-default-priority))
5343 (* 1000 (- org-lowest-priority
5344 (string-to-char (match-string 2 s)))))))
5348 (defvar org-last-changed-timestamp nil)
5350 (defun org-time-stamp (arg)
5351 "Prompt for a date/time and insert a time stamp.
5352 If the user specifies a time like HH:MM, or if this command is called
5353 with a prefix argument, the time stamp will contain date and time.
5354 Otherwise, only the date will be included. All parts of a date not
5355 specified by the user will be filled in from the current date/time.
5356 So if you press just return without typing anything, the time stamp
5357 will represent the current date/time. If there is already a timestamp
5358 at the cursor, it will be modified."
5360 (let ((fmt (if arg (cdr org-time-stamp-formats)
5361 (car org-time-stamp-formats)))
5362 (org-time-was-given nil)
5365 ((and (org-at-timestamp-p)
5366 (eq last-command 'org-time-stamp)
5367 (eq this-command 'org-time-stamp))
5369 (setq time (let ((this-command this-command))
5370 (org-read-date arg 'totime)))
5371 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5372 (insert (format-time-string fmt time)))
5373 ((org-at-timestamp-p)
5374 (setq time (let ((this-command this-command))
5375 (org-read-date arg 'totime)))
5376 (and (org-at-timestamp-p) (replace-match
5377 (setq org-last-changed-timestamp
5378 (format-time-string fmt time))
5380 (message "Timestamp updated"))
5382 (setq time (let ((this-command this-command))
5383 (org-read-date arg 'totime)))
5384 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5385 (insert (format-time-string fmt time))))))
5387 (defun org-time-stamp-inactive (&optional arg)
5388 "Insert an inactive time stamp.
5389 An inactive time stamp is enclosed in square brackets instead of angle
5390 brackets. It is inactive in the sense that it does not trigger agenda entries,
5391 does not link to the calendar and cannot be changed with the S-cursor keys.
5392 So these are more for recording a certain time/date."
5394 (let ((fmt (if arg (cdr org-time-stamp-formats)
5395 (car org-time-stamp-formats)))
5396 (org-time-was-given nil)
5398 (setq time (org-read-date arg 'totime))
5399 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5400 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
5401 (insert (format-time-string fmt time))))
5403 (defvar org-date-ovl (org-make-overlay 1 1))
5404 (org-overlay-put org-date-ovl 'face 'org-warning)
5405 (org-detatch-overlay org-date-ovl)
5407 (defun org-read-date (&optional with-time to-time)
5408 "Read a date and make things smooth for the user.
5409 The prompt will suggest to enter an ISO date, but you can also enter anything
5410 which will at least partially be understood by `parse-time-string'.
5411 Unrecognized parts of the date will default to the current day, month, year,
5412 hour and minute. For example,
5413 3-2-5 --> 2003-02-05
5414 feb 15 --> currentyear-02-15
5415 sep 12 9 --> 2009-09-12
5416 12:45 --> today 12:45
5417 22 sept 0:34 --> currentyear-09-22 0:34
5418 12 --> currentyear-currentmonth-12
5419 Fri --> nearest Friday (today or later)
5421 The function understands only English month and weekday abbreviations,
5422 but this can be configured with the variables `parse-time-months' and
5423 `parse-time-weekdays'.
5425 While prompting, a calendar is popped up - you can also select the
5426 date with the mouse (button 1). The calendar shows a period of three
5427 months. To scroll it to other months, use the keys `>' and `<'.
5428 If you don't like the calendar, turn it off with
5429 \(setq org-popup-calendar-for-date-prompt nil)
5431 With optional argument TO-TIME, the date will immediately be converted
5432 to an internal time.
5433 With an optional argument WITH-TIME, the prompt will suggest to also
5434 insert a time. Note that when WITH-TIME is not set, you can still
5435 enter a time, and this function will inform the calling routine about
5436 this change. The calling routine may then choose to change the format
5437 used to insert the time stamp into the buffer to include the time."
5438 (require 'parse-time)
5439 (let* ((org-time-stamp-rounding-minutes
5440 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5441 (ct (org-current-time))
5443 ;; Default time is either today, or, when entering a range,
5447 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5451 (mapcar (lambda(x) (or x 0))
5452 (parse-time-string (match-string 1))))
5454 (calendar-move-hook nil)
5455 (view-diary-entries-initially nil)
5456 (view-calendar-holidays-initially nil)
5457 (timestr (format-time-string
5458 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5459 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5461 second minute hour day month year tl wday wday1)
5463 (if org-popup-calendar-for-date-prompt
5465 (save-window-excursion
5467 (calendar-forward-day (- (time-to-days default-time)
5468 (calendar-absolute-from-gregorian
5469 (calendar-current-date))))
5470 (org-eval-in-calendar nil)
5471 (let* ((old-map (current-local-map))
5472 (map (copy-keymap calendar-mode-map))
5473 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5474 (define-key map (kbd "RET") 'org-calendar-select)
5475 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5476 'org-calendar-select-mouse)
5477 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5478 'org-calendar-select-mouse)
5479 (define-key minibuffer-local-map [(meta shift left)]
5480 (lambda () (interactive)
5481 (org-eval-in-calendar '(calendar-backward-month 1))))
5482 (define-key minibuffer-local-map [(meta shift right)]
5483 (lambda () (interactive)
5484 (org-eval-in-calendar '(calendar-forward-month 1))))
5485 (define-key minibuffer-local-map [(shift up)]
5486 (lambda () (interactive)
5487 (org-eval-in-calendar '(calendar-backward-week 1))))
5488 (define-key minibuffer-local-map [(shift down)]
5489 (lambda () (interactive)
5490 (org-eval-in-calendar '(calendar-forward-week 1))))
5491 (define-key minibuffer-local-map [(shift left)]
5492 (lambda () (interactive)
5493 (org-eval-in-calendar '(calendar-backward-day 1))))
5494 (define-key minibuffer-local-map [(shift right)]
5495 (lambda () (interactive)
5496 (org-eval-in-calendar '(calendar-forward-day 1))))
5497 (define-key minibuffer-local-map ">"
5498 (lambda () (interactive)
5499 (org-eval-in-calendar '(scroll-calendar-left 1))))
5500 (define-key minibuffer-local-map "<"
5501 (lambda () (interactive)
5502 (org-eval-in-calendar '(scroll-calendar-right 1))))
5506 (setq ans (read-string prompt "" nil nil))
5507 (if (not (string-match "\\S-" ans)) (setq ans nil))
5508 (setq ans (or ans1 ans ans2)))
5509 (use-local-map old-map)))))
5510 ;; Naked prompt only
5511 (setq ans (read-string prompt "" nil timestr)))
5512 (org-detatch-overlay org-date-ovl)
5515 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5517 (setq year (if (match-end 2)
5518 (string-to-number (match-string 2 ans))
5519 (string-to-number (format-time-string "%Y")))
5520 month (string-to-number (match-string 3 ans))
5521 day (string-to-number (match-string 4 ans)))
5522 (if (< year 100) (setq year (+ 2000 year)))
5523 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5525 (setq tl (parse-time-string ans)
5526 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5527 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5528 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5529 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5530 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5531 second (or (nth 0 tl) 0)
5533 (when (and wday (not (nth 3 tl)))
5534 ;; Weekday was given, but no day, so pick that day in the week
5535 ;; on or after the derived date.
5536 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5537 (unless (equal wday wday1)
5538 (setq day (+ day (% (- wday wday1 -7) 7)))))
5539 (if (and (boundp 'org-time-was-given)
5541 (setq org-time-was-given t))
5542 (if (< year 100) (setq year (+ 2000 year)))
5544 (encode-time second minute hour day month year)
5545 (if (or (nth 1 tl) (nth 2 tl))
5546 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5547 (format "%04d-%02d-%02d" year month day)))))
5549 (defun org-eval-in-calendar (form)
5550 "Eval FORM in the calendar window and return to current window.
5551 Also, store the cursor date in variable ans2."
5552 (let ((sw (selected-window)))
5553 (select-window (get-buffer-window "*Calendar*"))
5555 (when (calendar-cursor-to-date)
5556 (let* ((date (calendar-cursor-to-date))
5557 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5558 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5559 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5560 (select-window sw)))
5562 (defun org-calendar-select ()
5563 "Return to `org-read-date' with the date currently selected.
5564 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5566 (when (calendar-cursor-to-date)
5567 (let* ((date (calendar-cursor-to-date))
5568 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5569 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5570 (if (active-minibuffer-window) (exit-minibuffer))))
5572 (defun org-calendar-select-mouse (ev)
5573 "Return to `org-read-date' with the date currently selected.
5574 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5576 (mouse-set-point ev)
5577 (when (calendar-cursor-to-date)
5578 (let* ((date (calendar-cursor-to-date))
5579 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5580 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5581 (if (active-minibuffer-window) (exit-minibuffer))))
5583 (defun org-check-deadlines (ndays)
5584 "Check if there are any deadlines due or past due.
5585 A deadline is considered due if it happens within `org-deadline-warning-days'
5586 days from today's date. If the deadline appears in an entry marked DONE,
5587 it is not shown. The prefix arg NDAYS can be used to test that many
5588 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
5590 (let* ((org-warn-days
5592 ((equal ndays '(4)) 100000)
5593 (ndays (prefix-numeric-value ndays))
5594 (t org-deadline-warning-days)))
5595 (case-fold-search nil)
5596 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5599 (and (let ((d1 (time-to-days (current-time)))
5601 (org-time-string-to-time (match-string 1)))))
5602 (< (- d2 d1) org-warn-days))
5603 (not (org-entry-is-done-p))))))
5604 (message "%d deadlines past-due or due within %d days"
5605 (org-occur regexp callback)
5608 (defun org-evaluate-time-range (&optional to-buffer)
5609 "Evaluate a time range by computing the difference between start and end.
5610 Normally the result is just printed in the echo area, but with prefix arg
5611 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5612 If the time range is actually in a table, the result is inserted into the
5614 For time difference computation, a year is assumed to be exactly 365
5615 days in order to avoid rounding problems."
5618 (unless (org-at-date-range-p)
5619 (goto-char (point-at-bol))
5620 (re-search-forward org-tr-regexp (point-at-eol) t))
5621 (if (not (org-at-date-range-p))
5622 (error "Not at a time-stamp range, and none found in current line")))
5623 (let* ((ts1 (match-string 1))
5624 (ts2 (match-string 2))
5625 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5626 (match-end (match-end 0))
5627 (time1 (org-time-string-to-time ts1))
5628 (time2 (org-time-string-to-time ts2))
5629 (t1 (time-to-seconds time1))
5630 (t2 (time-to-seconds time2))
5631 (diff (abs (- t2 t1)))
5632 (negative (< (- t2 t1) 0))
5633 ;; (ys (floor (* 365 24 60 60)))
5636 (fy "%dy %dd %02d:%02d")
5638 (fd "%dd %02d:%02d")
5643 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5645 d (floor (/ diff ds)) diff (mod diff ds)
5646 h (floor (/ diff hs)) diff (mod diff hs)
5647 m (floor (/ diff 60)))
5648 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5650 d (floor (+ (/ diff ds) 0.5))
5653 (message (org-make-tdiff-string y d h m))
5654 (when (org-at-table-p)
5655 (goto-char match-end)
5657 (and (looking-at " *|") (goto-char (match-end 0))))
5659 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5661 (if negative (insert " -"))
5662 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5663 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5664 (insert " " (format fh h m))))
5665 (if align (org-table-align))
5666 (message "Time difference inserted"))))
5668 (defun org-make-tdiff-string (y d h m)
5671 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5673 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5675 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5677 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5679 (apply 'format fmt (nreverse l))))
5681 (defun org-time-string-to-time (s)
5682 (apply 'encode-time (org-parse-time-string s)))
5684 (defun org-parse-time-string (s &optional nodefault)
5685 "Parse the standard Org-mode time string.
5686 This should be a lot faster than the normal `parse-time-string'.
5687 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5688 hour and minute fields will be nil if not given."
5689 (if (string-match org-ts-regexp1 s)
5691 (if (or (match-beginning 8) (not nodefault))
5692 (string-to-number (or (match-string 8 s) "0")))
5693 (if (or (match-beginning 7) (not nodefault))
5694 (string-to-number (or (match-string 7 s) "0")))
5695 (string-to-number (match-string 4 s))
5696 (string-to-number (match-string 3 s))
5697 (string-to-number (match-string 2 s))
5701 (defun org-timestamp-up (&optional arg)
5702 "Increase the date item at the cursor by one.
5703 If the cursor is on the year, change the year. If it is on the month or
5704 the day, change that.
5705 With prefix ARG, change by that many units."
5707 (org-timestamp-change (prefix-numeric-value arg)))
5709 (defun org-timestamp-down (&optional arg)
5710 "Decrease the date item at the cursor by one.
5711 If the cursor is on the year, change the year. If it is on the month or
5712 the day, change that.
5713 With prefix ARG, change by that many units."
5715 (org-timestamp-change (- (prefix-numeric-value arg))))
5717 (defun org-timestamp-up-day (&optional arg)
5718 "Increase the date in the time stamp by one day.
5719 With prefix ARG, change that many days."
5721 (if (and (not (org-at-timestamp-p t))
5724 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5726 (defun org-timestamp-down-day (&optional arg)
5727 "Decrease the date in the time stamp by one day.
5728 With prefix ARG, change that many days."
5730 (if (and (not (org-at-timestamp-p t))
5733 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5735 (defsubst org-pos-in-match-range (pos n)
5736 (and (match-beginning n)
5737 (<= (match-beginning n) pos)
5738 (>= (match-end n) pos)))
5740 (defun org-at-timestamp-p (&optional also-inactive)
5741 "Determine if the cursor is in or at a timestamp."
5743 (let* ((tsr (if also-inactive org-ts-regexp3 org-ts-regexp2))
5745 (ans (or (looking-at tsr)
5747 (skip-chars-backward "^[<\n\r\t")
5748 (if (> (point) 1) (backward-char 1))
5749 (and (looking-at tsr)
5750 (> (- (match-end 0) pos) -1))))))
5751 (and (boundp 'org-ts-what)
5754 ((org-pos-in-match-range pos 2) 'year)
5755 ((org-pos-in-match-range pos 3) 'month)
5756 ((org-pos-in-match-range pos 7) 'hour)
5757 ((org-pos-in-match-range pos 8) 'minute)
5758 ((or (org-pos-in-match-range pos 4)
5759 (org-pos-in-match-range pos 5)) 'day)
5763 (defun org-timestamp-change (n &optional what)
5764 "Change the date in the time stamp at point.
5765 The date will be changed by N times WHAT. WHAT can be `day', `month',
5766 `year', `minute', `second'. If WHAT is not given, the cursor position
5767 in the timestamp determines what will be changed."
5768 (let ((fmt (car org-time-stamp-formats))
5772 (if (not (org-at-timestamp-p t))
5773 (error "Not at a timestamp"))
5774 (setq org-ts-what (or what org-ts-what))
5775 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5776 (- (match-end 0) (match-beginning 0))))
5778 (cdr org-time-stamp-formats)
5779 (car org-time-stamp-formats)))
5780 (if (= (char-after (match-beginning 0)) ?\[)
5781 (setq fmt (concat "[" (substring fmt 1 -1) "]")))
5782 (setq ts (match-string 0))
5784 (setq time0 (org-parse-time-string ts))
5788 (list (or (car time0) 0))
5789 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5790 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5791 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5792 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5793 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5795 (if (eq what 'calendar)
5799 (set-buffer "*Calendar*")
5800 (calendar-cursor-to-date)))))
5801 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5802 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5803 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5804 (setcar time0 (or (car time0) 0))
5805 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5806 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5807 (setq time (apply 'encode-time time0))))
5808 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5810 ;; Try to recenter the calendar window, if any
5811 (if (and org-calendar-follow-timestamp-change
5812 (get-buffer-window "*Calendar*" t)
5813 (memq org-ts-what '(day month year)))
5814 (org-recenter-calendar (time-to-days time)))))
5816 (defun org-recenter-calendar (date)
5817 "If the calendar is visible, recenter it to DATE."
5818 (let* ((win (selected-window))
5819 (cwin (get-buffer-window "*Calendar*" t))
5820 (calendar-move-hook nil))
5822 (select-window cwin)
5823 (calendar-goto-date (if (listp date) date
5824 (calendar-gregorian-from-absolute date)))
5825 (select-window win))))
5827 (defun org-goto-calendar (&optional arg)
5828 "Go to the Emacs calendar at the current date.
5829 If there is a time stamp in the current line, go to that date.
5830 A prefix ARG can be used to force the current date."
5832 (let ((tsr org-ts-regexp) diff
5833 (calendar-move-hook nil)
5834 (view-calendar-holidays-initially nil)
5835 (view-diary-entries-initially nil))
5836 (if (or (org-at-timestamp-p)
5838 (beginning-of-line 1)
5839 (looking-at (concat ".*" tsr))))
5840 (let ((d1 (time-to-days (current-time)))
5842 (org-time-string-to-time (match-string 1)))))
5843 (setq diff (- d2 d1))))
5845 (calendar-goto-today)
5846 (if (and diff (not arg)) (calendar-forward-day diff))))
5848 (defun org-date-from-calendar ()
5849 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5850 If there is already a time stamp at the cursor position, update it."
5852 (org-timestamp-change 0 'calendar))
5854 ;;; The clock for measuring work time.
5856 (defvar org-clock-marker (make-marker)
5857 "Marker recording the last clock-in.")
5859 (defun org-clock-in ()
5860 "Start the clock on the current item.
5861 If necessary, clock-out of the currently active clock."
5866 (org-back-to-heading t)
5867 (beginning-of-line 2)
5868 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5869 (not (equal (match-string 1) org-clock-string)))
5870 (beginning-of-line 1))
5871 (insert "\n") (backward-char 1)
5873 (insert org-clock-string " "
5874 (setq ts (concat "[" (format-time-string
5876 (cdr org-time-stamp-formats) 1 -1)
5879 (move-marker org-clock-marker (point))
5880 (message "Clock started at %s" ts))))
5882 (defun org-clock-out (&optional fail-quietly)
5883 "Stop the currently running clock.
5884 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
5887 (if (not (marker-buffer org-clock-marker))
5888 (if fail-quietly (throw 'exit t) (error "No active clock")))
5891 (set-buffer (marker-buffer org-clock-marker))
5892 (goto-char org-clock-marker)
5893 (beginning-of-line 1)
5894 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5895 (equal (match-string 1) org-clock-string))
5896 (setq ts (match-string 2))
5897 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
5898 (goto-char org-clock-marker)
5899 (setq te (concat "[" (format-time-string
5901 (cdr org-time-stamp-formats) 1 -1)
5904 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
5905 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
5906 h (floor (/ s 3600))
5910 (insert "--" te " => " (format "%2d:%02d" h m))
5911 (move-marker org-clock-marker nil)
5912 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
5914 (defun org-clock-cancel ()
5915 "Cancel the running clock be removing the start timestamp."
5917 (if (not (marker-buffer org-clock-marker))
5918 (error "No active clock"))
5920 (set-buffer (marker-buffer org-clock-marker))
5921 (goto-char org-clock-marker)
5922 (delete-region (1- (point-at-bol)) (point-at-eol)))
5923 (message "Clock canceled"))
5925 (defvar org-clock-file-total-minutes nil
5926 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
5927 (make-variable-buffer-local 'org-clock-file-total-minutes)
5929 (defun org-clock-sum ()
5930 "Sum the times for each subtree.
5931 Puts the resulting times in minutes as a text property on each headline."
5933 (let* ((bmp (buffer-modified-p))
5934 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
5936 ".*=>[ \t]*\\([0-9]+\\):\\([0-9]+\\)[ \t]*$"))
5938 (ltimes (make-vector lmax 0))
5942 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
5944 (goto-char (point-max))
5945 (while (re-search-backward re nil t)
5948 (setq t1 (+ t1 (* 60 (string-to-number (match-string 2)))
5949 (string-to-number (match-string 3))))
5951 (setq level (- (match-end 1) (match-beginning 1)))
5952 (when (or (> t1 0) (> (aref ltimes level) 0))
5953 (loop for l from 0 to level do
5954 (aset ltimes l (+ (aref ltimes l) t1)))
5955 (setq t1 0 time (aref ltimes level))
5956 (loop for l from level to (1- lmax) do
5958 (goto-char (match-beginning 0))
5959 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
5960 (setq org-clock-file-total-minutes (aref ltimes 0)))
5961 (set-buffer-modified-p bmp)))
5963 (defun org-clock-display (&optional total-only)
5964 "Show subtree times in the entire buffer.
5965 If TOTAL-ONLY is non-nil, only show the total time for the entire file
5968 (org-remove-clock-overlays)
5973 (goto-char (point-min))
5974 (while (setq p (next-single-property-change (point) :org-clock-minutes))
5976 (when (setq time (get-text-property p :org-clock-minutes))
5977 (org-put-clock-overlay time (funcall outline-level))))
5978 (setq h (/ org-clock-file-total-minutes 60)
5979 m (- org-clock-file-total-minutes (* 60 h)))
5980 ;; Arrange to remove the overlays upon next change.
5981 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
5983 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
5985 (defvar org-clock-overlays nil)
5986 (make-variable-buffer-local 'org-clock-overlays)
5988 (defun org-put-clock-overlay (time &optional level)
5989 "Put an overlays on the current line, displaying TIME.
5990 If LEVEL is given, prefix time with a corresponding number of stars.
5991 This creates a new overlay and stores it in `org-clock-overlays', so that it
5992 will be easy to remove."
5993 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
5994 (l (if level (org-get-legal-level level 0) 0))
5998 (unless (eolp) (skip-chars-backward "^ \t"))
5999 (skip-chars-backward " \t")
6000 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6001 tx (concat (buffer-substring (1- (point)) (point))
6002 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6003 (org-add-props (format "%s %2d:%02d%s"
6004 (make-string l ?*) h m
6005 (make-string (- 10 l) ?\ ))
6006 '(face secondary-selection))
6008 (org-overlay-put ov 'display tx)
6009 (push ov org-clock-overlays)))
6011 (defun org-remove-clock-overlays (&optional beg end noremove)
6012 "Remove the occur highlights from the buffer.
6013 BEG and END are ignored. If NOREMOVE is nil, remove this function
6014 from the `before-change-functions' in the current buffer."
6016 (unless org-inhibit-highlight-removal
6017 (mapc 'org-delete-overlay org-clock-overlays)
6018 (setq org-clock-overlays nil)
6020 (remove-hook 'before-change-functions
6021 'org-remove-clock-overlays 'local))))
6023 (defun org-clock-out-if-current ()
6024 "Clock out if the current entry contains the running clock.
6025 This is used to stop the clock after a TODO entry is marked DONE."
6026 (when (and (equal state org-done-string)
6027 (equal (marker-buffer org-clock-marker) (current-buffer))
6028 (< (point) org-clock-marker)
6029 (> (save-excursion (outline-next-heading) (point))
6033 (add-hook 'org-after-todo-state-change-hook
6034 'org-clock-out-if-current)
6036 (defun org-check-running-clock ()
6037 "Check if the current buffer contains the running clock.
6038 If yes, offer to stop it and to save the buffer with the changes."
6039 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6040 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6043 (when (y-or-n-p "Save changed buffer?")
6046 (defun org-clock-report ()
6047 "Create a table containing a report about clocked time.
6048 If the buffer contains lines
6049 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6052 then the table will be inserted between these lines, replacing whatever
6053 is was there before. If these lines are not in the buffer, the table
6054 is inserted at point, surrounded by the special lines.
6055 The BEGIN line can contain parameters. Allowed are:
6056 :maxlevel The maximum level to be included in the table. Default is 3.
6057 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6059 (org-remove-clock-overlays)
6060 (unless (org-find-dblock "clocktable")
6061 (org-create-dblock (list :name "clocktable"
6062 :maxlevel 2 :emphasize nil)))
6063 (org-update-dblock))
6065 (defun org-dblock-write:clocktable (params)
6066 "Write the standard clocktable."
6067 (let ((hlchars '((1 . "*") (2 . ?/)))
6070 ipos time h m p level hlc hdl maxlevel)
6071 (setq maxlevel (or (plist-get params :maxlevel) 3)
6072 emph (plist-get params :emphasize))
6073 (move-marker ins (point))
6075 (insert-before-markers "Clock summary at ["
6077 (format-time-string (cdr org-time-stamp-formats))
6079 "]\n|L|Headline|Time|\n")
6081 (setq h (/ org-clock-file-total-minutes 60)
6082 m (- org-clock-file-total-minutes (* 60 h)))
6083 (insert-before-markers "|-\n|0|" "*Total file time*| "
6084 (format "*%d:%02d*" h m)
6086 (goto-char (point-min))
6087 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6089 (when (setq time (get-text-property p :org-clock-minutes))
6090 (beginning-of-line 1)
6091 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6092 (setq level (- (match-end 1) (match-beginning 1)))
6093 (<= level maxlevel))
6094 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6095 hdl (match-string 2)
6097 m (- time (* 60 h)))
6100 (if (= level 1) (insert-before-markers "|-\n"))
6101 (insert-before-markers
6102 "| " (int-to-string level) "|" hlc hdl hlc " |"
6103 (make-string (1- level) ?|)
6105 (format "%d:%02d" h m)
6109 (backward-delete-char 1)
6111 (skip-chars-forward "^|")
6114 (defun org-collect-clock-time-entries ()
6115 "Return an internal list with clocking information.
6116 This list has one entry for each CLOCK interval.
6117 FIXME: describe the elements."
6119 (let ((re (concat "^[ \t]*" org-clock-string
6120 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6121 rtn beg end next cont level title total closedp leafp
6122 clockpos titlepos h m donep)
6125 (goto-char (point-min))
6126 (while (re-search-forward re nil t)
6127 (setq clockpos (match-beginning 0)
6128 beg (match-string 1) end (match-string 2)
6130 (setq beg (apply 'encode-time (org-parse-time-string beg))
6131 end (apply 'encode-time (org-parse-time-string end)))
6132 (org-back-to-heading t)
6133 (setq donep (org-entry-is-done-p))
6134 (setq titlepos (point)
6135 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6136 h (/ total 60) m (- total (* 60 h))
6138 (looking-at "\\(\\*+\\) +\\(.*\\)")
6139 (setq level (- (match-end 1) (match-beginning 1))
6140 title (org-match-string-no-properties 2))
6141 (save-excursion (outline-next-heading) (setq next (point)))
6142 (setq closedp (re-search-forward org-closed-time-regexp next t))
6144 (setq leafp (and (looking-at "^\\*+ ")
6145 (<= (- (match-end 0) (point)) level)))
6146 (push (list beg end clockpos closedp donep
6147 total title titlepos level leafp)
6152 ;;; Agenda, and Diary Integration
6156 (defvar org-agenda-mode-map (make-sparse-keymap)
6157 "Keymap for `org-agenda-mode'.")
6159 (defvar org-agenda-menu) ; defined later in this file.
6160 (defvar org-agenda-follow-mode nil)
6161 (defvar org-agenda-show-log nil)
6162 (defvar org-agenda-buffer-name "*Org Agenda*")
6163 (defvar org-agenda-redo-command nil)
6164 (defvar org-agenda-mode-hook nil)
6165 (defvar org-agenda-type nil)
6166 (defvar org-agenda-force-single-file nil)
6168 (defun org-agenda-mode ()
6169 "Mode for time-sorted view on action items in Org-mode files.
6171 The following commands are available:
6173 \\{org-agenda-mode-map}"
6175 (kill-all-local-variables)
6176 (setq major-mode 'org-agenda-mode)
6177 (setq mode-name "Org-Agenda")
6178 (use-local-map org-agenda-mode-map)
6179 (easy-menu-add org-agenda-menu)
6180 (if org-startup-truncated (setq truncate-lines t))
6181 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6182 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6183 (unless org-agenda-keep-modes
6184 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6185 org-agenda-show-log nil))
6187 '("Agenda") "Agenda Files"
6191 (if (get 'org-agenda-files 'org-restrict)
6192 "Restricted to single file"
6194 '(org-edit-agenda-file-list)
6195 (not (get 'org-agenda-files 'org-restrict)))
6197 (mapcar 'org-file-menu-entry (org-agenda-files))))
6198 (org-agenda-set-mode-name)
6200 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6201 (list 'org-agenda-mode-hook)))
6203 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6204 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6205 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6206 (define-key org-agenda-mode-map " " 'org-agenda-show)
6207 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6208 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6209 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6210 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6211 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6212 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6213 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6214 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6215 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6216 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6217 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6218 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6219 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6221 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6222 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6223 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6224 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6225 (while l (define-key org-agenda-mode-map
6226 (int-to-string (pop l)) 'digit-argument)))
6228 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6229 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6230 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6231 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6232 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6233 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6234 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6235 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6236 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6237 (define-key org-agenda-mode-map "n" 'next-line)
6238 (define-key org-agenda-mode-map "p" 'previous-line)
6239 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6240 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6241 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6242 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6243 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6244 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6245 (eval-after-load "calendar"
6246 '(define-key calendar-mode-map org-calendar-to-agenda-key
6247 'org-calendar-goto-agenda))
6248 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6249 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6250 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6251 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
6252 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6253 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6254 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6255 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6256 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6257 (define-key org-agenda-mode-map "O" 'org-clock-out)
6258 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6259 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6260 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6261 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6262 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6263 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6264 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6265 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6266 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6267 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6268 "Local keymap for agenda entries from Org-mode.")
6270 (define-key org-agenda-keymap
6271 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6272 (define-key org-agenda-keymap
6273 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6274 (when org-agenda-mouse-1-follows-link
6275 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6276 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6280 ["Show" org-agenda-show t]
6281 ["Go To (other window)" org-agenda-goto t]
6282 ["Go To (one window)" org-agenda-switch-to t]
6283 ["Follow Mode" org-agenda-follow-mode
6284 :style toggle :selected org-agenda-follow-mode :active t]
6286 ["Cycle TODO" org-agenda-todo t]
6288 ["Show all Tags" org-agenda-show-tags t]
6289 ["Set Tags" org-agenda-set-tags t])
6291 ["Schedule" org-agenda-schedule t]
6292 ["Set Deadline" org-agenda-deadline t]
6294 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6295 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6296 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6298 ["Set Priority" org-agenda-priority t]
6299 ["Increase Priority" org-agenda-priority-up t]
6300 ["Decrease Priority" org-agenda-priority-down t]
6301 ["Show Priority" org-agenda-show-priority t])
6303 ;; ["New agenda command" org-agenda t]
6304 ["Rebuild buffer" org-agenda-redo t]
6306 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6307 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6308 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6310 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6311 :style radio :selected (equal org-agenda-ndays 1)]
6312 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6313 :style radio :selected (equal org-agenda-ndays 7)]
6315 ["Show Logbook entries" org-agenda-log-mode
6316 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6317 ["Include Diary" org-agenda-toggle-diary
6318 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6319 ["Use Time Grid" org-agenda-toggle-time-grid
6320 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6322 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6323 ("Calendar Commands"
6324 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6325 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6326 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6327 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6328 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6329 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6331 ["Quit" org-agenda-quit t]
6332 ["Exit and Release Buffers" org-agenda-exit t]
6336 (defun org-agenda (arg)
6337 "Dispatch agenda commands to collect entries to the agenda buffer.
6338 Prompts for a character to select a command. Any prefix arg will be passed
6339 on to the selected command. The default selections are:
6341 a Call `org-agenda' to display the agenda for the current day or week.
6342 t Call `org-todo-list' to display the global todo list.
6343 T Call `org-todo-list' to display the global todo list, select only
6344 entries with a specific TODO keyword (the user gets a prompt).
6345 m Call `org-tags-view' to display headlines with tags matching
6346 a condition (the user is prompted for the condition).
6347 M Like `m', but select only TODO entries, no ordinary headlines.
6349 More commands can be added by configuring the variable
6350 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
6351 searches can be pre-defined in this way.
6353 If the current buffer is in Org-mode and visiting a file, you can also
6354 first press `1' to indicate that the agenda should be temporarily (until the
6355 next use of \\[org-agenda]) restricted to the current file."
6358 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
6359 (bfn buffer-file-name)
6360 (custom org-agenda-custom-commands)
6361 c entry key type string)
6362 (put 'org-agenda-files 'org-restrict nil)
6363 (save-window-excursion
6364 (delete-other-windows)
6365 (switch-to-buffer-other-window " *Agenda Commands*")
6368 "Press key for an agenda command:
6369 --------------------------------
6370 a Agenda for current week or day
6371 t List of all TODO entries T Entries with special TODO kwd
6372 m Match a TAGS query M Like m, but only TODO entries
6373 C Configure your own agenda commands")
6374 (while (setq entry (pop custom))
6375 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
6376 (insert (format "\n%-4s%-14s: %s"
6379 ((eq type 'tags) "Tags query")
6380 ((eq type 'todo) "TODO keyword")
6381 ((eq type 'tags-tree) "Tags tree")
6382 ((eq type 'todo-tree) "TODO kwd tree")
6383 ((eq type 'occur-tree) "Occur tree")
6385 (org-add-props string nil 'face 'org-warning))))
6386 (goto-char (point-min))
6387 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
6388 (message "Press key for agenda command%s"
6389 (if restrict-ok ", or [1] to restrict to current file" ""))
6390 (setq c (read-char-exclusive))
6394 (put 'org-agenda-files 'org-restrict (list bfn))
6395 (error "Cannot restrict agenda to current buffer"))
6396 (message "Press key for agenda command%s"
6397 (if restrict-ok " (restricted to current file)" ""))
6398 (setq c (read-char-exclusive))
6400 (require 'calendar) ; FIXME: can we avoid this for some commands?
6401 ;; For example the todo list should not need it (but does...)
6403 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
6404 ((equal c ?a) (call-interactively 'org-agenda-list))
6405 ((equal c ?t) (call-interactively 'org-todo-list))
6406 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
6407 ((equal c ?m) (call-interactively 'org-tags-view))
6408 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
6409 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
6410 (setq type (nth 1 entry) string (nth 2 entry))
6413 (org-tags-view current-prefix-arg string))
6414 ((eq type 'tags-todo)
6415 (org-tags-view '(4) string))
6417 (org-todo-list string))
6418 ((eq type 'tags-tree)
6419 (org-check-for-org-mode)
6420 (org-tags-sparse-tree current-prefix-arg string))
6421 ((eq type 'todo-tree)
6422 (org-check-for-org-mode)
6423 (org-occur (concat "^" outline-regexp "[ \t]*"
6424 (regexp-quote string) "\\>")))
6425 ((eq type 'occur-tree)
6426 (org-check-for-org-mode)
6428 (t (error "Invalid custom agenda command type %s" type))))
6429 (t (error "Invalid key"))))))
6431 (defun org-check-for-org-mode ()
6432 "Make sure current buffer is in org-mode. Error if not."
6433 (or (eq major-mode 'org-mode)
6434 (error "Cannot execute org-mode agenda command on buffer in %s."
6437 (defun org-fit-agenda-window ()
6438 "Fit the window to the buffer size."
6439 (and org-fit-agenda-window
6440 (fboundp 'fit-window-to-buffer)
6441 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
6442 (/ (frame-height) 2))))
6444 (defun org-agenda-files (&optional unrestricted)
6445 "Get the list of agenda files.
6446 Optional UNRESTRICTED means return the full list even if a restriction
6447 is currently in place."
6449 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
6450 ((stringp org-agenda-files) (org-read-agenda-file-list))
6451 ((listp org-agenda-files) org-agenda-files)
6452 (t (error "Invalid value of `org-agenda-files'"))))
6454 (defvar org-window-configuration)
6456 (defun org-edit-agenda-file-list ()
6457 "Edit the list of agenda files.
6458 Depending on setup, this either uses customize to edit the variable
6459 `org-agenda-files', or it visits the file that is holding the list. In the
6460 latter case, the buffer is set up in a way that saving it automatically kills
6461 the buffer and restores the previous window configuration."
6463 (if (stringp org-agenda-files)
6464 (let ((cw (current-window-configuration)))
6465 (find-file org-agenda-files)
6466 (set (make-local-variable 'org-window-configuration) cw)
6467 (org-add-hook 'after-save-hook
6469 (set-window-configuration
6470 (prog1 org-window-configuration
6471 (kill-buffer (current-buffer))))
6472 (org-install-agenda-files-menu)
6473 (message "New agenda file list installed"))
6475 (message (substitute-command-keys
6476 "Edit list and finish with \\[save-buffer]")))
6477 (customize-variable 'org-agenda-files)))
6479 (defun org-store-new-agenda-file-list (list)
6480 "Set new value for the agenda file list and save it correcly."
6481 (if (stringp org-agenda-files)
6482 (let ((f org-agenda-files) b)
6483 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
6485 (insert (mapconcat 'identity list "\n") "\n")))
6486 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
6487 (setq org-agenda-files list)
6488 (customize-save-variable 'org-agenda-files org-agenda-files))))
6490 (defun org-read-agenda-file-list ()
6491 "Read the list of agenda files from a file."
6492 (when (stringp org-agenda-files)
6494 (insert-file-contents org-agenda-files)
6495 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
6497 (defvar org-agenda-markers nil
6498 "List of all currently active markers created by `org-agenda'.")
6499 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
6500 "Creation time of the last agenda marker.")
6502 (defun org-agenda-new-marker (&optional pos)
6503 "Return a new agenda marker.
6504 Org-mode keeps a list of these markers and resets them when they are
6506 (let ((m (copy-marker (or pos (point)))))
6507 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
6508 (push m org-agenda-markers)
6511 (defun org-agenda-maybe-reset-markers (&optional force)
6512 "Reset markers created by `org-agenda'. But only if they are old enough."
6514 (> (- (time-to-seconds (current-time))
6515 org-agenda-last-marker-time)
6517 (while org-agenda-markers
6518 (move-marker (pop org-agenda-markers) nil))))
6520 (defvar org-agenda-new-buffers nil
6521 "Buffers created to visit agenda files.")
6523 (defun org-get-agenda-file-buffer (file)
6524 "Get a buffer visiting FILE. If the buffer needs to be created, add
6525 it to the list of buffers which might be released later."
6526 (let ((buf (find-buffer-visiting file)))
6528 buf ; just return it
6529 ;; Make a new buffer and remember it
6530 (setq buf (find-file-noselect file))
6531 (if buf (push buf org-agenda-new-buffers))
6534 (defun org-release-buffers (blist)
6535 "Release all buffers in list, asking the user for confirmation when needed.
6536 When a buffer is unmodified, it is just killed. When modified, it is saved
6537 \(if the user agrees) and then killed."
6539 (while (setq buf (pop blist))
6540 (setq file (buffer-file-name buf))
6541 (when (and (buffer-modified-p buf)
6543 (y-or-n-p (format "Save file %s? " file)))
6544 (with-current-buffer buf (save-buffer)))
6545 (kill-buffer buf))))
6547 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
6549 (defun org-timeline (&optional include-all keep-modes)
6550 "Show a time-sorted view of the entries in the current org file.
6551 Only entries with a time stamp of today or later will be listed. With
6552 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
6553 under the current date.
6554 If the buffer contains an active region, only check the region for
6558 (org-agenda-maybe-reset-markers 'force)
6559 (org-compile-prefix-format org-timeline-prefix-format)
6561 (dotodo include-all)
6562 (doclosed org-agenda-show-log)
6563 (org-agenda-keep-modes keep-modes)
6564 (entry buffer-file-name)
6565 (org-agenda-files (list buffer-file-name))
6566 (date (calendar-current-date))
6567 (win (selected-window))
6569 (beg (if (org-region-active-p) (region-beginning) (point-min)))
6570 (end (if (org-region-active-p) (region-end) (point-max)))
6571 (day-numbers (org-get-all-dates beg end 'no-ranges
6572 t doclosed ; always include today
6573 org-timeline-show-empty-dates))
6574 (today (time-to-days (current-time)))
6575 (org-respect-restriction t)
6579 (org-prepare-agenda-buffers org-agenda-files)
6580 (setq org-agenda-redo-command
6582 (list 'switch-to-buffer-other-window (current-buffer))
6583 (list 'org-timeline (list 'quote include-all) t)))
6585 ;; Remove past dates from the list of dates.
6586 (setq day-numbers (delq nil (mapcar (lambda(x)
6587 (if (>= x today) x nil))
6589 (switch-to-buffer-other-window
6590 (get-buffer-create org-agenda-buffer-name))
6591 (setq buffer-read-only nil)
6593 (org-agenda-mode) (setq buffer-read-only nil)
6594 (set (make-local-variable 'org-agenda-type) 'timeline)
6595 (if doclosed (push :closed args))
6596 (push :timestamp args)
6597 (if dotodo (push :todo args))
6598 (while (setq d (pop day-numbers))
6599 (if (and (listp d) (eq (car d) :omitted))
6602 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
6603 (put-text-property s (1- (point)) 'face 'org-level-3))
6604 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
6605 (if (and (>= d today)
6610 (insert (make-string 79 ?-) "\n")))
6611 (setq date (calendar-gregorian-from-absolute d))
6613 (setq rtn (and (not emptyp)
6614 (apply 'org-agenda-get-day-entries
6616 (if (or rtn (equal d today) org-timeline-show-empty-dates)
6618 (insert (calendar-day-name date) " "
6619 (number-to-string (extract-calendar-day date)) " "
6620 (calendar-month-name (extract-calendar-month date)) " "
6621 (number-to-string (extract-calendar-year date)) "\n")
6622 (put-text-property s (1- (point)) 'face
6625 (put-text-property s (1- (point)) 'org-today t))
6626 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
6627 (put-text-property s (1- (point)) 'day d)))))
6628 (goto-char (point-min))
6629 (setq buffer-read-only t)
6630 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6632 (when (not org-select-timeline-window)
6637 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
6638 "Produce a weekly view from all files in variable `org-agenda-files'.
6639 The view will be for the current week, but from the overview buffer you
6640 will be able to go to other weeks.
6641 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
6642 also be shown, under the current date.
6643 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
6644 on the days are also shown. See the variable `org-log-done' for how
6646 START-DAY defaults to TODAY, or to the most recent match for the weekday
6647 given in `org-agenda-start-on-weekday'.
6648 NDAYS defaults to `org-agenda-ndays'."
6650 (org-agenda-maybe-reset-markers 'force)
6651 (org-compile-prefix-format org-agenda-prefix-format)
6653 (let* ((org-agenda-start-on-weekday
6654 (if (or (equal ndays 1)
6655 (and (null ndays) (equal 1 org-agenda-ndays)))
6656 nil org-agenda-start-on-weekday))
6657 (org-agenda-keep-modes keep-modes)
6658 (thefiles (org-agenda-files))
6660 (win (selected-window))
6661 (today (time-to-days (current-time)))
6662 (sd (or start-day today))
6663 (start (if (or (null org-agenda-start-on-weekday)
6664 (< org-agenda-ndays 7))
6666 (let* ((nt (calendar-day-of-week
6667 (calendar-gregorian-from-absolute sd)))
6668 (n1 org-agenda-start-on-weekday)
6670 (- sd (+ (if (< d 0) 7 0) d)))))
6671 (day-numbers (list start))
6672 (inhibit-redisplay t)
6673 s e rtn rtnall file date d start-pos end-pos todayp nd)
6674 (org-prepare-agenda-buffers files)
6675 (setq org-agenda-redo-command
6676 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
6677 ;; Make the list of days
6678 (setq ndays (or ndays org-agenda-ndays)
6681 (push (1+ (car day-numbers)) day-numbers)
6682 (setq ndays (1- ndays)))
6683 (setq day-numbers (nreverse day-numbers))
6684 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6686 (delete-other-windows)
6687 (switch-to-buffer-other-window
6688 (get-buffer-create org-agenda-buffer-name))))
6689 (setq buffer-read-only nil)
6691 (org-agenda-mode) (setq buffer-read-only nil)
6692 (set (make-local-variable 'org-agenda-type) 'agenda)
6693 (set (make-local-variable 'starting-day) (car day-numbers))
6694 (set (make-local-variable 'include-all-loc) include-all)
6695 (when (and (or include-all org-agenda-include-all-todo)
6696 (member today day-numbers))
6697 (setq files thefiles
6699 (while (setq file (pop files))
6701 (org-check-agenda-file file)
6702 (setq date (calendar-gregorian-from-absolute today)
6703 rtn (org-agenda-get-day-entries
6705 (setq rtnall (append rtnall rtn))))
6707 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
6708 (add-text-properties (point-min) (1- (point))
6709 (list 'face 'org-level-3))
6710 (insert (org-finalize-agenda-entries rtnall) "\n")))
6711 (while (setq d (pop day-numbers))
6712 (setq date (calendar-gregorian-from-absolute d)
6714 (if (or (setq todayp (= d today))
6715 (and (not start-pos) (= d sd)))
6716 (setq start-pos (point))
6717 (if (and start-pos (not end-pos))
6718 (setq end-pos (point))))
6719 (setq files thefiles
6721 (while (setq file (pop files))
6723 (org-check-agenda-file file)
6724 (if org-agenda-show-log
6725 (setq rtn (org-agenda-get-day-entries
6727 :deadline :scheduled :timestamp :closed))
6728 (setq rtn (org-agenda-get-day-entries
6730 :deadline :scheduled :timestamp)))
6731 (setq rtnall (append rtnall rtn))))
6732 (if org-agenda-include-diary
6734 (require 'diary-lib)
6735 (setq rtn (org-get-entries-from-diary date))
6736 (setq rtnall (append rtnall rtn))))
6737 (if (or rtnall org-agenda-show-all-dates)
6739 (insert (format "%-9s %2d %s %4d\n"
6740 (calendar-day-name date)
6741 (extract-calendar-day date)
6742 (calendar-month-name (extract-calendar-month date))
6743 (extract-calendar-year date)))
6744 (put-text-property s (1- (point)) 'face
6747 (org-finalize-agenda-entries
6748 (org-agenda-add-time-grid-maybe
6751 (put-text-property s (1- (point)) 'day d))))
6752 (goto-char (point-min))
6753 (setq buffer-read-only t)
6754 (org-fit-agenda-window)
6755 (unless (and (pos-visible-in-window-p (point-min))
6756 (pos-visible-in-window-p (point-max)))
6757 (goto-char (1- (point-max)))
6759 (if (not (pos-visible-in-window-p (or start-pos 1)))
6761 (goto-char (or start-pos 1))
6763 (goto-char (or start-pos 1))
6764 (if (not org-select-agenda-window) (select-window win))
6767 (defvar org-select-this-todo-keyword nil)
6770 (defun org-todo-list (arg &optional keep-modes)
6771 "Show all TODO entries from all agenda file in a single list.
6772 The prefix arg can be used to select a specific TODO keyword and limit
6773 the list to these. When using \\[universal-argument], you will be prompted
6774 for a keyword. A numeric prefix directly selects the Nth keyword in
6775 `org-todo-keywords'."
6777 (org-agenda-maybe-reset-markers 'force)
6778 (org-compile-prefix-format org-agenda-prefix-format)
6779 (let* ((org-agenda-keep-modes keep-modes)
6780 (today (time-to-days (current-time)))
6781 (date (calendar-gregorian-from-absolute today))
6782 (win (selected-window))
6783 (kwds org-todo-keywords)
6784 (completion-ignore-case t)
6785 (org-select-this-todo-keyword
6786 (if (stringp arg) arg
6787 (and arg (integerp arg) (> arg 0)
6788 (nth (1- arg) org-todo-keywords))))
6789 rtn rtnall files file pos)
6790 (when (equal arg '(4))
6791 (setq org-select-this-todo-keyword
6792 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
6794 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
6795 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6797 (delete-other-windows)
6798 (switch-to-buffer-other-window
6799 (get-buffer-create org-agenda-buffer-name))))
6800 (setq buffer-read-only nil)
6802 (org-agenda-mode) (setq buffer-read-only nil)
6803 (set (make-local-variable 'org-agenda-type) 'todo)
6804 (set (make-local-variable 'last-arg) arg)
6805 (set (make-local-variable 'org-todo-keywords) kwds)
6806 (set (make-local-variable 'org-agenda-redo-command)
6807 '(org-todo-list (or current-prefix-arg last-arg) t))
6808 (setq files (org-agenda-files)
6810 (org-prepare-agenda-buffers files)
6811 (while (setq file (pop files))
6813 (org-check-agenda-file file)
6814 (setq rtn (org-agenda-get-day-entries file date :todo))
6815 (setq rtnall (append rtnall rtn))))
6816 (insert "Global list of TODO items of type: ")
6817 (add-text-properties (point-min) (1- (point))
6818 (list 'face 'org-level-3))
6820 (insert (or org-select-this-todo-keyword "ALL") "\n")
6821 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6824 "Available with `N r': (0)ALL "
6826 (mapconcat (lambda (x)
6827 (format "(%d)%s" (setq n (1+ n)) x))
6828 org-todo-keywords " "))
6830 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
6832 (insert (org-finalize-agenda-entries rtnall) "\n"))
6833 (goto-char (point-min))
6834 (setq buffer-read-only t)
6835 (org-fit-agenda-window)
6836 (if (not org-select-agenda-window) (select-window win))))
6838 (defun org-check-agenda-file (file)
6839 "Make sure FILE exists. If not, ask user what to do."
6840 (when (not (file-exists-p file))
6841 (message "non-existent file %s. [R]emove from list or [A]bort?"
6842 (abbreviate-file-name file))
6843 (let ((r (downcase (read-char-exclusive))))
6846 (org-remove-file file)
6847 (throw 'nextfile t))
6848 (t (error "Abort"))))))
6850 (defun org-agenda-check-type (error &rest types)
6851 "Check if agenda buffer is of allowed type.
6852 If ERROR is non-nil, throw an error, otherwise just return nil."
6853 (if (memq org-agenda-type types)
6856 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
6859 (defun org-agenda-quit ()
6860 "Exit agenda by removing the window or the buffer."
6862 (let ((buf (current-buffer)))
6863 (if (not (one-window-p)) (delete-window))
6865 (org-agenda-maybe-reset-markers 'force)))
6867 (defun org-agenda-exit ()
6868 "Exit agenda by removing the window or the buffer.
6869 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
6870 Org-mode buffers visited directly by the user will not be touched."
6872 (org-release-buffers org-agenda-new-buffers)
6873 (setq org-agenda-new-buffers nil)
6876 (defun org-agenda-redo ()
6878 When this is the global TODO list, a prefix argument will be interpreted."
6880 (message "Rebuilding agenda buffer...")
6881 (eval org-agenda-redo-command)
6882 (message "Rebuilding agenda buffer...done"))
6884 (defun org-agenda-goto-today ()
6887 (org-agenda-check-type t 'timeline 'agenda)
6888 (if (boundp 'starting-day)
6889 (let ((cmd (car org-agenda-redo-command))
6890 (iall (nth 1 org-agenda-redo-command))
6891 (nday (nth 3 org-agenda-redo-command))
6892 (keep (nth 4 org-agenda-redo-command)))
6893 (eval (list cmd iall nil nday keep)))
6894 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6897 (defun org-agenda-later (arg)
6898 "Go forward in time by `org-agenda-ndays' days.
6899 With prefix ARG, go forward that many times `org-agenda-ndays'."
6901 (org-agenda-check-type t 'agenda)
6902 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6903 (+ starting-day (* arg org-agenda-ndays)) nil t))
6905 (defun org-agenda-earlier (arg)
6906 "Go back in time by `org-agenda-ndays' days.
6907 With prefix ARG, go back that many times `org-agenda-ndays'."
6909 (org-agenda-check-type t 'agenda)
6910 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6911 (- starting-day (* arg org-agenda-ndays)) nil t))
6913 (defun org-agenda-week-view ()
6914 "Switch to weekly view for agenda."
6916 (org-agenda-check-type t 'agenda)
6917 (setq org-agenda-ndays 7)
6918 (org-agenda-list include-all-loc
6919 (or (get-text-property (point) 'day)
6922 (org-agenda-set-mode-name)
6923 (message "Switched to week view"))
6925 (defun org-agenda-day-view ()
6926 "Switch to daily view for agenda."
6928 (org-agenda-check-type t 'agenda)
6929 (setq org-agenda-ndays 1)
6930 (org-agenda-list include-all-loc
6931 (or (get-text-property (point) 'day)
6934 (org-agenda-set-mode-name)
6935 (message "Switched to day view"))
6937 (defun org-agenda-next-date-line (&optional arg)
6938 "Jump to the next line indicating a date in agenda buffer."
6940 (org-agenda-check-type t 'agenda 'timeline)
6941 (beginning-of-line 1)
6942 (if (looking-at "^\\S-") (forward-char 1))
6943 (if (not (re-search-forward "^\\S-" nil t arg))
6946 (error "No next date after this line in this buffer")))
6947 (goto-char (match-beginning 0)))
6949 (defun org-agenda-previous-date-line (&optional arg)
6950 "Jump to the previous line indicating a date in agenda buffer."
6952 (org-agenda-check-type t 'agenda 'timeline)
6953 (beginning-of-line 1)
6954 (if (not (re-search-backward "^\\S-" nil t arg))
6955 (error "No previous date before this line in this buffer")))
6957 ;; Initialize the highlight
6958 (defvar org-hl (org-make-overlay 1 1))
6959 (org-overlay-put org-hl 'face 'highlight)
6961 (defun org-highlight (begin end &optional buffer)
6962 "Highlight a region with overlay."
6963 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
6964 org-hl begin end (or buffer (current-buffer))))
6966 (defun org-unhighlight ()
6967 "Detach overlay INDEX."
6968 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
6971 (defun org-agenda-follow-mode ()
6972 "Toggle follow mode in an agenda buffer."
6974 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
6975 (org-agenda-set-mode-name)
6976 (message "Follow mode is %s"
6977 (if org-agenda-follow-mode "on" "off")))
6979 (defun org-agenda-log-mode ()
6980 "Toggle log mode in an agenda buffer."
6982 (org-agenda-check-type t 'agenda 'timeline)
6983 (setq org-agenda-show-log (not org-agenda-show-log))
6984 (org-agenda-set-mode-name)
6986 (message "Log mode is %s"
6987 (if org-agenda-show-log "on" "off")))
6989 (defun org-agenda-toggle-diary ()
6990 "Toggle diary inclusion in an agenda buffer."
6992 (org-agenda-check-type t 'agenda)
6993 (setq org-agenda-include-diary (not org-agenda-include-diary))
6995 (org-agenda-set-mode-name)
6996 (message "Diary inclusion turned %s"
6997 (if org-agenda-include-diary "on" "off")))
6999 (defun org-agenda-toggle-time-grid ()
7000 "Toggle time grid in an agenda buffer."
7002 (org-agenda-check-type t 'agenda)
7003 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
7005 (org-agenda-set-mode-name)
7006 (message "Time-grid turned %s"
7007 (if org-agenda-use-time-grid "on" "off")))
7009 (defun org-agenda-set-mode-name ()
7010 "Set the mode name to indicate all the small mode settings."
7012 (concat "Org-Agenda"
7013 (if (equal org-agenda-ndays 1) " Day" "")
7014 (if (equal org-agenda-ndays 7) " Week" "")
7015 (if org-agenda-follow-mode " Follow" "")
7016 (if org-agenda-include-diary " Diary" "")
7017 (if org-agenda-use-time-grid " Grid" "")
7018 (if org-agenda-show-log " Log" "")))
7019 (force-mode-line-update))
7021 (defun org-agenda-post-command-hook ()
7022 (and (eolp) (not (bolp)) (backward-char 1))
7023 (if (and org-agenda-follow-mode
7024 (get-text-property (point) 'org-marker))
7027 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
7029 (defun org-get-entries-from-diary (date)
7030 "Get the (Emacs Calendar) diary entries for DATE."
7031 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
7032 (diary-display-hook '(fancy-diary-display))
7033 (list-diary-entries-hook
7034 (cons 'org-diary-default-entry list-diary-entries-hook))
7035 (diary-file-name-prefix-function nil) ; turn this feature off
7036 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7038 (org-disable-agenda-to-diary t))
7040 (save-window-excursion
7041 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7042 (if (not (get-buffer fancy-diary-buffer))
7044 (with-current-buffer fancy-diary-buffer
7045 (setq buffer-read-only nil)
7046 (if (= (point-max) 1)
7049 ;; Omit the date and other unnecessary stuff
7050 (org-agenda-cleanup-fancy-diary)
7051 ;; Add prefix to each line and extend the text properties
7052 (if (= (point-max) 1)
7054 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7055 (set-buffer-modified-p nil)
7056 (kill-buffer fancy-diary-buffer)))
7058 (setq entries (org-split-string entries "\n"))
7062 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7063 ;; Extend the text properties to the beginning of the line
7064 (org-add-props x (text-properties-at (1- (length x)) x)))
7067 (defun org-agenda-cleanup-fancy-diary ()
7068 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7069 This gets rid of the date, the underline under the date, and
7070 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7071 date. It also removes lines that contain only whitespace."
7072 (goto-char (point-min))
7073 (if (looking-at ".*?:[ \t]*")
7076 (re-search-forward "\n=+$" nil t)
7078 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7079 (re-search-forward "\n=+$" nil t)
7080 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7081 (goto-char (point-min))
7082 (while (re-search-forward "^ +\n" nil t)
7084 (goto-char (point-min))
7085 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7086 (replace-match "")))
7088 ;; Make sure entries from the diary have the right text properties.
7089 (eval-after-load "diary-lib"
7090 '(if (boundp 'diary-modify-entry-list-string-function)
7091 ;; We can rely on the hook, nothing to do
7093 ;; Hook not avaiable, must use advice to make this work
7094 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7095 "Make the position visible."
7096 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7099 (setq string (org-modify-diary-entry-string string))))))
7101 (defun org-modify-diary-entry-string (string)
7102 "Add text properties to string, allowing org-mode to act on it."
7103 (org-add-props string nil
7104 'mouse-face 'highlight
7105 'keymap org-agenda-keymap
7106 'help-echo (format "mouse-2 or RET jump to diary file %s"
7107 (abbreviate-file-name buffer-file-name))
7108 'org-agenda-diary-link t
7109 'org-marker (org-agenda-new-marker (point-at-bol))))
7111 (defun org-diary-default-entry ()
7112 "Add a dummy entry to the diary.
7113 Needed to avoid empty dates which mess up holiday display."
7114 ;; Catch the error if dealing with the new add-to-diary-alist
7115 (when org-disable-agenda-to-diary
7117 (add-to-diary-list original-date "Org-mode dummy" "")
7119 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7121 (defun org-cycle-agenda-files ()
7122 "Cycle through the files in `org-agenda-files'.
7123 If the current buffer visits an agenda file, find the next one in the list.
7124 If the current buffer does not, find the first agenda file."
7126 (let* ((fs (org-agenda-files t))
7127 (files (append fs (list (car fs))))
7128 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7130 (unless files (error "No agenda files"))
7132 (while (setq file (pop files))
7133 (if (equal (file-truename file) tcf)
7135 (find-file (car files))
7137 (find-file (car fs)))))
7139 (defun org-agenda-file-to-end ()
7140 "Move/add the current file to the end of the agenda file list.
7141 If the file is not present in the list, it is appended to the list. If it is
7142 present, it is moved there."
7144 (org-agenda-file-to-front 'to-end))
7146 (defun org-agenda-file-to-front (&optional to-end)
7147 "Move/add the current file to the top of the agenda file list.
7148 If the file is not present in the list, it is added to the front. If it is
7149 present, it is moved there. With optional argument TO-END, add/move to the
7152 (let ((file-alist (mapcar (lambda (x)
7153 (cons (file-truename x) x))
7154 (org-agenda-files t)))
7155 (ctf (file-truename buffer-file-name))
7157 (setq x (assoc ctf file-alist) had x)
7159 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7161 (setq file-alist (append (delq x file-alist) (list x)))
7162 (setq file-alist (cons x (delq x file-alist))))
7163 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7164 (org-install-agenda-files-menu)
7165 (message "File %s to %s of agenda file list"
7166 (if had "moved" "added") (if to-end "end" "front"))))
7168 (defun org-remove-file (&optional file)
7169 "Remove current file from the list of files in variable `org-agenda-files'.
7170 These are the files which are being checked for agenda entries.
7171 Optional argument FILE means, use this file instead of the current."
7173 (let* ((file (or file buffer-file-name))
7174 (true-file (file-truename file))
7175 (afile (abbreviate-file-name file))
7176 (files (delq nil (mapcar
7178 (if (equal true-file
7181 (org-agenda-files t)))))
7182 (if (not (= (length files) (length (org-agenda-files t))))
7184 (org-store-new-agenda-file-list files)
7185 (org-install-agenda-files-menu)
7186 (message "Removed file: %s" afile))
7187 (message "File was not in list: %s" afile))))
7189 (defun org-file-menu-entry (file)
7190 (vector file (list 'find-file file) t))
7192 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7193 "Return a list of all relevant day numbers from BEG to END buffer positions.
7194 If NO-RANGES is non-nil, include only the start and end dates of a range,
7195 not every single day in the range. If FORCE-TODAY is non-nil, make
7196 sure that TODAY is included in the list. If INACTIVE is non-nil, also
7197 inactive time stamps (those in square brackets) are included.
7198 When EMPTY is non-nil, also include days without any entries."
7199 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
7200 dates dates1 date day day1 day2 ts1 ts2)
7202 (setq dates (list (time-to-days (current-time)))))
7205 (while (re-search-forward re end t)
7206 (setq day (time-to-days (org-time-string-to-time
7207 (substring (match-string 1) 0 10))))
7208 (or (memq day dates) (push day dates)))
7211 (while (re-search-forward org-tr-regexp end t)
7212 (setq ts1 (substring (match-string 1) 0 10)
7213 ts2 (substring (match-string 2) 0 10)
7214 day1 (time-to-days (org-time-string-to-time ts1))
7215 day2 (time-to-days (org-time-string-to-time ts2)))
7216 (while (< (setq day1 (1+ day1)) day2)
7217 (or (memq day1 dates) (push day1 dates)))))
7218 (setq dates (sort dates '<))
7220 (while (setq day (pop dates))
7221 (setq day2 (car dates))
7223 (when (and day2 empty)
7224 (if (or (eq empty t)
7225 (and (numberp empty) (<= (- day2 day) empty)))
7226 (while (< (setq day (1+ day)) day2)
7227 (push (list day) dates1))
7228 (push (cons :omitted (- day2 day)) dates1))))
7229 (setq dates (nreverse dates1)))
7233 (defun org-diary (&rest args)
7234 "Return diary information from org-files.
7235 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
7236 It accesses org files and extracts information from those files to be
7237 listed in the diary. The function accepts arguments specifying what
7238 items should be listed. The following arguments are allowed:
7240 :timestamp List the headlines of items containing a date stamp or
7241 date range matching the selected date. Deadlines will
7242 also be listed, on the expiration day.
7244 :deadline List any deadlines past due, or due within
7245 `org-deadline-warning-days'. The listing occurs only
7246 in the diary for *today*, not at any other date. If
7247 an entry is marked DONE, it is no longer listed.
7249 :scheduled List all items which are scheduled for the given date.
7250 The diary for *today* also contains items which were
7251 scheduled earlier and are not yet marked DONE.
7253 :todo List all TODO items from the org-file. This may be a
7254 long list - so this is not turned on by default.
7255 Like deadlines, these entries only show up in the
7256 diary for *today*, not at any other date.
7258 The call in the diary file should look like this:
7260 &%%(org-diary) ~/path/to/some/orgfile.org
7262 Use a separate line for each org file to check. Or, if you omit the file name,
7263 all files listed in `org-agenda-files' will be checked automatically:
7267 If you don't give any arguments (as in the example above), the default
7268 arguments (:deadline :scheduled :timestamp) are used. So the example above may
7271 &%%(org-diary :deadline :timestamp :scheduled)
7273 The function expects the lisp variables `entry' and `date' to be provided
7274 by the caller, because this is how the calendar works. Don't use this
7275 function from a program - use `org-agenda-get-day-entries' instead."
7276 (org-agenda-maybe-reset-markers)
7277 (org-compile-prefix-format org-agenda-prefix-format)
7278 (setq args (or args '(:deadline :scheduled :timestamp)))
7279 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
7281 (org-agenda-files t)))
7283 ;; If this is called during org-agenda, don't return any entries to
7284 ;; the calendar. Org Agenda will list these entries itself.
7285 (if org-disable-agenda-to-diary (setq files nil))
7286 (while (setq file (pop files))
7287 (setq rtn (apply 'org-agenda-get-day-entries file date args))
7288 (setq results (append results rtn)))
7290 (concat (org-finalize-agenda-entries results) "\n"))))
7291 (defvar org-category-table nil)
7292 (defun org-get-category-table ()
7293 "Get the table of categories and positions in current buffer."
7296 (goto-char (point-min))
7297 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
7298 (push (cons (point) (org-trim (match-string 2))) tbl)))
7300 (defun org-get-category (&optional pos)
7301 "Get the category applying to position POS."
7302 (if (not org-category-table)
7304 ((null org-category)
7306 (if buffer-file-name
7307 (file-name-sans-extension
7308 (file-name-nondirectory buffer-file-name))
7310 ((symbolp org-category) (symbol-name org-category))
7312 (let ((tbl org-category-table)
7313 (pos (or pos (point))))
7314 (while (and tbl (> (caar tbl) pos))
7316 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
7317 org-category-table))))))
7319 (defun org-agenda-get-day-entries (file date &rest args)
7320 "Does the work for `org-diary' and `org-agenda'.
7321 FILE is the path to a file to be checked for entries. DATE is date like
7322 the one returned by `calendar-current-date'. ARGS are symbols indicating
7323 which kind of entries should be extracted. For details about these, see
7324 the documentation of `org-diary'."
7325 (setq args (or args '(:deadline :scheduled :timestamp)))
7326 (let* ((org-startup-with-deadline-check nil)
7327 (org-startup-folded nil)
7328 (org-startup-align-all-tables nil)
7329 (buffer (if (file-exists-p file)
7330 (org-get-agenda-file-buffer file)
7331 (error "No such file %s" file)))
7334 ;; If file does not exist, make sure an error message ends up in diary
7335 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7336 (with-current-buffer buffer
7337 (unless (eq major-mode 'org-mode)
7338 (error "Agenda file %s is not in `org-mode'" file))
7339 (setq org-category-table (org-get-category-table))
7340 (let ((case-fold-search nil))
7343 (if org-respect-restriction
7344 (if (org-region-active-p)
7345 ;; Respect a region to restrict search
7346 (narrow-to-region (region-beginning) (region-end)))
7347 ;; If we work for the calendar or many files,
7348 ;; get rid of any restriction
7350 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
7351 (while (setq arg (pop args))
7353 ((and (eq arg :todo)
7354 (equal date (calendar-current-date)))
7355 (setq rtn (org-agenda-get-todos))
7356 (setq results (append results rtn)))
7357 ((eq arg :timestamp)
7358 (setq rtn (org-agenda-get-blocks))
7359 (setq results (append results rtn))
7360 (setq rtn (org-agenda-get-timestamps))
7361 (setq results (append results rtn)))
7362 ((eq arg :scheduled)
7363 (setq rtn (org-agenda-get-scheduled))
7364 (setq results (append results rtn)))
7366 (setq rtn (org-agenda-get-closed))
7367 (setq results (append results rtn)))
7368 ((and (eq arg :deadline)
7369 (equal date (calendar-current-date)))
7370 (setq rtn (org-agenda-get-deadlines))
7371 (setq results (append results rtn))))))))
7374 (defun org-entry-is-done-p ()
7375 "Is the current entry marked DONE?"
7377 (and (re-search-backward "[\r\n]\\*" nil t)
7378 (looking-at org-nl-done-regexp))))
7380 (defun org-at-date-range-p ()
7381 "Is the cursor inside a date range?"
7385 (let ((pos (point)))
7386 (skip-chars-backward "^<\r\n")
7387 (skip-chars-backward "<")
7388 (and (looking-at org-tr-regexp)
7389 (>= (match-end 0) pos)
7391 (skip-chars-backward "^<\r\n")
7392 (skip-chars-backward "<")
7393 (and (looking-at org-tr-regexp)
7394 (>= (match-end 0) pos)
7398 (defun org-agenda-get-todos ()
7399 "Return the TODO information for agenda display."
7400 (let* ((props (list 'face nil
7401 'done-face 'org-done
7402 'org-not-done-regexp org-not-done-regexp
7403 'mouse-face 'highlight
7404 'keymap org-agenda-keymap
7406 (format "mouse-2 or RET jump to org file %s"
7407 (abbreviate-file-name buffer-file-name))))
7408 (regexp (concat "[\n\r]\\*+ *\\("
7409 (if org-select-this-todo-keyword
7410 (concat "\\<\\(" org-select-this-todo-keyword
7412 org-not-done-regexp)
7414 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
7415 marker priority category tags
7417 (goto-char (point-min))
7418 (while (re-search-forward regexp nil t)
7420 (and org-agenda-todo-ignore-scheduled
7421 (looking-at sched-re)
7424 (goto-char (match-beginning 1))
7425 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
7426 category (org-get-category)
7427 tags (org-get-tags-at (point))
7428 txt (org-format-agenda-item "" (match-string 1) category tags)
7430 (+ (org-get-priority txt)
7431 (if org-todo-kwd-priority-p
7432 (- org-todo-kwd-max-priority -2
7434 (member (match-string 2) org-todo-keywords)))
7436 (org-add-props txt props
7437 'org-marker marker 'org-hd-marker marker
7438 'priority priority 'category category)
7440 (if org-agenda-todo-list-sublevels
7441 (goto-char (match-end 1))
7442 (org-end-of-subtree 'invisible))))
7445 (defconst org-agenda-no-heading-message
7446 "No heading for this item in buffer or region.")
7448 (defun org-agenda-get-timestamps ()
7449 "Return the date stamp information for agenda display."
7450 (let* ((props (list 'face nil
7451 'org-not-done-regexp org-not-done-regexp
7452 'mouse-face 'highlight
7453 'keymap org-agenda-keymap
7455 (format "mouse-2 or RET jump to org file %s"
7456 (abbreviate-file-name buffer-file-name))))
7457 (regexp (regexp-quote
7460 (car org-time-stamp-formats)
7461 (apply 'encode-time ; DATE bound by calendar
7462 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7464 marker hdmarker deadlinep scheduledp donep tmp priority category
7465 ee txt timestr tags)
7466 (goto-char (point-min))
7467 (while (re-search-forward regexp nil t)
7469 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
7471 (setq marker (org-agenda-new-marker (match-beginning 0))
7472 category (org-get-category (match-beginning 0))
7473 tmp (buffer-substring (max (point-min)
7474 (- (match-beginning 0)
7475 org-ds-keyword-length))
7476 (match-beginning 0))
7477 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7478 deadlinep (string-match org-deadline-regexp tmp)
7479 scheduledp (string-match org-scheduled-regexp tmp)
7480 donep (org-entry-is-done-p))
7481 (if (string-match ">" timestr)
7482 ;; substring should only run to end of time stamp
7483 (setq timestr (substring timestr 0 (match-end 0))))
7485 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7487 (goto-char (match-end 1))
7488 (setq hdmarker (org-agenda-new-marker)
7489 tags (org-get-tags-at))
7490 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7491 (setq txt (org-format-agenda-item
7493 (if deadlinep "Deadline: " "")
7494 (if scheduledp "Scheduled: " ""))
7495 (match-string 1) category tags timestr)))
7496 (setq txt org-agenda-no-heading-message))
7497 (setq priority (org-get-priority txt))
7498 (org-add-props txt props
7499 'org-marker marker 'org-hd-marker hdmarker)
7501 (org-add-props txt nil
7502 'face (if donep 'org-done 'org-warning)
7503 'undone-face 'org-warning 'done-face 'org-done
7504 'category category 'priority (+ 100 priority))
7506 (org-add-props txt nil
7507 'face 'org-scheduled-today
7508 'undone-face 'org-scheduled-today 'done-face 'org-done
7509 'category category 'priority (+ 99 priority))
7510 (org-add-props txt nil 'priority priority 'category category)))
7512 (outline-next-heading)))
7515 (defun org-agenda-get-closed ()
7516 "Return the logged TODO entries for agenda display."
7517 (let* ((props (list 'mouse-face 'highlight
7518 'org-not-done-regexp org-not-done-regexp
7519 'keymap org-agenda-keymap
7521 (format "mouse-2 or RET jump to org file %s"
7522 (abbreviate-file-name buffer-file-name))))
7524 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
7528 (car org-time-stamp-formats)
7529 (apply 'encode-time ; DATE bound by calendar
7530 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7532 marker hdmarker priority category tags closedp
7534 (goto-char (point-min))
7535 (while (re-search-forward regexp nil t)
7538 (setq marker (org-agenda-new-marker (match-beginning 0))
7539 closedp (equal (match-string 1) org-closed-string)
7540 category (org-get-category (match-beginning 0))
7541 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7542 ;; donep (org-entry-is-done-p)
7544 (if (string-match "\\]" timestr)
7545 ;; substring should only run to end of time stamp
7546 (setq timestr (substring timestr 0 (match-end 0))))
7548 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7550 (goto-char (match-end 1))
7551 (setq hdmarker (org-agenda-new-marker)
7552 tags (org-get-tags-at))
7553 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7554 (setq txt (org-format-agenda-item
7555 (if closedp "Closed: " "Clocked: ")
7556 (match-string 1) category tags timestr)))
7557 (setq txt org-agenda-no-heading-message))
7558 (setq priority 100000)
7559 (org-add-props txt props
7560 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
7561 'priority priority 'category category
7562 'undone-face 'org-warning 'done-face 'org-done)
7564 (outline-next-heading)))
7567 (defun org-agenda-get-deadlines ()
7568 "Return the deadline information for agenda display."
7569 (let* ((wdays org-deadline-warning-days)
7570 (props (list 'mouse-face 'highlight
7571 'org-not-done-regexp org-not-done-regexp
7572 'keymap org-agenda-keymap
7574 (format "mouse-2 or RET jump to org file %s"
7575 (abbreviate-file-name buffer-file-name))))
7576 (regexp org-deadline-time-regexp)
7577 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7578 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7579 d2 diff pos pos1 category tags
7581 (goto-char (point-min))
7582 (while (re-search-forward regexp nil t)
7585 (setq pos (1- (match-beginning 1))
7587 (org-time-string-to-time (match-string 1)))
7589 ;; When to show a deadline in the calendar:
7590 ;; If the expiration is within wdays warning time.
7591 ;; Past-due deadlines are only shown on the current date
7592 (if (and (< diff wdays) todayp (not (= diff 0)))
7594 (setq category (org-get-category))
7595 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7597 (goto-char (match-end 0))
7598 (setq pos1 (match-end 1))
7599 (setq tags (org-get-tags-at pos1))
7600 (setq head (buffer-substring-no-properties
7602 (progn (skip-chars-forward "^\r\n")
7604 (if (string-match org-looking-at-done-regexp head)
7606 (setq txt (org-format-agenda-item
7607 (format "In %3d d.: " diff) head category tags))))
7608 (setq txt org-agenda-no-heading-message))
7610 (setq face (cond ((<= diff 0) 'org-warning)
7611 ((<= diff 5) 'org-upcoming-deadline)
7613 (org-add-props txt props
7614 'org-marker (org-agenda-new-marker pos)
7615 'org-hd-marker (org-agenda-new-marker pos1)
7616 'priority (+ (- 10 diff) (org-get-priority txt))
7618 'face face 'undone-face face 'done-face 'org-done)
7622 (defun org-agenda-get-scheduled ()
7623 "Return the scheduled information for agenda display."
7624 (let* ((props (list 'face 'org-scheduled-previously
7625 'org-not-done-regexp org-not-done-regexp
7626 'undone-face 'org-scheduled-previously
7627 'done-face 'org-done
7628 'mouse-face 'highlight
7629 'keymap org-agenda-keymap
7631 (format "mouse-2 or RET jump to org file %s"
7632 (abbreviate-file-name buffer-file-name))))
7633 (regexp org-scheduled-time-regexp)
7634 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7635 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7636 d2 diff pos pos1 category tags
7638 (goto-char (point-min))
7639 (while (re-search-forward regexp nil t)
7642 (setq pos (1- (match-beginning 1))
7644 (org-time-string-to-time (match-string 1)))
7646 ;; When to show a scheduled item in the calendar:
7647 ;; If it is on or past the date.
7648 (if (and (< diff 0) todayp)
7650 (setq category (org-get-category))
7651 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7653 (goto-char (match-end 0))
7654 (setq pos1 (match-end 1))
7655 (setq tags (org-get-tags-at))
7656 (setq head (buffer-substring-no-properties
7658 (progn (skip-chars-forward "^\r\n") (point))))
7659 (if (string-match org-looking-at-done-regexp head)
7661 (setq txt (org-format-agenda-item
7662 (format "Sched.%2dx: " (- 1 diff)) head
7664 (setq txt org-agenda-no-heading-message))
7666 (org-add-props txt props
7667 'org-marker (org-agenda-new-marker pos)
7668 'org-hd-marker (org-agenda-new-marker pos1)
7669 'priority (+ (- 5 diff) (org-get-priority txt))
7674 (defun org-agenda-get-blocks ()
7675 "Return the date-range information for agenda display."
7676 (let* ((props (list 'face nil
7677 'org-not-done-regexp org-not-done-regexp
7678 'mouse-face 'highlight
7679 'keymap org-agenda-keymap
7681 (format "mouse-2 or RET jump to org file %s"
7682 (abbreviate-file-name buffer-file-name))))
7683 (regexp org-tr-regexp)
7684 (d0 (calendar-absolute-from-gregorian date))
7685 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
7686 (goto-char (point-min))
7687 (while (re-search-forward regexp nil t)
7690 (setq timestr (match-string 0)
7693 d1 (time-to-days (org-time-string-to-time s1))
7694 d2 (time-to-days (org-time-string-to-time s2)))
7695 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
7696 ;; Only allow days between the limits, because the normal
7697 ;; date stamps will catch the limits.
7699 (setq marker (org-agenda-new-marker (point)))
7700 (setq category (org-get-category))
7701 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7703 (setq hdmarker (org-agenda-new-marker (match-end 1)))
7704 (goto-char (match-end 1))
7705 (setq tags (org-get-tags-at))
7706 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7707 (setq txt (org-format-agenda-item
7708 (format (if (= d1 d2) "" "(%d/%d): ")
7709 (1+ (- d0 d1)) (1+ (- d2 d1)))
7710 (match-string 1) category tags
7711 (if (= d0 d1) timestr))))
7712 (setq txt org-agenda-no-heading-message))
7713 (org-add-props txt props
7714 'org-marker marker 'org-hd-marker hdmarker
7715 'priority (org-get-priority txt) 'category category)
7717 (outline-next-heading)))
7718 ;; Sort the entries by expiration date.
7721 (defconst org-plain-time-of-day-regexp
7724 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7727 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7729 "Regular expression to match a plain time or time range.
7730 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
7731 groups carry important information:
7733 1 the first time, range or not
7734 8 the second time, if it is a range.")
7736 (defconst org-stamp-time-of-day-regexp
7738 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
7739 "\\([012][0-9]:[0-5][0-9]\\)>"
7741 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
7742 "Regular expression to match a timestamp time or time range.
7743 After a match, the following groups carry important information:
7745 1 date plus weekday, for backreferencing to make sure both times on same day
7746 2 the first time, range or not
7747 4 the second time, if it is a range.")
7749 (defvar org-prefix-has-time nil
7750 "A flag, set by `org-compile-prefix-format'.
7751 The flag is set if the currently compiled format contains a `%t'.")
7752 (defvar org-prefix-has-tag nil
7753 "A flag, set by `org-compile-prefix-format'.
7754 The flag is set if the currently compiled format contains a `%T'.")
7756 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
7757 "Format TXT to be inserted into the agenda buffer.
7758 In particular, it adds the prefix and corresponding text properties. EXTRA
7759 must be a string and replaces the `%s' specifier in the prefix format.
7760 CATEGORY (string, symbol or nil) may be used to overrule the default
7761 category taken from local variable or file name. It will replace the `%c'
7762 specifier in the format. DOTIME, when non-nil, indicates that a
7763 time-of-day should be extracted from TXT for sorting of this entry, and for
7764 the `%t' specifier in the format. When DOTIME is a string, this string is
7765 searched for a time before TXT is. NOPREFIX is a flag and indicates that
7766 only the correctly processes TXT should be returned - this is used by
7767 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
7769 ;; Diary entries sometimes have extra whitespace at the beginning
7770 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
7771 (let* ((category (or category
7773 (if buffer-file-name
7774 (file-name-sans-extension
7775 (file-name-nondirectory buffer-file-name))
7777 (tag (if tags (nth (1- (length tags)) tags) ""))
7778 time ;; needed for the eval of the prefix format
7779 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
7780 (time-of-day (and dotime (org-get-time-of-day ts)))
7781 stamp plain s0 s1 s2 rtn)
7782 (when (and dotime time-of-day org-prefix-has-time)
7783 ;; Extract starting and ending time and move them to prefix
7784 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
7785 (setq plain (string-match org-plain-time-of-day-regexp ts)))
7786 (setq s0 (match-string 0 ts)
7787 s1 (match-string (if plain 1 2) ts)
7788 s2 (match-string (if plain 8 4) ts))
7790 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
7791 ;; them, we might want to remove them there to avoid duplication.
7792 ;; The user can turn this off with a variable.
7793 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
7794 (string-match (concat (regexp-quote s0) " *") txt)
7795 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
7796 (= (match-beginning 0) 0)
7798 (setq txt (replace-match "" nil nil txt))))
7799 ;; Normalize the time(s) to 24 hour
7800 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
7801 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
7803 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
7804 ;; Tags are in the string
7805 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
7806 (and org-agenda-remove-tags-when-in-prefix
7807 org-prefix-has-tag))
7808 (setq txt (replace-match "" t t txt))
7809 (setq txt (replace-match
7810 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
7811 (match-string 2 txt))
7814 ;; Create the final string
7817 ;; Prepare the variables needed in the eval of the compiled format
7818 (setq time (cond (s2 (concat s1 "-" s2))
7819 (s1 (concat s1 "......"))
7822 category (if (symbolp category) (symbol-name category) category))
7823 ;; Evaluate the compiled format
7824 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
7826 ;; And finally add the text properties
7827 (org-add-props rtn nil
7828 'category (downcase category) 'tags tags
7829 'prefix-length (- (length rtn) (length txt))
7830 'time-of-day time-of-day
7833 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
7835 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
7836 ((and todayp (member 'today (car org-agenda-time-grid))))
7837 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
7838 ((member 'weekly (car org-agenda-time-grid)))
7839 (t (throw 'exit list)))
7840 (let* ((have (delq nil (mapcar
7841 (lambda (x) (get-text-property 1 'time-of-day x))
7843 (string (nth 1 org-agenda-time-grid))
7844 (gridtimes (nth 2 org-agenda-time-grid))
7845 (req (car org-agenda-time-grid))
7846 (remove (member 'remove-match req))
7848 (if (and (member 'require-timed req) (not have))
7849 ;; don't show empty grid
7851 (while (setq time (pop gridtimes))
7852 (unless (and remove (member time have))
7853 (setq time (int-to-string time))
7854 (push (org-format-agenda-item
7856 (concat (substring time 0 -2) ":" (substring time -2)))
7859 1 (length (car new)) 'face 'org-time-grid (car new))))
7860 (if (member 'time-up org-agenda-sorting-strategy)
7862 (append list new)))))
7864 (defun org-compile-prefix-format (format)
7865 "Compile the prefix format into a Lisp form that can be evaluated.
7866 The resulting form is returned and stored in the variable
7867 `org-prefix-format-compiled'."
7868 (setq org-prefix-has-time nil org-prefix-has-tag nil)
7869 (let ((start 0) varform vars var (s format)e c f opt)
7870 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
7872 (setq var (cdr (assoc (match-string 4 s)
7873 '(("c" . category) ("t" . time) ("s" . extra)
7875 c (or (match-string 3 s) "")
7876 opt (match-beginning 1)
7877 start (1+ (match-beginning 0)))
7878 (if (equal var 'time) (setq org-prefix-has-time t))
7879 (if (equal var 'tag) (setq org-prefix-has-tag t))
7880 (setq f (concat "%" (match-string 2 s) "s"))
7883 `(if (equal "" ,var)
7885 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
7886 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
7887 (setq s (replace-match "%s" t nil s))
7888 (push varform vars))
7889 (setq vars (nreverse vars))
7890 (setq org-prefix-format-compiled `(format ,s ,@vars))))
7892 (defun org-get-time-of-day (s &optional string mod24)
7893 "Check string S for a time of day.
7894 If found, return it as a military time number between 0 and 2400.
7895 If not found, return nil.
7896 The optional STRING argument forces conversion into a 5 character wide string
7902 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
7904 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
7905 (let* ((h (string-to-number (match-string 1 s)))
7906 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
7907 (ampm (if (match-end 4) (downcase (match-string 4 s))))
7908 (am-p (equal ampm "am"))
7909 (h1 (cond ((not ampm) h)
7910 ((= h 12) (if am-p 0 12))
7911 (t (+ h (if am-p 0 12)))))
7912 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
7914 (t0 (+ (* 100 h2) m))
7915 (t1 (concat (if (>= h1 24) "+" " ")
7916 (if (< t0 100) "0" "")
7917 (if (< t0 10) "0" "")
7918 (int-to-string t0))))
7919 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
7921 (defun org-finalize-agenda-entries (list)
7922 "Sort and concatenate the agenda items."
7923 (setq list (mapcar 'org-agenda-highlight-todo list))
7924 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
7926 (defun org-agenda-highlight-todo (x)
7930 (beginning-of-line 1)
7931 (setq re (get-text-property (point) 'org-not-done-regexp))
7932 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
7933 (and (looking-at (concat "[ \t]*" re))
7934 (add-text-properties (match-beginning 0) (match-end 0)
7936 (setq re (get-text-property 0 'org-not-done-regexp x)
7937 pl (get-text-property 0 'prefix-length x))
7938 (and re (equal (string-match re x pl) pl)
7939 (add-text-properties (match-beginning 0) (match-end 0)
7940 '(face org-todo) x))
7943 (defsubst org-cmp-priority (a b)
7944 "Compare the priorities of string A and B."
7945 (let ((pa (or (get-text-property 1 'priority a) 0))
7946 (pb (or (get-text-property 1 'priority b) 0)))
7947 (cond ((> pa pb) +1)
7951 (defsubst org-cmp-category (a b)
7952 "Compare the string values of categories of strings A and B."
7953 (let ((ca (or (get-text-property 1 'category a) ""))
7954 (cb (or (get-text-property 1 'category b) "")))
7955 (cond ((string-lessp ca cb) -1)
7956 ((string-lessp cb ca) +1)
7959 (defsubst org-cmp-time (a b)
7960 "Compare the time-of-day values of strings A and B."
7961 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
7962 (ta (or (get-text-property 1 'time-of-day a) def))
7963 (tb (or (get-text-property 1 'time-of-day b) def)))
7964 (cond ((< ta tb) -1)
7968 (defun org-entries-lessp (a b)
7969 "Predicate for sorting agenda entries."
7970 ;; The following variables will be used when the form is evaluated.
7971 (let* ((time-up (org-cmp-time a b))
7972 (time-down (if time-up (- time-up) nil))
7973 (priority-up (org-cmp-priority a b))
7974 (priority-down (if priority-up (- priority-up) nil))
7975 (category-up (org-cmp-category a b))
7976 (category-down (if category-up (- category-up) nil))
7977 (category-keep (if category-up +1 nil)))
7979 (eval (cons 'or org-agenda-sorting-strategy))
7980 '((-1 . t) (1 . nil) (nil . nil))))))
7982 (defun org-agenda-show-priority ()
7983 "Show the priority of the current item.
7984 This priority is composed of the main priority given with the [#A] cookies,
7985 and by additional input from the age of a schedules or deadline entry."
7987 (let* ((pri (get-text-property (point-at-bol) 'priority)))
7988 (message "Priority is %d" (if pri pri -1000))))
7990 (defun org-agenda-show-tags ()
7991 "Show the tags applicable to the current item."
7993 (let* ((tags (get-text-property (point-at-bol) 'tags)))
7995 (message "Tags are :%s:"
7996 (org-no-properties (mapconcat 'identity tags ":")))
7997 (message "No tags associated with this line"))))
7999 (defun org-agenda-goto (&optional highlight)
8000 "Go to the Org-mode file which contains the item at point."
8002 (let* ((marker (or (get-text-property (point) 'org-marker)
8003 (org-agenda-error)))
8004 (buffer (marker-buffer marker))
8005 (pos (marker-position marker)))
8006 (switch-to-buffer-other-window buffer)
8009 (when (eq major-mode 'org-mode)
8010 (org-show-hidden-entry)
8012 (and (outline-next-heading)
8013 (org-flag-heading nil)))) ; show the next heading
8014 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
8016 (defun org-agenda-switch-to ()
8017 "Go to the Org-mode file which contains the item at point."
8019 (let* ((marker (or (get-text-property (point) 'org-marker)
8020 (org-agenda-error)))
8021 (buffer (marker-buffer marker))
8022 (pos (marker-position marker)))
8023 (switch-to-buffer buffer)
8024 (delete-other-windows)
8027 (when (eq major-mode 'org-mode)
8028 (org-show-hidden-entry)
8030 (and (outline-next-heading)
8031 (org-flag-heading nil)))))) ; show the next heading
8033 (defun org-agenda-goto-mouse (ev)
8034 "Go to the Org-mode file which contains the item at the mouse click."
8036 (mouse-set-point ev)
8039 (defun org-agenda-show ()
8040 "Display the Org-mode file which contains the item at point."
8042 (let ((win (selected-window)))
8044 (select-window win)))
8046 (defun org-agenda-recenter (arg)
8047 "Display the Org-mode file which contains the item at point and recenter."
8049 (let ((win (selected-window)))
8052 (select-window win)))
8054 (defun org-agenda-show-mouse (ev)
8055 "Display the Org-mode file which contains the item at the mouse click."
8057 (mouse-set-point ev)
8060 (defun org-agenda-check-no-diary ()
8061 "Check if the entry is a diary link and abort if yes."
8062 (if (get-text-property (point) 'org-agenda-diary-link)
8063 (org-agenda-error)))
8065 (defun org-agenda-error ()
8066 (error "Command not allowed in this line"))
8068 (defvar org-last-heading-marker (make-marker)
8069 "Marker pointing to the headline that last changed its TODO state
8070 by a remote command from the agenda.")
8072 (defun org-agenda-todo (&optional arg)
8073 "Cycle TODO state of line at point, also in Org-mode file.
8074 This changes the line at point, all other lines in the agenda referring to
8075 the same tree node, and the headline of the tree node in the Org-mode file."
8077 (org-agenda-check-no-diary)
8078 (let* ((col (current-column))
8079 (marker (or (get-text-property (point) 'org-marker)
8080 (org-agenda-error)))
8081 (buffer (marker-buffer marker))
8082 (pos (marker-position marker))
8083 (hdmarker (get-text-property (point) 'org-hd-marker))
8084 (buffer-read-only nil)
8086 (with-current-buffer buffer
8089 (org-show-hidden-entry)
8091 (and (outline-next-heading)
8092 (org-flag-heading nil))) ; show the next heading
8094 (and (bolp) (forward-char 1))
8095 (setq newhead (org-get-heading))
8097 (org-back-to-heading)
8098 (move-marker org-last-heading-marker (point))))
8099 (beginning-of-line 1)
8101 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8102 (move-to-column col)))
8104 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8105 "Change all lines in the agenda buffer which match HDMARKER.
8106 The new content of the line will be NEWHEAD (as modified by
8107 `org-format-agenda-item'). HDMARKER is checked with
8108 `equal' against all `org-hd-marker' text properties in the file.
8109 If FIXFACE is non-nil, the face of each item is modified acording to
8110 the new TODO state."
8111 (let* (props m pl undone-face done-face finish new dotime cat tags)
8112 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
8114 (goto-char (point-max))
8115 (beginning-of-line 1)
8117 (setq finish (bobp))
8118 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8120 (setq props (text-properties-at (point))
8121 dotime (get-text-property (point) 'dotime)
8122 cat (get-text-property (point) 'category)
8123 tags (get-text-property (point) 'tags)
8124 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
8125 pl (get-text-property (point) 'prefix-length)
8126 undone-face (get-text-property (point) 'undone-face)
8127 done-face (get-text-property (point) 'done-face))
8129 (if (looking-at ".*")
8131 (replace-match new t t)
8132 (beginning-of-line 1)
8133 (add-text-properties (point-at-bol) (point-at-eol) props)
8135 (add-text-properties
8136 (point-at-bol) (point-at-eol)
8138 (if org-last-todo-state-is-todo
8139 undone-face done-face)))
8140 (org-agenda-highlight-todo 'line))
8141 (beginning-of-line 1))
8142 (error "Line update did not work")))
8143 (beginning-of-line 0)))))
8145 (defun org-agenda-priority-up ()
8146 "Increase the priority of line at point, also in Org-mode file."
8148 (org-agenda-priority 'up))
8150 (defun org-agenda-priority-down ()
8151 "Decrease the priority of line at point, also in Org-mode file."
8153 (org-agenda-priority 'down))
8155 (defun org-agenda-priority (&optional force-direction)
8156 "Set the priority of line at point, also in Org-mode file.
8157 This changes the line at point, all other lines in the agenda referring to
8158 the same tree node, and the headline of the tree node in the Org-mode file."
8160 (org-agenda-check-no-diary)
8161 (let* ((marker (or (get-text-property (point) 'org-marker)
8162 (org-agenda-error)))
8163 (buffer (marker-buffer marker))
8164 (pos (marker-position marker))
8165 (hdmarker (get-text-property (point) 'org-hd-marker))
8166 (buffer-read-only nil)
8168 (with-current-buffer buffer
8171 (org-show-hidden-entry)
8173 (and (outline-next-heading)
8174 (org-flag-heading nil))) ; show the next heading
8175 (funcall 'org-priority force-direction)
8177 (setq newhead (org-get-heading)))
8178 (org-agenda-change-all-lines newhead hdmarker)
8179 (beginning-of-line 1)))
8181 (defun org-get-tags-at (&optional pos)
8182 "Get a list of all headline tags applicable at POS.
8183 POS defaults to point. If tags are inherited, the list contains
8184 the targets in the same sequence as the headlines appear, i.e.
8185 the tags of the current headline come last."
8189 (goto-char (or pos (point)))
8191 (org-back-to-heading t)
8194 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
8195 (setq tags (append (org-split-string
8196 (org-match-string-no-properties 1) ":")
8198 (or org-use-tag-inheritance (error ""))
8199 (org-up-heading-all 1))
8204 (defun org-agenda-set-tags ()
8205 "Set tags for the current headline."
8207 (org-agenda-check-no-diary)
8208 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
8209 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
8210 (org-agenda-error)))
8211 (buffer (marker-buffer hdmarker))
8212 (pos (marker-position hdmarker))
8213 (buffer-read-only nil)
8215 (with-current-buffer buffer
8218 (org-show-hidden-entry)
8220 (and (outline-next-heading)
8221 (org-flag-heading nil))) ; show the next heading
8222 (call-interactively 'org-set-tags)
8224 (setq newhead (org-get-heading)))
8225 (org-agenda-change-all-lines newhead hdmarker)
8226 (beginning-of-line 1)))
8228 (defun org-agenda-date-later (arg &optional what)
8229 "Change the date of this item to one day later."
8231 (org-agenda-check-type t 'agenda 'timeline)
8232 (org-agenda-check-no-diary)
8233 (let* ((marker (or (get-text-property (point) 'org-marker)
8234 (org-agenda-error)))
8235 (buffer (marker-buffer marker))
8236 (pos (marker-position marker)))
8237 (with-current-buffer buffer
8240 (if (not (org-at-timestamp-p))
8241 (error "Cannot find time stamp"))
8242 (org-timestamp-change arg (or what 'day))
8243 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8245 (defun org-agenda-date-earlier (arg &optional what)
8246 "Change the date of this item to one day earlier."
8248 (org-agenda-date-later (- arg) what))
8250 (defun org-agenda-date-prompt (arg)
8251 "Change the date of this item. Date is prompted for, with default today.
8252 The prefix ARG is passed to the `org-time-stamp' command and can therefore
8253 be used to request time specification in the time stamp."
8255 (org-agenda-check-type t 'agenda 'timeline)
8256 (org-agenda-check-no-diary)
8257 (let* ((marker (or (get-text-property (point) 'org-marker)
8258 (org-agenda-error)))
8259 (buffer (marker-buffer marker))
8260 (pos (marker-position marker)))
8261 (with-current-buffer buffer
8264 (if (not (org-at-timestamp-p))
8265 (error "Cannot find time stamp"))
8266 (org-time-stamp arg)
8267 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8269 (defun org-agenda-schedule (arg)
8270 "Schedule the item at point."
8272 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8273 (org-agenda-check-no-diary)
8274 (let* ((marker (or (get-text-property (point) 'org-marker)
8275 (org-agenda-error)))
8276 (buffer (marker-buffer marker))
8277 (pos (marker-position marker))
8278 (org-insert-labeled-timestamps-at-point nil)
8280 (with-current-buffer buffer
8283 (setq ts (org-schedule))
8284 (message "Item scheduled for %s" ts))))
8286 (defun org-agenda-deadline (arg)
8287 "Schedule the item at point."
8289 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
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 (org-insert-labeled-timestamps-at-point nil)
8297 (with-current-buffer buffer
8300 (setq ts (org-deadline))
8301 (message "Deadline for this item set to %s" ts))))
8303 (defun org-get-heading ()
8304 "Return the heading of the current entry, without the stars."
8306 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
8307 (if (and (re-search-backward "[\r\n]\\*" nil t)
8308 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
8312 (defun org-agenda-clock-in (&optional arg)
8313 "Start the clock on the currently selected item."
8315 (org-agenda-check-no-diary)
8316 (let* ((marker (or (get-text-property (point) 'org-marker)
8317 (org-agenda-error)))
8318 (pos (marker-position marker)))
8319 (with-current-buffer (marker-buffer marker)
8324 (defun org-agenda-diary-entry ()
8325 "Make a diary entry, like the `i' command from the calendar.
8326 All the standard commands work: block, weekly etc."
8328 (org-agenda-check-type t 'agenda 'timeline)
8329 (require 'diary-lib)
8331 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
8332 (read-char-exclusive)))
8333 (cmd (cdr (assoc char
8334 '((?d . insert-diary-entry)
8335 (?w . insert-weekly-diary-entry)
8336 (?m . insert-monthly-diary-entry)
8337 (?y . insert-yearly-diary-entry)
8338 (?a . insert-anniversary-diary-entry)
8339 (?b . insert-block-diary-entry)
8340 (?c . insert-cyclic-diary-entry)))))
8341 (oldf (symbol-function 'calendar-cursor-to-date))
8343 (mark (or (mark t) (point))))
8345 (error "No command associated with <%c>" char))
8346 (unless (and (get-text-property point 'day)
8347 (or (not (equal ?b char))
8348 (get-text-property mark 'day)))
8349 (error "Don't know which date to use for diary entry"))
8350 ;; We implement this by hacking the `calendar-cursor-to-date' function
8351 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
8352 (let ((calendar-mark-ring
8353 (list (calendar-gregorian-from-absolute
8354 (or (get-text-property mark 'day)
8355 (get-text-property point 'day))))))
8358 (fset 'calendar-cursor-to-date
8359 (lambda (&optional error)
8360 (calendar-gregorian-from-absolute
8361 (get-text-property point 'day))))
8362 (call-interactively cmd))
8363 (fset 'calendar-cursor-to-date oldf)))))
8366 (defun org-agenda-execute-calendar-command (cmd)
8367 "Execute a calendar command from the agenda, with the date associated to
8368 the cursor position."
8369 (org-agenda-check-type t 'agenda 'timeline)
8370 (require 'diary-lib)
8371 (unless (get-text-property (point) 'day)
8372 (error "Don't know which date to use for calendar command"))
8373 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
8375 (date (calendar-gregorian-from-absolute
8376 (get-text-property point 'day)))
8377 (displayed-day (extract-calendar-day date))
8378 (displayed-month (extract-calendar-month date))
8379 (displayed-year (extract-calendar-year date)))
8382 (fset 'calendar-cursor-to-date
8383 (lambda (&optional error)
8384 (calendar-gregorian-from-absolute
8385 (get-text-property point 'day))))
8386 (call-interactively cmd))
8387 (fset 'calendar-cursor-to-date oldf))))
8389 (defun org-agenda-phases-of-moon ()
8390 "Display the phases of the moon for the 3 months around the cursor date."
8392 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
8394 (defun org-agenda-holidays ()
8395 "Display the holidays for the 3 months around the cursor date."
8397 (org-agenda-execute-calendar-command 'list-calendar-holidays))
8399 (defun org-agenda-sunrise-sunset (arg)
8400 "Display sunrise and sunset for the cursor date.
8401 Latitude and longitude can be specified with the variables
8402 `calendar-latitude' and `calendar-longitude'. When called with prefix
8403 argument, latitude and longitude will be prompted for."
8405 (let ((calendar-longitude (if arg nil calendar-longitude))
8406 (calendar-latitude (if arg nil calendar-latitude))
8407 (calendar-location-name
8408 (if arg "the given coordinates" calendar-location-name)))
8409 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
8411 (defun org-agenda-goto-calendar ()
8412 "Open the Emacs calendar with the date at the cursor."
8414 (org-agenda-check-type t 'agenda 'timeline)
8415 (let* ((day (or (get-text-property (point) 'day)
8416 (error "Don't know which date to open in calendar")))
8417 (date (calendar-gregorian-from-absolute day))
8418 (calendar-move-hook nil)
8419 (view-calendar-holidays-initially nil)
8420 (view-diary-entries-initially nil))
8422 (calendar-goto-date date)))
8424 (defun org-calendar-goto-agenda ()
8425 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
8426 This is a command that has to be installed in `calendar-mode-map'."
8428 (org-agenda-list nil (calendar-absolute-from-gregorian
8429 (calendar-cursor-to-date))
8432 (defun org-agenda-convert-date ()
8434 (org-agenda-check-type t 'agenda 'timeline)
8435 (let ((day (get-text-property (point) 'day))
8438 (error "Don't know which date to convert"))
8439 (setq date (calendar-gregorian-from-absolute day))
8441 "Gregorian: " (calendar-date-string date) "\n"
8442 "ISO: " (calendar-iso-date-string date) "\n"
8443 "Day of Yr: " (calendar-day-of-year-string date) "\n"
8444 "Julian: " (calendar-julian-date-string date) "\n"
8445 "Astron. JD: " (calendar-astro-date-string date)
8446 " (Julian date number at noon UTC)\n"
8447 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
8448 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
8449 "French: " (calendar-french-date-string date) "\n"
8450 "Mayan: " (calendar-mayan-date-string date) "\n"
8451 "Coptic: " (calendar-coptic-date-string date) "\n"
8452 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
8453 "Persian: " (calendar-persian-date-string date) "\n"
8454 "Chinese: " (calendar-chinese-date-string date) "\n"))
8455 (with-output-to-temp-buffer "*Dates*"
8457 (if (fboundp 'fit-window-to-buffer)
8458 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
8462 (defun org-scan-tags (action matcher &optional todo-only)
8463 "Scan headline tags with inheritance and produce output ACTION.
8464 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8465 evaluated, testing if a given set of tags qualifies a headline for
8466 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8467 are included in the output."
8468 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8469 (mapconcat 'regexp-quote
8470 (nreverse (cdr (reverse org-todo-keywords)))
8472 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
8473 (props (list 'face nil
8474 'done-face 'org-done
8476 'mouse-face 'highlight
8477 'keymap org-agenda-keymap
8479 (format "mouse-2 or RET jump to org file %s"
8480 (abbreviate-file-name buffer-file-name))))
8482 tags tags-list tags-alist (llast 0) rtn level category i txt
8485 (goto-char (point-min))
8486 (when (eq action 'sparse-tree) (org-overview))
8487 (while (re-search-forward re nil t)
8489 (and (eq action 'agenda) (org-agenda-skip))
8490 (setq todo (if (match-end 1) (match-string 2))
8491 tags (if (match-end 4) (match-string 4)))
8492 (goto-char (setq lspos (1+ (match-beginning 0))))
8493 (setq level (funcall outline-level)
8494 category (org-get-category))
8495 (setq i llast llast level)
8496 ;; remove tag lists from same and sublevels
8498 (when (setq entry (assoc i tags-alist))
8499 (setq tags-alist (delete entry tags-alist)))
8503 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8505 (cons (cons level tags) tags-alist)))
8506 ;; compile tags for current headline
8508 (if org-use-tag-inheritance
8509 (apply 'append (mapcar 'cdr tags-alist))
8511 (when (and (or (not todo-only) todo)
8513 (or (not org-agenda-skip-archived-trees)
8514 (not (member org-archive-tag tags-list))))
8515 ;; list this headline
8516 (if (eq action 'sparse-tree)
8518 (org-show-hierarchy-above))
8519 (setq txt (org-format-agenda-item
8522 (if org-tags-match-list-sublevels
8523 (make-string (1- level) ?.) "")
8525 category tags-list))
8527 (setq marker (org-agenda-new-marker))
8528 (org-add-props txt props
8529 'org-marker marker 'org-hd-marker marker 'category category)
8531 ;; if we are to skip sublevels, jump to end of subtree
8533 (or org-tags-match-list-sublevels (org-end-of-subtree))))))
8534 (when (and (eq action 'sparse-tree)
8535 (not org-sparse-tree-open-archived-trees))
8536 (org-hide-archived-subtrees (point-min) (point-max)))
8539 (defun org-tags-sparse-tree (&optional arg match)
8540 "Create a sparse tree according to tags search string MATCH.
8541 MATCH can contain positive and negative selection of tags, like
8542 \"+WORK+URGENT-WITHBOSS\"."
8544 (let ((org-show-following-heading nil)
8545 (org-show-hierarchy-above nil))
8546 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
8548 (defun org-make-tags-matcher (match)
8549 "Create the TAGS matcher form for the tags-selecting string MATCH."
8551 ;; Get a new match request, with completion
8552 (setq org-last-tags-completion-table
8553 (or (org-get-buffer-tags)
8554 org-last-tags-completion-table))
8555 (setq match (completing-read
8556 "Tags: " 'org-tags-completion-function nil nil nil
8557 'org-tags-history)))
8558 ;; parse the string and create a lisp form
8559 (let ((match0 match) minus tag mm matcher orterms term orlist)
8560 (setq orterms (org-split-string match "|"))
8561 (while (setq term (pop orterms))
8562 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
8563 (setq minus (and (match-end 1)
8564 (equal (match-string 1 term) "-"))
8565 tag (match-string 2 term)
8566 term (substring term (match-end 0))
8567 mm (list 'member (downcase tag) 'tags-list)
8568 mm (if minus (list 'not mm) mm))
8570 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
8573 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8574 ;; Return the string and lisp forms of the matcher
8575 (cons match0 matcher)))
8578 (defun org-tags-view (&optional todo-only match keep-modes)
8579 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
8580 The prefix arg TODO-ONLY limits the search to TODO entries."
8582 (org-agenda-maybe-reset-markers 'force)
8583 (org-compile-prefix-format org-agenda-prefix-format)
8584 (let* ((org-agenda-keep-modes keep-modes)
8585 (org-tags-match-list-sublevels
8586 (if todo-only t org-tags-match-list-sublevels))
8587 (win (selected-window))
8588 (completion-ignore-case t)
8589 rtn rtnall files file pos matcher
8591 (setq matcher (org-make-tags-matcher match)
8592 match (car matcher) matcher (cdr matcher))
8593 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
8595 (delete-other-windows)
8596 (switch-to-buffer-other-window
8597 (get-buffer-create org-agenda-buffer-name))))
8598 (setq buffer-read-only nil)
8600 (org-agenda-mode) (setq buffer-read-only nil)
8601 (set (make-local-variable 'org-agenda-type) 'tags)
8602 (set (make-local-variable 'org-agenda-redo-command)
8603 (list 'org-tags-view (list 'quote todo-only)
8604 (list 'if 'current-prefix-arg nil match) t))
8605 (setq files (org-agenda-files)
8607 (org-prepare-agenda-buffers files)
8608 (while (setq file (pop files))
8610 (org-check-agenda-file file)
8611 (setq buffer (if (file-exists-p file)
8612 (org-get-agenda-file-buffer file)
8613 (error "No such file %s" file)))
8615 ;; If file does not exist, merror message to agenda
8617 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8618 rtnall (append rtnall rtn))
8619 (with-current-buffer buffer
8620 (unless (eq major-mode 'org-mode)
8621 (error "Agenda file %s is not in `org-mode'" file))
8622 (setq org-category-table (org-get-category-table))
8625 (if org-respect-restriction
8626 (if (org-region-active-p)
8627 ;; Respect a region to restrict search
8628 (narrow-to-region (region-beginning) (region-end)))
8629 ;; If we work for the calendar or many files,
8630 ;; get rid of any restriction
8632 (setq rtn (org-scan-tags 'agenda matcher todo-only))
8633 (setq rtnall (append rtnall rtn))))))))
8634 (insert "Headlines with TAGS match: ")
8635 (add-text-properties (point-min) (1- (point))
8636 (list 'face 'org-level-3))
8639 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
8641 (insert "Press `C-u r' to search again with new search string\n")
8642 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
8644 (insert (mapconcat 'identity rtnall "\n")))
8645 (goto-char (point-min))
8646 (setq buffer-read-only t)
8647 (org-fit-agenda-window)
8648 (if (not org-select-agenda-window) (select-window win))))
8650 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8651 (defun org-set-tags (&optional arg just-align)
8652 "Set the tags for the current headline.
8653 With prefix ARG, realign all tags in headings in the current buffer."
8655 (let* ((re (concat "^" outline-regexp))
8656 (col (current-column))
8657 (current (org-get-tags))
8658 table current-tags inherited-tags ; computed below when needed
8659 tags hd empty invis)
8662 (goto-char (point-min))
8663 (while (re-search-forward re nil t)
8664 (org-set-tags nil t))
8665 (message "All tags realigned to column %d" org-tags-column))
8668 (setq table (or org-tag-alist (org-get-buffer-tags))
8669 org-last-tags-completion-table table
8670 current-tags (org-split-string current ":")
8671 inherited-tags (nreverse
8672 (nthcdr (length current-tags)
8673 (nreverse (org-get-tags-at))))
8675 (if (or (eq t org-use-fast-tag-selection)
8676 (and org-use-fast-tag-selection
8677 (delq nil (mapcar 'cdr table))))
8678 (org-fast-tag-selection current-tags inherited-tags table)
8679 (let ((org-add-colon-after-tag-completion t))
8680 (completing-read "Tags: " 'org-tags-completion-function
8681 nil nil current 'org-tags-history))))
8682 (while (string-match "[-+&]+" tags)
8683 (setq tags (replace-match ":" t t tags))))
8685 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
8686 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8687 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8688 (if (equal current "")
8691 (or empty (insert-before-markers " ")))
8692 (beginning-of-line 1)
8693 (setq invis (org-invisible-p))
8694 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
8695 (setq hd (match-string 1))
8696 (delete-region (match-beginning 0) (match-end 0))
8697 (insert-before-markers (org-trim hd) (if empty "" " ")))
8700 (beginning-of-line 1)
8701 (and (re-search-forward "[ \t]+$" (point-at-eol) t)
8702 (replace-match "")))
8703 (move-to-column (max (current-column)
8704 (if (> org-tags-column 0)
8706 (- (- org-tags-column) (length tags))))
8708 (insert-before-markers tags)
8709 (if (and (not invis) (org-invisible-p))
8710 (outline-flag-region (point-at-bol) (point) nil)))
8711 (move-to-column col))))
8713 (defun org-tags-completion-function (string predicate &optional flag)
8714 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8715 (confirm (lambda (x) (stringp (car x)))))
8716 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8717 (setq s1 (match-string 1 string)
8718 s2 (match-string 2 string))
8719 (setq s1 "" s2 string))
8723 (setq rtn (try-completion s2 ctable confirm))
8725 (concat s1 s2 (substring rtn (length s2))
8726 (if (and org-add-colon-after-tag-completion
8732 (all-completions s2 ctable confirm)
8739 (defun org-fast-tag-insert (kwd tags face &optional end)
8740 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
8741 (insert (format "%-12s" (concat kwd ":"))
8742 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
8745 (defun org-fast-tag-selection (current inherited table)
8746 "Fast tag selection with single keys.
8747 CURRENT is the current list of tags in the headline, INHERITED is the
8748 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
8749 possibly with grouping information.
8750 If the keys are nil, a-z are automatically assigned.
8751 Returns the new tags string, or nil to not change the current settings."
8752 (let* ((maxlen (apply 'max (mapcar
8754 (if (stringp (car x)) (string-width (car x)) 0))
8756 (fwidth (+ maxlen 3 1 3))
8757 (ncol (/ (- (window-width) 4) fwidth))
8760 tg cnt e c char c1 c2 ntable tbl rtn
8762 (save-window-excursion
8763 (delete-other-windows)
8764 (split-window-vertically)
8765 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
8767 (org-fast-tag-insert "Inherited" inherited i-face "\n")
8768 (org-fast-tag-insert "Current" current c-face "\n\n")
8769 (setq tbl table char ?a cnt 0)
8770 (while (setq e (pop tbl))
8772 ((equal e '(:startgroup))
8773 (push '() groups) (setq ingroup t)
8774 (when (not (= cnt 0))
8778 ((equal e '(:endgroup))
8779 (setq ingroup nil cnt 0)
8782 (setq tg (car e) c2 nil)
8785 ;; automatically assign a character.
8786 (setq c1 (string-to-char
8787 (downcase (substring
8788 tg (if (= (string-to-char tg) ?@) 1 0)))))
8789 (if (or (rassoc c1 ntable) (rassoc c1 table))
8790 (while (or (rassoc char ntable) (rassoc char table))
8791 (setq char (1+ char)))
8793 (setq c (or c2 char)))
8794 (if ingroup (push tg (car groups)))
8795 (setq tg (org-add-props tg nil 'face
8797 ((member tg current) c-face)
8798 ((member tg inherited) i-face)
8800 (if (and (= cnt 0) (not ingroup)) (insert " "))
8801 (insert "[" c "] " tg (make-string
8802 (- fwidth 4 (length tg)) ?\ ))
8803 (push (cons tg c) ntable)
8804 (when (= (setq cnt (1+ cnt)) ncol)
8806 (if ingroup (insert " "))
8808 (setq ntable (nreverse ntable))
8810 (goto-char (point-min))
8811 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
8815 (message "[key]:Toggle SPC: clear current RET accept%s"
8816 (if groups " [!] ignore goups" ""))
8817 (setq c (read-char-exclusive))
8819 ((= c ?\r) (throw 'exit t))
8822 (goto-char (point-min))
8823 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
8825 (and (= c ?q) (not (rassoc c ntable))))
8827 ((= c ?\ ) (setq current nil))
8828 ((setq e (rassoc c ntable) tg (car e))
8829 (if (member tg current)
8830 (setq current (delete tg current))
8831 (loop for g in groups do
8834 (setq current (delete x current)))
8836 (setq current (cons tg current)))))
8837 ;; Create a sorted list
8841 (assoc b (cdr (memq (assoc a ntable) ntable))))))
8842 (goto-char (point-min))
8843 (beginning-of-line 2)
8844 (delete-region (point) (point-at-eol))
8845 (org-fast-tag-insert "Current" current c-face)
8846 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
8847 (setq tg (match-string 1))
8848 (add-text-properties (match-beginning 1) (match-end 1)
8851 ((member tg current) c-face)
8852 ((member tg inherited) i-face)
8854 (goto-char (point-min)))))
8856 (mapconcat 'identity current ":")
8859 (defun org-get-tags ()
8860 "Get the TAGS string in the current headline."
8861 (unless (org-on-heading-p)
8862 (error "Not on a heading"))
8864 (beginning-of-line 1)
8865 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
8866 (org-match-string-no-properties 1)
8869 (defun org-get-buffer-tags ()
8870 "Get a table of all tags used in the buffer, for completion."
8873 (goto-char (point-min))
8874 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
8875 (mapc (lambda (x) (add-to-list 'tags x))
8876 (org-split-string (org-match-string-no-properties 1) ":"))))
8877 (mapcar 'list tags)))
8881 (defvar org-create-file-search-functions nil
8882 "List of functions to construct the right search string for a file link.
8883 These functions are called in turn with point at the location to
8884 which the link should point.
8886 A function in the hook should first test if it would like to
8887 handle this file type, for example by checking the major-mode or
8888 the file extension. If it decides not to handle this file, it
8889 should just return nil to give other functions a chance. If it
8890 does handle the file, it must return the search string to be used
8891 when following the link. The search string will be part of the
8892 file link, given after a double colon, and `org-open-at-point'
8893 will automatically search for it. If special measures must be
8894 taken to make the search successful, another function should be
8895 added to the companion hook `org-execute-file-search-functions',
8898 A function in this hook may also use `setq' to set the variable
8899 `description' to provide a suggestion for the descriptive text to
8900 be used for this link when it gets inserted into an Org-mode
8901 buffer with \\[org-insert-link].")
8903 (defvar org-execute-file-search-functions nil
8904 "List of functions to execute a file search triggered by a link.
8906 Functions added to this hook must accept a single argument, the
8907 search string that was part of the file link, the part after the
8908 double colon. The function must first check if it would like to
8909 handle this search, for example by checking the major-mode or the
8910 file extension. If it decides not to handle this search, it
8911 should just return nil to give other functions a chance. If it
8912 does handle the search, it must return a non-nil value to keep
8913 other functions from trying.
8915 Each function can access the current prefix argument through the
8916 variable `current-prefix-argument'. Note that a single prefix is
8917 used to force opening a link in Emacs, so it may be good to only
8918 use a numeric or double prefix to guide the search function.
8920 In case this is needed, a function in this hook can also restore
8921 the window configuration before `org-open-at-point' was called using:
8923 (set-window-configuration org-window-config-before-follow-link)")
8925 (defun org-find-file-at-mouse (ev)
8926 "Open file link or URL at mouse."
8928 (mouse-set-point ev)
8929 (org-open-at-point 'in-emacs))
8931 (defun org-open-at-mouse (ev)
8932 "Open file link or URL at mouse."
8934 (mouse-set-point ev)
8935 (org-open-at-point))
8937 (defvar org-window-config-before-follow-link nil
8938 "The window configuration before following a link.
8939 This is saved in case the need arises to restore it.")
8941 (defun org-open-at-point (&optional in-emacs)
8942 "Open link at or after point.
8943 If there is no link at point, this function will search forward up to
8944 the end of the current subtree.
8945 Normally, files will be opened by an appropriate application. If the
8946 optional argument IN-EMACS is non-nil, Emacs will visit the file."
8948 (setq org-window-config-before-follow-link (current-window-configuration))
8949 (org-remove-occur-highlights nil nil t)
8950 (if (org-at-timestamp-p)
8951 (org-agenda-list nil (time-to-days (org-time-string-to-time
8952 (substring (match-string 1) 0 10)))
8954 (let (type path link line search (pos (point)))
8957 (skip-chars-forward "^]\n\r")
8958 (when (and (re-search-backward "\\[\\[" nil t)
8959 (looking-at org-bracket-link-regexp)
8960 (<= (match-beginning 0) pos)
8961 (>= (match-end 0) pos))
8962 (setq link (org-link-unescape (org-match-string-no-properties 1)))
8963 (while (string-match " *\n *" link)
8964 (setq link (replace-match " " t t link)))
8965 (if (string-match org-link-re-with-space2 link)
8966 (setq type (match-string 1 link)
8967 path (match-string 2 link))
8968 (setq type "thisfile"
8972 (when (get-text-property (point) 'org-linked-text)
8973 (setq type "thisfile"
8974 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8975 (1+ (point)) (point))
8976 path (buffer-substring
8977 (previous-single-property-change pos 'org-linked-text)
8978 (next-single-property-change pos 'org-linked-text)))
8982 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
8983 (if (equal (char-before) ?<) (backward-char 1))
8984 (when (or (looking-at org-angle-link-re)
8985 (looking-at org-plain-link-re)
8986 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
8987 (re-search-forward org-plain-link-re (point-at-eol) t))
8988 (<= (match-beginning 0) pos)
8989 (>= (match-end 0) pos)))
8990 (setq type (match-string 1)
8991 path (match-string 2))
8994 (skip-chars-backward "^ \t\n\r")
8995 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
8997 path (match-string 1))
8998 (while (string-match ":" path)
8999 (setq path (replace-match "+" t t path)))
9002 (skip-chars-backward "a-zA-Z_")
9003 (when (and (memq 'camel org-activate-links)
9004 (looking-at org-camel-regexp))
9005 (setq type "camel" path (match-string 0))
9006 (if (equal (char-before) ?*)
9007 (setq path (concat "*" path))))
9010 (error "No link found"))
9011 ;; Remove any trailing spaces in path
9012 (if (string-match " +\\'" path)
9013 (setq path (replace-match "" t t path)))
9017 ((member type '("http" "https" "ftp" "mailto" "news"))
9018 (browse-url (concat type ":" path)))
9020 ((string= type "tags")
9021 (org-tags-view in-emacs path))
9022 ((or (string= type "camel")
9023 (string= type "thisfile"))
9024 (org-mark-ring-push)
9027 (cond ((equal in-emacs '(4)) 'occur)
9028 ((equal in-emacs '(16)) 'org-occur)
9031 ((string= type "file")
9032 (if (string-match "::\\([0-9]+\\)\\'" path)
9033 (setq line (string-to-number (match-string 1 path))
9034 path (substring path 0 (match-beginning 0)))
9035 (if (string-match "::\\(.+\\)\\'" path)
9036 (setq search (match-string 1 path)
9037 path (substring path 0 (match-beginning 0)))))
9038 (org-open-file path in-emacs line search))
9040 ((string= type "news")
9041 (org-follow-gnus-link path))
9043 ((string= type "bbdb")
9044 (org-follow-bbdb-link path))
9046 ((string= type "info")
9047 (org-follow-info-link path))
9049 ((string= type "gnus")
9050 (let (group article)
9051 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9052 (error "Error in Gnus link"))
9053 (setq group (match-string 1 path)
9054 article (match-string 3 path))
9055 (org-follow-gnus-link group article)))
9057 ((string= type "vm")
9058 (let (folder article)
9059 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9060 (error "Error in VM link"))
9061 (setq folder (match-string 1 path)
9062 article (match-string 3 path))
9063 ;; in-emacs is the prefix arg, will be interpreted as read-only
9064 (org-follow-vm-link folder article in-emacs)))
9066 ((string= type "wl")
9067 (let (folder article)
9068 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9069 (error "Error in Wanderlust link"))
9070 (setq folder (match-string 1 path)
9071 article (match-string 3 path))
9072 (org-follow-wl-link folder article)))
9074 ((string= type "mhe")
9075 (let (folder article)
9076 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9077 (error "Error in MHE link"))
9078 (setq folder (match-string 1 path)
9079 article (match-string 3 path))
9080 (org-follow-mhe-link folder article)))
9082 ((string= type "rmail")
9083 (let (folder article)
9084 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9085 (error "Error in RMAIL link"))
9086 (setq folder (match-string 1 path)
9087 article (match-string 3 path))
9088 (org-follow-rmail-link folder article)))
9090 ((string= type "shell")
9092 (while (string-match "@{" cmd)
9093 (setq cmd (replace-match "<" t t cmd)))
9094 (while (string-match "@}" cmd)
9095 (setq cmd (replace-match ">" t t cmd)))
9096 (if (or (not org-confirm-shell-link-function)
9097 (funcall org-confirm-shell-link-function
9098 (format "Execute \"%s\" in shell? "
9099 (org-add-props cmd nil
9100 'face 'org-warning))))
9102 (message "Executing %s" cmd)
9103 (shell-command cmd))
9106 ((string= type "elisp")
9108 (if (or (not org-confirm-elisp-link-function)
9109 (funcall org-confirm-elisp-link-function
9110 (format "Execute \"%s\" as elisp? "
9111 (org-add-props cmd nil
9112 'face 'org-warning))))
9113 (message "%s => %s" cmd (eval (read cmd)))
9117 (browse-url-at-point))))))
9119 (defun org-link-search (s &optional type)
9120 "Search for a link search option.
9121 When S is a CamelCaseWord, search for a target, or for a sentence containing
9122 the words. If S is surrounded by forward slashes, it is interpreted as a
9123 regular expression. In org-mode files, this will create an `org-occur'
9124 sparse tree. In ordinary files, `occur' will be used to list matches.
9125 If the current buffer is in `dired-mode', grep will be used to search
9127 (let ((case-fold-search t)
9128 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9131 words re0 re1 re2 re3 re4 re5 re2a reall camel)
9133 ;; First check if there are any special
9134 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9135 ;; Now try the builtin stuff
9137 (goto-char (point-min))
9140 (concat "<<" (regexp-quote s0) ">>") nil t)
9141 (setq pos (match-beginning 0))))
9142 ;; There is an exact target for this
9144 ((string-match "^/\\(.*\\)/$" s)
9145 ;; A regular expression
9147 ((eq major-mode 'org-mode)
9148 (org-occur (match-string 1 s)))
9149 ;;((eq major-mode 'dired-mode)
9150 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9151 (t (org-do-occur (match-string 1 s)))))
9152 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
9154 ;; A camel or a normal search string
9155 (when (equal (string-to-char s) ?*)
9156 ;; Anchor on headlines, post may include tags.
9157 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9158 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9160 (remove-text-properties
9162 '(face nil mouse-face nil keymap nil fontified nil) s)
9163 ;; Make a series of regular expressions to find a match
9166 (org-camel-to-words s)
9167 (org-split-string s "[ \n\r\t]+"))
9168 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9169 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9170 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9171 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9172 re1 (concat pre re2 post)
9173 re3 (concat pre re4 post)
9174 re5 (concat pre ".*" re4)
9175 re2 (concat pre re2)
9176 re2a (concat pre re2a)
9177 re4 (concat pre re4)
9178 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9179 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9183 ((eq type 'org-occur) (org-occur reall))
9184 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9185 (t (goto-char (point-min))
9186 (if (or (org-search-not-link re0 nil t)
9187 (org-search-not-link re1 nil t)
9188 (org-search-not-link re2 nil t)
9189 (org-search-not-link re2a nil t)
9190 (org-search-not-link re3 nil t)
9191 (org-search-not-link re4 nil t)
9192 (org-search-not-link re5 nil t)
9194 (goto-char (match-beginning 1))
9196 (error "No match")))))
9198 ;; Normal string-search
9199 (goto-char (point-min))
9200 (if (search-forward s nil t)
9201 (goto-char (match-beginning 0))
9202 (error "No match"))))
9203 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
9205 (defun org-search-not-link (&rest args)
9206 "Execute `re-search-forward', but only accept matches that are not a link."
9209 (while (apply 're-search-forward args)
9211 (if (not (save-match-data
9212 (and (re-search-backward "\\[\\[" nil t)
9213 (looking-at org-bracket-link-regexp)
9214 (<= (match-beginning 0) p1)
9215 (>= (match-end 0) p1))))
9216 (progn (goto-char (match-end 0))
9217 (throw 'exit (point)))
9218 (goto-char (match-end 0)))))))
9220 (defun org-do-occur (regexp &optional cleanup)
9221 "Call the Emacs command `occur'.
9222 If CLEANUP is non-nil, remove the printout of the regular expression
9223 in the *Occur* buffer. This is useful if the regex is long and not useful
9227 (let ((cwin (selected-window)) win beg end)
9228 (when (setq win (get-buffer-window "*Occur*"))
9229 (select-window win))
9230 (goto-char (point-min))
9231 (when (re-search-forward "match[a-z]+" nil t)
9232 (setq beg (match-end 0))
9233 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9234 (setq end (1- (match-beginning 0)))))
9235 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9236 (goto-char (point-min))
9237 (select-window cwin))))
9239 (defvar org-mark-ring nil
9240 "Mark ring for positions before jumps in Org-mode.")
9241 (defvar org-mark-ring-last-goto nil
9242 "Last position in the mark ring used to go back.")
9243 ;; Fill and close the ring
9244 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9245 (loop for i from 1 to org-mark-ring-length do
9246 (push (make-marker) org-mark-ring))
9247 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9250 (defun org-mark-ring-push (&optional pos buffer)
9251 "Put the current position or POS into the mark ring and rotate it."
9253 (setq pos (or pos (point)))
9254 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9255 (move-marker (car org-mark-ring)
9257 (or buffer (current-buffer)))
9259 (substitute-command-keys
9260 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9262 (defun org-mark-ring-goto (&optional n)
9263 "Jump to the previous position in the mark ring.
9264 With prefix arg N, jump back that many stored positions. When
9265 called several times in succession, walk through the entire ring.
9266 Org-mode commands jumping to a different position in the current file,
9267 or to another Org-mode file, automatically push the old position
9271 (if (eq last-command this-command)
9272 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9273 (setq p org-mark-ring))
9274 (setq org-mark-ring-last-goto p)
9276 (switch-to-buffer (marker-buffer m))
9278 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
9280 (defun org-camel-to-words (s)
9281 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
9282 (let ((case-fold-search nil)
9284 (while (string-match "[a-z][A-Z]" s)
9285 (push (substring s 0 (1+ (match-beginning 0))) words)
9286 (setq s (substring s (1+ (match-beginning 0)))))
9287 (nreverse (cons s words))))
9289 (defun org-remove-angle-brackets (s)
9290 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9291 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9293 (defun org-add-angle-brackets (s)
9294 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9295 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9298 (defun org-follow-bbdb-link (name)
9299 "Follow a BBDB link to NAME."
9301 (let ((inhibit-redisplay t)
9302 (bbdb-electric-p nil))
9304 ;; Exact match on name
9305 (bbdb-name (concat "\\`" name "\\'") nil)
9306 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9307 ;; Exact match on name
9308 (bbdb-company (concat "\\`" name "\\'") nil)
9309 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9310 ;; Partial match on name
9311 (bbdb-name name nil)
9312 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9313 ;; Partial match on company
9314 (bbdb-company name nil)
9315 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9316 ;; General match including network address and notes
9318 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9319 (delete-window (get-buffer-window "*BBDB*"))
9320 (error "No matching BBDB record")))))
9323 (defun org-follow-info-link (name)
9324 "Follow an info file & node link to NAME."
9325 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9326 (string-match "\\(.*\\)" name))
9329 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9330 (Info-find-node (match-string 1 name) (match-string 2 name))
9331 (Info-find-node (match-string 1 name) "Top")))
9332 (message (concat "Could not open: " name))))
9334 (defun org-follow-gnus-link (&optional group article)
9335 "Follow a Gnus link to GROUP and ARTICLE."
9337 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9338 (if group (gnus-fetch-group group))
9340 (or (gnus-summary-goto-article article nil 'force)
9341 (if (fboundp 'gnus-summary-insert-cached-articles)
9343 (gnus-summary-insert-cached-articles)
9344 (gnus-summary-goto-article article nil 'force))
9345 (message "Message could not be found.")))))
9347 (defun org-follow-vm-link (&optional folder article readonly)
9348 "Follow a VM link to FOLDER and ARTICLE."
9350 (setq article (org-add-angle-brackets article))
9351 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9352 ;; ange-ftp or efs or tramp access
9353 (let ((user (or (match-string 1 folder) (user-login-name)))
9354 (host (match-string 2 folder))
9355 (file (match-string 3 folder)))
9358 ;; use tramp to access the file
9359 (if (featurep 'xemacs)
9360 (setq folder (format "[%s@%s]%s" user host file))
9361 (setq folder (format "/%s@%s:%s" user host file))))
9363 ;; use ange-ftp or efs
9364 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9365 (setq folder (format "/%s@%s:%s" user host file))))))
9367 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9370 (vm-select-folder-buffer)
9372 (let ((case-fold-search t))
9373 (goto-char (point-min))
9374 (if (not (re-search-forward
9375 (concat "^" "message-id: *" (regexp-quote article))))
9376 (error "Could not find the specified message in this folder"))
9379 (vm-beginning-of-message)
9382 (defun org-follow-wl-link (folder article)
9383 "Follow a Wanderlust link to FOLDER and ARTICLE."
9384 (setq article (org-add-angle-brackets article))
9385 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
9386 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
9387 (wl-summary-redisplay))
9389 (defun org-follow-rmail-link (folder article)
9390 "Follow an RMAIL link to FOLDER and ARTICLE."
9391 (setq article (org-add-angle-brackets article))
9392 (let (message-number)
9394 (save-window-excursion
9395 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9396 (setq message-number
9399 (goto-char (point-max))
9400 (if (re-search-backward
9401 (concat "^Message-ID:\\s-+" (regexp-quote
9404 (rmail-what-message))))))
9407 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9408 (rmail-show-message message-number)
9410 (error "Message not found"))))
9412 ;; mh-e integration based on planner-mode
9413 (defun org-mhe-get-message-real-folder ()
9414 "Return the name of the current message real folder, so if you use
9415 sequences, it will now work."
9418 (if (equal major-mode 'mh-folder-mode)
9420 ;; Refer to the show buffer
9421 mh-show-folder-buffer))
9423 (if (boundp 'mh-index-folder)
9424 (min (length mh-index-folder) (length folder))))
9426 ;; a simple test on mh-index-data does not work, because
9427 ;; mh-index-data is always nil in a show buffer.
9428 (if (and (boundp 'mh-index-folder)
9429 (string= mh-index-folder (substring folder 0 end-index)))
9430 (if (equal major-mode 'mh-show-mode)
9431 (save-window-excursion
9432 (when (buffer-live-p (get-buffer folder))
9434 (pop-to-buffer folder)
9435 (org-mhe-get-message-folder-from-index)
9438 (org-mhe-get-message-folder-from-index)
9444 (defun org-mhe-get-message-folder-from-index ()
9445 "Returns the name of the message folder in a index folder buffer."
9447 (mh-index-previous-folder)
9448 (re-search-forward "^\\(+.*\\)$" nil t)
9449 (message (match-string 1))))
9451 (defun org-mhe-get-message-folder ()
9452 "Return the name of the current message folder. Be careful if you
9455 (if (equal major-mode 'mh-folder-mode)
9457 ;; Refer to the show buffer
9458 mh-show-folder-buffer)))
9460 (defun org-mhe-get-message-num ()
9461 "Return the number of the current message. Be careful if you
9464 (if (equal major-mode 'mh-folder-mode)
9465 (mh-get-msg-num nil)
9466 ;; Refer to the show buffer
9467 (mh-show-buffer-message-number))))
9469 (defun org-mhe-get-header (header)
9470 "Return a header of the message in folder mode. This will create a
9471 show buffer for the corresponding message. If you have a more clever
9473 (let* ((folder (org-mhe-get-message-folder))
9474 (num (org-mhe-get-message-num))
9475 (buffer (get-buffer-create (concat "show-" folder)))
9477 (with-current-buffer buffer
9478 (mh-display-msg num folder)
9479 (if (equal major-mode 'mh-folder-mode)
9481 (mh-show-header-display))
9483 (setq header-field (mh-get-header-field header))
9484 (if (equal major-mode 'mh-folder-mode)
9489 (defun org-follow-mhe-link (folder article)
9490 "Follow an MHE link to FOLDER and ARTICLE.
9491 If ARTICLE is nil FOLDER is shown. If the configuration variable
9492 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9493 ARTICLE is searched in all folders. Indexed searches (swish++,
9494 namazu, and others supported by MH-E) will always search in all
9497 (require 'mh-search)
9501 (mh-visit-folder (mh-normalize-folder-name folder))
9502 (setq article (org-add-angle-brackets article))
9504 (if (equal mh-searcher 'pick)
9506 (mh-search folder (list "--message-id" article))
9507 (when (and org-mhe-search-all-folders
9508 (not (org-mhe-get-message-real-folder)))
9510 (mh-search "+" (list "--message-id" article))))
9511 (mh-search "+" article))
9512 (if (org-mhe-get-message-real-folder)
9515 (error "Message not found"))))
9519 ;; Use the custom search meachnism to construct and use search strings for
9520 ;; file links to BibTeX database entries.
9522 (defun org-create-file-search-in-bibtex ()
9523 "Create the search string and description for a BibTeX database entry."
9524 (when (eq major-mode 'bibtex-mode)
9525 ;; yes, we want to construct this search string.
9526 ;; Make a good description for this entry, using names, year and the title
9527 ;; Put it into the `description' variable which is dynamically scoped.
9528 (let ((bibtex-autokey-names 1)
9529 (bibtex-autokey-names-stretch 1)
9530 (bibtex-autokey-name-case-convert-function 'identity)
9531 (bibtex-autokey-name-separator " & ")
9532 (bibtex-autokey-additional-names " et al.")
9533 (bibtex-autokey-year-length 4)
9534 (bibtex-autokey-name-year-separator " ")
9535 (bibtex-autokey-titlewords 3)
9536 (bibtex-autokey-titleword-separator " ")
9537 (bibtex-autokey-titleword-case-convert-function 'identity)
9538 (bibtex-autokey-titleword-length 'infty)
9539 (bibtex-autokey-year-title-separator ": "))
9540 (setq description (bibtex-generate-autokey)))
9541 ;; Now parse the entry, get the key and return it.
9543 (bibtex-beginning-of-entry)
9544 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9546 (defun org-execute-file-search-in-bibtex (s)
9547 "Find the link search string S as a key for a database entry."
9548 (when (eq major-mode 'bibtex-mode)
9549 ;; Yes, we want to do the search in this file.
9550 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9551 (goto-char (point-min))
9552 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9553 (regexp-quote s) "[ \t\n]*,") nil t)
9554 (goto-char (match-beginning 0)))
9555 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9556 ;; Use double prefix to indicate that any web link should be browsed
9557 (let ((b (current-buffer)) (p (point)))
9558 ;; Restore the window configuration because we just use the web link
9559 (set-window-configuration org-window-config-before-follow-link)
9560 (save-excursion (set-buffer b) (goto-char p)
9562 (recenter 0)) ; Move entry start to beginning of window
9563 ;; return t to indicate that the search is done.
9566 ;; Finally add the functions to the right hooks.
9567 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9568 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9570 ;; end of Bibtex link setup
9572 (defun org-upgrade-old-links (&optional query-description)
9573 "Transfer old <...> style links to new [[...]] style links.
9574 With arg query-description, ask at each match for a description text to use
9576 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
9578 (goto-char (point-min))
9579 (let ((re (concat "\\([^[]\\)<\\("
9580 "\\(" (mapconcat 'identity org-link-types "\\|")
9582 "[^" org-non-link-chars "]+\\)>"))
9584 (while (re-search-forward re nil t)
9586 l1 (org-match-string-no-properties 2)
9587 l2 (save-match-data (org-link-escape l1)))
9588 (when query-description (setq l1 (read-string "Desc: " l1)))
9590 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
9591 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
9592 (message "%d matches have beed treated" cnt))))
9594 (defun org-open-file (path &optional in-emacs line search)
9595 "Open the file at PATH.
9596 First, this expands any special file name abbreviations. Then the
9597 configuration variable `org-file-apps' is checked if it contains an
9598 entry for this file type, and if yes, the corresponding command is launched.
9599 If no application is found, Emacs simply visits the file.
9600 With optional argument IN-EMACS, Emacs will visit the file.
9601 Optional LINE specifies a line to go to, optional SEARCH a string to
9602 search for. If LINE or SEARCH is given, the file will always be
9604 If the file does not exist, an error is thrown."
9605 (setq in-emacs (or in-emacs line search))
9606 (let* ((file (if (equal path "")
9609 (apps (append org-file-apps (org-default-apps)))
9610 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9611 (dirp (if remp nil (file-directory-p file)))
9612 (dfile (downcase file))
9613 (old-buffer (current-buffer))
9615 (old-mode major-mode)
9617 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9618 (setq ext (match-string 1 dfile))
9619 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9620 (setq ext (match-string 1 dfile))))
9623 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9624 (and dirp (cdr (assoc 'directory apps)))
9625 (cdr (assoc ext apps))
9626 (cdr (assoc t apps)))))
9627 (when (eq cmd 'mailcap)
9629 (mailcap-parse-mailcaps)
9630 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9631 (command (mailcap-mime-info mime-type)))
9632 (if (stringp command)
9634 (setq cmd 'emacs))))
9635 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
9636 (not (file-exists-p file))
9637 (not org-open-non-existing-files))
9638 (error "No such file: %s" file))
9640 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9641 ;; Normalize use of quote, this can vary.
9642 (if (string-match "['\"]%s['\"]" cmd)
9643 (setq cmd (replace-match "'%s'" t t cmd)))
9644 (setq cmd (format cmd file))
9645 (save-window-excursion
9646 (shell-command (concat cmd " &"))))
9649 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
9650 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
9651 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9652 (if line (goto-line line)
9653 (if search (org-link-search search))))
9656 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9657 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
9658 (or (not (equal old-buffer (current-buffer)))
9659 (not (equal old-pos (point))))
9660 (org-mark-ring-push old-pos old-buffer))))
9662 (defun org-default-apps ()
9663 "Return the default applications for this operating system."
9665 ((eq system-type 'darwin)
9666 org-file-apps-defaults-macosx)
9667 ((eq system-type 'windows-nt)
9668 org-file-apps-defaults-windowsnt)
9669 (t org-file-apps-defaults-gnu)))
9671 (defun org-expand-file-name (path)
9672 "Replace special path abbreviations and expand the file name."
9673 (expand-file-name path))
9675 (defun org-file-remote-p (file)
9676 "Test whether FILE specifies a location on a remote system.
9677 Return non-nil if the location is indeed remote.
9679 For example, the filename \"/user@host:/foo\" specifies a location
9680 on the system \"/user@host:\"."
9681 (cond ((fboundp 'file-remote-p)
9682 (file-remote-p file))
9683 ((fboundp 'tramp-handle-file-remote-p)
9684 (tramp-handle-file-remote-p file))
9685 ((and (boundp 'ange-ftp-name-format)
9686 (string-match ange-ftp-name-format file))
9690 (defvar org-insert-link-history nil
9691 "Minibuffer history for links inserted with `org-insert-link'.")
9693 (defvar org-stored-links nil
9694 "Contains the links stored with `org-store-link'.")
9697 (defun org-store-link (arg)
9698 "\\<org-mode-map>Store an org-link to the current location.
9699 This link can later be inserted into an org-buffer with
9700 \\[org-insert-link].
9701 For some link types, a prefix arg is interpreted:
9702 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9703 For file links, arg negates `org-context-in-file-links'."
9705 (let (link cpltxt desc description search txt (pos (point)))
9708 ((eq major-mode 'bbdb-mode)
9709 (setq cpltxt (concat
9711 (or (bbdb-record-name (bbdb-current-record))
9712 (bbdb-record-company (bbdb-current-record))))
9713 link (org-make-link cpltxt)))
9715 ((eq major-mode 'Info-mode)
9716 (setq link (org-make-link "info:"
9717 (file-name-nondirectory Info-current-file)
9718 ":" Info-current-node))
9719 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9720 ":" Info-current-node)))
9722 ((eq major-mode 'calendar-mode)
9723 (let ((cd (calendar-cursor-to-date)))
9726 (car org-time-stamp-formats)
9728 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9731 ((or (eq major-mode 'vm-summary-mode)
9732 (eq major-mode 'vm-presentation-mode))
9733 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9734 (vm-follow-summary-cursor)
9736 (vm-select-folder-buffer)
9737 (let* ((message (car vm-message-pointer))
9738 (folder buffer-file-name)
9739 (subject (vm-su-subject message))
9740 (author (vm-su-full-name message))
9741 (message-id (vm-su-message-id message)))
9742 (setq message-id (org-remove-angle-brackets message-id))
9743 (setq folder (abbreviate-file-name folder))
9744 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9746 (setq folder (replace-match "" t t folder)))
9747 (setq cpltxt (concat author " on: " subject))
9748 (setq link (org-make-link "vm:" folder "#" message-id)))))
9750 ((eq major-mode 'wl-summary-mode)
9751 (let* ((msgnum (wl-summary-message-number))
9752 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9753 msgnum 'message-id))
9754 (wl-message-entity (elmo-msgdb-overview-get-entity
9755 msgnum (wl-summary-buffer-msgdb)))
9756 (author (wl-summary-line-from)) ; FIXME: correct?
9757 (subject "???")) ; FIXME:
9758 (setq message-id (org-remove-angle-brackets message-id))
9759 (setq cpltxt (concat author " on: " subject))
9760 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9763 ((or (equal major-mode 'mh-folder-mode)
9764 (equal major-mode 'mh-show-mode))
9765 (let ((from-header (org-mhe-get-header "From:"))
9766 (to-header (org-mhe-get-header "To:"))
9767 (subject (org-mhe-get-header "Subject:")))
9768 (setq cpltxt (concat from-header " on: " subject))
9769 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9770 (org-remove-angle-brackets
9771 (org-mhe-get-header "Message-Id:"))))))
9773 ((eq major-mode 'rmail-mode)
9776 (rmail-narrow-to-non-pruned-header)
9777 (let ((folder buffer-file-name)
9778 (message-id (mail-fetch-field "message-id"))
9779 (author (mail-fetch-field "from"))
9780 (subject (mail-fetch-field "subject")))
9781 (setq message-id (org-remove-angle-brackets message-id))
9782 (setq cpltxt (concat author " on: " subject))
9783 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9785 ((eq major-mode 'gnus-group-mode)
9786 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9787 (gnus-group-group-name)) ; version
9788 ((fboundp 'gnus-group-name)
9791 (setq cpltxt (concat
9792 (if (org-xor arg org-usenet-links-prefer-google)
9793 "http://groups.google.com/groups?group="
9796 link (org-make-link cpltxt))))
9798 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9799 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9800 (gnus-summary-beginning-of-article)
9801 (let* ((group (car gnus-article-current))
9802 (article (cdr gnus-article-current))
9803 (header (gnus-summary-article-header article))
9804 (author (mail-header-from header))
9805 (message-id (mail-header-id header))
9806 (date (mail-header-date header))
9807 (subject (gnus-summary-subject-string)))
9808 (setq cpltxt (concat author " on: " subject))
9809 (if (org-xor arg org-usenet-links-prefer-google)
9813 (format "http://groups.google.com/groups?as_umsgid=%s"
9814 (org-fixup-message-id-for-http message-id))))
9815 (setq link (org-make-link "gnus:" group
9816 "#" (number-to-string article))))))
9818 ((eq major-mode 'w3-mode)
9819 (setq cpltxt (url-view-url t)
9820 link (org-make-link cpltxt)))
9821 ((eq major-mode 'w3m-mode)
9822 (setq cpltxt (or w3m-current-title w3m-current-url)
9823 link (org-make-link w3m-current-url)))
9825 ((setq search (run-hook-with-args-until-success
9826 'org-create-file-search-functions))
9827 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9829 (setq cpltxt (or description link)))
9831 ((eq major-mode 'image-mode)
9832 (setq cpltxt (concat "file:"
9833 (abbreviate-file-name buffer-file-name))
9834 link (org-make-link cpltxt)))
9836 ((eq major-mode 'org-mode)
9837 ;; Just link to current headline
9838 (setq cpltxt (concat "file:"
9839 (abbreviate-file-name buffer-file-name)))
9840 ;; Add a context search string
9841 (when (org-xor org-context-in-file-links arg)
9842 ;; Check if we are on a target
9844 (skip-chars-forward "^>\n\r")
9845 (and (re-search-backward "<<" nil t)
9846 (looking-at "<<\\(.*?\\)>>")
9847 (<= (match-beginning 0) pos)
9848 (>= (match-end 0) pos)))
9849 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9851 ((org-on-heading-p) nil)
9852 ((org-region-active-p)
9853 (buffer-substring (region-beginning) (region-end)))
9854 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9855 (when (or (null txt) (string-match "\\S-" txt))
9858 (if org-file-link-context-use-camel-case
9859 (org-make-org-heading-camel txt)
9860 (org-make-org-heading-search-string txt)))
9862 (if (string-match "::\\'" cpltxt)
9863 (setq cpltxt (substring cpltxt 0 -2)))
9864 (setq link (org-make-link cpltxt)))
9867 ;; Just link to this file here.
9868 (setq cpltxt (concat "file:"
9869 (abbreviate-file-name buffer-file-name)))
9870 ;; Add a context string
9871 (when (org-xor org-context-in-file-links arg)
9872 (setq txt (if (org-region-active-p)
9873 (buffer-substring (region-beginning) (region-end))
9874 (buffer-substring (point-at-bol) (point-at-eol))))
9875 ;; Only use search option if there is some text.
9876 (when (string-match "\\S-" txt)
9879 (if org-file-link-context-use-camel-case
9880 (org-make-org-heading-camel txt)
9881 (org-make-org-heading-search-string txt)))
9883 (setq link (org-make-link cpltxt)))
9886 (error "Cannot link to a buffer which is not visiting a file"))
9888 (t (setq link nil)))
9890 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9891 (setq link (or link cpltxt)
9892 desc (or desc cpltxt))
9893 (if (equal desc "NONE") (setq desc nil))
9895 (if (and (interactive-p) link)
9897 (setq org-stored-links
9898 (cons (list cpltxt link desc) org-stored-links))
9899 (message "Stored: %s" (or cpltxt link)))
9900 (org-make-link-string link desc))))
9902 (defun org-make-org-heading-search-string (&optional string heading)
9903 "Make search string for STRING or current headline."
9905 (let ((s (or string (org-get-heading))))
9906 (unless (and string (not heading))
9907 ;; We are using a headline, clean up garbage in there.
9908 (if (string-match org-todo-regexp s)
9909 (setq s (replace-match "" t t s)))
9910 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9911 (setq s (replace-match "" t t s)))
9912 (setq s (org-trim s))
9913 (if (string-match (concat "^\\(" org-quote-string "\\|"
9914 org-comment-string "\\)") s)
9915 (setq s (replace-match "" t t s)))
9916 (while (string-match org-ts-regexp s)
9917 (setq s (replace-match "" t t s))))
9918 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
9919 (setq s (replace-match " " t t s)))
9920 (or string (setq s (concat "*" s))) ; Add * for headlines
9921 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9923 (defun org-make-org-heading-camel (&optional string heading)
9924 "Make a CamelCase string for STRING or the current headline."
9926 (let ((s (or string (org-get-heading))))
9927 (unless (and string (not heading))
9928 ;; We are using a headline, clean up garbage in there.
9929 (if (string-match org-todo-regexp s)
9930 (setq s (replace-match "" t t s)))
9931 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9932 (setq s (replace-match "" t t s)))
9933 (setq s (org-trim s))
9934 (if (string-match (concat "^\\(" org-quote-string "\\|"
9935 org-comment-string "\\)") s)
9936 (setq s (replace-match "" t t s)))
9937 (while (string-match org-ts-regexp s)
9938 (setq s (replace-match "" t t s))))
9939 (while (string-match "[^a-zA-Z_ \t]+" s)
9940 (setq s (replace-match " " t t s)))
9941 (or string (setq s (concat "*" s))) ; Add * for headlines
9942 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
9944 (defun org-make-link (&rest strings)
9945 "Concatenate STRINGS, format resulting string with `org-link-format'."
9946 (format org-link-format (apply 'concat strings)))
9948 (defun org-make-link-string (link &optional description)
9949 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9950 (if (eq org-link-style 'plain)
9951 (if (equal description link)
9953 (concat description "\n" link))
9954 (when (stringp description)
9955 ;; Remove brackets from the description, they are fatal.
9956 (while (string-match "\\[\\|\\]" description)
9957 (setq description (replace-match "" t t description))))
9958 (when (equal (org-link-escape link) description)
9959 ;; No description needed, it is identical
9960 (setq description nil))
9961 (when (and (not description)
9962 (not (equal link (org-link-escape link))))
9963 (setq description link))
9964 (concat "[[" (org-link-escape link) "]"
9965 (if description (concat "[" description "]") "")
9968 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9969 "Association list of escapes for some characters problematic in links.")
9971 (defun org-link-escape (text)
9972 "Escape charaters in TEXT that are problematic for links."
9974 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9975 org-link-escape-chars "\\|")))
9976 (while (string-match re text)
9979 (cdr (assoc (match-string 0 text) org-link-escape-chars))
9983 (defun org-link-unescape (text)
9984 "Reverse the action of `org-link-escape'."
9986 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
9987 org-link-escape-chars "\\|")))
9988 (while (string-match re text)
9991 (car (rassoc (match-string 0 text) org-link-escape-chars))
9995 (defun org-xor (a b)
9999 (defun org-get-header (header)
10000 "Find a header field in the current buffer."
10002 (goto-char (point-min))
10003 (let ((case-fold-search t) s)
10006 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10007 (setq s (match-string 1)))
10008 (while (string-match "\"" s)
10009 (setq s (replace-match "" t t s)))
10010 (if (string-match "[<(].*" s)
10011 (setq s (replace-match "" t t s))))
10012 ((eq header 'message-id)
10013 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10014 (setq s (match-string 1))))
10015 ((eq header 'subject)
10016 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10017 (setq s (match-string 1)))))
10018 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10019 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10023 (defun org-fixup-message-id-for-http (s)
10024 "Replace special characters in a message id, so it can be used in an http query."
10025 (while (string-match "<" s)
10026 (setq s (replace-match "%3C" t t s)))
10027 (while (string-match ">" s)
10028 (setq s (replace-match "%3E" t t s)))
10029 (while (string-match "@" s)
10030 (setq s (replace-match "%40" t t s)))
10033 (defun org-insert-link (&optional complete-file)
10034 "Insert a link. At the prompt, enter the link.
10036 Completion can be used to select a link previously stored with
10037 `org-store-link'. When the empty string is entered (i.e. if you just
10038 press RET at the prompt), the link defaults to the most recently
10039 stored link. As SPC triggers completion in the minibuffer, you need to
10040 use M-SPC or C-q SPC to force the insertion of a space character.
10042 You will also be prompted for a description, and if one is given, it will
10043 be displayed in the buffer instead of the link.
10045 If there is already a link at point, this command will allow you to edit link
10046 and description parts.
10048 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10049 selected using completion. The path to the file will be relative to
10050 the current directory if the file is in the current directory or a
10051 subdirectory. Otherwise, the link will be the absolute path as
10052 completed in the minibuffer (i.e. normally ~/path/to/file).
10054 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10055 is in the current directory or below.
10056 With three \\[universal-argument] prefixes, negate the meaning of
10057 `org-keep-stored-link-after-insertion'."
10059 (let (link desc entry remove file (pos (point)))
10062 (skip-chars-forward "^]\n\r")
10063 (and (re-search-backward "\\[\\[" nil t)
10064 (looking-at org-bracket-link-regexp)
10065 (<= (match-beginning 0) pos)
10066 (>= (match-end 0) pos)))
10067 ;; We do have a link at point, and we are going to edit it.
10068 (setq remove (list (match-beginning 0) (match-end 0)))
10069 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10070 (setq link (read-string "Link: "
10072 (org-match-string-no-properties 1)))))
10073 ((equal complete-file '(4))
10074 ;; Completing read for file names.
10075 (setq file (read-file-name "File: "))
10076 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10077 (pwd1 (file-name-as-directory (abbreviate-file-name
10078 (expand-file-name ".")))))
10080 ((equal complete-file '(16))
10081 (setq link (org-make-link
10083 (abbreviate-file-name (expand-file-name file)))))
10084 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10085 (setq link (org-make-link "file:" (match-string 1 file))))
10086 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10087 (expand-file-name file))
10088 (setq link (org-make-link
10089 "file:" (match-string 1 (expand-file-name file)))))
10090 (t (setq link (org-make-link "file:" file))))))
10092 ;; Read link, with completion for stored links.
10093 (setq link (org-completing-read
10094 "Link: " org-stored-links nil nil nil
10095 org-insert-link-history
10096 (or (car (car org-stored-links)))))
10097 (setq entry (assoc link org-stored-links))
10098 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10099 (not org-keep-stored-link-after-insertion))
10100 (setq org-stored-links (delq (assoc link org-stored-links)
10101 org-stored-links)))
10102 (setq link (if entry (nth 1 entry) link)
10103 desc (or desc (nth 2 entry)))))
10105 (if (string-match org-plain-link-re link)
10106 ;; URL-like link, normalize the use of angular brackets.
10107 (setq link (org-make-link (org-remove-angle-brackets link))))
10109 ;; Check if we are linking to the current file with a search option
10110 ;; If yes, simplify the link by using only the search option.
10111 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
10112 (let* ((path (match-string 1 link))
10113 (case-fold-search nil)
10114 (search (match-string 2 link)))
10116 (if (equal (file-truename buffer-file-name) (file-truename path))
10117 ;; We are linking to this same file, with a search option
10118 (setq link search)))))
10120 ;; Check if we can/should use a relative path. If yes, simplify the link
10121 (when (string-match "\\<file:\\(.*\\)" link)
10122 (let* ((path (match-string 1 link))
10123 (case-fold-search nil))
10125 ((eq org-link-file-path-type 'absolute)
10126 (setq path (abbreviate-file-name (expand-file-name path))))
10127 ((eq org-link-file-path-type 'noabbrev)
10128 (setq path (expand-file-name path)))
10129 ((eq org-link-file-path-type 'relative)
10130 (setq path (file-relative-name path)))
10133 (if (string-match (concat "^" (regexp-quote
10134 (file-name-as-directory
10135 (expand-file-name "."))))
10136 (expand-file-name path))
10137 ;; We are linking a file with relative path name.
10138 (setq path (substring (expand-file-name path)
10139 (match-end 0)))))))
10140 (setq link (concat "file:" path))))
10142 (setq desc (read-string "Description: " desc))
10143 (unless (string-match "\\S-" desc) (setq desc nil))
10144 (if remove (apply 'delete-region remove))
10145 (insert (org-make-link-string link desc))))
10147 (defun org-completing-read (&rest args)
10148 (let ((minibuffer-local-completion-map
10149 (copy-keymap minibuffer-local-completion-map)))
10150 (define-key minibuffer-local-completion-map " " 'self-insert-command)
10151 (apply 'completing-read args)))
10153 ;;; Hooks for remember.el
10155 (defvar org-finish-function nil)
10158 (defun org-remember-annotation ()
10159 "Return a link to the current location as an annotation for remember.el.
10160 If you are using Org-mode files as target for data storage with
10161 remember.el, then the annotations should include a link compatible with the
10162 conventions in Org-mode. This function returns such a link."
10163 (org-store-link nil))
10165 (defconst org-remember-help
10166 "Select a destination location for the note.
10167 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10168 RET at beg-of-buf -> Append to file as level 2 headline
10169 RET on headline -> Store as sublevel entry to current headline
10170 <left>/<right> -> before/after current headline, same headings level")
10173 (defun org-remember-apply-template ()
10174 "Initialize *remember* buffer with template, invoke `org-mode'.
10175 This function should be placed into `remember-mode-hook' and in fact requires
10176 to be run from that hook to fucntion properly."
10177 (if org-remember-templates
10179 (let* ((entry (if (= (length org-remember-templates) 1)
10180 (cdar org-remember-templates)
10181 (message "Select template: %s"
10183 (lambda (x) (char-to-string (car x)))
10184 org-remember-templates " "))
10185 (cdr (assoc (read-char-exclusive) org-remember-templates))))
10187 (file (if (consp (cdr entry)) (nth 1 entry)))
10188 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10189 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10190 (v-u (concat "[" (substring v-t 1 -1) "]"))
10191 (v-U (concat "[" (substring v-T 1 -1) "]"))
10192 (v-a annotation) ; defined in `remember-mode'
10193 (v-i initial) ; defined in `remember-mode'
10194 (v-n user-full-name)
10196 (unless tpl (setq tpl "") (message "No template") (ding))
10197 (insert tpl) (goto-char (point-min))
10198 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
10199 (when (and initial (equal (match-string 0) "%i"))
10201 (let* ((lead (buffer-substring
10202 (point-at-bol) (match-beginning 0))))
10203 (setq v-i (mapconcat 'identity
10204 (org-split-string initial "\n")
10205 (concat "\n" lead))))))
10207 (or (eval (intern (concat "v-" (match-string 1)))) "")
10209 (let ((org-startup-folded nil)
10210 (org-startup-with-deadline-check nil))
10212 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10213 (set (make-local-variable 'org-default-notes-file) file))
10214 (goto-char (point-min))
10215 (if (re-search-forward "%\\?" nil t) (replace-match "")))
10216 (let ((org-startup-folded nil)
10217 (org-startup-with-deadline-check nil))
10219 (set (make-local-variable 'org-finish-function) 'remember-buffer))
10222 (defun org-remember-handler ()
10223 "Store stuff from remember.el into an org file.
10224 First prompts for an org file. If the user just presses return, the value
10225 of `org-default-notes-file' is used.
10226 Then the command offers the headings tree of the selected file in order to
10227 file the text at a specific location.
10228 You can either immediately press RET to get the note appended to the
10229 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10230 find a better place. Then press RET or <left> or <right> in insert the note.
10232 Key Cursor position Note gets inserted
10233 -----------------------------------------------------------------------------
10234 RET buffer-start as level 2 heading at end of file
10235 RET on headline as sublevel of the heading at cursor
10236 RET no heading at cursor position, level taken from context.
10237 Or use prefix arg to specify level manually.
10238 <left> on headline as same level, before current heading
10239 <right> on headline as same level, after current heading
10241 So the fastest way to store the note is to press RET RET to append it to
10242 the default file. This way your current train of thought is not
10243 interrupted, in accordance with the principles of remember.el. But with
10244 little extra effort, you can push it directly to the correct location.
10246 Before being stored away, the function ensures that the text has a
10247 headline, i.e. a first line that starts with a \"*\". If not, a headline
10248 is constructed from the current date and some additional data.
10250 If the variable `org-adapt-indentation' is non-nil, the entire text is
10251 also indented so that it starts in the same column as the headline
10252 \(i.e. after the stars).
10254 See also the variable `org-reverse-note-order'."
10256 (let* ((txt (buffer-substring (point-min) (point-max)))
10257 (fastp current-prefix-arg)
10258 (file (if fastp org-default-notes-file (org-get-org-file)))
10259 (visiting (find-buffer-visiting file))
10260 (org-startup-with-deadline-check nil)
10261 (org-startup-folded nil)
10262 (org-startup-align-all-tables nil)
10263 spos level indent reversed)
10264 ;; Modify text so that it becomes a nice subtree which can be inserted
10265 ;; into an org tree.
10266 (let* ((lines (split-string txt "\n"))
10268 ;; remove empty lines at the beginning
10269 (while (and lines (string-match "^[ \t]*\n" (car lines)))
10270 (setq lines (cdr lines)))
10271 (setq first (car lines) lines (cdr lines))
10272 (if (string-match "^\\*+" first)
10273 ;; Is already a headline
10275 ;; We need to add a headline: Use time and first buffer line
10276 (setq lines (cons first lines)
10277 first (concat "* " (current-time-string)
10278 " (" (remember-buffer-desc) ")")
10280 (if (and org-adapt-indentation indent)
10281 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10282 (setq txt (concat first "\n"
10283 (mapconcat 'identity lines "\n"))))
10286 (find-file-noselect file))
10287 (with-current-buffer (get-file-buffer file)
10288 (save-excursion (and (goto-char (point-min))
10289 (not (re-search-forward "^\\* " nil t))
10290 (insert "\n* Notes\n")))
10291 (setq reversed (org-notes-order-reversed-p))
10295 ;; Ask the User for a location
10296 (setq spos (if fastp 1 (org-get-location
10298 org-remember-help)))
10299 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10300 ; not handle this note
10303 ;; Put it at the start or end, as level 2
10306 (goto-char (if reversed (point-min) (point-max)))
10307 (if (not (bolp)) (newline))
10308 (org-paste-subtree 2 txt)))
10309 ((and (org-on-heading-p nil) (not current-prefix-arg))
10310 ;; Put it below this entry, at the beg/end of the subtree
10311 (org-back-to-heading)
10312 (setq level (funcall outline-level))
10314 (outline-end-of-heading)
10315 (outline-end-of-subtree))
10316 (if (not (bolp)) (newline))
10317 (beginning-of-line 1)
10318 (org-paste-subtree (1+ level) txt))
10320 ;; Put it right there, with automatic level determined by
10321 ;; org-paste-subtree or from prefix arg
10322 (org-paste-subtree current-prefix-arg txt)))
10323 (when remember-save-after-remembering
10325 (if (not visiting) (kill-buffer (current-buffer)))))))))
10326 t) ;; return t to indicate that we took care of this note.
10328 (defun org-get-org-file ()
10329 "Read a filename, with default directory `org-directory'."
10330 (let ((default (or org-default-notes-file remember-data-file)))
10331 (read-file-name (format "File name [%s]: " default)
10332 (file-name-as-directory org-directory)
10335 (defun org-notes-order-reversed-p ()
10336 "Check if the current file should receive notes in reversed order."
10338 ((not org-reverse-note-order) nil)
10339 ((eq t org-reverse-note-order) t)
10340 ((not (listp org-reverse-note-order)) nil)
10342 (let ((all org-reverse-note-order)
10344 (while (setq entry (pop all))
10345 (if (string-match (car entry) buffer-file-name)
10346 (throw 'exit (cdr entry))))
10351 ;; Watch out: Here we are talking about two different kind of tables.
10352 ;; Most of the code is for the tables created with the Org-mode table editor.
10353 ;; Sometimes, we talk about tables created and edited with the table.el
10354 ;; Emacs package. We call the former org-type tables, and the latter
10355 ;; table.el-type tables.
10358 (defun org-before-change-function (beg end)
10359 "Every change indicates that a table might need an update."
10360 (setq org-table-may-need-update t))
10362 (defconst org-table-line-regexp "^[ \t]*|"
10363 "Detects an org-type table line.")
10364 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
10365 "Detects an org-type table line.")
10366 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
10367 "Detects a table line marked for automatic recalculation.")
10368 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
10369 "Detects a table line marked for automatic recalculation.")
10370 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
10371 "Detects a table line marked for automatic recalculation.")
10372 (defconst org-table-hline-regexp "^[ \t]*|-"
10373 "Detects an org-type table hline.")
10374 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
10375 "Detects a table-type table hline.")
10376 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
10377 "Detects an org-type or table-type table.")
10378 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
10379 "Searching from within a table (any type) this finds the first line
10380 outside the table.")
10381 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
10382 "Searching from within a table (any type) this finds the first line
10383 outside the table.")
10385 (defun org-table-create-with-table.el ()
10386 "Use the table.el package to insert a new table.
10387 If there is already a table at point, convert between Org-mode tables
10388 and table.el tables."
10392 ((org-at-table.el-p)
10393 (if (y-or-n-p "Convert table to Org-mode table? ")
10394 (org-table-convert)))
10396 (if (y-or-n-p "Convert table to table.el table? ")
10397 (org-table-convert)))
10398 (t (call-interactively 'table-insert))))
10400 (defun org-table-create-or-convert-from-region (arg)
10401 "Convert region to table, or create an empty table.
10402 If there is an active region, convert it to a table. If there is no such
10403 region, create an empty table."
10405 (if (org-region-active-p)
10406 (org-table-convert-region (region-beginning) (region-end) arg)
10407 (org-table-create arg)))
10409 (defun org-table-create (&optional size)
10410 "Query for a size and insert a table skeleton.
10411 SIZE is a string Columns x Rows like for example \"3x2\"."
10414 (setq size (read-string
10415 (concat "Table size Columns x Rows [e.g. "
10416 org-table-default-size "]: ")
10417 "" nil org-table-default-size)))
10419 (let* ((pos (point))
10420 (indent (make-string (current-column) ?\ ))
10421 (split (org-split-string size " *x *"))
10422 (rows (string-to-number (nth 1 split)))
10423 (columns (string-to-number (car split)))
10424 (line (concat (apply 'concat indent "|" (make-list columns " |"))
10426 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
10427 (point-at-bol) (point)))
10428 (beginning-of-line 1)
10430 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
10431 (dotimes (i rows) (insert line))
10434 ;; Insert a hline after the first row.
10439 (org-table-align)))
10441 (defun org-table-convert-region (beg0 end0 &optional nspace)
10442 "Convert region to a table.
10443 The region goes from BEG0 to END0, but these borders will be moved
10444 slightly, to make sure a beginning of line in the first line is included.
10445 When NSPACE is non-nil, it indicates the minimum number of spaces that
10446 separate columns (default: just one space)."
10448 (let* ((beg (min beg0 end0))
10449 (end (max beg0 end0))
10453 (beginning-of-line 1)
10454 (setq beg (move-marker (make-marker) (point)))
10456 (if (bolp) (backward-char 1) (end-of-line 1))
10457 (setq end (move-marker (make-marker) (point)))
10458 ;; Lets see if this is tab-separated material. If every nonempty line
10459 ;; contains a tab, we will assume that it is tab-separated material
10463 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
10464 (if nspace (setq tabsep nil))
10467 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
10468 (max 1 (prefix-numeric-value nspace)))))
10470 (while (re-search-forward re end t)
10471 (replace-match "|" t t))
10474 (org-table-align)))
10476 (defun org-table-import (file arg)
10477 "Import FILE as a table.
10478 The file is assumed to be tab-separated. Such files can be produced by most
10479 spreadsheet and database applications. If no tabs (at least one per line)
10480 are found, lines will be split on whitespace into fields."
10481 (interactive "f\nP")
10482 (or (bolp) (newline))
10483 (let ((beg (point))
10485 (insert-file-contents file)
10486 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
10488 (defun org-table-export ()
10489 "Export table as a tab-separated file.
10490 Such a file can be imported into a spreadsheet program like Excel."
10492 (let* ((beg (org-table-begin))
10493 (end (org-table-end))
10494 (table (buffer-substring beg end))
10495 (file (read-file-name "Export table to: "))
10497 (unless (or (not (file-exists-p file))
10498 (y-or-n-p (format "Overwrite file %s? " file)))
10500 (with-current-buffer (find-file-noselect file)
10501 (setq buf (current-buffer))
10505 (goto-char (point-min))
10506 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
10507 (replace-match "" t t)
10509 (goto-char (point-min))
10510 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
10511 (replace-match "" t t)
10512 (goto-char (min (1+ (point)) (point-max))))
10513 (goto-char (point-min))
10514 (while (re-search-forward "^-[-+]*$" nil t)
10516 (if (looking-at "\n")
10518 (goto-char (point-min))
10519 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
10520 (replace-match "\t" t t))
10522 (kill-buffer buf)))
10524 (defvar org-table-aligned-begin-marker (make-marker)
10525 "Marker at the beginning of the table last aligned.
10526 Used to check if cursor still is in that table, to minimize realignment.")
10527 (defvar org-table-aligned-end-marker (make-marker)
10528 "Marker at the end of the table last aligned.
10529 Used to check if cursor still is in that table, to minimize realignment.")
10530 (defvar org-table-last-alignment nil
10531 "List of flags for flushright alignment, from the last re-alignment.
10532 This is being used to correctly align a single field after TAB or RET.")
10533 (defvar org-table-last-column-widths nil
10534 "List of max width of fields in each column.
10535 This is being used to correctly align a single field after TAB or RET.")
10537 (defvar org-last-recalc-line nil)
10538 (defconst org-narrow-column-arrow "=>"
10539 "Used as display property in narrowed table columns.")
10541 (defun org-table-align ()
10542 "Align the table at point by aligning all vertical bars."
10546 (beg (org-table-begin))
10547 (end (org-table-end))
10548 ;; Current cursor position
10549 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10550 (colpos (org-table-current-column))
10551 (winstart (window-start))
10552 lines (new "") lengths l typenums ty fields maxfields i
10554 (indent "") cnt frac
10560 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
10562 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
10563 emptystrings links narrow fmax f1 len c e)
10565 (remove-text-properties beg end '(org-cwidth t display t))
10566 ;; Check if we have links
10568 (setq links (re-search-forward org-bracket-link-regexp end t))
10569 ;; Make sure the link properties are right
10570 (when links (goto-char beg) (while (org-activate-bracket-links end)))
10571 ;; Check if we are narrowing any columns
10573 (setq narrow (and org-format-transports-properties-p
10574 (re-search-forward "<[0-9]+>" end t)))
10576 (setq lines (org-split-string
10577 (buffer-substring beg end) "\n"))
10578 ;; Store the indentation of the first line
10579 (if (string-match "^ *" (car lines))
10580 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
10581 ;; Mark the hlines by setting the corresponding element to nil
10582 ;; At the same time, we remove trailing space.
10583 (setq lines (mapcar (lambda (l)
10584 (if (string-match "^ *|-" l)
10586 (if (string-match "[ \t]+$" l)
10587 (substring l 0 (match-beginning 0))
10590 ;; Get the data fields by splitting the lines.
10591 (setq fields (mapcar
10593 (org-split-string l " *| *"))
10594 (delq nil (copy-sequence lines))))
10595 ;; How many fields in the longest line?
10596 (condition-case nil
10597 (setq maxfields (apply 'max (mapcar 'length fields)))
10599 (kill-region beg end)
10600 (org-table-create org-table-default-size)
10601 (error "Empty table - created default table")))
10602 ;; A list of empty string to fill any short rows on output
10603 (setq emptystrings (make-list maxfields ""))
10604 ;; Check for special formatting.
10606 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
10607 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
10608 ;; Check if there is an explicit width specified
10609 (when (and org-table-limit-column-width narrow)
10610 (setq c column fmax nil)
10613 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
10614 (setq fmax (string-to-number (match-string 1 e)) c nil)))
10615 ;; Find fields that are wider than fmax, and shorten them
10617 (loop for xx in column do
10618 (when (and (stringp xx)
10619 (> (org-string-width xx) fmax))
10620 (org-add-props xx nil
10622 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
10623 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
10625 (error "Cannot narrow field starting with wide link \"%s\""
10626 (match-string 0 xx)))
10627 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
10628 (add-text-properties (- f1 2) f1
10629 (list 'display org-narrow-column-arrow)
10631 ;; Get the maximum width for each column
10632 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
10633 ;; Get the fraction of numbers, to decide about alignment of the column
10634 (setq cnt 0 frac 0.0)
10635 (loop for x in column do
10638 (setq frac ( / (+ (* frac cnt)
10639 (if (string-match org-table-number-regexp x) 1 0))
10640 (setq cnt (1+ cnt))))))
10641 (push (>= frac org-table-number-fraction) typenums))
10642 (setq lengths (nreverse lengths) typenums (nreverse typenums))
10644 ;; Store the alignment of this table, for later editing of single fields
10645 (setq org-table-last-alignment typenums
10646 org-table-last-column-widths lengths)
10648 ;; With invisible characters, `format' does not get the field width right
10649 ;; So we need to make these fields wide by hand.
10651 (loop for i from 0 upto (1- maxfields) do
10652 (setq len (nth i lengths))
10653 (loop for j from 0 upto (1- (length fields)) do
10654 (setq c (nthcdr i (car (nthcdr j fields))))
10655 (if (and (stringp (car c))
10656 (string-match org-bracket-link-regexp (car c))
10657 (< (org-string-width (car c)) len))
10658 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
10660 ;; Compute the formats needed for output of the table
10661 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
10662 (while (setq l (pop lengths))
10663 (setq ty (if (pop typenums) "" "-")) ; number types flushright
10664 (setq rfmt (concat rfmt (format rfmt1 ty l))
10665 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
10666 (setq rfmt (concat rfmt "\n")
10667 hfmt (concat (substring hfmt 0 -1) "|\n"))
10669 (setq new (mapconcat
10671 (if l (apply 'format rfmt
10672 (append (pop fields) emptystrings))
10675 ;; Replace the old one
10676 (delete-region beg end)
10677 (move-marker end nil)
10678 (move-marker org-table-aligned-begin-marker (point))
10680 (move-marker org-table-aligned-end-marker (point))
10681 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
10682 (goto-char org-table-aligned-begin-marker)
10683 (while (org-hide-wide-columns org-table-aligned-end-marker)))
10684 ;; Try to move to the old location (approximately)
10685 (goto-line linepos)
10686 (set-window-start (selected-window) winstart 'noforce)
10687 (org-table-goto-column colpos)
10688 (setq org-table-may-need-update nil)
10691 (defun org-string-width (s)
10692 "Compute width of string, ignoring invisible characters.
10693 This ignores character with invisibility property `org-link', and also
10694 characters with property `org-cwidth', because these will become invisible
10695 upon the next fontification round."
10697 (when (or (eq t buffer-invisibility-spec)
10698 (assq 'org-link buffer-invisibility-spec))
10699 (while (setq b (text-property-any 0 (length s)
10700 'invisible 'org-link s))
10701 (setq s (concat (substring s 0 b)
10702 (substring s (or (next-single-property-change
10703 b 'invisible s) (length s)))))))
10704 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
10705 (setq s (concat (substring s 0 b)
10706 (substring s (or (next-single-property-change
10707 b 'org-cwidth s) (length s))))))
10710 (defun org-table-begin (&optional table-type)
10711 "Find the beginning of the table and return its position.
10712 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
10714 (if (not (re-search-backward
10715 (if table-type org-table-any-border-regexp
10716 org-table-border-regexp)
10718 (progn (goto-char (point-min)) (point))
10719 (goto-char (match-beginning 0))
10720 (beginning-of-line 2)
10723 (defun org-table-end (&optional table-type)
10724 "Find the end of the table and return its position.
10725 With argument TABLE-TYPE, go to the end of a table.el-type table."
10727 (if (not (re-search-forward
10728 (if table-type org-table-any-border-regexp
10729 org-table-border-regexp)
10731 (goto-char (point-max))
10732 (goto-char (match-beginning 0)))
10735 (defun org-table-justify-field-maybe (&optional new)
10736 "Justify the current field, text to left, number to right.
10737 Optional argument NEW may specify text to replace the current field content."
10739 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
10740 ((org-at-table-hline-p))
10742 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
10744 (< (point) org-table-aligned-begin-marker)
10745 (>= (point) org-table-aligned-end-marker)))
10746 ;; This is not the same table, force a full re-align
10747 (setq org-table-may-need-update t))
10748 (t ;; realign the current field, based on previous full realign
10749 (let* ((pos (point)) s
10750 (col (org-table-current-column))
10751 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
10754 (skip-chars-backward "^|\n")
10755 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
10757 (setq s (match-string 1)
10759 l (max 1 (- (match-end 0) (match-beginning 0) 3))
10760 e (not (= (match-beginning 2) (match-end 2))))
10761 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
10762 l (if e "|" (setq org-table-may-need-update t) ""))
10765 (if (<= (length new) l) ;; FIXME: length -> str-width?
10766 (setq n (format f new))
10767 (setq n (concat new "|") org-table-may-need-update t)))
10769 (let (org-table-may-need-update)
10770 (replace-match n))))
10771 (setq org-table-may-need-update t))
10772 (goto-char pos))))))
10774 (defun org-table-next-field ()
10775 "Go to the next field in the current table, creating new lines as needed.
10776 Before doing so, re-align the table if necessary."
10778 (org-table-maybe-eval-formula)
10779 (org-table-maybe-recalculate-line)
10780 (if (and org-table-automatic-realign
10781 org-table-may-need-update)
10783 (let ((end (org-table-end)))
10784 (if (org-at-table-hline-p)
10786 (condition-case nil
10788 (re-search-forward "|" end)
10789 (if (looking-at "[ \t]*$")
10790 (re-search-forward "|" end))
10791 (if (and (looking-at "-")
10792 org-table-tab-jumps-over-hlines
10793 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
10794 (goto-char (match-beginning 1)))
10795 (if (looking-at "-")
10797 (beginning-of-line 0)
10798 (org-table-insert-row 'below))
10799 (if (looking-at " ") (forward-char 1))))
10801 (org-table-insert-row 'below)))))
10803 (defun org-table-previous-field ()
10804 "Go to the previous field in the table.
10805 Before doing so, re-align the table if necessary."
10807 (org-table-justify-field-maybe)
10808 (org-table-maybe-recalculate-line)
10809 (if (and org-table-automatic-realign
10810 org-table-may-need-update)
10812 (if (org-at-table-hline-p)
10814 (re-search-backward "|" (org-table-begin))
10815 (re-search-backward "|" (org-table-begin))
10816 (while (looking-at "|\\(-\\|[ \t]*$\\)")
10817 (re-search-backward "|" (org-table-begin)))
10818 (if (looking-at "| ?")
10819 (goto-char (match-end 0))))
10821 (defun org-table-next-row ()
10822 "Go to the next row (same column) in the current table.
10823 Before doing so, re-align the table if necessary."
10825 (org-table-maybe-eval-formula)
10826 (org-table-maybe-recalculate-line)
10827 (if (or (looking-at "[ \t]*$")
10828 (save-excursion (skip-chars-backward " \t") (bolp)))
10830 (if (and org-table-automatic-realign
10831 org-table-may-need-update)
10833 (let ((col (org-table-current-column)))
10834 (beginning-of-line 2)
10835 (if (or (not (org-at-table-p))
10836 (org-at-table-hline-p))
10838 (beginning-of-line 0)
10839 (org-table-insert-row 'below)))
10840 (org-table-goto-column col)
10841 (skip-chars-backward "^|\n\r")
10842 (if (looking-at " ") (forward-char 1)))))
10844 (defun org-table-copy-down (n)
10845 "Copy a field down in the current column.
10846 If the field at the cursor is empty, copy into it the content of the nearest
10847 non-empty field above. With argument N, use the Nth non-empty field.
10848 If the current field is not empty, it is copied down to the next row, and
10849 the cursor is moved with it. Therefore, repeating this command causes the
10850 column to be filled row-by-row.
10851 If the variable `org-table-copy-increment' is non-nil and the field is an
10852 integer, it will be incremented while copying."
10854 (let* ((colpos (org-table-current-column))
10855 (field (org-table-get-field))
10856 (non-empty (string-match "[^ \t]" field))
10857 (beg (org-table-begin))
10859 (org-table-check-inside-data-field)
10862 (setq txt (org-trim field))
10863 (org-table-next-row)
10864 (org-table-blank-field))
10868 (while (progn (beginning-of-line 1)
10869 (re-search-backward org-table-dataline-regexp
10871 (org-table-goto-column colpos t)
10872 (if (and (looking-at
10873 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
10874 (= (setq n (1- n)) 0))
10875 (throw 'exit (match-string 1))))))))
10878 (if (and org-table-copy-increment
10879 (string-match "^[0-9]+$" txt))
10880 (setq txt (format "%d" (+ (string-to-number txt) 1))))
10882 (org-table-maybe-recalculate-line)
10884 (error "No non-empty field found"))))
10886 (defun org-table-check-inside-data-field ()
10887 "Is point inside a table data field?
10888 I.e. not on a hline or before the first or after the last column?
10889 This actually throws an error, so it aborts the current command."
10890 (if (or (not (org-at-table-p))
10891 (= (org-table-current-column) 0)
10892 (org-at-table-hline-p)
10893 (looking-at "[ \t]*$"))
10894 (error "Not in table data field")))
10896 (defvar org-table-clip nil
10897 "Clipboard for table regions.")
10899 (defun org-table-blank-field ()
10900 "Blank the current table field or active region."
10902 (org-table-check-inside-data-field)
10903 (if (and (interactive-p) (org-region-active-p))
10904 (let (org-table-clip)
10905 (org-table-cut-region (region-beginning) (region-end)))
10906 (skip-chars-backward "^|")
10908 (if (looking-at "|[^|\n]+")
10909 (let* ((pos (match-beginning 0))
10910 (match (match-string 0))
10911 (len (org-string-width match)))
10912 (replace-match (concat "|" (make-string (1- len) ?\ )))
10913 (goto-char (+ 2 pos))
10914 (substring match 1)))))
10916 (defun org-table-get-field (&optional n replace)
10917 "Return the value of the field in column N of current row.
10918 N defaults to current field.
10919 If REPLACE is a string, replace field with this value. The return value
10920 is always the old value."
10921 (and n (org-table-goto-column n))
10922 (skip-chars-backward "^|\n")
10924 (if (looking-at "|[^|\r\n]*")
10925 (let* ((pos (match-beginning 0))
10926 (val (buffer-substring (1+ pos) (match-end 0))))
10928 (replace-match (concat "|" replace)))
10929 (goto-char (min (point-at-eol) (+ 2 pos)))
10931 (forward-char 1) ""))
10933 (defun org-table-current-column ()
10934 "Find out which column we are in.
10935 When called interactively, column is also displayed in echo area."
10937 (if (interactive-p) (org-table-check-inside-data-field))
10939 (let ((cnt 0) (pos (point)))
10940 (beginning-of-line 1)
10941 (while (search-forward "|" pos t)
10942 (setq cnt (1+ cnt)))
10943 (if (interactive-p) (message "This is table column %d" cnt))
10946 (defun org-table-goto-column (n &optional on-delim force)
10947 "Move the cursor to the Nth column in the current table line.
10948 With optional argument ON-DELIM, stop with point before the left delimiter
10950 If there are less than N fields, just go to after the last delimiter.
10951 However, when FORCE is non-nil, create new columns if necessary."
10953 (let ((pos (point-at-eol)))
10954 (beginning-of-line 1)
10956 (while (and (> (setq n (1- n)) -1)
10957 (or (search-forward "|" pos t)
10959 (progn (end-of-line 1)
10960 (skip-chars-backward "^|")
10961 (insert " | "))))))
10962 ; (backward-char 2) t)))))
10963 (when (and force (not (looking-at ".*|")))
10964 (save-excursion (end-of-line 1) (insert " | ")))
10967 (if (looking-at " ") (forward-char 1))))))
10969 (defun org-at-table-p (&optional table-type)
10970 "Return t if the cursor is inside an org-type table.
10971 If TABLE-TYPE is non-nil, also check for table.el-type tables."
10972 (if org-enable-table-editor
10974 (beginning-of-line 1)
10975 (looking-at (if table-type org-table-any-line-regexp
10976 org-table-line-regexp)))
10979 (defun org-at-table.el-p ()
10980 "Return t if and only if we are at a table.el table."
10981 (and (org-at-table-p 'any)
10983 (goto-char (org-table-begin 'any))
10984 (looking-at org-table1-hline-regexp))))
10986 (defun org-table-recognize-table.el ()
10987 "If there is a table.el table nearby, recognize it and move into it."
10988 (if org-table-tab-recognizes-table.el
10989 (if (org-at-table.el-p)
10991 (beginning-of-line 1)
10992 (if (looking-at org-table-dataline-regexp)
10994 (if (looking-at org-table1-hline-regexp)
10996 (beginning-of-line 2)
10997 (if (looking-at org-table-any-border-regexp)
10998 (beginning-of-line -1)))))
10999 (if (re-search-forward "|" (org-table-end t) t)
11002 (if (table--at-cell-p (point))
11004 (message "recognizing table.el table...")
11005 (table-recognize-table)
11006 (message "recognizing table.el table...done")))
11007 (error "This should not happen..."))
11012 (defun org-at-table-hline-p ()
11013 "Return t if the cursor is inside a hline in a table."
11014 (if org-enable-table-editor
11016 (beginning-of-line 1)
11017 (looking-at org-table-hline-regexp))
11020 (defun org-table-insert-column ()
11021 "Insert a new column into the table."
11023 (if (not (org-at-table-p))
11024 (error "Not at a table"))
11025 (org-table-find-dataline)
11026 (let* ((col (max 1 (org-table-current-column)))
11027 (beg (org-table-begin))
11028 (end (org-table-end))
11029 ;; Current cursor position
11030 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11033 (while (< (point) end)
11034 (if (org-at-table-hline-p)
11036 (org-table-goto-column col t)
11038 (beginning-of-line 2))
11039 (move-marker end nil)
11040 (goto-line linepos)
11041 (org-table-goto-column colpos)
11043 (org-table-modify-formulas 'insert col)))
11045 (defun org-table-find-dataline ()
11046 "Find a dataline in the current table, which is needed for column commands."
11047 (if (and (org-at-table-p)
11048 (not (org-at-table-hline-p)))
11050 (let ((col (current-column))
11051 (end (org-table-end)))
11052 (move-to-column col)
11053 (while (and (< (point) end)
11054 (or (not (= (current-column) col))
11055 (org-at-table-hline-p)))
11056 (beginning-of-line 2)
11057 (move-to-column col))
11058 (if (and (org-at-table-p)
11059 (not (org-at-table-hline-p)))
11062 "Please position cursor in a data line for column operations")))))
11064 (defun org-table-delete-column ()
11065 "Delete a column from the table."
11067 (if (not (org-at-table-p))
11068 (error "Not at a table"))
11069 (org-table-find-dataline)
11070 (org-table-check-inside-data-field)
11071 (let* ((col (org-table-current-column))
11072 (beg (org-table-begin))
11073 (end (org-table-end))
11074 ;; Current cursor position
11075 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11078 (while (< (point) end)
11079 (if (org-at-table-hline-p)
11081 (org-table-goto-column col t)
11082 (and (looking-at "|[^|\n]+|")
11083 (replace-match "|")))
11084 (beginning-of-line 2))
11085 (move-marker end nil)
11086 (goto-line linepos)
11087 (org-table-goto-column colpos)
11089 (org-table-modify-formulas 'remove col)))
11091 (defun org-table-move-column-right ()
11092 "Move column to the right."
11094 (org-table-move-column nil))
11095 (defun org-table-move-column-left ()
11096 "Move column to the left."
11098 (org-table-move-column 'left))
11100 (defun org-table-move-column (&optional left)
11101 "Move the current column to the right. With arg LEFT, move to the left."
11103 (if (not (org-at-table-p))
11104 (error "Not at a table"))
11105 (org-table-find-dataline)
11106 (org-table-check-inside-data-field)
11107 (let* ((col (org-table-current-column))
11108 (col1 (if left (1- col) col))
11109 (beg (org-table-begin))
11110 (end (org-table-end))
11111 ;; Current cursor position
11112 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11113 (colpos (if left (1- col) (1+ col))))
11114 (if (and left (= col 1))
11115 (error "Cannot move column further left"))
11116 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
11117 (error "Cannot move column further right"))
11119 (while (< (point) end)
11120 (if (org-at-table-hline-p)
11122 (org-table-goto-column col1 t)
11123 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
11124 (replace-match "|\\2|\\1|")))
11125 (beginning-of-line 2))
11126 (move-marker end nil)
11127 (goto-line linepos)
11128 (org-table-goto-column colpos)
11130 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
11132 (defun org-table-move-row-down ()
11133 "Move table row down."
11135 (org-table-move-row nil))
11136 (defun org-table-move-row-up ()
11137 "Move table row up."
11139 (org-table-move-row 'up))
11141 (defun org-table-move-row (&optional up)
11142 "Move the current table line down. With arg UP, move it up."
11144 (let ((col (current-column))
11146 (tonew (if up 0 2))
11148 (beginning-of-line tonew)
11149 (if (not (org-at-table-p))
11152 (error "Cannot move row further")))
11154 (beginning-of-line 1)
11156 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
11157 (delete-region (point) (1+ (point-at-eol)))
11158 (beginning-of-line tonew)
11160 (beginning-of-line 0)
11161 (move-to-column col)))
11163 (defun org-table-insert-row (&optional arg)
11164 "Insert a new row above the current line into the table.
11165 With prefix ARG, insert below the current line."
11167 (if (not (org-at-table-p))
11168 (error "Not at a table"))
11169 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
11170 (new (org-table-clean-line line)))
11171 ;; Fix the first field if necessary
11172 (if (string-match "^[ \t]*| *[#$] *|" line)
11173 (setq new (replace-match (match-string 0 line) t t new)))
11174 (beginning-of-line (if arg 2 1))
11175 (let (org-table-may-need-update) (insert-before-markers new "\n"))
11176 (beginning-of-line 0)
11177 (re-search-forward "| ?" (point-at-eol) t)
11178 (and org-table-may-need-update (org-table-align))))
11180 (defun org-table-insert-hline (&optional arg)
11181 "Insert a horizontal-line below the current line into the table.
11182 With prefix ARG, insert above the current line."
11184 (if (not (org-at-table-p))
11185 (error "Not at a table"))
11186 (let ((line (org-table-clean-line
11187 (buffer-substring (point-at-bol) (point-at-eol))))
11188 (col (current-column)))
11189 (while (string-match "|\\( +\\)|" line)
11190 (setq line (replace-match
11191 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
11192 ?-) "|") t t line)))
11193 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
11194 (beginning-of-line (if arg 1 2))
11196 (beginning-of-line (if arg 1 -1))
11197 (move-to-column col)))
11199 (defun org-table-clean-line (s)
11200 "Convert a table line S into a string with only \"|\" and space.
11201 In particular, this does handle wide and invisible characters."
11202 (if (string-match "^[ \t]*|-" s)
11203 ;; It's a hline, just map the characters
11204 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
11205 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
11206 (setq s (replace-match
11207 (concat "|" (make-string (org-string-width (match-string 1 s))
11212 (defun org-table-kill-row ()
11213 "Delete the current row or horizontal line from the table."
11215 (if (not (org-at-table-p))
11216 (error "Not at a table"))
11217 (let ((col (current-column)))
11218 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
11219 (if (not (org-at-table-p)) (beginning-of-line 0))
11220 (move-to-column col)))
11222 (defun org-table-sort-lines (beg end numericp)
11223 "Sort table lines in region.
11224 Point and mark define the first and last line to include. Both point and
11225 mark should be in the column that is used for sorting. For example, to
11226 sort according to column 3, put the mark in the first line to sort, in
11227 table column 3. Put point into the last line to be included in the sorting,
11228 also in table column 3. The command will prompt for the sorting method
11229 \(n for numerical, a for alphanumeric)."
11230 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
11231 (setq numericp (string-match "[nN]" numericp))
11232 (org-table-align) ;; Just to be safe
11233 (let* (bcol ecol cmp column lns)
11235 (org-table-check-inside-data-field)
11236 (setq column (org-table-current-column)
11237 beg (move-marker (make-marker) (point-at-bol)))
11239 (org-table-check-inside-data-field)
11240 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
11243 (org-table-goto-column column)
11244 (skip-chars-backward "^|")
11245 (setq bcol (current-column))
11246 (org-table-goto-column (1+ column))
11247 (skip-chars-backward "^|")
11248 (setq ecol (1- (current-column)))
11249 (setq cmp (if numericp
11250 (lambda (a b) (< (car a) (car b)))
11251 (lambda (a b) (string< (car a) (car b)))))
11252 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
11253 (org-split-string (buffer-substring beg end) "\n")))
11255 (setq lns (mapcar (lambda(x)
11256 (cons (string-to-number (car x)) (cdr x)))
11258 (delete-region beg end)
11259 (move-marker beg nil)
11260 (move-marker end nil)
11261 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
11262 (message "%d lines sorted %s based on column %d"
11264 (if numericp "numerically" "alphabetically") column)))
11266 (defun org-table-cut-region (beg end)
11267 "Copy region in table to the clipboard and blank all relevant fields."
11269 (org-table-copy-region beg end 'cut))
11271 (defun org-table-copy-region (beg end &optional cut)
11272 "Copy rectangular region in table to clipboard.
11273 A special clipboard is used which can only be accessed
11274 with `org-table-paste-rectangle'."
11276 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
11278 (rpl (if cut " " nil)))
11280 (org-table-check-inside-data-field)
11281 (setq l01 (count-lines (point-min) (point))
11282 c01 (org-table-current-column))
11284 (org-table-check-inside-data-field)
11285 (setq l02 (count-lines (point-min) (point))
11286 c02 (org-table-current-column))
11287 (setq l1 (min l01 l02) l2 (max l01 l02)
11288 c1 (min c01 c02) c2 (max c01 c02))
11292 (if (> l1 l2) (throw 'exit t))
11294 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
11295 (setq cols nil ic1 c1 ic2 c2)
11296 (while (< ic1 (1+ ic2))
11297 (push (org-table-get-field ic1 rpl) cols)
11298 (setq ic1 (1+ ic1)))
11299 (push (nreverse cols) region)
11300 (setq l1 (1+ l1)))))
11301 (setq org-table-clip (nreverse region))
11302 (if cut (org-table-align))
11305 (defun org-table-paste-rectangle ()
11306 "Paste a rectangular region into a table.
11307 The upper right corner ends up in the current field. All involved fields
11308 will be overwritten. If the rectangle does not fit into the present table,
11309 the table is enlarged as needed. The process ignores horizontal separator
11312 (unless (and org-table-clip (listp org-table-clip))
11313 (error "First cut/copy a region to paste!"))
11314 (org-table-check-inside-data-field)
11315 (let* ((clip org-table-clip)
11316 (line (count-lines (point-min) (point)))
11317 (col (org-table-current-column))
11318 (org-enable-table-editor t)
11319 (org-table-automatic-realign nil)
11321 (while (setq cols (pop clip))
11322 (while (org-at-table-hline-p) (beginning-of-line 2))
11323 (if (not (org-at-table-p))
11324 (progn (end-of-line 0) (org-table-next-field)))
11326 (while (setq field (pop cols))
11327 (org-table-goto-column c nil 'force)
11328 (org-table-get-field nil field)
11330 (beginning-of-line 2))
11332 (org-table-goto-column col)
11333 (org-table-align)))
11335 (defun org-table-convert ()
11336 "Convert from `org-mode' table to table.el and back.
11337 Obviously, this only works within limits. When an Org-mode table is
11338 converted to table.el, all horizontal separator lines get lost, because
11339 table.el uses these as cell boundaries and has no notion of horizontal lines.
11340 A table.el table can be converted to an Org-mode table only if it does not
11341 do row or column spanning. Multiline cells will become multiple cells.
11342 Beware, Org-mode does not test if the table can be successfully converted - it
11343 blindly applies a recipe that works for simple tables."
11346 (if (org-at-table.el-p)
11347 ;; convert to Org-mode table
11348 (let ((beg (move-marker (make-marker) (org-table-begin t)))
11349 (end (move-marker (make-marker) (org-table-end t))))
11350 (table-unrecognize-region beg end)
11352 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
11353 (replace-match ""))
11355 (if (org-at-table-p)
11356 ;; convert to table.el table
11357 (let ((beg (move-marker (make-marker) (org-table-begin)))
11358 (end (move-marker (make-marker) (org-table-end))))
11359 ;; first, get rid of all horizontal lines
11361 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
11362 (replace-match ""))
11363 ;; insert a hline before first
11365 (org-table-insert-hline 'above)
11366 (beginning-of-line -1)
11367 ;; insert a hline after each line
11368 (while (progn (beginning-of-line 3) (< (point) end))
11369 (org-table-insert-hline))
11371 (setq end (move-marker end (org-table-end)))
11372 ;; replace "+" at beginning and ending of hlines
11373 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
11374 (replace-match "\\1+-"))
11376 (while (re-search-forward "-|[ \t]*$" end t)
11377 (replace-match "-+"))
11378 (goto-char beg)))))
11380 (defun org-table-wrap-region (arg)
11381 "Wrap several fields in a column like a paragraph.
11382 This is useful if you'd like to spread the contents of a field over several
11383 lines, in order to keep the table compact.
11385 If there is an active region, and both point and mark are in the same column,
11386 the text in the column is wrapped to minimum width for the given number of
11387 lines. Generally, this makes the table more compact. A prefix ARG may be
11388 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
11389 formats the selected text to two lines. If the region was longer than two
11390 lines, the remaining lines remain empty. A negative prefix argument reduces
11391 the current number of lines by that amount. The wrapped text is pasted back
11392 into the table. If you formatted it to more lines than it was before, fields
11393 further down in the table get overwritten - so you might need to make space in
11396 If there is no region, the current field is split at the cursor position and
11397 the text fragment to the right of the cursor is prepended to the field one
11400 If there is no region, but you specify a prefix ARG, the current field gets
11401 blank, and the content is appended to the field above."
11403 (org-table-check-inside-data-field)
11404 (if (org-region-active-p)
11405 ;; There is a region: fill as a paragraph
11406 (let ((beg (region-beginning))
11408 (org-table-cut-region (region-beginning) (region-end))
11409 (if (> (length (car org-table-clip)) 1)
11410 (error "Region must be limited to single column"))
11411 (setq nlines (if arg
11413 (+ (length org-table-clip) arg)
11415 (length org-table-clip)))
11416 (setq org-table-clip
11417 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
11420 (org-table-paste-rectangle))
11421 ;; No region, split the current field at point
11423 ;; combine with field above
11424 (let ((s (org-table-blank-field))
11425 (col (org-table-current-column)))
11426 (beginning-of-line 0)
11427 (while (org-at-table-hline-p) (beginning-of-line 0))
11428 (org-table-goto-column col)
11429 (skip-chars-forward "^|")
11430 (skip-chars-backward " ")
11431 (insert " " (org-trim s))
11434 (when (looking-at "\\([^|]+\\)+|")
11435 (let ((s (match-string 1)))
11436 (replace-match " |")
11437 (goto-char (match-beginning 0))
11438 (org-table-next-row)
11439 (insert (org-trim s) " ")
11440 (org-table-align))))))
11442 (defvar org-field-marker nil)
11444 (defun org-table-edit-field (arg)
11445 "Edit table field in a different window.
11446 This is mainly useful for fields that contain hidden parts.
11447 When called with a \\[universal-argument] prefix, just make the full field visible so that
11448 it can be edited in place."
11451 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
11452 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
11453 (remove-text-properties b e '(org-cwidth t invisible t
11454 display t intangible t))
11455 (if (and (boundp 'font-lock-mode) font-lock-mode)
11456 (font-lock-fontify-block)))
11457 (let ((pos (move-marker (make-marker) (point)))
11458 (field (org-table-get-field))
11459 (cw (current-window-configuration))
11461 (switch-to-buffer-other-window "*Org tmp*")
11463 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
11465 (goto-char (setq p (point-max)))
11466 (insert (org-trim field))
11467 (remove-text-properties p (point-max)
11468 '(invisible t org-cwidth t display t
11471 (set (make-local-variable 'org-finish-function)
11472 'org-table-finish-edit-field)
11473 (set (make-local-variable 'org-window-configuration) cw)
11474 (set (make-local-variable 'org-field-marker) pos)
11475 (message "Edit and finish with C-c C-c"))))
11477 (defun org-table-finish-edit-field ()
11478 "Finish editing a table data field.
11479 Remove all newline characters, insert the result into the table, realign
11480 the table and kill the editing buffer."
11481 (let ((pos org-field-marker)
11482 (cw org-window-configuration)
11483 (cb (current-buffer))
11485 (goto-char (point-min))
11486 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
11487 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
11488 (replace-match " "))
11489 (setq text (org-trim (buffer-string)))
11490 (set-window-configuration cw)
11492 (select-window (get-buffer-window (marker-buffer pos)))
11494 (move-marker pos nil)
11495 (org-table-check-inside-data-field)
11496 (org-table-get-field nil text)
11498 (message "New field value inserted")))
11500 (defun org-trim (s)
11501 "Remove whitespace at beginning and end of string."
11502 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
11503 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
11506 (defun org-wrap (string &optional width lines)
11507 "Wrap string to either a number of lines, or a width in characters.
11508 If WIDTH is non-nil, the string is wrapped to that width, however many lines
11509 that costs. If there is a word longer than WIDTH, the text is actually
11510 wrapped to the length of that word.
11511 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
11512 many lines, whatever width that takes.
11513 The return value is a list of lines, without newlines at the end."
11514 (let* ((words (org-split-string string "[ \t\n]+"))
11515 (maxword (apply 'max (mapcar 'org-string-width words)))
11518 (org-do-wrap words (max maxword width)))
11521 (setq ll (org-do-wrap words maxword))
11522 (if (<= (length ll) lines)
11525 (while (> (length ll) lines)
11527 (setq ll (org-do-wrap words w)))
11529 (t (error "Cannot wrap this")))))
11532 (defun org-do-wrap (words width)
11533 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
11536 (setq line (pop words))
11537 (while (and words (< (+ (length line) (length (car words))) width))
11538 (setq line (concat line " " (pop words))))
11539 (setq lines (push line lines)))
11542 (defun org-split-string (string &optional separators)
11543 "Splits STRING into substrings at SEPARATORS.
11544 No empty strings are returned if there are matches at the beginning
11545 and end of string."
11546 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
11550 (while (and (string-match rexp string
11552 (= start (match-beginning 0))
11553 (< start (length string)))
11555 (< (match-beginning 0) (length string)))
11557 (or (eq (match-beginning 0) 0)
11558 (and (eq (match-beginning 0) (match-end 0))
11559 (eq (match-beginning 0) start))
11561 (cons (substring string start (match-beginning 0))
11563 (setq start (match-end 0)))
11564 (or (eq start (length string))
11566 (cons (substring string start)
11570 (defun org-table-map-tables (function)
11571 "Apply FUNCTION to the start of all tables in the buffer."
11575 (goto-char (point-min))
11576 (while (re-search-forward org-table-any-line-regexp nil t)
11577 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
11578 (beginning-of-line 1)
11579 (if (looking-at org-table-line-regexp)
11580 (save-excursion (funcall function)))
11581 (re-search-forward org-table-any-border-regexp nil 1))))
11582 (message "Mapping tables: done"))
11584 (defun org-table-sum (&optional beg end nlast)
11585 "Sum numbers in region of current table column.
11586 The result will be displayed in the echo area, and will be available
11587 as kill to be inserted with \\[yank].
11589 If there is an active region, it is interpreted as a rectangle and all
11590 numbers in that rectangle will be summed. If there is no active
11591 region and point is located in a table column, sum all numbers in that
11594 If at least one number looks like a time HH:MM or HH:MM:SS, all other
11595 numbers are assumed to be times as well (in decimal hours) and the
11596 numbers are added as such.
11598 If NLAST is a number, only the NLAST fields will actually be summed."
11601 (let (col (timecnt 0) diff h m s org-table-clip)
11603 ((and beg end)) ; beg and end given explicitly
11604 ((org-region-active-p)
11605 (setq beg (region-beginning) end (region-end)))
11607 (setq col (org-table-current-column))
11608 (goto-char (org-table-begin))
11609 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
11610 (error "No table data"))
11611 (org-table-goto-column col)
11612 ;not needed? (skip-chars-backward "^|")
11614 (goto-char (org-table-end))
11615 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
11616 (error "No table data"))
11617 (org-table-goto-column col)
11618 ;not needed? (skip-chars-forward "^|")
11619 (setq end (point))))
11620 (let* ((items (apply 'append (org-table-copy-region beg end)))
11621 (items1 (cond ((not nlast) items)
11622 ((>= nlast (length items)) items)
11623 (t (setq items (reverse items))
11624 (setcdr (nthcdr (1- nlast) items) nil)
11625 (nreverse items))))
11626 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
11628 (res (apply '+ numbers))
11629 (sres (if (= timecnt 0)
11631 (setq diff (* 3600 res)
11632 h (floor (/ diff 3600)) diff (mod diff 3600)
11633 m (floor (/ diff 60)) diff (mod diff 60)
11635 (format "%d:%02d:%02d" h m s))))
11637 (if (interactive-p)
11639 (substitute-command-keys
11640 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
11641 (length numbers) sres))))
11644 (defun org-table-get-number-for-summing (s)
11646 (if (string-match "^ *|? *" s)
11647 (setq s (replace-match "" nil nil s)))
11648 (if (string-match " *|? *$" s)
11649 (setq s (replace-match "" nil nil s)))
11650 (setq n (string-to-number s))
11652 ((and (string-match "0" s)
11653 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
11654 ((string-match "\\`[ \t]+\\'" s) nil)
11655 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
11656 (let ((h (string-to-number (or (match-string 1 s) "0")))
11657 (m (string-to-number (or (match-string 2 s) "0")))
11658 (s (string-to-number (or (match-string 4 s) "0"))))
11659 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
11660 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
11664 (defun org-table-get-vertical-vector (desc &optional tbeg col)
11665 "Get a calc vector from a column, accorting to descriptor DESC.
11666 Optional arguments TBEG and COL can give the beginning of the table and
11667 the current column, to avoid unnecessary parsing."
11669 (or tbeg (setq tbeg (org-table-begin)))
11670 (or col (setq col (org-table-current-column)))
11671 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
11673 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
11674 (setq n1 (- (match-end 1) (match-beginning 1)))
11675 (if (match-beginning 3)
11676 (setq n2 (- (match-end 2) (match-beginning 3))))
11677 (setq n (if n2 (max n1 n2) n1))
11678 (setq n1 (if n2 (min n1 n2)))
11680 (while (and (> nn 0)
11681 (re-search-backward org-table-hline-regexp tbeg t))
11682 (push (org-current-line) hline-list)
11684 (setq hline-list (nreverse hline-list))
11685 (goto-line (nth (1- n) hline-list))
11686 (when (re-search-forward org-table-dataline-regexp)
11687 (org-table-goto-column col)
11688 (setq beg (point)))
11689 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
11690 (when (re-search-backward org-table-dataline-regexp)
11691 (org-table-goto-column col)
11692 (setq end (point)))
11693 (setq l (apply 'append (org-table-copy-region beg end)))
11694 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
11695 (if (equal x "") "0" x))
11697 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
11698 (setq n1 (string-to-number (match-string 1 desc))
11699 n2 (string-to-number (match-string 2 desc)))
11700 (beginning-of-line 1)
11702 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
11703 (org-table-goto-column col)
11704 (setq beg (point))))
11705 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
11706 (org-table-goto-column col)
11707 (setq end (point)))
11708 (setq l (apply 'append (org-table-copy-region beg end)))
11709 (concat "[" (mapconcat
11710 (lambda (x) (setq x (org-trim x))
11711 (if (equal x "") "0" x))
11713 ((string-match "\\([0-9]+\\)" desc)
11714 (beginning-of-line 1)
11715 (when (re-search-backward org-table-dataline-regexp tbeg t
11716 (string-to-number (match-string 0 desc)))
11717 (org-table-goto-column col)
11718 (org-trim (org-table-get-field))))))))
11720 (defvar org-table-formula-history nil)
11722 (defvar org-table-column-names nil
11723 "Alist with column names, derived from the `!' line.")
11724 (defvar org-table-column-name-regexp nil
11725 "Regular expression matching the current column names.")
11726 (defvar org-table-local-parameters nil
11727 "Alist with parameter names, derived from the `$' line.")
11728 (defvar org-table-named-field-locations nil
11729 "Alist with locations of named fields.")
11731 (defun org-table-get-formula (&optional equation named)
11732 "Read a formula from the minibuffer, offer stored formula as default."
11733 (let* ((name (car (rassoc (list (org-current-line)
11734 (org-table-current-column))
11735 org-table-named-field-locations)))
11738 (error "Not in a named field"))
11739 (int-to-string (org-table-current-column))))
11740 (dummy (and name (not named)
11741 (not (y-or-n-p "Replace named-field formula with column equation? " ))
11743 (org-table-may-need-update nil)
11744 (stored-list (org-table-get-stored-formulas))
11745 (stored (cdr (assoc scol stored-list)))
11747 ((and stored equation (string-match "^ *=? *$" equation))
11749 ((stringp equation)
11752 (format "%s formula $%s=" (if named "Field" "Column") scol)
11753 (or stored "") 'org-table-formula-history
11757 (when (not (string-match "\\S-" eq))
11759 (setq stored-list (delq (assoc scol stored-list) stored-list))
11760 (org-table-store-formulas stored-list)
11761 (error "Formula removed"))
11762 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
11763 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
11764 (if (and name (not named))
11765 ;; We set the column equation, delete the named one.
11766 (setq stored-list (delq (assoc name stored-list) stored-list)
11769 (setcdr (assoc scol stored-list) eq)
11770 (setq stored-list (cons (cons scol eq) stored-list)))
11771 (if (or mustsave (not (equal stored eq)))
11772 (org-table-store-formulas stored-list))
11775 (defun org-table-store-formulas (alist)
11776 "Store the list of formulas below the current table."
11777 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
11779 (goto-char (org-table-end))
11780 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
11781 (delete-region (point) (match-end 0)))
11782 (insert "#+TBLFM: "
11783 (mapconcat (lambda (x)
11784 (concat "$" (car x) "=" (cdr x)))
11788 (defun org-table-get-stored-formulas ()
11789 "Return an alist with the stored formulas directly after current table."
11791 (let (scol eq eq-alist strings string seen)
11793 (goto-char (org-table-end))
11794 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
11795 (setq strings (org-split-string (match-string 2) " *:: *"))
11796 (while (setq string (pop strings))
11797 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
11798 (setq scol (match-string 1 string)
11799 eq (match-string 2 string)
11800 eq-alist (cons (cons scol eq) eq-alist))
11801 (if (member scol seen)
11802 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
11803 (push scol seen))))))
11804 (nreverse eq-alist)))
11806 (defun org-table-modify-formulas (action &rest columns)
11807 "Modify the formulas stored below the current table.
11808 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
11809 expected, for the other actions only a single column number is needed."
11810 (let ((list (org-table-get-stored-formulas))
11811 (nmax (length (org-split-string
11812 (buffer-substring (point-at-bol) (point-at-eol))
11814 col col1 col2 scol si sc1 sc2)
11816 ((null list)) ; No action needed if there are no stored formulas
11817 ((eq action 'remove)
11818 (setq col (car columns)
11819 scol (int-to-string col))
11820 (org-table-replace-in-formulas list scol "INVALID")
11821 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
11822 (loop for i from (1+ col) upto nmax by 1 do
11823 (setq si (int-to-string i))
11824 (org-table-replace-in-formulas list si (int-to-string (1- i)))
11825 (if (assoc si list) (setcar (assoc si list)
11826 (int-to-string (1- i))))))
11827 ((eq action 'insert)
11828 (setq col (car columns))
11829 (loop for i from nmax downto col by 1 do
11830 (setq si (int-to-string i))
11831 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
11832 (if (assoc si list) (setcar (assoc si list)
11833 (int-to-string (1+ i))))))
11835 (setq col1 (car columns) col2 (nth 1 columns)
11836 sc1 (int-to-string col1) sc2 (int-to-string col2))
11837 ;; Hopefully, ZqZtZ will never be a name in a table
11838 (org-table-replace-in-formulas list sc1 "ZqZtZ")
11839 (org-table-replace-in-formulas list sc2 sc1)
11840 (org-table-replace-in-formulas list "ZqZtZ" sc2)
11841 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
11842 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
11843 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
11844 (t (error "Invalid action in `org-table-modify-formulas'")))
11845 (if list (org-table-store-formulas list))))
11847 (defun org-table-replace-in-formulas (list s1 s2)
11849 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
11850 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
11851 re (concat (regexp-quote s1) "\\>"))
11852 (while (setq elt (pop list))
11854 (while (string-match re s)
11855 (setq s (replace-match s2 t t s)))
11858 (defun org-table-get-specials ()
11859 "Get the column names and local parameters for this table."
11861 (let ((beg (org-table-begin)) (end (org-table-end))
11862 names name fields fields1 field cnt c v line col)
11863 (setq org-table-column-names nil
11864 org-table-local-parameters nil
11865 org-table-named-field-locations nil)
11867 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
11868 (setq names (org-split-string (match-string 1) " *| *")
11870 (while (setq name (pop names))
11871 (setq cnt (1+ cnt))
11872 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
11873 (push (cons name (int-to-string cnt)) org-table-column-names))))
11874 (setq org-table-column-names (nreverse org-table-column-names))
11875 (setq org-table-column-name-regexp
11876 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
11878 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
11879 (setq fields (org-split-string (match-string 1) " *| *"))
11880 (while (setq field (pop fields))
11881 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
11882 (push (cons (match-string 1 field) (match-string 2 field))
11883 org-table-local-parameters))))
11885 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
11886 (setq c (match-string 1)
11887 fields (org-split-string (match-string 2) " *| *"))
11889 (beginning-of-line (if (equal c "_") 2 0))
11890 (setq line (org-current-line) col 1)
11891 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
11892 (setq fields1 (org-split-string (match-string 1) " *| *"))))
11893 (while (and fields1 (setq field (pop fields)))
11894 (setq v (pop fields1) col (1+ col))
11895 (when (and (stringp field) (stringp v)
11896 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
11897 (push (cons field v) org-table-local-parameters)
11898 (push (list field line col) org-table-named-field-locations)))))))
11900 (defun org-this-word ()
11901 ;; Get the current word
11903 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
11904 (end (progn (skip-chars-forward "^ \t\n") (point))))
11905 (buffer-substring-no-properties beg end))))
11907 (defun org-table-maybe-eval-formula ()
11908 "Check if the current field starts with \"=\" or \":=\".
11909 If yes, store the formula and apply it."
11910 ;; We already know we are in a table. Get field will only return a formula
11911 ;; when appropriate. It might return a separator line, but no problem.
11912 (when org-table-formula-evaluate-inline
11913 (let* ((field (org-trim (or (org-table-get-field) "")))
11915 (when (string-match "^:?=\\(.*\\)" field)
11916 (setq named (equal (string-to-char field) ?:)
11917 eq (match-string 1 field))
11918 (if (fboundp 'calc-eval)
11919 (org-table-eval-formula (if named '(4) nil) eq))))))
11921 (defvar org-recalc-commands nil
11922 "List of commands triggering the recalculation of a line.
11923 Will be filled automatically during use.")
11925 (defvar org-recalc-marks
11926 '((" " . "Unmarked: no special line, no automatic recalculation")
11927 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
11928 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
11929 ("!" . "Column name definition line. Reference in formula as $name.")
11930 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
11931 ("_" . "Names for values in row below this one.")
11932 ("^" . "Names for values in row above this one.")))
11934 (defun org-table-rotate-recalc-marks (&optional newchar)
11935 "Rotate the recalculation mark in the first column.
11936 If in any row, the first field is not consistent with a mark,
11937 insert a new column for the markers.
11938 When there is an active region, change all the lines in the region,
11939 after prompting for the marking character.
11940 After each change, a message will be displayed indicating the meaning
11943 (unless (org-at-table-p) (error "Not at a table"))
11944 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
11945 (beg (org-table-begin))
11946 (end (org-table-end))
11947 (l (org-current-line))
11948 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
11949 (l2 (if (org-region-active-p) (org-current-line (region-end))))
11953 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
11954 (col (org-table-current-column))
11955 (forcenew (car (assoc newchar org-recalc-marks)))
11958 (message "Change region to what mark? Type # * ! $ or SPC: ")
11959 (setq newchar (char-to-string (read-char-exclusive))
11960 forcenew (car (assoc newchar org-recalc-marks))))
11961 (if (and newchar (not forcenew))
11962 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
11964 (if l1 (goto-line l1))
11966 (beginning-of-line 1)
11967 (unless (looking-at org-table-dataline-regexp)
11968 (error "Not at a table data line")))
11970 (org-table-goto-column 1)
11971 (org-table-insert-column)
11972 (org-table-goto-column (1+ col)))
11973 (setq epos (point-at-eol))
11975 (beginning-of-line 1)
11976 (org-table-get-field
11977 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
11979 (setq new (or forcenew
11980 (cadr (member (match-string 1) marks))))
11986 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
11987 (and (looking-at org-table-dataline-regexp)
11988 (org-table-get-field 1 (concat " " new " "))))
11990 (if (not (= epos (point-at-eol))) (org-table-align))
11992 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
11994 (defun org-table-maybe-recalculate-line ()
11995 "Recompute the current line if marked for it, and if we haven't just done it."
11997 (and org-table-allow-automatic-line-recalculation
11998 (not (and (memq last-command org-recalc-commands)
11999 (equal org-last-recalc-line (org-current-line))))
12000 (save-excursion (beginning-of-line 1)
12001 (looking-at org-table-auto-recalculate-regexp))
12002 (fboundp 'calc-eval)
12003 (org-table-recalculate) t))
12005 (defvar org-table-formula-debug nil
12006 "Non-nil means, debug table formulas.
12007 When nil, simply write \"#ERROR\" in corrupted fields.")
12010 (defsubst org-set-calc-mode (var &optional value)
12012 (setq var (assoc var '(("D" calc-angle-mode deg)
12013 ("R" calc-angle-mode rad)
12014 ("F" calc-prefer-frac t)
12015 ("S" calc-symbolic-mode t)))
12016 value (nth 2 var) var (nth 1 var)))
12017 (if (memq var modes)
12018 (setcar (cdr (memq var modes)) value)
12019 (cons var (cons value modes)))
12022 (defun org-table-eval-formula (&optional arg equation
12023 suppress-align suppress-const
12025 "Replace the table field value at the cursor by the result of a calculation.
12027 This function makes use of Dave Gillespie's Calc package, in my view the
12028 most exciting program ever written for GNU Emacs. So you need to have Calc
12029 installed in order to use this function.
12031 In a table, this command replaces the value in the current field with the
12032 result of a formula. It also installs the formula as the \"current\" column
12033 formula, by storing it in a special line below the table. When called
12034 with a `C-u' prefix, the current field must ba a named field, and the
12035 formula is installed as valid in only this specific field.
12037 When called, the command first prompts for a formula, which is read in
12038 the minibuffer. Previously entered formulas are available through the
12039 history list, and the last used formula is offered as a default.
12040 These stored formulas are adapted correctly when moving, inserting, or
12041 deleting columns with the corresponding commands.
12043 The formula can be any algebraic expression understood by the Calc package.
12044 For details, see the Org-mode manual.
12046 This function can also be called from Lisp programs and offers
12047 additional arguments: EQUATION can be the formula to apply. If this
12048 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
12049 used to speed-up recursive calls by by-passing unnecessary aligns.
12050 SUPPRESS-CONST suppresses the interpretation of constants in the
12051 formula, assuming that this has been done already outside the function.
12052 SUPPRESS-STORE means the formula should not be stored, either because
12053 it is already stored, or because it is a modified equation that should
12054 not overwrite the stored one."
12057 (org-table-check-inside-data-field)
12058 (org-table-get-specials)
12060 (ndown (if (integerp arg) arg 1))
12061 (org-table-automatic-realign nil)
12062 (case-fold-search nil)
12064 (formula (if (and equation suppress-store)
12066 (org-table-get-formula equation (equal arg '(4)))))
12067 (n0 (org-table-current-column))
12068 (modes (copy-sequence org-calc-default-modes))
12069 n form fmt x ev orig c lispp)
12070 ;; Parse the format string. Since we have a lot of modes, this is
12071 ;; a lot of work. However, I think calc still uses most of the time.
12072 (if (string-match ";" formula)
12073 (let ((tmp (org-split-string formula ";")))
12074 (setq formula (car tmp)
12075 fmt (concat (cdr (assoc "%" org-table-local-parameters))
12077 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
12078 (setq c (string-to-char (match-string 1 fmt))
12079 n (string-to-number (or (match-string 1 fmt) "")))
12080 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
12081 (setq modes (org-set-calc-mode
12083 (list (cdr (assoc c '((?n . float) (?f . fix)
12084 (?s . sci) (?e . eng))))
12086 (setq fmt (replace-match "" t t fmt)))
12087 (while (string-match "[DRFS]" fmt)
12088 (setq modes (org-set-calc-mode (match-string 0 fmt)))
12089 (setq fmt (replace-match "" t t fmt)))
12090 (unless (string-match "\\S-" fmt)
12092 (if (and (not suppress-const) org-table-formula-use-constants)
12093 (setq formula (org-table-formula-substitute-names formula)))
12094 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
12096 (setq fields (org-split-string
12098 (point-at-bol) (point-at-eol)) " *| *"))
12099 (if org-table-formula-numbers-only
12100 (setq fields (mapcar
12101 (lambda (x) (number-to-string (string-to-number x)))
12103 (setq ndown (1- ndown))
12104 (setq form (copy-sequence formula)
12105 lispp (equal (substring form 0 2) "'("))
12106 ;; Insert the references to fields in same row
12107 (while (string-match "\\$\\([0-9]+\\)?" form)
12108 (setq n (if (match-beginning 1)
12109 (string-to-number (match-string 1 form))
12111 x (nth (1- n) fields))
12112 (unless x (error "Invalid field specifier \"%s\""
12113 (match-string 0 form)))
12114 (if (equal x "") (setq x "0"))
12115 (setq form (replace-match
12116 (if lispp x (concat "(" x ")"))
12118 ;; Insert ranges in current column
12119 (while (string-match "\\&[-I0-9]+" form)
12120 (setq form (replace-match
12122 (org-table-get-vertical-vector (match-string 0 form)
12126 (setq ev (eval (eval (read form)))
12127 ev (if (numberp ev) (number-to-string ev) ev))
12128 (setq ev (calc-eval (cons form modes)
12129 (if org-table-formula-numbers-only 'num))))
12131 (when org-table-formula-debug
12132 (with-output-to-temp-buffer "*Help*"
12133 (princ (format "Substitution history of formula
12136 $1-> %s\n" orig formula form))
12138 (princ (format " %s^\nError: %s"
12139 (make-string (car ev) ?\-) (nth 1 ev)))
12140 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
12142 (if fmt (format fmt (string-to-number ev)) ev)))))
12143 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
12144 (unless (and (interactive-p) (not ndown))
12145 (unless (let (inhibit-redisplay)
12146 (y-or-n-p "Debugging Formula. Continue to next? "))
12149 (delete-window (get-buffer-window "*Help*"))
12151 (if (listp ev) (setq fmt nil ev "#ERROR"))
12152 (org-table-justify-field-maybe
12153 (if fmt (format fmt (string-to-number ev)) ev))
12154 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
12155 (call-interactively 'org-return)
12157 (and down (org-table-maybe-recalculate-line))
12158 (or suppress-align (and org-table-may-need-update
12159 (org-table-align)))))
12161 (defun org-table-recalculate (&optional all noalign)
12162 "Recalculate the current table line by applying all stored formulas.
12163 With prefix arg ALL, do this for all lines in the table."
12165 (or (memq this-command org-recalc-commands)
12166 (setq org-recalc-commands (cons this-command org-recalc-commands)))
12167 (unless (org-at-table-p) (error "Not at a table"))
12168 (org-table-get-specials)
12169 (let* ((eqlist (sort (org-table-get-stored-formulas)
12170 (lambda (a b) (string< (car a) (car b)))))
12171 (inhibit-redisplay t)
12172 (line-re org-table-dataline-regexp)
12173 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
12174 (thiscol (org-table-current-column))
12175 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
12176 ;; Insert constants in all formulas
12178 (mapcar (lambda (x)
12179 (setcdr x (org-table-formula-substitute-names (cdr x)))
12182 ;; Split the equation list
12183 (while (setq eq (pop eqlist))
12184 (if (<= (string-to-char (car eq)) ?9)
12186 (push eq eqlname)))
12187 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
12190 (setq end (move-marker (make-marker) (1+ (org-table-end))))
12191 (goto-char (setq beg (org-table-begin)))
12192 (if (re-search-forward org-table-calculate-mark-regexp end t)
12193 ;; This is a table with marked lines, only compute selected lines
12194 (setq line-re org-table-recalculate-regexp)
12195 ;; Move forward to the first non-header line
12196 (if (and (re-search-forward org-table-dataline-regexp end t)
12197 (re-search-forward org-table-hline-regexp end t)
12198 (re-search-forward org-table-dataline-regexp end t))
12199 (setq beg (match-beginning 0))
12200 nil))) ;; just leave beg where it is
12201 (setq beg (point-at-bol)
12202 end (move-marker (make-marker) (1+ (point-at-eol)))))
12204 (and all (message "Re-applying formulas to full table..."))
12205 (while (re-search-forward line-re end t)
12206 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
12207 ;; Unprotected line, recalculate
12208 (and all (message "Re-applying formulas to full table...(line %d)"
12209 (setq cnt (1+ cnt))))
12210 (setq org-last-recalc-line (org-current-line))
12212 (while (setq entry (pop eql))
12213 (goto-line org-last-recalc-line)
12214 (org-table-goto-column (string-to-number (car entry)) nil 'force)
12215 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
12216 (goto-line thisline)
12217 (org-table-goto-column thiscol)
12218 (or noalign (and org-table-may-need-update (org-table-align))
12219 (and all (message "Re-applying formulas to %d lines...done" cnt)))
12220 ;; Now do the names fields
12221 (while (setq eq (pop eqlname))
12222 (setq name (car eq)
12223 a (assoc name org-table-named-field-locations))
12225 (message "Re-applying formula to named field: %s" name)
12226 (goto-line (nth 1 a))
12227 (org-table-goto-column (nth 2 a))
12228 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
12229 ;; back to initial position
12230 (goto-line thisline)
12231 (org-table-goto-column thiscol)
12232 (or noalign (and org-table-may-need-update (org-table-align))
12233 (and all (message "Re-applying formulas...done")))))
12235 (defun org-table-formula-substitute-names (f)
12236 "Replace $const with values in string F."
12237 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
12238 ;; First, check for column names
12239 (while (setq start (string-match org-table-column-name-regexp f start))
12240 (setq start (1+ start))
12241 (setq a (assoc (match-string 1 f) org-table-column-names))
12242 (setq f (replace-match (concat "$" (cdr a)) t t f)))
12243 ;; Expand ranges to vectors
12244 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
12245 (setq n1 (string-to-number (match-string 1 f))
12246 n2 (string-to-number (match-string 2 f))
12247 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
12248 s (concat "[($" (number-to-string (1- nn1)) ")"))
12249 (loop for i from nn1 upto nn2 do
12250 (setq s (concat s ",($" (int-to-string i) ")")))
12251 (setq s (concat s "]"))
12252 (if (< n2 n1) (setq s (concat "rev(" s ")")))
12253 (setq f (replace-match s t t f)))
12254 ;; Parameters and constants
12256 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
12257 (setq start (1+ start))
12258 (if (setq a (save-match-data
12259 (org-table-get-constant (match-string 1 f))))
12260 (setq f (replace-match (concat "(" a ")") t t f))))
12261 (if org-table-formula-debug
12262 (put-text-property 0 (length f) :orig-formula f1 f))
12265 (defun org-table-get-constant (const)
12266 "Find the value for a parameter or constant in a formula.
12267 Parameters get priority."
12268 (or (cdr (assoc const org-table-local-parameters))
12269 (cdr (assoc const org-table-formula-constants))
12270 (and (fboundp 'constants-get) (constants-get const))
12271 "#UNDEFINED_NAME"))
12273 (defvar org-edit-formulas-map (make-sparse-keymap))
12274 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
12275 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
12276 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
12280 (defun org-table-edit-formulas ()
12281 "Edit the formulas of the current table in a separate buffer."
12283 (unless (org-at-table-p)
12284 (error "Not at a table"))
12285 (org-table-get-specials)
12286 (let ((eql (org-table-get-stored-formulas))
12287 (pos (move-marker (make-marker) (point)))
12288 (wc (current-window-configuration))
12290 (switch-to-buffer-other-window "*Edit Formulas*")
12293 (set (make-local-variable 'org-pos) pos)
12294 (set (make-local-variable 'org-window-configuration) wc)
12295 (use-local-map org-edit-formulas-map)
12296 (setq s "# Edit formulas and finish with `C-c C-c'.
12297 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
12298 # Use `C-c ?' to get information about $name at point.
12299 # To cancel editing, press `C-c C-q'.\n")
12300 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12302 (while (setq entry (pop eql))
12303 (when (setq loc (assoc (car entry) org-table-named-field-locations))
12304 (setq s (format "# Named formula, referring to column %d in line %d\n"
12305 (nth 2 loc) (nth 1 loc)))
12306 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12308 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
12309 (remove-text-properties 0 (length s) '(face nil) s)
12311 (goto-char (point-min))
12312 (message "Edit formulas and finish with `C-c C-c'.")))
12314 (defun org-show-variable ()
12315 "Show the location/value of the $ expression at point."
12317 (let (var (pos org-pos) (win (selected-window)) e)
12319 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
12320 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
12321 (setq var (match-string 1))
12322 (error "No variable at point")))
12324 ((setq e (assoc var org-table-named-field-locations))
12325 (switch-to-buffer-other-window (marker-buffer pos))
12326 (goto-line (nth 1 e))
12327 (org-table-goto-column (nth 2 e))
12328 (select-window win)
12329 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
12330 ((setq e (assoc var org-table-column-names))
12331 (switch-to-buffer-other-window (marker-buffer pos))
12333 (goto-char (org-table-begin))
12334 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
12337 (goto-char (match-beginning 1))
12338 (message "Named column (column %s)" (cdr e)))
12339 (error "Column name not found"))
12340 (select-window win))
12341 ((string-match "^[0-9]$" var)
12343 (switch-to-buffer-other-window (marker-buffer pos))
12345 (goto-char (org-table-begin))
12347 (if (re-search-forward org-table-dataline-regexp
12350 (goto-char (match-beginning 0))
12351 (org-table-goto-column (string-to-number var))
12352 (message "Column %s" var))
12353 (error "Column name not found"))
12354 (select-window win))
12355 ((setq e (assoc var org-table-local-parameters))
12356 (switch-to-buffer-other-window (marker-buffer pos))
12358 (goto-char (org-table-begin))
12359 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
12361 (goto-char (match-beginning 1))
12362 (message "Local parameter."))
12363 (error "Parameter not found"))
12364 (select-window win))
12367 ((setq e (assoc var org-table-formula-constants))
12368 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
12369 ((setq e (and (fboundp 'constants-get) (constants-get var)))
12370 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
12371 (t (error "Undefined name $%s" var)))))))
12373 (defun org-finish-edit-formulas (&optional arg)
12374 "Parse the buffer for formula definitions and install them.
12375 With prefix ARG, apply the new formulas to the table."
12377 (let ((pos org-pos) eql)
12378 (goto-char (point-min))
12379 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
12380 (push (cons (match-string 1) (match-string 2)) eql))
12381 (set-window-configuration org-window-configuration)
12382 (select-window (get-buffer-window (marker-buffer pos)))
12384 (unless (org-at-table-p)
12385 (error "Lost table position - cannot install formulae"))
12386 (org-table-store-formulas eql)
12387 (move-marker pos nil)
12388 (kill-buffer "*Edit Formulas*")
12390 (org-table-recalculate 'all)
12391 (message "New formulas installed - press C-u C-c C-c to apply."))))
12393 (defun org-abort-edit-formulas ()
12394 "Abort editing formulas, without installing the changes."
12396 (let ((pos org-pos))
12397 (set-window-configuration org-window-configuration)
12398 (select-window (get-buffer-window (marker-buffer pos)))
12400 (message "Formula editing aborted without installing changes")))
12402 ;;; The orgtbl minor mode
12404 ;; Define a minor mode which can be used in other modes in order to
12405 ;; integrate the org-mode table editor.
12407 ;; This is really a hack, because the org-mode table editor uses several
12408 ;; keys which normally belong to the major mode, for example the TAB and
12409 ;; RET keys. Here is how it works: The minor mode defines all the keys
12410 ;; necessary to operate the table editor, but wraps the commands into a
12411 ;; function which tests if the cursor is currently inside a table. If that
12412 ;; is the case, the table editor command is executed. However, when any of
12413 ;; those keys is used outside a table, the function uses `key-binding' to
12414 ;; look up if the key has an associated command in another currently active
12415 ;; keymap (minor modes, major mode, global), and executes that command.
12416 ;; There might be problems if any of the keys used by the table editor is
12417 ;; otherwise used as a prefix key.
12419 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
12420 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
12421 ;; addresses this by checking explicitly for both bindings.
12423 ;; The optimized version (see variable `orgtbl-optimized') takes over
12424 ;; all keys which are bound to `self-insert-command' in the *global map*.
12425 ;; Some modes bind other commands to simple characters, for example
12426 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
12427 ;; active, this binding is ignored inside tables and replaced with a
12428 ;; modified self-insert.
12430 (defvar orgtbl-mode nil
12431 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
12432 table editor in arbitrary modes.")
12433 (make-variable-buffer-local 'orgtbl-mode)
12435 (defvar orgtbl-mode-map (make-keymap)
12436 "Keymap for `orgtbl-mode'.")
12439 (defun turn-on-orgtbl ()
12440 "Unconditionally turn on `orgtbl-mode'."
12444 (defun orgtbl-mode (&optional arg)
12445 "The `org-mode' table editor as a minor mode for use in other modes."
12447 (if (eq major-mode 'org-mode)
12448 ;; Exit without error, in case some hook functions calls this
12449 ;; by accident in org-mode.
12450 (message "Orgtbl-mode is not useful in org-mode, command ignored")
12452 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
12455 (and (orgtbl-setup) (defun orgtbl-setup () nil))
12456 ;; Make sure we are first in minor-mode-map-alist
12457 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
12458 (and c (setq minor-mode-map-alist
12459 (cons c (delq c minor-mode-map-alist)))))
12460 (set (make-local-variable (quote org-table-may-need-update)) t)
12461 (org-add-hook 'before-change-functions 'org-before-change-function
12463 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
12464 auto-fill-inhibit-regexp)
12465 (set (make-local-variable 'auto-fill-inhibit-regexp)
12466 (if auto-fill-inhibit-regexp
12467 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
12469 (org-add-to-invisibility-spec '(org-cwidth))
12470 (easy-menu-add orgtbl-mode-menu)
12471 (run-hooks 'orgtbl-mode-hook))
12472 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
12473 (org-cleanup-narrow-column-properties)
12474 (org-remove-from-invisibility-spec '(org-cwidth))
12475 (remove-hook 'before-change-functions 'org-before-change-function t)
12476 (easy-menu-remove orgtbl-mode-menu)
12477 (force-mode-line-update 'all))))
12479 (defun org-cleanup-narrow-column-properties ()
12480 "Remove all properties related to narrow-column invisibility."
12482 (while (setq s (text-property-any s (point-max)
12483 'display org-narrow-column-arrow))
12484 (remove-text-properties s (1+ s) '(display t)))
12486 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
12487 (remove-text-properties s (1+ s) '(org-cwidth t)))
12489 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
12490 (remove-text-properties s (1+ s) '(invisible t)))))
12492 ;; Install it as a minor mode.
12493 (put 'orgtbl-mode :included t)
12494 (put 'orgtbl-mode :menu-tag "Org Table Mode")
12495 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
12497 (defun orgtbl-make-binding (fun n &rest keys)
12498 "Create a function for binding in the table minor mode.
12499 FUN is the command to call inside a table. N is used to create a unique
12500 command name. KEYS are keys that should be checked in for a command
12501 to execute outside of tables."
12504 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
12506 (concat "In tables, run `" (symbol-name fun) "'.\n"
12507 "Outside of tables, run the binding of `"
12508 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
12513 (list 'call-interactively (list 'quote fun))
12514 (list 'let '(orgtbl-mode)
12515 (list 'call-interactively
12517 (mapcar (lambda (k)
12518 (list 'key-binding k))
12520 '('orgtbl-error))))))))
12522 (defun orgtbl-error ()
12523 "Error when there is no default binding for a table key."
12525 (error "This key is has no function outside tables"))
12527 (defun orgtbl-setup ()
12528 "Setup orgtbl keymaps."
12532 '([(meta shift left)] org-table-delete-column)
12533 '([(meta left)] org-table-move-column-left)
12534 '([(meta right)] org-table-move-column-right)
12535 '([(meta shift right)] org-table-insert-column)
12536 '([(meta shift up)] org-table-kill-row)
12537 '([(meta shift down)] org-table-insert-row)
12538 '([(meta up)] org-table-move-row-up)
12539 '([(meta down)] org-table-move-row-down)
12540 '("\C-c\C-w" org-table-cut-region)
12541 '("\C-c\M-w" org-table-copy-region)
12542 '("\C-c\C-y" org-table-paste-rectangle)
12543 '("\C-c-" org-table-insert-hline)
12544 ; '([(shift tab)] org-table-previous-field)
12545 '("\C-m" org-table-next-row)
12546 (list (org-key 'S-return) 'org-table-copy-down)
12547 '([(meta return)] org-table-wrap-region)
12548 '("\C-c\C-q" org-table-wrap-region)
12549 '("\C-c?" org-table-current-column)
12550 '("\C-c " org-table-blank-field)
12551 '("\C-c+" org-table-sum)
12552 '("\C-c=" org-table-eval-formula)
12553 '("\C-c'" org-table-edit-formulas)
12554 '("\C-c`" org-table-edit-field)
12555 '("\C-c*" org-table-recalculate)
12556 '("\C-c|" org-table-create-or-convert-from-region)
12557 '("\C-c^" org-table-sort-lines)
12558 '([(control ?#)] org-table-rotate-recalc-marks)))
12560 (while (setq elt (pop bindings))
12561 (setq nfunc (1+ nfunc))
12562 (setq key (car elt)
12564 cmd (orgtbl-make-binding fun nfunc key))
12565 (define-key orgtbl-mode-map key cmd))
12566 ;; Special treatment needed for TAB and RET
12567 (define-key orgtbl-mode-map [(return)]
12568 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
12569 (define-key orgtbl-mode-map "\C-m"
12570 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
12571 (define-key orgtbl-mode-map [(tab)]
12572 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
12573 (define-key orgtbl-mode-map "\C-i"
12574 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
12575 (define-key orgtbl-mode-map "\C-i"
12576 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
12577 (define-key orgtbl-mode-map "\C-c\C-c"
12578 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
12579 (when orgtbl-optimized
12580 ;; If the user wants maximum table support, we need to hijack
12581 ;; some standard editing functions
12582 (org-remap orgtbl-mode-map
12583 'self-insert-command 'orgtbl-self-insert-command
12584 'delete-char 'org-delete-char
12585 'delete-backward-char 'org-delete-backward-char)
12586 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
12587 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
12589 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
12590 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
12591 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
12592 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
12594 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
12595 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
12596 ["Copy Field from Above"
12597 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
12600 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
12601 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
12602 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
12603 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
12605 ["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])
12607 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
12608 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
12609 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
12610 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
12611 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
12613 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
12615 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
12616 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
12617 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
12618 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
12620 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
12621 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12622 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
12623 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
12624 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
12625 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
12626 ["Sum Column/Rectangle" org-table-sum
12627 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
12628 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
12630 (setq org-table-formula-debug (not org-table-formula-debug))
12631 :style toggle :selected org-table-formula-debug]
12635 (defun orgtbl-tab (arg)
12636 "Justification and field motion for `orgtbl-mode'."
12638 (if arg (org-table-edit-field t)
12639 (org-table-justify-field-maybe)
12640 (org-table-next-field)))
12642 (defun orgtbl-ret ()
12643 "Justification and field motion for `orgtbl-mode'."
12645 (org-table-justify-field-maybe)
12646 (org-table-next-row))
12648 (defun orgtbl-self-insert-command (N)
12649 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12650 If the cursor is in a table looking at whitespace, the whitespace is
12651 overwritten, and the table is not marked as requiring realignment."
12653 (if (and (org-at-table-p)
12655 (and org-table-auto-blank-field
12656 (member last-command
12657 '(orgtbl-hijacker-command-100
12658 orgtbl-hijacker-command-101
12659 orgtbl-hijacker-command-102
12660 orgtbl-hijacker-command-103
12661 orgtbl-hijacker-command-104
12662 orgtbl-hijacker-command-105))
12663 (org-table-blank-field))
12666 (looking-at "[^|\n]* +|"))
12667 (let (org-table-may-need-update)
12668 (goto-char (1- (match-end 0)))
12669 (delete-backward-char 1)
12670 (goto-char (match-beginning 0))
12671 (self-insert-command N))
12672 (setq org-table-may-need-update t)
12674 (call-interactively (key-binding (vector last-input-event))))))
12676 (defun org-force-self-insert (N)
12677 "Needed to enforce self-insert under remapping."
12679 (self-insert-command N))
12683 (defconst org-level-max 20)
12685 (defvar org-export-html-preamble nil
12686 "Preamble, to be inserted just after <body>. Set by publishing functions.")
12687 (defvar org-export-html-postamble nil
12688 "Preamble, to be inserted just before </body>. Set by publishing functions.")
12689 (defvar org-export-html-auto-preamble t
12690 "Should default preamble be inserted? Set by publishing functions.")
12691 (defvar org-export-html-auto-postamble t
12692 "Should default postamble be inserted? Set by publishing functions.")
12694 (defconst org-export-plist-vars
12695 '((:language . org-export-default-language)
12696 (:headline-levels . org-export-headline-levels)
12697 (:section-numbers . org-export-with-section-numbers)
12698 (:table-of-contents . org-export-with-toc)
12699 (:archived-trees . org-export-with-archived-trees)
12700 (:emphasize . org-export-with-emphasize)
12701 (:sub-superscript . org-export-with-sub-superscripts)
12702 (:TeX-macros . org-export-with-TeX-macros)
12703 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
12704 (:fixed-width . org-export-with-fixed-width)
12705 (:timestamps . org-export-with-timestamps)
12706 (:tables . org-export-with-tables)
12707 (:table-auto-headline . org-export-highlight-first-table-line)
12708 (:style . org-export-html-style)
12709 (:convert-org-links . org-export-html-link-org-files-as-html)
12710 (:inline-images . org-export-html-inline-images)
12711 (:expand-quoted-html . org-export-html-expand)
12712 (:timestamp . org-export-html-with-timestamp)
12713 (:publishing-directory . org-export-publishing-directory)
12714 (:preamble . org-export-html-preamble)
12715 (:postamble . org-export-html-postamble)
12716 (:auto-preamble . org-export-html-auto-preamble)
12717 (:auto-postamble . org-export-html-auto-postamble)
12718 (:author . user-full-name)
12719 (:email . user-mail-address)))
12721 (defun org-default-export-plist ()
12722 "Return the property list with default settings for the export variables."
12723 (let ((l org-export-plist-vars) rtn e)
12724 (while (setq e (pop l))
12725 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
12728 (defun org-infile-export-plist ()
12729 "Return the property list with file-local settings for export."
12732 (let ((re (org-make-options-regexp
12733 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12734 p key val text options)
12735 (while (re-search-forward re nil t)
12736 (setq key (org-match-string-no-properties 1)
12737 val (org-match-string-no-properties 2))
12739 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
12740 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
12741 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
12742 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
12743 ((string-equal key "TEXT")
12744 (setq text (if text (concat text "\n" val) val)))
12745 ((string-equal key "OPTIONS") (setq options val))))
12746 (setq p (plist-put p :text text))
12748 (let ((op '(("H" . :headline-levels)
12749 ("num" . :section-numbers)
12750 ("toc" . :table-of-contents)
12751 ("\\n" . :preserve-breaks)
12752 ("@" . :expand-quoted-html)
12753 (":" . :fixed-width)
12755 ("^" . :sub-superscript)
12757 ("TeX" . :TeX-macros)
12758 ("LaTeX" . :LaTeX-fragments)))
12760 (while (setq o (pop op))
12761 (if (string-match (concat (regexp-quote (car o))
12762 ":\\([^ \t\n\r;,.]*\\)")
12764 (setq p (plist-put p (cdr o)
12765 (car (read-from-string
12766 (match-string 1 options)))))))))
12769 (defun org-combine-plists (&rest plists)
12770 "Create a single property list from all plists in PLISTS.
12771 The process starts by copying the last list, and then setting properties
12772 from the other lists. Settings in the first list are the most significant
12773 ones and overrule settings in the other lists."
12774 (let ((rtn (copy-sequence (pop plists)))
12777 (setq ls (pop plists))
12779 (setq p (pop ls) v (pop ls))
12780 (setq rtn (plist-put rtn p v))))
12783 (defun org-export-directory (type plist)
12784 (let* ((val (plist-get plist :publishing-directory))
12785 (dir (if (listp val)
12786 (or (cdr (assoc type val)) ".")
12790 (defun org-export-find-first-heading-line (list)
12791 "Remove all lines from LIST which are before the first headline."
12792 (let ((orig-list list)
12793 (re (concat "^" outline-regexp)))
12795 (not (string-match re (car list))))
12797 (or list orig-list)))
12799 (defun org-skip-comments (lines)
12800 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
12801 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
12802 (re2 "^\\(\\*+\\)[ \t\n\r]")
12804 (while (setq line (pop lines))
12806 ((and (string-match re1 line)
12807 (setq level (- (match-end 1) (match-beginning 1))))
12808 ;; Beginning of a COMMENT subtree. Skip it.
12809 (while (and (setq line (pop lines))
12810 (or (not (string-match re2 line))
12811 (> (- (match-end 1) (match-beginning 1)) level))))
12812 (setq lines (cons line lines)))
12813 ((string-match "^#" line)
12814 ;; an ordinary comment line
12816 ((and org-export-table-remove-special-lines
12817 (string-match "^[ \t]*|" line)
12818 (or (string-match "^[ \t]*| *[!_^] *|" line)
12819 (and (string-match "| *<[0-9]+> *|" line)
12820 (not (string-match "| *[^ <|]" line)))))
12821 ;; a special table line that should be removed
12823 (t (setq rtn (cons line rtn)))))
12826 (defun org-export (&optional arg)
12828 (let ((help "[t] insert the export option template
12829 \[v] limit export to visible part of outline tree
12831 \[a] export as ASCII
12832 \[h] export as HTML
12833 \[b] export as HTML and browse immediately
12834 \[x] export as XOXO
12836 \[i] export current file as iCalendar file
12837 \[I] export all agenda files as iCalendar files
12838 \[c] export agenda files into combined iCalendar file
12840 \[F] publish current file
12841 \[P] publish current project
12842 \[X] publish... (project will be prompted for)
12843 \[A] publish all projects")
12845 '((?t . org-insert-export-options-template)
12846 (?v . org-export-visible)
12847 (?a . org-export-as-ascii)
12848 (?h . org-export-as-html)
12849 (?b . org-export-as-html-and-open)
12850 (?x . org-export-as-xoxo)
12851 (?i . org-export-icalendar-this-file)
12852 (?I . org-export-icalendar-all-agenda-files)
12853 (?c . org-export-icalendar-combine-agenda-files)
12854 (?F . org-publish-current-file)
12855 (?P . org-publish-current-project)
12857 (?A . org-publish-all)))
12859 (save-window-excursion
12860 (delete-other-windows)
12861 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
12863 (message "Select command: ")
12864 (setq r1 (read-char-exclusive)))
12865 (setq r2 (if (< r1 27) (+ r1 96) r1))
12866 (if (setq ass (assq r2 cmds))
12867 (call-interactively (cdr ass))
12868 (error "No command associated with key %c" r1))))
12872 (defconst org-html-entities
12912 ("Aring") ("AA"."Å")
13001 ("varepsilon"."ε")
13014 ("sigmaf") ("varsigma"."ς")
13022 ("thetasym") ("vartheta"."ϑ")
13025 ("bull") ("bullet"."•")
13026 ("hellip") ("dots"."…")
13036 ("larr") ("leftarrow"."←") ("gets"."←")
13037 ("uarr") ("uparrow"."↑")
13038 ("rarr") ("to"."→") ("rightarrow"."→")
13039 ("darr")("downarrow"."↓")
13040 ("harr") ("leftrightarrow"."↔")
13041 ("crarr") ("hookleftarrow"."↵") ; has round hook, not quite CR
13042 ("lArr") ("Leftarrow"."⇐")
13043 ("uArr") ("Uparrow"."⇑")
13044 ("rArr") ("Rightarrow"."⇒")
13045 ("dArr") ("Downarrow"."⇓")
13046 ("hArr") ("Leftrightarrow"."⇔")
13048 ("part") ("partial"."∂")
13049 ("exist") ("exists"."∃")
13050 ("empty") ("emptyset"."∅")
13052 ("isin") ("in"."∈")
13058 ("lowast") ("ast"."∗")
13060 ("prop") ("proptp"."∝")
13061 ("infin") ("infty"."∞")
13062 ("ang") ("angle"."∠")
13063 ("and") ("vee"."∧")
13064 ("or") ("wedge"."∨")
13070 ("cong") ("simeq"."≅")
13071 ("asymp")("approx"."≈")
13072 ("ne") ("neq"."≠")
13076 ("sub") ("subset"."⊂")
13077 ("sup") ("supset"."⊃")
13084 ("sdot") ("cdot"."⋅")
13091 ("loz") ("Diamond"."◊")
13092 ("spades") ("spadesuit"."♠")
13093 ("clubs") ("clubsuit"."♣")
13094 ("hearts") ("diamondsuit"."♥")
13095 ("diams") ("diamondsuit"."♦")
13129 ("arccos"."arccos")
13130 ("arcsin"."arcsin")
13131 ("arctan"."arctan")
13148 ("liminf"."liminf")
13149 ("limsup"."limsup")
13162 "Entities for TeX->HTML translation.
13163 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
13164 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
13165 In that case, \"\\ent\" will be translated to \"&other;\".
13166 The list contains HTML entities for Latin-1, Greek and other symbols.
13167 It is supplemented by a number of commonly used TeX macros with appropriate
13168 translations. There is currently no way for users to extend this.")
13170 (defun org-cleaned-string-for-export (string &rest parameters)
13171 "Cleanup a buffer substring so that links can be created safely."
13173 (let* ((re-radio (and org-target-link-regexp
13174 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
13175 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
13176 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
13177 (re-archive (concat ":" org-archive-tag ":"))
13180 (set-buffer (get-buffer-create " org-mode-tmp"))
13183 (let ((org-inhibit-startup t)) (org-mode))
13185 ;; Get rid of archived trees
13186 (when (not (eq org-export-with-archived-trees t))
13187 (goto-char (point-min))
13188 (while (re-search-forward re-archive nil t)
13189 (if (not (org-on-heading-p))
13190 (org-end-of-subtree t)
13191 (beginning-of-line 1)
13193 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
13194 (org-end-of-subtree)))))
13196 ;; Find targets in comments and move them out of comments,
13197 ;; but mark them as targets that should be invisible
13198 (goto-char (point-min))
13199 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
13200 (replace-match "\\1(INVISIBLE)"))
13202 ;; Find matches for radio targets and turn them into internal links
13203 (goto-char (point-min))
13205 (while (re-search-forward re-radio nil t)
13206 (replace-match "\\1[[\\2]]")))
13208 ;; Find all links that contain a newline and put them into a single line
13209 (goto-char (point-min))
13210 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
13211 (replace-match "\\1 \\3")
13212 (goto-char (match-beginning 0)))
13214 ;; Convert LaTeX fragments to images
13215 (when (memq :LaTeX-fragments parameters)
13217 (concat "ltxpng/" (file-name-sans-extension
13218 (file-name-nondirectory
13219 org-current-export-file)))
13220 org-current-export-dir nil "Creating LaTeX image %s"))
13221 (message "Exporting...")
13223 ;; Normalize links: Convert angle and plain links into bracket links
13224 (goto-char (point-min))
13225 (while (re-search-forward re-plain-link nil t)
13228 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13230 (goto-char (point-min))
13231 (while (re-search-forward re-angle-link nil t)
13234 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13237 ;; Find multiline emphasis and put them into single line
13238 (when (memq :emph-multiline parameters)
13239 (goto-char (point-min))
13240 (while (re-search-forward org-emph-re nil t)
13241 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
13242 (goto-char (1- (match-end 0)))))
13245 (goto-char (point-min))
13246 (while (re-search-forward "^#.*\n?" nil t)
13247 (replace-match ""))
13248 (setq rtn (buffer-string)))
13249 (kill-buffer " org-mode-tmp")
13252 (defun org-solidify-link-text (s &optional alist)
13253 "Take link text and make a safe target out of it."
13258 (org-split-string s "[ \t\r\n]+") "--"))
13259 (a (assoc rtn alist)))
13260 (or (cdr a) rtn))))
13262 (defun org-convert-to-odd-levels ()
13263 "Convert an org-mode file with all levels allowed to one with odd levels.
13264 This will leave level 1 alone, convert level 2 to level 3, level 3 to
13267 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
13268 (let ((org-odd-levels-only nil) n)
13270 (goto-char (point-min))
13271 (while (re-search-forward "^\\*\\*+" nil t)
13272 (setq n (1- (length (match-string 0))))
13273 (while (>= (setq n (1- n)) 0)
13275 (end-of-line 1))))))
13278 (defun org-convert-to-oddeven-levels ()
13279 "Convert an org-mode file with only odd levels to one with odd and even levels.
13280 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
13281 section with an even level, conversion would destroy the structure of the file. An error
13282 is signaled in this case."
13284 (goto-char (point-min))
13285 ;; First check if there are no even levels
13286 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
13287 (org-show-hierarchy-above)
13288 (error "Not all levels are odd in this file. Conversion not possible."))
13289 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
13290 (let ((org-odd-levels-only nil) n)
13292 (goto-char (point-min))
13293 (while (re-search-forward "^\\*\\*+" nil t)
13294 (setq n (/ (length (match-string 0)) 2))
13295 (while (>= (setq n (1- n)) 0)
13297 (end-of-line 1))))))
13299 (defun org-tr-level (n)
13300 "Make N odd if required."
13301 (if org-odd-levels-only (1+ (/ n 2)) n))
13303 (defvar org-last-level nil) ; dynamically scoped variable
13304 (defvar org-ascii-current-indentation nil) ; For communication
13306 (defun org-export-as-ascii (arg)
13307 "Export the outline as a pretty ASCII file.
13308 If there is an active region, export only the region.
13309 The prefix ARG specifies how many levels of the outline should become
13310 underlined headlines. The default is 3."
13312 (setq-default org-todo-line-regexp org-todo-line-regexp)
13313 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13314 (org-infile-export-plist)))
13317 (if (org-region-active-p) (region-beginning) (point-min))
13318 (if (org-region-active-p) (region-end) (point-max))))
13319 (lines (org-export-find-first-heading-line
13322 (org-cleaned-string-for-export region)
13324 (org-ascii-current-indentation '(0 . 0))
13325 (org-startup-with-deadline-check nil)
13328 (case-fold-search nil)
13329 (filename (concat (file-name-as-directory
13330 (org-export-directory :ascii opt-plist))
13331 (file-name-sans-extension
13332 (file-name-nondirectory buffer-file-name))
13334 (buffer (find-file-noselect filename))
13335 (levels-open (make-vector org-level-max nil))
13336 (odd org-odd-levels-only)
13337 (date (format-time-string "%Y/%m/%d" (current-time)))
13338 (time (format-time-string "%X" (org-current-time)))
13339 (author (plist-get opt-plist :author))
13340 (title (or (plist-get opt-plist :title)
13341 (file-name-sans-extension
13342 (file-name-nondirectory buffer-file-name))))
13343 (email (plist-get opt-plist :email))
13344 (language (plist-get opt-plist :language))
13349 (setq org-last-level 1)
13350 (org-init-section-numbers)
13352 (find-file-noselect filename)
13354 (setq lang-words (or (assoc language org-export-language-setup)
13355 (assoc "en" org-export-language-setup)))
13356 (if org-export-ascii-show-new-buffer
13357 (switch-to-buffer-other-window buffer)
13358 (set-buffer buffer))
13361 ;; create local variables for all options, to make sure all called
13362 ;; functions get the correct information
13363 (mapcar (lambda (x)
13364 (set (make-local-variable (cdr x))
13365 (plist-get opt-plist (car x))))
13366 org-export-plist-vars)
13367 (set (make-local-variable 'org-odd-levels-only) odd)
13368 (setq umax (if arg (prefix-numeric-value arg)
13369 org-export-headline-levels))
13372 (if title (org-insert-centered title ?=))
13374 (if (or author email)
13375 (insert (concat (nth 1 lang-words) ": " (or author "")
13376 (if email (concat " <" email ">") "")
13378 (if (and date time)
13379 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
13380 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
13384 (if org-export-with-toc
13386 (insert (nth 3 lang-words) "\n"
13387 (make-string (length (nth 3 lang-words)) ?=) "\n")
13388 (mapcar '(lambda (line)
13389 (if (string-match org-todo-line-regexp
13391 ;; This is a headline
13393 (setq level (- (match-end 1) (match-beginning 1))
13394 level (org-tr-level level)
13395 txt (match-string 3 line)
13397 (or (and org-export-mark-todo-in-toc
13398 (match-beginning 2)
13399 (not (equal (match-string 2 line)
13402 (and org-export-mark-todo-in-toc
13404 (org-search-todo-below
13405 line lines level))))
13406 (setq txt (org-html-expand-for-ascii txt))
13408 (if org-export-with-section-numbers
13409 (setq txt (concat (org-section-number level)
13411 (if (<= level umax)
13414 (make-string (* (1- level) 4) ?\ )
13415 (format (if todo "%s (*)\n" "%s\n") txt))
13416 (setq org-last-level level))
13420 (org-init-section-numbers)
13421 (while (setq line (pop lines))
13422 ;; Remove the quoted HTML tags.
13423 (setq line (org-html-expand-for-ascii line))
13425 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
13426 (setq line (replace-match "" t t line)))
13427 ;; Replace internal links
13428 (while (string-match org-bracket-link-regexp line)
13429 (setq line (replace-match
13430 (if (match-end 3) "[\\3]" "[\\1]")
13433 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13435 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13436 txt (match-string 2 line))
13437 (org-ascii-level-start level txt umax lines))
13439 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
13442 ;; remove display and invisible chars
13444 (goto-char (point-min))
13445 (while (setq beg (next-single-property-change (point) 'display))
13446 (setq end (next-single-property-change beg 'display))
13447 (delete-region beg end)
13450 (goto-char (point-min))
13451 (while (setq beg (next-single-property-change (point) 'org-cwidth))
13452 (setq end (next-single-property-change beg 'org-cwidth))
13453 (delete-region beg end)
13455 (goto-char (point-min))))
13457 (defun org-search-todo-below (line lines level)
13458 "Search the subtree below LINE for any TODO entries."
13459 (let ((rest (cdr (memq line lines)))
13460 (re org-todo-line-regexp)
13463 (while (setq line (pop rest))
13464 (if (string-match re line)
13466 (setq lv (- (match-end 1) (match-beginning 1))
13467 todo (and (match-beginning 2)
13468 (not (equal (match-string 2 line)
13469 org-done-string))))
13471 (if (<= lv level) (throw 'exit nil))
13472 (if todo (throw 'exit t))))))))
13474 (defun org-html-expand-for-ascii (line)
13475 "Handle quoted HTML for ASCII export."
13476 (if org-export-html-expand
13477 (while (string-match "@<[^<>\n]*>" line)
13478 ;; We just remove the tags for now.
13479 (setq line (replace-match "" nil nil line))))
13482 (defun org-insert-centered (s &optional underline)
13483 "Insert the string S centered and underline it with character UNDERLINE."
13484 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
13485 (insert (make-string ind ?\ ) s "\n")
13487 (insert (make-string ind ?\ )
13488 (make-string (string-width s) underline)
13491 (defun org-ascii-level-start (level title umax &optional lines)
13492 "Insert a new level in ASCII export."
13493 (let (char (n (- level umax 1)) (ind 0))
13496 (insert (make-string (* 2 n) ?\ )
13497 (char-to-string (nth (% n (length org-export-ascii-bullets))
13498 org-export-ascii-bullets))
13500 ;; find the indentation of the next non-empty line
13503 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
13504 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
13505 (throw 'stop (setq ind (org-get-indentation (car lines)))))
13507 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
13508 (if (or (not (equal (char-before) ?\n))
13509 (not (equal (char-before (1- (point))) ?\n)))
13511 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
13512 (if org-export-with-section-numbers
13513 (setq title (concat (org-section-number level) " " title)))
13514 (insert title "\n" (make-string (string-width title) char) "\n")
13515 (setq org-ascii-current-indentation '(0 . 0)))))
13517 (defun org-export-visible (type arg)
13518 "Create a copy of the visible part of the current buffer, and export it.
13519 The copy is created in a temporary buffer and removed after use.
13520 TYPE is the final key (as a string) that also select the export command in
13521 the `C-c C-e' export dispatcher.
13522 As a special case, if the you type SPC at the prompt, the temporary
13523 org-mode file will not be removed but presented to you so that you can
13524 continue to use it. The prefix arg ARG is passed through to the exporting
13528 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
13529 (read-char-exclusive))
13530 current-prefix-arg))
13531 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
13532 (error "Invalid export key"))
13533 (let* ((binding (cdr (assoc type
13534 '((?a . org-export-as-ascii)
13535 (?\C-a . org-export-as-ascii)
13536 (?b . org-export-as-html-and-open)
13537 (?\C-b . org-export-as-html-and-open)
13538 (?h . org-export-as-html)
13539 (?x . org-export-as-xoxo)))))
13540 (keepp (equal type ?\ ))
13541 (file buffer-file-name)
13542 (buffer (get-buffer-create "*Org Export Visible*"))
13544 (with-current-buffer buffer (erase-buffer))
13546 (setq s (goto-char (point-min)))
13547 (while (not (= (point) (point-max)))
13548 (goto-char (org-find-invisible))
13549 (append-to-buffer buffer s (point))
13550 (setq s (goto-char (org-find-visible))))
13551 (goto-char (point-min))
13553 ;; Copy all comment lines to the end, to make sure #+ settings are
13554 ;; still available for the second export step. Kind of a hack, but
13555 ;; does do the trick.
13556 (if (looking-at "#[^\r\n]*")
13557 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
13558 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
13559 (append-to-buffer buffer (1+ (match-beginning 0))
13560 (min (point-max) (1+ (match-end 0))))))
13561 (set-buffer buffer)
13562 (let ((buffer-file-name file)
13563 (org-inhibit-startup t))
13566 (unless keepp (funcall binding arg))))
13568 (kill-buffer buffer)
13569 (switch-to-buffer-other-window buffer)
13570 (goto-char (point-min)))))
13572 (defun org-find-visible ()
13573 (if (featurep 'noutline)
13575 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13576 (get-char-property s 'invisible)))
13578 (skip-chars-forward "^\n")
13580 (defun org-find-invisible ()
13581 (if (featurep 'noutline)
13583 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13584 (not (get-char-property s 'invisible))))
13586 (skip-chars-forward "^\r")
13592 (defun org-get-current-options ()
13593 "Return a string with current options as keyword options.
13594 Does include HTML export options as well as TODO and CATEGORY stuff."
13600 #+TEXT: Some descriptive text to be emitted. Several lines OK.
13601 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
13605 #+STARTUP: %s %s %s %s %s %s
13609 (buffer-name) (user-full-name) user-mail-address org-export-default-language
13610 org-export-headline-levels
13611 org-export-with-section-numbers
13612 org-export-with-toc
13613 org-export-preserve-breaks
13614 org-export-html-expand
13615 org-export-with-fixed-width
13616 org-export-with-tables
13617 org-export-with-sub-superscripts
13618 org-export-with-emphasize
13619 org-export-with-TeX-macros
13620 org-export-with-LaTeX-fragments
13621 (file-name-nondirectory buffer-file-name)
13622 (if (equal org-todo-interpretation 'sequence)
13623 (mapconcat 'identity org-todo-keywords " ")
13624 "TODO FEEDBACK VERIFY DONE")
13625 (if (equal org-todo-interpretation 'type)
13626 (mapconcat 'identity org-todo-keywords " ")
13627 "Me Jason Marie DONE")
13628 (cdr (assoc org-startup-folded
13629 '((nil . "showall") (t . "overview") (content . "content"))))
13630 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
13631 (if org-odd-levels-only "odd" "oddeven")
13632 (if org-hide-leading-stars "hidestars" "showstars")
13633 (if org-startup-align-all-tables "align" "noalign")
13634 (if org-log-done "logging" "nologging")
13635 (if org-tag-alist (mapconcat 'car org-tag-alist " ") "")
13636 org-archive-location
13639 (defun org-insert-export-options-template ()
13640 "Insert into the buffer a template with information for exporting."
13642 (if (not (bolp)) (newline))
13643 (let ((s (org-get-current-options)))
13644 (and (string-match "#\\+CATEGORY" s)
13645 (setq s (substring s 0 (match-beginning 0))))
13648 (defun org-toggle-fixed-width-section (arg)
13649 "Toggle the fixed-width export.
13650 If there is no active region, the QUOTE keyword at the current headline is
13651 inserted or removed. When present, it causes the text between this headline
13652 and the next to be exported as fixed-width text, and unmodified.
13653 If there is an active region, this command adds or removes a colon as the
13654 first character of this line. If the first character of a line is a colon,
13655 this line is also exported in fixed-width font."
13658 (regionp (org-region-active-p))
13659 (beg (if regionp (region-beginning) (point)))
13660 (end (if regionp (region-end)))
13661 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13662 (re "[ \t]*\\(:\\)")
13667 (setq cc (current-column))
13668 (beginning-of-line 1)
13669 (setq off (looking-at re))
13670 (while (> nlines 0)
13671 (setq nlines (1- nlines))
13672 (beginning-of-line 1)
13675 (move-to-column cc t)
13678 ((and off (looking-at re))
13679 (replace-match "" t t nil 1))
13680 ((not off) (move-to-column cc t) (insert ":")))
13683 (org-back-to-heading)
13684 (if (looking-at (concat outline-regexp
13685 "\\( +\\<" org-quote-string "\\>\\)"))
13686 (replace-match "" t t nil 1)
13687 (if (looking-at outline-regexp)
13689 (goto-char (match-end 0))
13690 (insert " " org-quote-string))))))))
13692 (defun org-export-as-html-and-open (arg)
13693 "Export the outline as HTML and immediately open it with a browser.
13694 If there is an active region, export only the region.
13695 The prefix ARG specifies how many levels of the outline should become
13696 headlines. The default is 3. Lower levels will become bulleted lists."
13698 (org-export-as-html arg 'hidden)
13699 (org-open-file buffer-file-name))
13701 (defun org-export-as-html-batch ()
13702 "Call `org-export-as-html', may be used in batch processing as
13704 --load=$HOME/lib/emacs/org.el
13705 --eval \"(setq org-export-headline-levels 2)\"
13706 --visit=MyFile --funcall org-export-as-html-batch"
13707 (org-export-as-html org-export-headline-levels 'hidden))
13709 (defun org-export-as-html (arg &optional hidden ext-plist)
13710 "Export the outline as a pretty HTML file.
13711 If there is an active region, export only the region.
13712 The prefix ARG specifies how many levels of the outline should become
13713 headlines. The default is 3. Lower levels will become bulleted lists.
13714 When HIDDEN is non-nil, don't display the HTML buffer.
13715 EXT-PLIST is a property list with external parameters overriding
13716 org-mode's default settings, but still inferior to file-local settings."
13718 (message "Exporting...")
13719 (setq-default org-todo-line-regexp org-todo-line-regexp)
13720 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
13721 (setq-default org-done-string org-done-string)
13722 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13724 (org-infile-export-plist)))
13726 (style (plist-get opt-plist :style))
13727 (link-validate (plist-get opt-plist :link-validation-function))
13729 (odd org-odd-levels-only)
13730 (region-p (org-region-active-p))
13733 (if region-p (region-beginning) (point-min))
13734 (if region-p (region-end) (point-max))))
13735 ;; The following two are dynamically scoped into other
13737 (org-current-export-dir (org-export-directory :html opt-plist))
13738 (org-current-export-file buffer-file-name)
13740 (org-skip-comments (org-split-string
13741 (org-cleaned-string-for-export
13742 region :emph-multiline
13743 (if (plist-get opt-plist :LaTeX-fragments)
13746 (lines (org-export-find-first-heading-line all_lines))
13747 (level 0) (line "") (origline "") txt todo
13749 (filename (concat (file-name-as-directory
13750 (org-export-directory :html opt-plist))
13751 (file-name-sans-extension
13752 (file-name-nondirectory buffer-file-name))
13754 (current-dir (file-name-directory buffer-file-name))
13755 (buffer (find-file-noselect filename))
13756 (levels-open (make-vector org-level-max nil))
13757 (date (format-time-string "%Y/%m/%d" (current-time)))
13758 (time (format-time-string "%X" (org-current-time)))
13759 (author (plist-get opt-plist :author))
13760 (title (or (plist-get opt-plist :title)
13761 (file-name-sans-extension
13762 (file-name-nondirectory buffer-file-name))))
13763 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
13764 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
13767 (in-local-list nil)
13768 (local-list-num nil)
13769 (local-list-indent nil)
13770 (llt org-plain-list-ordered-item-terminator)
13771 (email (plist-get opt-plist :email))
13772 (language (plist-get opt-plist :language))
13773 (text (plist-get opt-plist :text))
13775 (target-alist nil) tg
13778 (coding-system (and (fboundp 'coding-system-get)
13779 (boundp 'buffer-file-coding-system)
13780 buffer-file-coding-system))
13781 (coding-system-for-write (or coding-system coding-system-for-write))
13782 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
13783 (charset (and coding-system
13784 (coding-system-get coding-system 'mime-charset)))
13786 table-buffer table-orig-buffer
13787 ind start-is-num starter
13788 rpl path desc descp desc1 desc2 link
13790 (message "Exporting...")
13792 (setq org-last-level 1)
13793 (org-init-section-numbers)
13795 ;; Get the language-dependent settings
13796 (setq lang-words (or (assoc language org-export-language-setup)
13797 (assoc "en" org-export-language-setup)))
13799 ;; Switch to the output buffer
13800 (if (or hidden (not org-export-html-show-new-buffer))
13801 (set-buffer buffer)
13802 (switch-to-buffer-other-window buffer))
13805 (let ((case-fold-search nil)
13806 (org-odd-levels-only odd))
13807 ;; create local variables for all options, to make sure all called
13808 ;; functions get the correct information
13809 (mapcar (lambda (x)
13810 (set (make-local-variable (cdr x))
13811 (plist-get opt-plist (car x))))
13812 org-export-plist-vars)
13813 (setq umax (if arg (prefix-numeric-value arg)
13814 org-export-headline-levels))
13818 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
13819 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
13820 <html xmlns=\"http://www.w3.org/1999/xhtml\"
13821 lang=\"%s\" xml:lang=\"%s\">
13824 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
13825 <meta name=\"generator\" content=\"Org-mode\"/>
13826 <meta name=\"generated\" content=\"%s %s\"/>
13827 <meta name=\"author\" content=\"%s\"/>
13831 language language (org-html-expand title) (or charset "iso-8859-1")
13832 date time author style))
13835 (insert (or (plist-get opt-plist :preamble) ""))
13837 (when (plist-get opt-plist :auto-preamble)
13838 (if title (insert (concat "<h1 class=\"title\">"
13839 (org-html-expand title) "</h1>\n")))
13841 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
13843 (if org-export-with-toc
13845 (insert (format "<h2>%s</h2>\n" (nth 3 lang-words)))
13846 (insert "<ul>\n<li>")
13848 (mapcar '(lambda (line)
13849 (if (string-match org-todo-line-regexp line)
13850 ;; This is a headline
13852 (setq level (- (match-end 1) (match-beginning 1))
13853 level (org-tr-level level)
13854 txt (save-match-data
13856 (org-export-cleanup-toc-line
13857 (match-string 3 line))))
13859 (or (and org-export-mark-todo-in-toc
13860 (match-beginning 2)
13861 (not (equal (match-string 2 line)
13864 (and org-export-mark-todo-in-toc
13866 (org-search-todo-below
13867 line lines level))))
13868 (if org-export-with-section-numbers
13869 (setq txt (concat (org-section-number level)
13871 (if (<= level umax)
13873 (setq head-count (+ head-count 1))
13874 (if (> level org-last-level)
13876 (setq cnt (- level org-last-level))
13877 (while (>= (setq cnt (1- cnt)) 0)
13878 (insert "\n<ul>\n<li>"))
13880 (if (< level org-last-level)
13882 (setq cnt (- org-last-level level))
13883 (while (>= (setq cnt (1- cnt)) 0)
13884 (insert "</li>\n</ul>"))
13886 ;; Check for targets
13887 (while (string-match org-target-regexp line)
13888 (setq tg (match-string 1 line)
13889 line (replace-match
13890 (concat "@<span class=\"target\">" tg "@</span> ")
13892 (push (cons (org-solidify-link-text tg)
13893 (format "sec-%d" head-count))
13895 (while (string-match "<\\(<\\)+\\|>\\(>\\)+" txt)
13896 (setq txt (replace-match "" t t txt)))
13900 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
13901 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
13904 (setq org-last-level level))
13908 (while (> org-last-level 0)
13909 (setq org-last-level (1- org-last-level))
13910 (insert "</li>\n</ul>\n"))
13912 (setq head-count 0)
13913 (org-init-section-numbers)
13915 (while (setq line (pop lines) origline line)
13918 ;; end of quote section?
13919 (when (and inquote (string-match "^\\*+" line))
13920 (insert "</pre>\n")
13921 (setq inquote nil))
13922 ;; inside a quote section?
13924 (insert (org-html-protect line) "\n")
13925 (throw 'nextline nil))
13928 (when (and org-export-with-fixed-width
13929 (string-match "^[ \t]*:\\(.*\\)" line))
13930 (when (not infixed)
13932 (insert "<pre>\n"))
13933 (insert (org-html-protect (match-string 1 line)) "\n")
13935 (not (string-match "^[ \t]*\\(:.*\\)"
13938 (insert "</pre>\n"))
13939 (throw 'nextline nil))
13942 ;; make targets to anchors
13943 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
13946 (setq line (replace-match
13947 (concat "@<a name=\""
13948 (org-solidify-link-text (match-string 1 line))
13951 ((and org-export-with-toc (equal (string-to-char line) ?*))
13952 (setq line (replace-match
13953 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
13954 ; (concat "@<i>" (match-string 1 line) "@</i> ")
13957 (setq line (replace-match
13958 (concat "@<a name=\""
13959 (org-solidify-link-text (match-string 1 line))
13960 "\" class=\"target\">" (match-string 1 line) "@</a> ")
13963 (setq line (org-html-handle-time-stamps line))
13965 ;; replace "&" by "&", "<" and ">" by "<" and ">"
13966 ;; handle @<..> HTML tags (replace "@>..<" by "<..>")
13967 ;; Also handle sub_superscripts and checkboxes
13968 (setq line (org-html-expand line))
13970 ;; Format the links
13972 (while (string-match org-bracket-link-analytic-regexp line start)
13973 (setq start (match-beginning 0))
13974 (setq type (if (match-end 2) (match-string 2 line) "internal"))
13975 (setq path (match-string 3 line))
13976 (setq desc1 (if (match-end 5) (match-string 5 line))
13977 desc2 (if (match-end 2) (concat type ":" path) path)
13978 descp (and desc1 (not (equal desc1 desc2)))
13979 desc (or desc1 desc2))
13980 ;; FIXME: do we need to unescape here somewhere?
13982 ((equal type "internal")
13986 (org-solidify-link-text path target-alist)
13987 "\">" desc "</a>")))
13988 ((member type '("http" "https" "ftp" "mailto" "news"))
13990 (setq link (concat type ":" path))
13991 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
13992 ((string= type "file")
13994 (let* ((filename path)
13995 (abs-p (file-name-absolute-p filename))
13996 thefile file-is-image-p search)
13998 (if (string-match "::\\(.*\\)" filename)
13999 (setq search (match-string 1 filename)
14000 filename (replace-match "" t nil filename)))
14002 (if (functionp link-validate)
14003 (funcall link-validate filename current-dir)
14005 (setq file-is-image-p
14006 (string-match (org-image-file-name-regexp) filename))
14007 (setq thefile (if abs-p (expand-file-name filename) filename))
14008 (when (and org-export-html-link-org-files-as-html
14009 (string-match "\\.org$" thefile))
14010 (setq thefile (concat (substring thefile 0
14011 (match-beginning 0))
14014 ;; make sure this is can be used as target search
14015 (not (string-match "^[0-9]*$" search))
14016 (not (string-match "^\\*" search))
14017 (not (string-match "^/.*/$" search)))
14018 (setq thefile (concat thefile "#"
14019 (org-solidify-link-text
14020 (org-link-unescape search)))))
14021 (when (string-match "^file:" desc)
14022 (setq desc (replace-match "" t t desc))
14023 (if (string-match "\\.org$" desc)
14024 (setq desc (replace-match "" t t desc))))))
14025 (setq rpl (if (and file-is-image-p
14026 (or (eq t org-export-html-inline-images)
14027 (and org-export-html-inline-images
14029 (concat "<img src=\"" thefile "\"/>")
14030 (concat "<a href=\"" thefile "\">" desc "</a>")))
14031 (if (not valid) (setq rpl desc))))
14032 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
14033 (setq rpl (concat "<i><" type ":"
14034 (save-match-data (org-link-unescape path))
14036 (setq line (replace-match rpl t t line)
14037 start (+ start (length rpl))))
14039 (if (and (string-match org-todo-line-regexp line)
14040 (match-beginning 2))
14041 (if (equal (match-string 2 line) org-done-string)
14042 (setq line (replace-match
14043 "<span class=\"done\">\\2</span>"
14045 (setq line (replace-match "<span class=\"todo\">\\2</span>"
14049 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14050 ;; This is a headline
14051 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14052 txt (match-string 2 line))
14053 (if (string-match quote-re0 txt)
14054 (setq txt (replace-match "" t t txt)))
14055 (if (<= level umax) (setq head-count (+ head-count 1)))
14056 (when in-local-list
14057 ;; Close any local lists before inserting a new header line
14058 (while local-list-num
14060 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14061 (pop local-list-num))
14062 (setq local-list-indent nil
14063 in-local-list nil))
14064 (org-html-level-start level txt umax
14065 (and org-export-with-toc (<= level umax))
14068 (when (string-match quote-re line)
14072 ((and org-export-with-tables
14073 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
14074 (if (not table-open)
14075 ;; New table starts
14076 (setq table-open t table-buffer nil table-orig-buffer nil))
14077 ;; Accumulate lines
14078 (setq table-buffer (cons line table-buffer)
14079 table-orig-buffer (cons origline table-orig-buffer))
14080 (when (or (not lines)
14081 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
14083 (setq table-open nil
14084 table-buffer (nreverse table-buffer)
14085 table-orig-buffer (nreverse table-orig-buffer))
14086 (org-close-par-maybe)
14087 (insert (org-format-table-html table-buffer table-orig-buffer))))
14090 (when (string-match
14092 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14093 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14094 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14095 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
14097 (setq ind (org-get-string-indentation line)
14098 start-is-num (match-beginning 4)
14099 starter (if (match-beginning 2)
14100 (substring (match-string 2 line) 0 -1))
14101 line (substring line (match-beginning 5)))
14102 (unless (string-match "[^ \t]" line)
14103 ;; empty line. Pretend indentation is large.
14104 (setq ind (1+ (or (car local-list-indent) 1))))
14105 (while (and in-local-list
14106 (or (and (= ind (car local-list-indent))
14108 (< ind (car local-list-indent))))
14110 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14111 (pop local-list-num) (pop local-list-indent)
14112 (setq in-local-list local-list-indent))
14115 (or (not in-local-list)
14116 (> ind (car local-list-indent))))
14117 ;; Start new (level of ) list
14118 (org-close-par-maybe)
14119 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
14120 (push start-is-num local-list-num)
14121 (push ind local-list-indent)
14122 (setq in-local-list t))
14124 ;; continue current list
14126 (insert "<li>\n")))
14127 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
14130 (if (equal (match-string 1 line) "X")
14132 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
14135 ;; Empty lines start a new paragraph. If hand-formatted lists
14136 ;; are not fully interpreted, lines starting with "-", "+", "*"
14137 ;; also start a new paragraph.
14138 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
14140 ;; Check if the line break needs to be conserved
14142 ((string-match "\\\\\\\\[ \t]*$" line)
14143 (setq line (replace-match "<br/>" t t line)))
14144 (org-export-preserve-breaks
14145 (setq line (concat line "<br/>"))))
14147 (insert line "\n")))))
14149 ;; Properly close all local lists and other lists
14150 (when inquote (insert "</pre>\n"))
14151 (when in-local-list
14152 ;; Close any local lists before inserting a new header line
14153 (while local-list-num
14155 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
14156 (pop local-list-num))
14157 (setq local-list-indent nil
14158 in-local-list nil))
14159 (org-html-level-start 1 nil umax
14160 (and org-export-with-toc (<= level umax))
14163 (when (plist-get opt-plist :auto-postamble)
14165 (insert "<p class=\"author\"> "
14166 (nth 1 lang-words) ": " author "\n")
14168 (insert "<a href=\"mailto:" email "\"><"
14169 email "></a>\n"))
14171 (when (and date time)
14172 (insert "<p class=\"date\"> "
14173 (nth 2 lang-words) ": "
14174 date " " time "</p>\n")))
14176 (if org-export-html-with-timestamp
14177 (insert org-export-html-html-helper-timestamp))
14178 (insert (or (plist-get opt-plist :postamble) ""))
14179 (insert "</body>\n</html>\n")
14181 ;; remove empty paragraphs and lists
14182 (goto-char (point-min))
14183 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
14184 (replace-match ""))
14185 (goto-char (point-min))
14186 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
14187 (replace-match ""))
14189 (goto-char (point-min))
14190 (message "Exporting... done"))))
14193 (defun org-format-table-html (lines olines)
14194 "Find out which HTML converter to use and return the HTML code."
14195 (if (string-match "^[ \t]*|" (car lines))
14196 ;; A normal org table
14197 (org-format-org-table-html lines)
14198 ;; Table made by table.el - test for spanning
14199 (let* ((hlines (delq nil (mapcar
14201 (if (string-match "^[ \t]*\\+-" x) x
14204 (first (car hlines))
14205 (ll (and (string-match "\\S-+" first)
14206 (match-string 0 first)))
14207 (re (concat "^[ \t]*" (regexp-quote ll)))
14208 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
14210 (if (and (not spanning)
14211 (not org-export-prefer-native-exporter-for-tables))
14212 ;; We can use my own converter with HTML conversions
14213 (org-format-table-table-html lines)
14214 ;; Need to use the code generator in table.el, with the original text.
14215 (org-format-table-table-html-using-table-generate-source olines)))))
14217 (defun org-format-org-table-html (lines)
14218 "Format a table into HTML."
14219 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14220 (setq lines (nreverse lines))
14221 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14222 (setq lines (nreverse lines))
14223 (when org-export-table-remove-special-lines
14224 ;; Check if the table has a marking column. If yes remove the
14225 ;; column and the special lines
14231 (or (string-match "^[ \t]*|-" x)
14232 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
14239 (if (string-match "^[ \t]*| *[!_^] *|" x)
14240 nil ; ignore this line
14241 (and (or (string-match "^[ \t]*|-+\\+" x)
14242 (string-match "^[ \t]*|[^|]*|" x))
14243 (replace-match "|" t t x))))
14246 (let ((head (and org-export-highlight-first-table-line
14248 (lambda (x) (string-match "^[ \t]*|-" x))
14251 (setq html (concat org-export-html-table-tag "\n"))
14252 (while (setq line (pop lines))
14254 (if (string-match "^[ \t]*|-" line)
14256 (setq head nil) ;; head ends here, first time around
14257 ;; ignore this line
14258 (throw 'next-line t)))
14259 ;; Break the line into fields
14260 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14264 (mapconcat (lambda (x)
14266 (concat "<th>" x "</th>")
14267 (concat "<td>" x "</td>")))
14270 (setq html (concat html "</table>\n"))
14273 (defun org-fake-empty-table-line (line)
14274 "Replace everything except \"|\" with spaces."
14275 (let ((i (length line))
14276 (newstr (copy-sequence line)))
14279 (if (not (eq (aref newstr i) ?|))
14280 (aset newstr i ?\ )))
14283 (defun org-format-table-table-html (lines)
14284 "Format a table generated by table.el into HTML.
14285 This conversion does *not* use `table-generate-source' from table.el.
14286 This has the advantage that Org-mode's HTML conversions can be used.
14287 But it has the disadvantage, that no cell- or row-spanning is allowed."
14288 (let (line field-buffer
14289 (head org-export-highlight-first-table-line)
14291 (setq html (concat org-export-html-table-tag "\n"))
14292 (while (setq line (pop lines))
14293 (setq empty " ")
14295 (if (string-match "^[ \t]*\\+-" line)
14304 (if (equal x "") (setq x empty))
14306 (concat "<th>" x "</th>\n")
14307 (concat "<td>" x "</td>\n")))
14311 (setq field-buffer nil)))
14312 ;; Ignore this line
14313 (throw 'next-line t)))
14314 ;; Break the line into fields and store the fields
14315 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14317 (setq field-buffer (mapcar
14319 (concat x "<br/>" (pop fields)))
14321 (setq field-buffer fields))))
14322 (setq html (concat html "</table>\n"))
14325 (defun org-format-table-table-html-using-table-generate-source (lines)
14326 "Format a table into html, using `table-generate-source' from table.el.
14327 This has the advantage that cell- or row-spanning is allowed.
14328 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
14330 (with-current-buffer (get-buffer-create " org-tmp1 ")
14332 (insert (mapconcat 'identity lines "\n"))
14333 (goto-char (point-min))
14334 (if (not (re-search-forward "|[^+]" nil t))
14335 (error "Error processing table"))
14336 (table-recognize-table)
14337 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
14338 (table-generate-source 'html " org-tmp2 ")
14339 (set-buffer " org-tmp2 ")
14340 (buffer-substring (point-min) (point-max))))
14342 (defun org-html-handle-time-stamps (s)
14343 "Format time stamps in string S, or remove them."
14346 (while (string-match org-maybe-keyword-time-regexp s)
14347 ;; FIXME: is it good to never export CLOCK, or do we need control?
14348 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
14350 (or b (setq b (substring s 0 (match-beginning 0))))
14351 (if (not org-export-with-timestamps)
14352 (setq r (concat r (substring s 0 (match-beginning 0)))
14353 s (substring s (match-end 0)))
14355 r (substring s 0 (match-beginning 0))
14357 (format "@<span class=\"timestamp-kwd\">%s @</span>"
14358 (match-string 1 s)))
14359 (format " @<span class=\"timestamp\">%s@</span>"
14360 (substring (match-string 3 s) 1 -1)))
14361 s (substring s (match-end 0)))))
14362 ;; Line break if line started and ended with time stamp stuff
14365 (setq r (concat r s))
14366 (unless (string-match "\\S-" (concat b s))
14367 (setq r (concat r "@<br/>")))
14370 (defun org-html-protect (s)
14371 ;; convert & to &, < to < and > to >
14373 (while (string-match "&" s start)
14374 (setq s (replace-match "&" t t s)
14375 start (1+ (match-beginning 0))))
14376 (while (string-match "<" s)
14377 (setq s (replace-match "<" t t s)))
14378 (while (string-match ">" s)
14379 (setq s (replace-match ">" t t s))))
14382 (defun org-export-cleanup-toc-line (s)
14383 "Remove tags and time staps from lines going into the toc."
14384 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
14385 (setq s (replace-match "" t t s)))
14386 (when org-export-remove-timestamps-from-toc
14387 (while (string-match org-maybe-keyword-time-regexp s)
14388 (setq s (replace-match "" t t s))))
14391 (defun org-html-expand (string)
14392 "Prepare STRING for HTML export. Applies all active conversions.
14393 If there are links in the string, don't modify these."
14395 (while (setq m (string-match org-bracket-link-regexp string))
14396 (setq s (substring string 0 m)
14397 l (match-string 0 string)
14398 string (substring string (match-end 0)))
14399 (push (org-html-do-expand s) res)
14401 (push (org-html-do-expand string) res)
14402 (apply 'concat (nreverse res))))
14404 (defun org-html-do-expand (s)
14405 "Apply all active conversions to translate special ASCII to HTML."
14406 (setq s (org-html-protect s))
14407 (if org-export-html-expand
14408 (while (string-match "@<\\([^&]*\\)>" s)
14409 (setq s (replace-match "<\\1>" t nil s))))
14410 (if org-export-with-emphasize
14411 (setq s (org-export-html-convert-emphasize s)))
14412 (if org-export-with-sub-superscripts
14413 (setq s (org-export-html-convert-sub-super s)))
14414 (if org-export-with-TeX-macros
14415 (let ((start 0) wd ass)
14416 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
14417 (setq wd (match-string 1 s))
14418 (if (setq ass (assoc wd org-html-entities))
14419 (setq s (replace-match (or (cdr ass)
14420 (concat "&" (car ass) ";"))
14422 (setq start (+ start (length wd)))))))
14425 (defun org-create-multibrace-regexp (left right n)
14426 "Create a regular expression which will match a balanced sexp.
14427 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
14428 as single character strings.
14429 The regexp returned will match the entire expression including the
14430 delimiters. It will also define a single group which contains the
14431 match except for the outermost delimiters. The maximum depth of
14432 stacked delimiters is N. Escaping delimiters is not possible."
14433 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
14436 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
14439 re (concat re or next)
14440 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
14441 (concat left "\\(" re "\\)" right)))
14443 (defvar org-match-substring-regexp
14445 "\\([^\\]\\)\\([_^]\\)\\("
14446 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
14448 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
14450 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
14451 "The regular expression matching a sub- or superscript.")
14453 (defun org-export-html-convert-sub-super (string)
14454 "Convert sub- and superscripts in STRING to HTML."
14456 (while (string-match org-match-substring-regexp string)
14457 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
14458 (setq c (or (match-string 8 string)
14459 (match-string 6 string)
14460 (match-string 5 string)))
14461 (setq string (replace-match
14462 (concat (match-string 1 string)
14463 "<" key ">" c "</" key ">")
14465 (while (string-match "\\\\\\([_^]\\)" string)
14466 (setq string (replace-match (match-string 1 string) t t string))))
14469 (defun org-export-html-convert-emphasize (string)
14471 (while (string-match org-emph-re string)
14472 (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)))
14475 (defvar org-par-open nil)
14476 (defun org-open-par ()
14477 "Insert <p>, but first close previous paragraph if any."
14478 (org-close-par-maybe)
14480 (setq org-par-open t))
14481 (defun org-close-par-maybe ()
14482 "Close paragraph if there is one open."
14485 (setq org-par-open nil)))
14486 (defun org-close-li ()
14487 "Close <li> if necessary."
14488 (org-close-par-maybe)
14489 (insert "</li>\n"))
14490 ; (when (save-excursion
14491 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
14492 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
14493 ; (insert "</li>"))))
14495 (defun org-html-level-start (level title umax with-toc head-count)
14496 "Insert a new level in HTML export.
14497 When TITLE is nil, just close all open levels."
14498 (org-close-par-maybe)
14499 (let ((l (1+ (max level umax))))
14500 (while (<= l org-level-max)
14501 (if (aref levels-open (1- l))
14503 (org-html-level-close l)
14504 (aset levels-open (1- l) nil)))
14507 ;; If title is nil, this means this function is called to close
14508 ;; all levels, so the rest is done only if title is given
14509 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14510 (setq title (replace-match
14511 (if org-export-with-tags
14514 " <span class=\"tag\">"
14515 (mapconcat 'identity (org-split-string
14516 (match-string 1 title) ":")
14523 (if (aref levels-open (1- level))
14526 (insert "<li>" title "<br/>\n"))
14527 (aset levels-open (1- level) t)
14528 (org-close-par-maybe)
14529 (insert "<ul>\n<li>" title "<br/>\n")))
14530 (if org-export-with-section-numbers
14531 (setq title (concat (org-section-number level) " " title)))
14532 (setq level (+ level 1))
14534 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
14535 level head-count title level))
14536 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
14539 (defun org-html-level-close (&rest args)
14540 "Terminate one level in HTML export."
14544 ;; Variable holding the vector with section numbers
14545 (defvar org-section-numbers (make-vector org-level-max 0))
14547 (defun org-init-section-numbers ()
14548 "Initialize the vector for the section numbers."
14550 (numbers (nreverse (org-split-string "" "\\.")))
14551 (depth (1- (length org-section-numbers)))
14552 (i depth) number-string)
14555 (aset org-section-numbers i 0)
14556 (setq number-string (or (car numbers) "0"))
14557 (if (string-match "\\`[A-Z]\\'" number-string)
14558 (aset org-section-numbers i
14559 (- (string-to-char number-string) ?A -1))
14560 (aset org-section-numbers i (string-to-number number-string)))
14564 (defun org-section-number (&optional level)
14565 "Return a string with the current section number.
14566 When LEVEL is non-nil, increase section numbers on that level."
14567 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
14570 (aset org-section-numbers
14571 level (1+ (aref org-section-numbers level))))
14572 (setq idx (1+ level))
14573 (while (<= idx depth)
14574 (if (not (= idx 1))
14575 (aset org-section-numbers idx 0))
14576 (setq idx (1+ idx))))
14578 (while (<= idx depth)
14579 (setq n (aref org-section-numbers idx))
14580 (setq string (concat string (if (not (string= string "")) "." "")
14581 (int-to-string n)))
14582 (setq idx (1+ idx)))
14584 (if (string-match "\\`\\([@0]\\.\\)+" string)
14585 (setq string (replace-match "" t nil string)))
14586 (if (string-match "\\(\\.0\\)+\\'" string)
14587 (setq string (replace-match "" t nil string))))
14592 (defun org-export-icalendar-this-file ()
14593 "Export current file as an iCalendar file.
14594 The iCalendar file will be located in the same directory as the Org-mode
14595 file, but with extension `.ics'."
14597 (org-export-icalendar nil buffer-file-name))
14599 (defun org-export-as-xoxo-insert-into (buffer &rest output)
14600 (with-current-buffer buffer
14601 (apply 'insert output)))
14603 (defun org-export-as-xoxo (&optional buffer)
14604 "Export the org buffer as XOXO.
14605 The XOXO buffer is named *xoxo-<source buffer name>*"
14606 (interactive (list (current-buffer)))
14607 ;; A quickie abstraction
14609 ;; Output everything as XOXO
14610 (with-current-buffer (get-buffer buffer)
14611 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
14612 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14613 (org-infile-export-plist)))
14614 (filename (concat (file-name-as-directory
14615 (org-export-directory :xoxo opt-plist))
14616 (file-name-sans-extension
14617 (file-name-nondirectory buffer-file-name))
14619 (out (find-file-noselect filename))
14622 ;; Check the output buffer is empty.
14623 (with-current-buffer out (erase-buffer))
14624 ;; Kick off the output
14625 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
14626 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
14627 (let* ((hd (match-string-no-properties 1))
14628 (level (length hd))
14630 (match-string-no-properties 2)
14632 (goto-char (match-end 0))
14637 (if (looking-at "^[ \t]\\(.*\\)")
14638 (setq str (concat str (match-string-no-properties 1)))
14639 (throw 'loop str)))))))))
14641 ;; Handle level rendering
14643 ((> level last-level)
14644 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
14646 ((< level last-level)
14647 (dotimes (- (- last-level level) 1)
14649 (org-export-as-xoxo-insert-into out "</li>\n"))
14650 (org-export-as-xoxo-insert-into out "</ol>\n"))
14652 (org-export-as-xoxo-insert-into out "</li>\n")
14653 (setq hanging-li nil)))
14655 ((equal level last-level)
14657 (org-export-as-xoxo-insert-into out "</li>\n")))
14660 (setq last-level level)
14662 ;; And output the new li
14663 (setq hanging-li 't)
14664 (if (equal ?+ (elt text 0))
14665 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
14666 (org-export-as-xoxo-insert-into out "<li>" text))))
14668 ;; Finally finish off the ol
14669 (dotimes (- last-level 1)
14671 (org-export-as-xoxo-insert-into out "</li>\n"))
14672 (org-export-as-xoxo-insert-into out "</ol>\n"))
14674 ;; Finish the buffer off and clean it up.
14675 (switch-to-buffer-other-window out)
14676 (indent-region (point-min) (point-max) nil)
14678 (goto-char (point-min))
14682 (defun org-export-icalendar-all-agenda-files ()
14683 "Export all files in `org-agenda-files' to iCalendar .ics files.
14684 Each iCalendar file will be located in the same directory as the Org-mode
14685 file, but with extension `.ics'."
14687 (apply 'org-export-icalendar nil (org-agenda-files t)))
14690 (defun org-export-icalendar-combine-agenda-files ()
14691 "Export all files in `org-agenda-files' to a single combined iCalendar file.
14692 The file is stored under the name `org-combined-agenda-icalendar-file'."
14694 (apply 'org-export-icalendar t (org-agenda-files t)))
14696 (defun org-export-icalendar (combine &rest files)
14697 "Create iCalendar files for all elements of FILES.
14698 If COMBINE is non-nil, combine all calendar entries into a single large
14699 file and store it under the name `org-combined-agenda-icalendar-file'."
14701 (let* ((dir (org-export-directory
14702 :ical (list :publishing-directory
14703 org-export-publishing-directory)))
14704 file ical-file ical-buffer category started org-agenda-new-buffers)
14708 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
14709 org-combined-agenda-icalendar-file
14710 (expand-file-name org-combined-agenda-icalendar-file dir))
14711 ical-buffer (org-get-agenda-file-buffer ical-file))
14712 (set-buffer ical-buffer) (erase-buffer))
14713 (while (setq file (pop files))
14715 (org-check-agenda-file file)
14716 (set-buffer (org-get-agenda-file-buffer file))
14718 (setq ical-file (concat (file-name-as-directory dir)
14719 (file-name-sans-extension
14720 (file-name-nondirectory buffer-file-name))
14722 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
14723 (with-current-buffer ical-buffer (erase-buffer)))
14724 (setq category (or org-category
14725 (file-name-sans-extension
14726 (file-name-nondirectory buffer-file-name))))
14727 (if (symbolp category) (setq category (symbol-name category)))
14728 (let ((standard-output ical-buffer))
14730 (and (not started) (setq started t)
14731 (org-start-icalendar-file org-icalendar-combined-name))
14732 (org-start-icalendar-file category))
14733 (org-print-icalendar-entries combine category)
14734 (when (or (and combine (not files)) (not combine))
14735 (org-finish-icalendar-file)
14736 (set-buffer ical-buffer)
14738 (run-hooks 'org-after-save-iCalendar-file-hook)))))
14739 (org-release-buffers org-agenda-new-buffers))))
14741 (defvar org-after-save-iCalendar-file-hook nil
14742 "Hook run after an iCalendar file has been saved.
14743 The iCalendar buffer is still current when this hook is run.
14744 A good way to use this is to tell a desktop calenndar application to re-read
14745 the iCalendar file.")
14747 (defun org-print-icalendar-entries (&optional combine category)
14748 "Print iCalendar entries for the current Org-mode file to `standard-output'.
14749 When COMBINE is non nil, add the category to each line."
14750 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
14751 (dts (org-ical-ts-to-string
14752 (format-time-string (cdr org-time-stamp-formats) (current-time))
14754 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
14756 (goto-char (point-min))
14757 (while (re-search-forward org-ts-regexp nil t)
14758 (setq pos (match-beginning 0)
14759 ts (match-string 0)
14761 hd (org-get-heading))
14762 (if (looking-at re2)
14764 (goto-char (match-end 0))
14765 (setq ts2 (match-string 1) inc nil))
14767 tmp (buffer-substring (max (point-min)
14768 (- pos org-ds-keyword-length))
14770 deadlinep (string-match org-deadline-regexp tmp)
14771 scheduledp (string-match org-scheduled-regexp tmp)
14772 ;; donep (org-entry-is-done-p)
14774 (if (or (string-match org-tr-regexp hd)
14775 (string-match org-ts-regexp hd))
14776 (setq hd (replace-match "" t t hd)))
14778 (setq hd (concat hd " (category " category ")")))
14779 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
14780 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
14781 (princ (format "BEGIN:VEVENT
14786 (org-ical-ts-to-string ts "DTSTART")
14787 (org-ical-ts-to-string ts2 "DTEND" inc)
14789 (when org-icalendar-include-todo
14790 (goto-char (point-min))
14791 (while (re-search-forward org-todo-line-regexp nil t)
14792 (setq state (match-string 1))
14793 (unless (equal state org-done-string)
14794 (setq hd (match-string 3))
14795 (if (string-match org-priority-regexp hd)
14796 (setq pri (string-to-char (match-string 2 hd))
14797 hd (concat (substring hd 0 (match-beginning 1))
14798 (substring hd (- (match-end 1)))))
14799 (setq pri org-default-priority))
14800 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
14801 (- org-lowest-priority ?A))))))
14803 (princ (format "BEGIN:VTODO
14811 (defun org-start-icalendar-file (name)
14812 "Start an iCalendar file by inserting the header."
14813 (let ((user user-full-name)
14814 (name (or name "unknown"))
14815 (timezone (cadr (current-time-zone))))
14817 (format "BEGIN:VCALENDAR
14820 PRODID:-//%s//Emacs with Org-mode//EN
14822 CALSCALE:GREGORIAN\n" name user timezone))))
14824 (defun org-finish-icalendar-file ()
14825 "Finish an iCalendar file by inserting the END statement."
14826 (princ "END:VCALENDAR\n"))
14828 (defun org-ical-ts-to-string (s keyword &optional inc)
14829 "Take a time string S and convert it to iCalendar format.
14830 KEYWORD is added in front, to make a complete line like DTSTART....
14831 When INC is non-nil, increase the hour by two (if time string contains
14832 a time), or the day by one (if it does not contain a time)."
14833 (let ((t1 (org-parse-time-string s 'nodefault))
14834 t2 fmt have-time time)
14835 (if (and (car t1) (nth 1 t1) (nth 2 t1))
14836 (setq t2 t1 have-time t)
14837 (setq t2 (org-parse-time-string s)))
14838 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
14839 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
14841 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
14842 (setq time (encode-time s mi h d m y)))
14843 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
14844 (concat keyword (format-time-string fmt time))))
14848 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14849 "Keymap for the minor `org-cdlatex-mode'.")
14851 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14852 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14853 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14854 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14855 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14857 (defvar org-cdlatex-texmathp-advice-is-done nil
14858 "Flag remembering if we have applied the advice to texmathp already.")
14860 (define-minor-mode org-cdlatex-mode
14861 "Toggle the minor `org-cdlatex-mode'.
14862 This mode supports entering LaTeX environment and math in LaTeX fragments
14864 \\{org-cdlatex-mode-map}"
14866 (when org-cdlatex-mode (require 'cdlatex))
14867 (unless org-cdlatex-texmathp-advice-is-done
14868 (setq org-cdlatex-texmathp-advice-is-done t)
14869 (defadvice texmathp (around org-math-always-on activate)
14870 "Always return t in org-mode buffers.
14871 This is because we want to insert math symbols without dollars even outside
14872 the LaTeX math segments. If Orgmode thinks that point is actually inside
14873 en embedded LaTeX fragement, let texmathp do its job.
14874 \\[org-cdlatex-mode-map]"
14878 ((not (eq major-mode 'org-mode)) ad-do-it)
14879 ((eq this-command 'cdlatex-math-symbol)
14880 (setq ad-return-value t
14881 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14883 (let ((p (org-inside-LaTeX-fragment-p)))
14884 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14885 (setq ad-return-value t
14886 texmathp-why '("Org-mode embedded math" . 0))
14887 (if p ad-do-it)))))))))
14889 (defun turn-on-org-cdlatex ()
14890 "Unconditionally turn on `org-cdlatex-mode'."
14891 (org-cdlatex-mode 1))
14893 (defun org-inside-LaTeX-fragment-p ()
14894 "Test if point is inside a LaTeX fragment.
14895 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14896 sequence appearing also before point.
14897 Even though the matchers for math are configurable, this function assumes
14898 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14899 delimiters are skipped when they have been removed by customization.
14900 The return value is nil, or a cons cell with the delimiter and
14901 and the position of this delimiter.
14903 This function does a reasonably good job, but can locally be fooled by
14904 for example currency specifications. For example it will assume being in
14905 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14906 fragments that are properly closed, but during editing, we have to live
14907 with the uncertainty caused by missing closing delimiters. This function
14908 looks only before point, not after."
14910 (let ((pos (point))
14911 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14913 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14915 dd-on str (start 0) m re)
14918 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14919 re (nth 1 (assoc "$" org-latex-regexps)))
14920 (while (string-match re str start)
14922 ((= (match-end 0) (length str))
14923 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
14924 ((= (match-end 0) (- (length str) 5))
14926 (t (setq start (match-end 0))))))
14927 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14929 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14930 (and (match-beginning 2) (throw 'exit nil))
14932 (while (re-search-backward "\\$\\$" lim t)
14933 (setq dd-on (not dd-on)))
14935 (if dd-on (cons "$$" m))))))
14938 (defun org-try-cdlatex-tab ()
14939 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14940 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14941 - inside a LaTeX fragment, or
14942 - after the first word in a line, where an abbreviation expansion could
14943 insert a LaTeX environment."
14944 ;; FIXME: This may still need refinement.
14945 (when org-cdlatex-mode
14948 (skip-chars-backward "a-zA-Z0-9*")
14949 (skip-chars-backward " \t")
14952 ((org-inside-LaTeX-fragment-p)
14956 (defun org-cdlatex-underscore-caret (&optional arg)
14957 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14958 Revert to the normal definition outside of these fragments."
14960 (if (org-inside-LaTeX-fragment-p)
14961 (call-interactively 'cdlatex-sub-superscript)
14962 (let (org-cdlatex-mode)
14963 (call-interactively (key-binding (vector last-input-event))))))
14965 (defun org-cdlatex-math-modify (&optional arg)
14966 "Execute `cdlatex-math-modify' in LaTeX fragments.
14967 Revert to the normal definition outside of these fragments."
14969 (if (org-inside-LaTeX-fragment-p)
14970 (call-interactively 'cdlatex-math-modify)
14971 (let (org-cdlatex-mode)
14972 (call-interactively (key-binding (vector last-input-event))))))
14974 (defvar org-latex-fragment-image-overlays nil
14975 "List of overlays carrying the images of latex fragments.")
14976 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14978 (defun org-remove-latex-fragment-image-overlays ()
14979 "Remove all overlays with LaTeX fragment images in current buffer."
14980 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14981 (setq org-latex-fragment-image-overlays nil))
14983 (defun org-preview-latex-fragment (&optional subtree)
14984 "Preview the LaTeX fragment at point, or all locally or globally.
14985 If the cursor is in a LaTeX fragment, create the image and overlay
14986 it over the source code. If there is no fragment at point, display
14987 all fragments in the current text, from one headline to the next. With
14988 prefix SUBTREE, display all fragments in the current subtree. With a
14989 double prefix `C-u C-u', or when the cursor is before the first headline,
14990 display all fragments in the buffer.
14991 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14993 (org-remove-latex-fragment-image-overlays)
14996 (let (beg end at msg)
14998 ((or (equal subtree '(16))
14999 (not (save-excursion
15000 (re-search-backward (concat "^" outline-regexp) nil t))))
15001 (setq beg (point-min) end (point-max)
15002 msg "Creating images for buffer...%s"))
15003 ((equal subtree '(4))
15004 (org-back-to-heading)
15005 (setq beg (point) end (org-end-of-subtree)
15006 msg "Creating images for subtree...%s"))
15008 (if (setq at (org-inside-LaTeX-fragment-p))
15009 (goto-char (max (point-min) (- (cdr at) 2)))
15010 (org-back-to-heading))
15011 (setq beg (point) end (progn (outline-next-heading) (point))
15012 msg (if at "Creating image...%s"
15013 "Creating images for entry...%s"))))
15015 (narrow-to-region beg end)
15017 (concat "ltxpng/" (file-name-sans-extension
15018 (file-name-nondirectory
15019 buffer-file-name)))
15020 default-directory 'overlays msg at)
15021 (message msg "done. Use `C-c C-c' to remove images.")))))
15023 (defvar org-latex-regexps
15024 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15025 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15026 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15027 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
15028 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15029 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
15030 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
15031 "Regular expressions for matching embedded LaTeX.")
15033 (defun org-format-latex (prefix &optional dir overlays msg at)
15034 "Replace LaTeX fragments with links to an image, and produce images."
15035 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15036 (let* ((prefixnodir (file-name-nondirectory prefix))
15037 (absprefix (expand-file-name prefix dir))
15038 (todir (file-name-directory absprefix))
15039 (opt org-format-latex-options)
15040 (matchers (plist-get opt :matchers))
15041 (re-list org-latex-regexps)
15042 (cnt 0) txt link beg end re e oldfiles
15043 m n block linkfile movefile ov)
15044 ;; Make sure the directory exists
15045 (or (file-directory-p todir) (make-directory todir))
15046 ;; Check if there are old images files with this prefix, and remove them
15047 (setq oldfiles (directory-files
15049 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
15050 (while oldfiles (delete-file (pop oldfiles)))
15051 ;; Check the different regular expressions
15052 (while (setq e (pop re-list))
15053 (setq m (car e) re (nth 1 e) n (nth 2 e)
15054 block (if (nth 3 e) "\n\n" ""))
15055 (when (member m matchers)
15056 (goto-char (point-min))
15057 (while (re-search-forward re nil t)
15058 (when (or (not at) (equal (cdr at) (match-beginning n)))
15059 (setq txt (match-string n)
15060 beg (match-beginning n) end (match-end n)
15062 linkfile (format "%s_%04d.png" prefix cnt)
15063 movefile (format "%s_%04d.png" absprefix cnt)
15064 link (concat block "[[file:" linkfile "]]" block))
15065 (if msg (message msg cnt))
15067 (org-create-formula-image
15071 (setq ov (org-make-overlay beg end))
15072 (if (featurep 'xemacs)
15074 (org-overlay-put ov 'invisible t)
15077 (make-glyph (vector 'png :file movefile))))
15080 (list 'image :type 'png :file movefile :ascent 'center)))
15081 (push ov org-latex-fragment-image-overlays)
15083 (delete-region beg end)
15084 (insert link))))))))
15086 ;; This function borrows from Ganesh Swami's latex2png.el
15087 (defun org-create-formula-image (string tofile options)
15088 (let* ((tmpdir (if (featurep 'xemacs)
15090 temporary-file-directory))
15091 (texfilebase (make-temp-name
15092 (expand-file-name "orgtex" tmpdir)))
15094 ;(texfilebase (make-temp-file "orgtex"))
15095 ; (dummy (delete-file texfilebase))
15096 (texfile (concat texfilebase ".tex"))
15097 (dvifile (concat texfilebase ".dvi"))
15098 (pngfile (concat texfilebase ".png"))
15099 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15100 (fg (or (plist-get options :foreground) "Black"))
15101 (bg (or (plist-get options :background) "Transparent")))
15102 (with-temp-file texfile
15103 (insert "\\documentclass{article}
15104 \\usepackage{fullpage}
15105 \\usepackage{amssymb}
15106 \\usepackage[usenames]{color}
15107 \\usepackage{amsmath}
15108 \\usepackage{latexsym}
15109 \\usepackage[mathscr]{eucal}
15111 \\begin{document}\n" string "\n\\end{document}\n"))
15112 (let ((dir default-directory))
15113 (condition-case nil
15116 (call-process "latex" nil nil nil texfile))
15119 (if (not (file-exists-p dvifile))
15120 (progn (message "Failed to create dvi file from %s" texfile) nil)
15121 (call-process "dvipng" nil nil nil
15122 "-E" "-fg" fg "-bg" bg
15123 "-x" scale "-y" scale "-T" "tight"
15126 (if (not (file-exists-p pngfile))
15127 (progn (message "Failed to create png file from %s" texfile) nil)
15128 ;; Use the requested file name and clean up
15129 (copy-file pngfile tofile 'replace)
15130 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15131 (delete-file (concat texfilebase e)))
15136 ;; - Bindings in Org-mode map are currently
15137 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
15138 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
15139 ;; e (?) useful from outline-mode
15140 ;; i k @ expendable from outline-mode
15141 ;; 0123456789 % & ()_{} " ` free
15143 ;; Make `C-c C-x' a prefix key
15144 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
15146 ;; TAB key with modifiers
15147 (define-key org-mode-map "\C-i" 'org-cycle)
15148 (define-key org-mode-map [(tab)] 'org-cycle)
15149 (define-key org-mode-map [(meta tab)] 'org-complete)
15150 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
15151 ;; The following line is necessary under Suse GNU/Linux
15152 (unless (featurep 'xemacs)
15153 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
15154 (define-key org-mode-map [(shift tab)] 'org-shifttab)
15156 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
15157 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
15158 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15159 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
15160 (define-key org-mode-map [(meta return)] 'org-meta-return)
15161 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
15162 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
15164 ;; Cursor keys with modifiers
15165 (define-key org-mode-map [(meta left)] 'org-metaleft)
15166 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
15167 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
15168 (define-key org-mode-map [(meta right)] 'org-metaright)
15169 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
15170 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
15171 (define-key org-mode-map [(meta up)] 'org-metaup)
15172 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
15173 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
15174 (define-key org-mode-map [(meta down)] 'org-metadown)
15175 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
15176 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
15178 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15179 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
15180 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
15181 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
15182 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
15183 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
15184 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
15185 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
15186 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
15187 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
15188 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
15189 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
15190 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
15191 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
15192 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
15193 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
15195 ;; All the other keys
15197 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15198 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
15199 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
15200 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
15201 (define-key org-mode-map "\C-c\C-j" 'org-goto)
15202 (define-key org-mode-map "\C-c\C-t" 'org-todo)
15203 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
15204 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
15205 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
15206 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15207 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
15208 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
15209 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
15210 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
15211 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
15212 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
15213 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
15214 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
15215 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
15216 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
15217 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15218 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15219 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15220 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15221 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
15222 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
15223 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15224 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
15225 (define-key org-mode-map "\C-c]" 'org-remove-file)
15226 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
15227 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
15228 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
15229 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15230 (define-key org-mode-map "\C-m" 'org-return)
15231 (define-key org-mode-map "\C-c?" 'org-table-current-column)
15232 (define-key org-mode-map "\C-c " 'org-table-blank-field)
15233 (define-key org-mode-map "\C-c+" 'org-table-sum)
15234 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
15235 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
15236 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
15237 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15238 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
15239 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15240 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
15241 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
15242 (define-key org-mode-map "\C-c\C-e" 'org-export)
15243 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15245 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
15246 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15247 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15248 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15250 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15251 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15252 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15253 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15254 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15255 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15256 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15257 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15259 (when (featurep 'xemacs)
15260 (define-key org-mode-map 'button3 'popup-mode-menu))
15262 (defsubst org-table-p () (org-at-table-p))
15264 (defun org-self-insert-command (N)
15265 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15266 If the cursor is in a table looking at whitespace, the whitespace is
15267 overwritten, and the table is not marked as requiring realignment."
15269 (if (and (org-table-p)
15271 ;; check if we blank the field, and if that triggers align
15272 (and org-table-auto-blank-field
15273 (member last-command
15274 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
15275 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15276 ;; got extra space, this field does not determine column width
15277 (let (org-table-may-need-update) (org-table-blank-field))
15278 ;; no extra space, this field may determine column width
15279 (org-table-blank-field)))
15282 (looking-at "[^|\n]* |"))
15283 (let (org-table-may-need-update)
15284 (goto-char (1- (match-end 0)))
15285 (delete-backward-char 1)
15286 (goto-char (match-beginning 0))
15287 (self-insert-command N))
15288 (setq org-table-may-need-update t)
15289 (self-insert-command N)))
15291 (defun org-delete-backward-char (N)
15292 "Like `delete-backward-char', insert whitespace at field end in tables.
15293 When deleting backwards, in tables this function will insert whitespace in
15294 front of the next \"|\" separator, to keep the table aligned. The table will
15295 still be marked for re-alignment if the field did fill the entire column,
15296 because, in this case the deletion might narrow the column."
15298 (if (and (org-table-p)
15300 (string-match "|" (buffer-substring (point-at-bol) (point)))
15301 (looking-at ".*?|"))
15302 (let ((pos (point))
15303 (noalign (looking-at "[^|\n\r]* |"))
15304 (c org-table-may-need-update))
15305 (backward-delete-char N)
15306 (skip-chars-forward "^|")
15308 (goto-char (1- pos))
15309 ;; noalign: if there were two spaces at the end, this field
15310 ;; does not determine the width of the column.
15311 (if noalign (setq org-table-may-need-update c)))
15312 (backward-delete-char N)))
15314 (defun org-delete-char (N)
15315 "Like `delete-char', but insert whitespace at field end in tables.
15316 When deleting characters, in tables this function will insert whitespace in
15317 front of the next \"|\" separator, to keep the table aligned. The table will
15318 still be marked for re-alignment if the field did fill the entire column,
15319 because, in this case the deletion might narrow the column."
15321 (if (and (org-table-p)
15323 (not (= (char-after) ?|))
15325 (if (looking-at ".*?|")
15326 (let ((pos (point))
15327 (noalign (looking-at "[^|\n\r]* |"))
15328 (c org-table-may-need-update))
15329 (replace-match (concat
15330 (substring (match-string 0) 1 -1)
15333 ;; noalign: if there were two spaces at the end, this field
15334 ;; does not determine the width of the column.
15335 (if noalign (setq org-table-may-need-update c)))
15339 ;; How to do this: Measure non-white length of current string
15340 ;; If equal to column width, we should realign.
15342 (defun org-remap (map &rest commands)
15343 "In MAP, remap the functions given in COMMANDS.
15344 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15347 (setq old (pop commands) new (pop commands))
15348 (if (fboundp 'command-remapping)
15349 (define-key map (vector 'remap old) new)
15350 (substitute-key-definition old new map global-map)))))
15352 (when (eq org-enable-table-editor 'optimized)
15353 ;; If the user wants maximum table support, we need to hijack
15354 ;; some standard editing functions
15355 (org-remap org-mode-map
15356 'self-insert-command 'org-self-insert-command
15357 'delete-char 'org-delete-char
15358 'delete-backward-char 'org-delete-backward-char)
15359 (define-key org-mode-map "|" 'org-force-self-insert))
15361 (defun org-shiftcursor-error ()
15362 "Throw an error because Shift-Cursor command was applied in wrong context."
15363 (error "This command is active in special context like tables, headlines or timestamps"))
15365 (defun org-shifttab (&optional arg)
15366 "Global visibility cycling or move to previous table field.
15367 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15369 See the individual commands for more information."
15372 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15373 (t (call-interactively 'org-global-cycle))))
15375 (defun org-shiftmetaleft ()
15376 "Promote subtree or delete table column.
15377 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
15378 See the individual commands for more information."
15381 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15382 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15383 ((org-at-item-p) (call-interactively 'org-outdent-item))
15384 (t (org-shiftcursor-error))))
15386 (defun org-shiftmetaright ()
15387 "Demote subtree or insert table column.
15388 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
15389 See the individual commands for more information."
15392 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15393 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15394 ((org-at-item-p) (call-interactively 'org-indent-item))
15395 (t (org-shiftcursor-error))))
15397 (defun org-shiftmetaup (&optional arg)
15398 "Move subtree up or kill table row.
15399 Calls `org-move-subtree-up' or `org-table-kill-row' or
15400 `org-move-item-up' depending on context. See the individual commands
15401 for more information."
15404 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15405 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15406 ((org-at-item-p) (call-interactively 'org-move-item-up))
15407 (t (org-shiftcursor-error))))
15408 (defun org-shiftmetadown (&optional arg)
15409 "Move subtree down or insert table row.
15410 Calls `org-move-subtree-down' or `org-table-insert-row' or
15411 `org-move-item-down', depending on context. See the individual
15412 commands for more information."
15415 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15416 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15417 ((org-at-item-p) (call-interactively 'org-move-item-down))
15418 (t (org-shiftcursor-error))))
15420 (defun org-metaleft (&optional arg)
15421 "Promote heading or move table column to left.
15422 Calls `org-do-promote' or `org-table-move-column', depending on context.
15423 With no specific context, calls the Emacs default `backward-word'.
15424 See the individual commands for more information."
15427 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15428 ((or (org-on-heading-p) (org-region-active-p))
15429 (call-interactively 'org-do-promote))
15430 (t (call-interactively 'backward-word))))
15432 (defun org-metaright (&optional arg)
15433 "Demote subtree or move table column to right.
15434 Calls `org-do-demote' or `org-table-move-column', depending on context.
15435 With no specific context, calls the Emacs default `forward-word'.
15436 See the individual commands for more information."
15439 ((org-at-table-p) (call-interactively 'org-table-move-column))
15440 ((or (org-on-heading-p) (org-region-active-p))
15441 (call-interactively 'org-do-demote))
15442 (t (call-interactively 'forward-word))))
15444 (defun org-metaup (&optional arg)
15445 "Move subtree up or move table row up.
15446 Calls `org-move-subtree-up' or `org-table-move-row' or
15447 `org-move-item-up', depending on context. See the individual commands
15448 for more information."
15451 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15452 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15453 ((org-at-item-p) (call-interactively 'org-move-item-up))
15454 (t (org-shiftcursor-error))))
15456 (defun org-metadown (&optional arg)
15457 "Move subtree down or move table row down.
15458 Calls `org-move-subtree-down' or `org-table-move-row' or
15459 `org-move-item-down', depending on context. See the individual
15460 commands for more information."
15463 ((org-at-table-p) (call-interactively 'org-table-move-row))
15464 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15465 ((org-at-item-p) (call-interactively 'org-move-item-down))
15466 (t (org-shiftcursor-error))))
15468 (defun org-shiftup (&optional arg)
15469 "Increase item in timestamp or increase priority of current headline.
15470 Calls `org-timestamp-up' or `org-priority-up', depending on context.
15471 See the individual commands for more information."
15474 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
15475 ((org-on-heading-p) (call-interactively 'org-priority-up))
15476 ((org-at-item-p) (call-interactively 'org-previous-item))
15477 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
15479 (defun org-shiftdown (&optional arg)
15480 "Decrease item in timestamp or decrease priority of current headline.
15481 Calls `org-timestamp-down' or `org-priority-down', depending on context.
15482 See the individual commands for more information."
15485 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
15486 ((org-on-heading-p) (call-interactively 'org-priority-down))
15487 (t (call-interactively 'org-next-item))))
15489 (defun org-shiftright ()
15490 "Next TODO keyword or timestamp one day later, depending on context."
15493 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15494 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
15495 (t (org-shiftcursor-error))))
15497 (defun org-shiftleft ()
15498 "Previous TODO keyword or timestamp one day earlier, depending on context."
15501 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15502 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
15503 (t (org-shiftcursor-error))))
15505 (defun org-copy-special ()
15506 "Copy region in table or copy current subtree.
15507 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15508 See the individual commands for more information."
15510 (call-interactively
15511 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15513 (defun org-cut-special ()
15514 "Cut region in table or cut current subtree.
15515 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15516 See the individual commands for more information."
15518 (call-interactively
15519 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15521 (defun org-paste-special (arg)
15522 "Paste rectangular region into table, or past subtree relative to level.
15523 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15524 See the individual commands for more information."
15526 (if (org-at-table-p)
15527 (org-table-paste-rectangle)
15528 (org-paste-subtree arg)))
15530 (defun org-ctrl-c-ctrl-c (&optional arg)
15531 "Set tags in headline, or update according to changed information at point.
15533 This command does many different things, depending on context:
15535 - If the cursor is in a headline, prompt for tags and insert them
15536 into the current line, aligned to `org-tags-column'. When called
15537 with prefix arg, realign all tags in the current buffer.
15539 - If the cursor is in one of the special #+KEYWORD lines, this
15540 triggers scanning the buffer for these lines and updating the
15543 - If the cursor is inside a table, realign the table. This command
15544 works even if the automatic table editor has been turned off.
15546 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15549 - If the cursor is inside a table created by the table.el package,
15550 activate that table.
15552 - If the current buffer is a remember buffer, close note and file it.
15553 with a prefix argument, file it without further interaction to the default
15556 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15557 links in this buffer.
15559 - If the cursor is on a numbered item in a plain list, renumber the
15562 (let ((org-enable-table-editor t))
15564 ((or org-clock-overlays org-occur-highlights
15565 org-latex-fragment-image-overlays)
15566 (org-remove-clock-overlays)
15567 (org-remove-occur-highlights)
15568 (org-remove-latex-fragment-image-overlays)
15569 (message "Temporary highlights/overlays removed from current buffer"))
15570 ((and (local-variable-p 'org-finish-function (current-buffer))
15571 (fboundp org-finish-function))
15572 (funcall org-finish-function))
15573 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15574 ((org-on-heading-p) (call-interactively 'org-set-tags))
15575 ((org-at-table.el-p)
15577 (beginning-of-line 1)
15578 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15579 (call-interactively 'table-recognize-table))
15581 (org-table-maybe-eval-formula)
15583 (call-interactively 'org-table-recalculate)
15584 (org-table-maybe-recalculate-line))
15585 (call-interactively 'org-table-align))
15586 ((org-at-item-checkbox-p)
15587 (call-interactively 'org-toggle-checkbox))
15589 (call-interactively 'org-renumber-ordered-list))
15590 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
15592 ((equal (match-string 1) "TBLFM")
15593 ;; Recalculate the table before this line
15595 (beginning-of-line 1)
15596 (skip-chars-backward " \r\n\t")
15597 (if (org-at-table-p)
15598 (org-call-with-arg 'org-table-recalculate t))))
15600 (call-interactively 'org-mode-restart))))
15601 (t (error "C-c C-c can do nothing useful at this location.")))))
15603 (defun org-mode-restart ()
15604 "Restart Org-mode, to scan again for special lines.
15605 Also updates the keyword regular expressions."
15607 (let ((org-inhibit-startup t)) (org-mode))
15608 (message "Org-mode restarted to refresh keyword and special line setup"))
15610 (defun org-return ()
15611 "Goto next table row or insert a newline.
15612 Calls `org-table-next-row' or `newline', depending on context.
15613 See the individual commands for more information."
15617 (org-table-justify-field-maybe)
15618 (call-interactively 'org-table-next-row))
15621 (defun org-meta-return (&optional arg)
15622 "Insert a new heading or wrap a region in a table.
15623 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15624 See the individual commands for more information."
15628 (call-interactively 'org-table-wrap-region))
15629 (t (call-interactively 'org-insert-heading))))
15633 ;; Define the Org-mode menus
15634 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15636 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
15637 ["Next Field" org-cycle (org-at-table-p)]
15638 ["Previous Field" org-shifttab (org-at-table-p)]
15639 ["Next Row" org-return (org-at-table-p)]
15641 ["Blank Field" org-table-blank-field (org-at-table-p)]
15642 ["Edit Field" org-table-edit-field (org-at-table-p)]
15643 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15646 ["Move Column Left" org-metaleft (org-at-table-p)]
15647 ["Move Column Right" org-metaright (org-at-table-p)]
15648 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15649 ["Insert Column" org-shiftmetaright (org-at-table-p)]
15651 ["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])
15653 ["Move Row Up" org-metaup (org-at-table-p)]
15654 ["Move Row Down" org-metadown (org-at-table-p)]
15655 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15656 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15657 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15659 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
15661 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15662 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15663 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15664 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15667 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15668 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15669 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
15671 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15672 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15673 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15675 ["Sum Column/Rectangle" org-table-sum
15676 (or (org-at-table-p) (org-region-active-p))]
15677 ["Which Column?" org-table-current-column (org-at-table-p)])
15679 (setq org-table-formula-debug (not org-table-formula-debug))
15680 :style toggle :selected org-table-formula-debug]
15682 ["Create" org-table-create (and (not (org-at-table-p))
15683 org-enable-table-editor)]
15684 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15685 ["Import from File" org-table-import (not (org-at-table-p))]
15686 ["Export to File" org-table-export (org-at-table-p)]
15688 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15690 (easy-menu-define org-org-menu org-mode-map "Org menu"
15692 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
15693 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
15694 ["Sparse Tree" org-occur t]
15695 ["Show All" show-all t]
15697 ["New Heading" org-insert-heading t]
15698 ("Navigate Headings"
15699 ["Up" outline-up-heading t]
15700 ["Next" outline-next-visible-heading t]
15701 ["Previous" outline-previous-visible-heading t]
15702 ["Next Same Level" outline-forward-same-level t]
15703 ["Previous Same Level" outline-backward-same-level t]
15705 ["Jump" org-goto t])
15707 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15708 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15710 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15711 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15712 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15714 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15715 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15716 ["Demote Heading" org-metaright (not (org-at-table-p))]
15717 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15719 ["Convert to odd levels" org-convert-to-odd-levels t]
15720 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15722 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15723 ["Check and Tag Children" (org-toggle-archive-tag (4))
15724 :active t :keys "C-u C-c C-x C-a"]
15725 ["Sparse trees open ARCHIVE trees"
15726 (setq org-sparse-tree-open-archived-trees
15727 (not org-sparse-tree-open-archived-trees))
15728 :style toggle :selected org-sparse-tree-open-archived-trees]
15729 ["Cycling opens ARCHIVE trees"
15730 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15731 :style toggle :selected org-cycle-open-archived-trees]
15732 ["Agenda includes ARCHIVE trees"
15733 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
15734 :style toggle :selected (not org-agenda-skip-archived-trees)]
15736 ["Move Subtree to Archive" org-archive-subtree t]
15737 ["Check and Move Children" (org-archive-subtree '(4))
15738 :active t :keys "C-u C-c $"])
15741 ["TODO/DONE/-" org-todo t]
15742 ["Show TODO Tree" org-show-todo-tree t]
15743 ["Global TODO list" org-todo-list t]
15745 ["Set Priority" org-priority t]
15746 ["Priority Up" org-shiftup t]
15747 ["Priority Down" org-shiftdown t])
15748 ("Dates and Scheduling"
15749 ["Timestamp" org-time-stamp t]
15750 ["Timestamp (inactive)" org-time-stamp-inactive t]
15752 ["1 Day Later" org-timestamp-up-day t]
15753 ["1 Day Earlier" org-timestamp-down-day t]
15754 ["1 ... Later" org-shiftup t]
15755 ["1 ... Earlier" org-shiftdown t])
15756 ["Compute Time Range" org-evaluate-time-range t]
15757 ["Schedule Item" org-schedule t]
15758 ["Deadline" org-deadline t]
15760 ["Goto Calendar" org-goto-calendar t]
15761 ["Date from Calendar" org-date-from-calendar t])
15763 ["Clock in" org-clock-in t]
15764 ["Clock out" org-clock-out t]
15765 ["Clock cancel" org-clock-cancel t]
15766 ["Display times" org-clock-display t]
15767 ["Create clock table" org-clock-report t]
15769 ["Record DONE time"
15770 (progn (setq org-log-done (not org-log-done))
15771 (message "Switching to %s will %s record a timestamp"
15773 (if org-log-done "automatically" "not")))
15774 :style toggle :selected org-log-done])
15776 ["Agenda Command" org-agenda t]
15777 ("File List for Agenda")
15778 ("Special views current file"
15779 ["TODO Tree" org-show-todo-tree t]
15780 ["Check Deadlines" org-check-deadlines t]
15781 ["Timeline" org-timeline t]
15782 ["Tags Tree" org-tags-sparse-tree t])
15785 ["Store Link (Global)" org-store-link t]
15786 ["Insert Link" org-insert-link t]
15787 ["Follow Link" org-open-at-point t]
15789 ["Descriptive Links"
15790 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15791 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
15794 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15795 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
15797 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
15798 (save-excursion (goto-char (point-min))
15799 (re-search-forward "<[a-z]+:" nil t))])
15801 ["Export/Publish" org-export t]
15803 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15804 :selected org-cdlatex-mode]
15805 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15806 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15807 ["Modify math symbol" org-cdlatex-math-modify
15808 (org-inside-LaTeX-fragment-p)]
15809 ["Export LaTeX fragments as images"
15810 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
15811 :style toggle :selected org-export-with-LaTeX-fragments])
15814 ["Show Version" org-version t]
15815 ["Info Documentation" org-info t])
15817 ["Browse Org Group" org-customize t]
15819 ["Expand This Menu" org-create-customize-menu
15820 (fboundp 'customize-menu-create)])
15822 ["Refresh setup" org-mode-restart t]
15825 (defun org-info (&optional node)
15826 "Read documentation for Org-mode in the info system.
15827 With optional NODE, go directly to that node."
15830 (Info-goto-node (format "(org)%s" (or node ""))))
15832 (defun org-install-agenda-files-menu ()
15833 (let ((bl (buffer-list)))
15836 (set-buffer (pop bl))
15837 (if (eq major-mode 'org-mode) (setq bl nil)))
15838 (when (eq major-mode 'org-mode)
15840 '("Org") "File List for Agenda"
15843 ["Edit File List" (org-edit-agenda-file-list) t]
15844 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15845 ["Remove Current File from List" org-remove-file t]
15846 ["Cycle through agenda files" org-cycle-agenda-files t]
15848 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15852 (defun org-customize ()
15853 "Call the customize function with org as argument."
15855 (customize-browse 'org))
15857 (defun org-create-customize-menu ()
15858 "Create a full customization menu for Org-mode, insert it into the menu."
15860 (if (fboundp 'customize-menu-create)
15863 '("Org") "Customize"
15864 `(["Browse Org group" org-customize t]
15866 ,(customize-menu-create 'org)
15867 ["Set" Custom-set t]
15868 ["Save" Custom-save t]
15869 ["Reset to Current" Custom-reset-current t]
15870 ["Reset to Saved" Custom-reset-saved t]
15871 ["Reset to Standard Settings" Custom-reset-standard t]))
15872 (message "\"Org\"-menu now contains full customization menu"))
15873 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15875 ;;; Miscellaneous stuff
15877 (defun org-context ()
15878 "Return a list of contexts of the current cursor position.
15879 If several contexts apply, all are returned.
15880 Each context entry is a list with a symbol naming the context, and
15881 two positions indicating start and end of the context. Possible
15884 :headline anywhere in a headline
15885 :headline-stars on the leading stars in a headline
15886 :todo-keyword on a TODO keyword (including DONE) in a headline
15887 :tags on the TAGS in a headline
15888 :priority on the priority cookie in a headline
15889 :item on the first line of a plain list item
15890 :item-bullet on the bullet/number of a plain list item
15891 :checkbox on the checkbox in a plain list item
15892 :table in an org-mode table
15893 :table-special on a special filed in a table
15894 :table-table in a table.el table
15895 :link on a hyperline
15896 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15897 :target on a <<target>>
15898 :radio-target on a <<<radio-target>>>
15899 :latex-fragment on a LaTeX fragment
15900 :latex-preview on a LaTeX fragment with overlayed preview image
15902 This function expects the position to be visible because it uses font-lock
15903 faces as a help to recognize the following contexts: :table-special, :link,
15905 (let* ((f (get-text-property (point) 'face))
15906 (faces (if (listp f) f (list f)))
15907 (p (point)) clist o)
15908 ;; First the large context
15910 ((org-on-heading-p)
15911 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15913 (beginning-of-line 1)
15914 (looking-at org-todo-line-tags-regexp))
15915 (push (org-point-in-group p 1 :headline-stars) clist)
15916 (push (org-point-in-group p 2 :todo-keyword) clist)
15917 (push (org-point-in-group p 4 :tags) clist))
15919 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15920 (if (looking-at "\\[#[A-Z]\\]")
15921 (push (org-point-in-group p 0 :priority) clist)))
15924 (push (org-point-in-group p 2 :item-bullet) clist)
15925 (push (list :item (point-at-bol)
15926 (save-excursion (org-end-of-item) (point)))
15928 (and (org-at-item-checkbox-p)
15929 (push (org-point-in-group p 0 :checkbox) clist)))
15932 (push (list :table (org-table-begin) (org-table-end)) clist)
15933 (if (memq 'org-formula faces)
15934 (push (list :table-special
15935 (previous-single-property-change p 'face)
15936 (next-single-property-change p 'face)) clist)))
15937 ((org-at-table-p 'any)
15938 (push (list :table-table) clist)))
15941 ;; Now the small context
15943 ((org-at-timestamp-p)
15944 (push (org-point-in-group p 0 :timestamp) clist))
15945 ((memq 'org-link faces)
15947 (previous-single-property-change p 'face)
15948 (next-single-property-change p 'face)) clist))
15949 ((memq 'org-special-keyword faces)
15950 (push (list :keyword
15951 (previous-single-property-change p 'face)
15952 (next-single-property-change p 'face)) clist))
15954 (push (org-point-in-group p 0 :target) clist)
15955 (goto-char (1- (match-beginning 0)))
15956 (if (looking-at org-radio-target-regexp)
15957 (push (org-point-in-group p 0 :radio-target) clist))
15959 ((setq o (car (delq nil
15962 (if (memq x org-latex-fragment-image-overlays) x))
15963 (org-overlays-at (point))))))
15964 (push (list :latex-fragment
15965 (org-overlay-start o) (org-overlay-end o)) clist)
15966 (push (list :latex-preview
15967 (org-overlay-start o) (org-overlay-end o)) clist))
15968 ((org-inside-LaTeX-fragment-p)
15969 ;; FIXME: positions wring.
15970 (push (list :latex-fragment (point) (point)) clist)))
15972 (setq clist (nreverse (delq nil clist)))
15975 (defun org-point-in-group (point group &optional context)
15976 "Check if POINT is in match-group GROUP.
15977 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15978 match. If the match group does ot exist or point is not inside it,
15980 (and (match-beginning group)
15981 (>= point (match-beginning group))
15982 (<= point (match-end group))
15984 (list context (match-beginning group) (match-end group))
15987 (defun org-move-line-down (arg)
15988 "Move the current line down. With prefix argument, move it past ARG lines."
15990 (let ((col (current-column))
15992 (beginning-of-line 1) (setq beg (point))
15993 (beginning-of-line 2) (setq end (point))
15994 (beginning-of-line (+ 1 arg))
15995 (setq pos (move-marker (make-marker) (point)))
15996 (insert (delete-and-extract-region beg end))
15998 (move-to-column col)))
16000 (defun org-move-line-up (arg)
16001 "Move the current line up. With prefix argument, move it past ARG lines."
16003 (let ((col (current-column))
16005 (beginning-of-line 1) (setq beg (point))
16006 (beginning-of-line 2) (setq end (point))
16007 (beginning-of-line (- arg))
16008 (setq pos (move-marker (make-marker) (point)))
16009 (insert (delete-and-extract-region beg end))
16011 (move-to-column col)))
16013 ;; Paragraph filling stuff.
16014 ;; We want this to be just right, so use the full arsenal.
16016 (defun org-set-autofill-regexps ()
16018 ;; In the paragraph separator we include headlines, because filling
16019 ;; text in a line directly attached to a headline would otherwise
16020 ;; fill the headline as well.
16021 (set (make-local-variable 'comment-start-skip) "^#+[ \t]*")
16022 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
16023 ;; The paragraph starter includes hand-formatted lists.
16024 (set (make-local-variable 'paragraph-start)
16025 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
16026 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16027 ;; But only if the user has not turned off tables or fixed-width regions
16028 (set (make-local-variable 'auto-fill-inhibit-regexp)
16030 "\\|[ \t]*" org-keyword-time-regexp
16031 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16034 (if org-enable-table-editor "|" "")
16035 (if org-enable-fixed-width-editor ":" "")
16037 ;; We use our own fill-paragraph function, to make sure that tables
16038 ;; and fixed-width regions are not wrapped. That function will pass
16039 ;; through to `fill-paragraph' when appropriate.
16040 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
16041 ;; Adaptive filling: To get full control, first make sure that
16042 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16043 (set (make-local-variable 'adaptive-fill-regexp) "\000")
16044 (set (make-local-variable 'adaptive-fill-function)
16045 'org-adaptive-fill-function))
16047 (defun org-fill-paragraph (&optional justify)
16048 "Re-align a table, pass through to fill-paragraph if no table."
16049 (let ((table-p (org-at-table-p))
16050 (table.el-p (org-at-table.el-p)))
16051 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
16052 (table.el-p t) ; skip table.el tables
16053 (table-p (org-table-align) t) ; align org-mode tables
16054 (t nil)))) ; call paragraph-fill
16056 ;; For reference, this is the default value of adaptive-fill-regexp
16057 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16059 (defun org-adaptive-fill-function ()
16060 "Return a fill prefix for org-mode files.
16061 In particular, this makes sure hanging paragraphs for hand-formatted lists
16063 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
16064 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
16066 ;; Functions needed for Emacs/XEmacs region compatibility
16068 (defun org-add-hook (hook function &optional append local)
16069 "Add-hook, compatible with both Emacsen."
16070 (if (and local (featurep 'xemacs))
16071 (add-local-hook hook function append)
16072 (add-hook hook function append local)))
16074 (defun org-region-active-p ()
16075 "Is `transient-mark-mode' on and the region active?
16076 Works on both Emacs and XEmacs."
16077 (if org-ignore-region
16079 (if (featurep 'xemacs)
16080 (and zmacs-regions (region-active-p))
16081 (and transient-mark-mode mark-active))))
16083 (defun org-add-to-invisibility-spec (arg)
16084 "Add elements to `buffer-invisibility-spec'.
16085 See documentation for `buffer-invisibility-spec' for the kind of elements
16086 that can be added."
16088 ((fboundp 'add-to-invisibility-spec)
16089 (add-to-invisibility-spec arg))
16090 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
16091 (setq buffer-invisibility-spec (list arg)))
16093 (setq buffer-invisibility-spec
16094 (cons arg buffer-invisibility-spec)))))
16096 (defun org-remove-from-invisibility-spec (arg)
16097 "Remove elements from `buffer-invisibility-spec'."
16098 (if (fboundp 'remove-from-invisibility-spec)
16099 (remove-from-invisibility-spec arg)
16100 (if (consp buffer-invisibility-spec)
16101 (setq buffer-invisibility-spec
16102 (delete arg buffer-invisibility-spec)))))
16104 (defun org-in-invisibility-spec-p (arg)
16105 "Is ARG a member of `buffer-invisibility-spec'?"
16106 (if (consp buffer-invisibility-spec)
16107 (member arg buffer-invisibility-spec)
16110 (defun org-image-file-name-regexp ()
16111 "Return regexp matching the file names of images."
16112 (if (fboundp 'image-file-name-regexp)
16113 (image-file-name-regexp)
16114 (let ((image-file-name-extensions
16115 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16116 "xbm" "xpm" "pbm" "pgm" "ppm")))
16118 (regexp-opt (nconc (mapcar 'upcase
16119 image-file-name-extensions)
16120 image-file-name-extensions)
16124 ;; Functions needed for compatibility with old outline.el.
16126 ;; Programming for the old outline.el (that uses selective display
16127 ;; instead of `invisible' text properties) is a nightmare, mostly
16128 ;; because regular expressions can no longer be anchored at
16129 ;; beginning/end of line. Therefore a number of function need special
16130 ;; treatment when the old outline.el is being used.
16132 ;; The following functions capture almost the entire compatibility code
16133 ;; between the different versions of outline-mode. The only other
16134 ;; places where this is important are the font-lock-keywords, and in
16135 ;; `org-export-visible'. Search for `org-noutline-p' to find them.
16137 ;; C-a should go to the beginning of a *visible* line, also in the
16138 ;; new outline.el. I guess this should be patched into Emacs?
16139 (defun org-beginning-of-line ()
16140 "Go to the beginning of the current line. If that is invisible, continue
16141 to a visible line beginning. This makes the function of C-a more intuitive."
16143 (beginning-of-line 1)
16147 (if (org-invisible-p)
16148 (while (and (not (bobp)) (org-invisible-p))
16150 (beginning-of-line 1))
16151 (forward-char 1))))
16153 (when org-noutline-p
16154 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
16156 (defun org-invisible-p ()
16157 "Check if point is at a character currently not visible."
16159 ;; Early versions of noutline don't have `outline-invisible-p'.
16160 (if (fboundp 'outline-invisible-p)
16161 (outline-invisible-p)
16162 (get-char-property (point) 'invisible))
16164 (skip-chars-backward "^\r\n")
16165 (equal (char-before) ?\r))))
16167 (defun org-invisible-p2 ()
16168 "Check if point is at a character currently not visible."
16172 (if (and (eolp) (not (bobp))) (backward-char 1))
16173 ;; Early versions of noutline don't have `outline-invisible-p'.
16174 (if (fboundp 'outline-invisible-p)
16175 (outline-invisible-p)
16176 (get-char-property (point) 'invisible)))
16177 (skip-chars-backward "^\r\n")
16178 (equal (char-before) ?\r))))
16180 (defun org-back-to-heading (&optional invisible-ok)
16181 "Move to previous heading line, or beg of this line if it's a heading.
16182 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
16184 (outline-back-to-heading invisible-ok)
16185 (if (and (or (bobp) (memq (char-before) '(?\n ?\r)))
16186 (looking-at outline-regexp))
16188 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
16192 (progn (goto-char (or (match-end 1) (match-beginning 0)))
16193 (looking-at outline-regexp)))
16194 (error "Before first heading")))))
16196 (defun org-on-heading-p (&optional invisible-ok)
16197 "Return t if point is on a (visible) heading line.
16198 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
16200 (outline-on-heading-p 'invisible-ok)
16202 (skip-chars-backward "^\n\r")
16203 (and (looking-at outline-regexp)
16206 (equal (char-before) ?\n))))))
16208 (defun org-on-target-p ()
16209 (let ((pos (point)))
16211 (skip-chars-forward "<")
16212 (and (re-search-backward "<<" nil t)
16213 (or (looking-at org-radio-target-regexp)
16214 (looking-at org-target-regexp))
16215 (<= (match-beginning 0) pos)
16216 (>= (1+ (match-end 0)) pos)))))
16218 (defun org-up-heading-all (arg)
16219 "Move to the heading line of which the present line is a subheading.
16220 This function considers both visible and invisible heading lines.
16221 With argument, move up ARG levels."
16223 (if (fboundp 'outline-up-heading-all)
16224 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16225 (outline-up-heading arg t)) ; emacs 22 version of outline.el
16226 (org-back-to-heading t)
16227 (looking-at outline-regexp)
16228 (if (<= (- (match-end 0) (match-beginning 0)) arg)
16229 (error "Cannot move up %d levels" arg)
16230 (re-search-backward
16231 (concat "[\n\r]" (regexp-quote
16232 (make-string (- (match-end 0) (match-beginning 0) arg)
16235 (forward-char 1))))
16237 (defun org-show-hidden-entry ()
16238 "Show an entry where even the heading is hidden."
16240 (if (not org-noutline-p)
16242 (org-back-to-heading t)
16243 (org-flag-heading nil)))
16246 (defun org-check-occur-regexp (regexp)
16247 "If REGEXP starts with \"^\", modify it to check for \\r as well.
16248 Of course, only for the old outline mode."
16251 (if (string-match "^\\^" regexp)
16252 (concat "[\n\r]" (substring regexp 1))
16255 (defun org-flag-heading (flag &optional entry)
16256 "Flag the current heading. FLAG non-nil means make invisible.
16257 When ENTRY is non-nil, show the entire entry."
16259 (org-back-to-heading t)
16260 (if (not org-noutline-p)
16261 ;; Make the current headline visible
16262 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
16263 ;; Check if we should show the entire entry
16268 (and (outline-next-heading)
16269 (org-flag-heading nil))))
16270 (outline-flag-region (max 1 (1- (point)))
16271 (save-excursion (outline-end-of-heading) (point))
16274 (if flag ?\r ?\n))))))
16276 (defun org-end-of-subtree (&optional invisible-OK)
16277 ;; This is an exact copy of the original function, but it uses
16278 ;; `org-back-to-heading', to make it work also in invisible
16279 ;; trees. And is uses an invisible-OK argument.
16280 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16281 (org-back-to-heading invisible-OK)
16283 (level (funcall outline-level)))
16284 (while (and (not (eobp))
16285 (or first (> (funcall outline-level) level)))
16287 (outline-next-heading))
16288 (if (memq (preceding-char) '(?\n ?\^M))
16290 ;; Go to end of line before heading
16292 (if (memq (preceding-char) '(?\n ?\^M))
16293 ;; leave blank line before heading
16294 (forward-char -1)))))
16297 (defun org-show-subtree ()
16298 "Show everything after this heading at deeper levels."
16299 (outline-flag-region
16302 (outline-end-of-subtree) (outline-next-heading) (point))
16303 (if org-noutline-p nil ?\n)))
16305 (defun org-show-entry ()
16306 "Show the body directly following this heading.
16307 Show the heading too, if it is currently invisible."
16310 (org-back-to-heading t)
16311 (outline-flag-region
16312 (max 1 (1- (point)))
16314 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
16315 (or (match-beginning 1) (point-max)))
16316 (if org-noutline-p nil ?\n))))
16318 (defun org-make-options-regexp (kwds)
16319 "Make a regular expression for keyword lines."
16321 (if org-noutline-p "^" "[\n\r]")
16323 (mapconcat 'regexp-quote kwds "\\|")
16325 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
16327 ;; Make `bookmark-jump' show the jump location if it was hidden.
16328 (eval-after-load "bookmark"
16329 '(if (boundp 'bookmark-after-jump-hook)
16330 ;; We can use the hook
16331 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16332 ;; Hook not available, use advice
16333 (defadvice bookmark-jump (after org-make-visible activate)
16334 "Make the position visible."
16335 (org-bookmark-jump-unhide))))
16337 (defun org-bookmark-jump-unhide ()
16338 "Unhide the current position, to show the bookmark location."
16339 (and (eq major-mode 'org-mode)
16340 (or (org-invisible-p)
16341 (save-excursion (goto-char (max (point-min) (1- (point))))
16342 (org-invisible-p)))
16343 (org-show-hierarchy-above)))
16345 ;;; Experimental code
16351 (run-hooks 'org-load-hook)
16353 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16354 ;;; org.el ends here