1 ;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (c) 2004, 2005 Free Software Foundation
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 a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
63 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
64 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
66 ;; This setup will put all files with extension ".org" into Org-mode. As
67 ;; an alternative, make the first line of a file look like this:
69 ;; MY PROJECTS -*- mode: org; -*-
71 ;; which will select Org-mode for this buffer no matter what the file's
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke. This card can be found
80 ;; in the etc/ directory of Emacs 22.
85 ;; - Tags can also be set remotely from agenda buffer.
86 ;; - Boolean logic for tag searches.
87 ;; - Additional agenda commands can be configured through the variable
88 ;; `org-agenda-custom-commands'.
92 ;; - Headlines can contain TAGS, and Org-mode can produced a list
93 ;; of matching headlines based on a TAG search expression.
94 ;; - `org-agenda' has now become a dispatcher that will produce the agenda
95 ;; and other views on org-mode data with an additional keypress.
98 ;; - Switching and item to DONE records a time stamp when the variable
99 ;; `org-log-done' is turned on. Default is off.
102 ;; - M-RET makes new items as well as new headings.
103 ;; - Various small bug fixes
106 ;; - CamelCase words link to other locations in the same file.
107 ;; - File links accept search options, to link to specific locations.
108 ;; - Plain list items can be folded with `org-cycle'. See new option
109 ;; `org-cycle-include-plain-lists'.
110 ;; - Sparse trees for specific TODO keywords through numeric prefix
111 ;; argument to `C-c C-v'.
112 ;; - Global TODO list, also for specific keywords.
113 ;; - Matches in sparse trees are highlighted (highlights disappear with
114 ;; next buffer change due to editing).
117 ;; - Improved CSS support for the HTML export. Thanks to Christian Egli.
118 ;; - Editing support for hand-formatted lists
119 ;; - M-S-cursor keys handle plain list items
120 ;; - C-c C-c renumbers ordered plain lists
123 ;; - There is finally an option to make TAB jump over horizontal lines
124 ;; in tables instead of creating a new line before that line.
125 ;; The option is `org-table-tab-jumps-over-hlines', default nil.
126 ;; - New command for sorting tables, on `C-c ^'.
127 ;; - Changes to the HTML exporter
128 ;; - hand-formatted lists are exported correctly, similar to
129 ;; markdown lists. Nested lists are possible. See the docstring
130 ;; of the variable `org-export-plain-list-max-depth'.
131 ;; - cleaned up to produce valid HTML 4.0 (transitional).
132 ;; - support for cascading style sheets.
133 ;; - New command to cycle through all agenda files, on C-,
134 ;; - C-c [ can now also be used to change the sequence of agenda files.
140 ;; - Export of calendar information in the standard iCalendar format.
144 ;; - HTML export specifies character set depending on coding-system.
147 ;; - In tables, directly after the field motion commands like TAB and RET,
148 ;; typing a character will blank the field. Can be turned off with
149 ;; variable `org-table-auto-blank-field'.
150 ;; - Inactive timestamps with `C-c !'. These do not trigger the agenda
151 ;; and are not linked to the calendar.
152 ;; - Additional key bindings to allow Org-mode to function on a tty emacs.
153 ;; - `C-c C-h' prefix key replaced by `C-c C-x', and `C-c C-x C-h' replaced
154 ;; by `C-c C-x b' (b=Browser). This was necessary to recover the
155 ;; standard meaning of C-h after a prefix key (show prefix bindings).
158 ;; - QUOTE keyword at the beginning of an entry causes fixed-width export
159 ;; of unmodified entry text. `C-c :' toggles this keyword.
160 ;; - New face `org-special-keyword' which is used for COMMENT, QUOTE,
161 ;; DEADLINE and SCHEDULED, and priority cookies. Default is only a weak
162 ;; color, to reduce the amount of aggressive color in the buffer.
165 ;; - Formulas for individual fields in table.
166 ;; - Automatic recalculation in calculating tables.
167 ;; - Named fields and columns in tables.
168 ;; - Fixed bug with calling `org-archive' several times in a row.
171 ;; - Efficiency improvements: Fewer table re-alignments needed.
172 ;; - New special lines in tables, for defining names for individual cells.
175 ;; - Tables can store formulas (one per column) and compute fields.
176 ;; Not quite like a full spreadsheet, but very powerful.
177 ;; - table.el keybinding is now `C-c ~'.
178 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
179 ;; - Small changes to keys in agenda buffer. Affected keys:
180 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
184 ;; - Links inserted with C-c C-l are now by default enclosed in angle
185 ;; brackets. See the new variable `org-link-format'.
186 ;; - ">" terminates a link, this is a way to have several links in a line.
187 ;; Both "<" and ">" are no longer allowed as characters in a link.
188 ;; - Archiving of finished tasks.
189 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
190 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
191 ;; - Compatibility problems with viper-mode fixed.
192 ;; - Improved html export of tables.
193 ;; - Various clean-up changes.
196 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
199 ;; - Time-of-day specifications in agenda are extracted and placed
200 ;; into the prefix. Timed entries can be placed into a time grid for
204 ;; - "|" no longer allowed as part of a link, to allow links in tables.
205 ;; - The prefix of items in the agenda buffer can be configured.
209 ;; - Some folding inconsistencies removed.
210 ;; - BBDB links to company-only entries.
211 ;; - Bug fixes and global cleanup.
214 ;; - M-S-RET inserts a new TODO heading.
215 ;; - New startup option `content'.
216 ;; - Better visual response when TODO items in agenda change status.
217 ;; - Window positioning after visibility state changes optimized and made
218 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
221 ;; - Agenda entries from the diary are linked to the diary file, so
222 ;; adding and editing diary entries can be done directly from the agenda.
223 ;; - Many calendar/diary commands available directly from agenda.
224 ;; - Field copying in tables with S-RET does increment.
225 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
226 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
229 ;; - Table editor optimized to need fewer realignments, and to keep
230 ;; table shape when typing in fields.
231 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
232 ;; into arbitrary major modes.
233 ;; - Fixed bug with realignment in XEmacs.
234 ;; - Startup options can be set with special #+STARTUP line.
235 ;; - Heading following a match in org-occur can be suppressed.
238 ;; - Copyright transfer to the FSF.
239 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
240 ;; - Timeline now always contains today, and `.' jumps to it.
242 ;; - cut and paste of rectangular regions in tables
243 ;; - command to convert org-mode table to table.el table and back
244 ;; - command to treat several cells like a paragraph and fill it
245 ;; - command to convert a buffer region to a table
246 ;; - import/export tables as tab-separated files (exchange with Excel)
248 ;; - Sorting mechanism for agenda items rewritten from scratch.
249 ;; - Sorting fully configurable.
250 ;; - Entries specifying a time are sorted together.
251 ;; - Completion also covers option keywords after `#-'.
255 ;; - New reference card, thanks to Philip Rooke for creating it.
256 ;; - Single file agenda renamed to "Timeline". It no longer shows
257 ;; warnings about upcoming deadlines/overdue scheduled items.
258 ;; That functionality is now limited to the (multifile) agenda.
259 ;; - When reading a date, the calendar can be manipulated with keys.
260 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
261 ;; - Minor bug fixes and documentation improvements.
265 (eval-when-compile (require 'cl) (require 'calendar))
270 (defvar calc-embedded-close-formula)
271 (defvar calc-embedded-open-formula)
272 (defvar font-lock-unfontify-region-function)
274 ;;; Customization variables
276 (defvar org-version "4.01"
277 "The version number of the file org.el.")
278 (defun org-version ()
280 (message "Org-mode version %s" org-version))
282 ;; The following two constants are for compatibility with different Emacs
283 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
284 ;; The compatibility code in org.el is based on these two constants.
285 (defconst org-xemacs-p (featurep 'xemacs)
286 "Are we running xemacs?")
287 (defconst org-noutline-p (featurep 'noutline)
288 "Are we using the new outline mode?")
291 "Outline-based notes management and organizer "
297 (defgroup org-startup nil
298 "Options concerning startup of Org-mode."
302 (defcustom org-CUA-compatible nil
303 "Non-nil means use alternative key bindings for S-<cursor movement>.
304 Org-mode used S-<cursor movement> for changing timestamps and priorities.
305 S-<cursor movement> is also used for example by `CUA-mode' to select text.
306 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
307 alternative bindings. Setting this variable to t will replace the following
308 keys both in Org-mode and in the Org-agenda buffer.
316 If you do not like the alternative keys, take a look at the variable
319 This option is only relevant at load-time of Org-mode. Changing it requires
320 a restart of Emacs to become effective."
324 (defvar org-disputed-keys
325 '((S-up [(shift up)] [(meta ?p)])
326 (S-down [(shift down)] [(meta ?n)])
327 (S-left [(shift left)] [(meta ?-)])
328 (S-right [(shift right)] [(meta ?+)])
329 (S-return [(shift return)] [(control shift return)]))
330 "Keys for which Org-mode and other modes compete.
331 This is an alist, cars are symbols for lookup, 1st element is the default key,
332 second element will be used when `org-CUA-compatible' is t.")
335 "Select a key according to `org-CUA-compatible'."
336 (nth (if org-CUA-compatible 2 1)
337 (or (assq key org-disputed-keys)
338 (error "Invalid Key %s in `org-key'" key))))
340 (defcustom org-startup-folded t
341 "Non-nil means, entering Org-mode will switch to OVERVIEW.
342 This can also be configured on a per-file basis by adding one of
343 the following lines anywhere in the buffer:
350 (const :tag "nofold: show all" nil)
351 (const :tag "fold: overview" t)
352 (const :tag "content: all headlines" content)))
354 (defcustom org-startup-truncated t
355 "Non-nil means, entering Org-mode will set `truncate-lines'.
356 This is useful since some lines containing links can be very long and
357 uninteresting. Also tables look terrible when wrapped."
361 (defcustom org-startup-with-deadline-check nil
362 "Non-nil means, entering Org-mode will run the deadline check.
363 This means, if you start editing an org file, you will get an
364 immediate reminder of any due deadlines.
365 This can also be configured on a per-file basis by adding one of
366 the following lines anywhere in the buffer:
369 #+STARTUP: nodlcheck"
373 (defcustom org-insert-mode-line-in-empty-file nil
374 "Non-nil means insert the first line setting Org-mode in empty files.
375 When the function `org-mode' is called interactively in an empty file, this
376 normally means that the file name does not automatically trigger Org-mode.
377 To ensure that the file will always be in Org-mode in the future, a
378 line enforcing Org-mode will be inserted into the buffer, if this option
383 (defgroup org-keywords nil
384 "Options concerning TODO items in Org-mode."
388 (defcustom org-todo-keywords '("TODO" "DONE")
389 "List of TODO entry keywords.
390 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
391 considered to mean that the entry is \"done\". All the other mean that
392 action is required, and will make the entry show up in todo lists, diaries
394 The command \\[org-todo] cycles an entry through these states, and an
395 additional state where no keyword is present. For details about this
396 cycling, see also the variable `org-todo-interpretation'
397 Changes become only effective after restarting Emacs."
399 :type '(repeat (string :tag "Keyword")))
401 (defcustom org-todo-interpretation 'sequence
402 "Controls how TODO keywords are interpreted.
403 \\<org-mode-map>Possible values are `sequence' and `type'.
404 This variable is only relevant if `org-todo-keywords' contains more than two
405 states. There are two ways how these keywords can be used:
407 - As a sequence in the process of working on a TODO item, for example
408 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
409 org-todo-interpretation 'sequence)
411 - As different types of TODO items, for example
412 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
413 org-todo-interpretation 'type)
415 When the states are interpreted as a sequence, \\[org-todo] always cycles
416 to the next state, in order to walk through all different states. So with
417 \\[org-todo], you turn an empty entry into the state TODO. When you started
418 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
419 later to VERIFY and finally to DONE.
421 When the states are interpreted as types, \\[org-todo] still cycles through
422 when it is called several times in direct succession, in order to initially
423 select the type. However, if not called immediately after a previous
424 \\[org-todo], it switches from each type directly to DONE. So with the
425 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
426 RELAXED. If you later return to this entry and press \\[org-todo] again,
427 RELAXED will not be changed REMIND, but directly to DONE.
429 You can create a large number of types. To initially select a
430 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
431 type with completion. Of course, you can also type the keyword
432 directly into the buffer. M-TAB completes TODO keywords at the
433 beginning of a headline."
435 :type '(choice (const sequence)
438 (defcustom org-default-priority ?B
439 "The default priority of TODO items.
440 This is the priority an item get if no explicit priority is given."
444 (defcustom org-lowest-priority ?C
445 "The lowest priority of TODO items. A character like ?A, ?B etc."
449 (defcustom org-deadline-string "DEADLINE:"
450 "String to mark deadline entries.
451 A deadline is this string, followed by a time stamp. Should be a word,
452 terminated by a colon. You can insert a schedule keyword and
453 a timestamp with \\[org-deadline].
454 Changes become only effective after restarting Emacs."
458 (defcustom org-scheduled-string "SCHEDULED:"
459 "String to mark scheduled TODO entries.
460 A schedule is this string, followed by a time stamp. Should be a word,
461 terminated by a colon. You can insert a schedule keyword and
462 a timestamp with \\[org-schedule].
463 Changes become only effective after restarting Emacs."
467 (defcustom org-closed-string "CLOSED:"
468 "String ued as the prefix for timestamps logging closing a TODO entry."
472 (defcustom org-comment-string "COMMENT"
473 "Entries starting with this keyword will never be exported.
474 An entry can be toggled between COMMENT and normal with
475 \\[org-toggle-comment].
476 Changes become only effective after restarting Emacs."
480 (defcustom org-quote-string "QUOTE"
481 "Entries starting with this keyword will be exported in fixed-width font.
482 Quoting applies only to the text in the entry following the headline, and does
483 not extend beyond the next headline, even if that is lower level.
484 An entry can be toggled between QUOTE and normal with
485 \\[org-toggle-fixed-width-section]"
489 (defcustom org-after-todo-state-change-hook nil
490 "Hook which is run after the state of a TODO item was changed.
491 The new state (a string with a todo keyword, or nil) is available in the
492 Lisp variable `state'."
496 ;; Variables for pre-computed regular expressions, all buffer local
497 (defvar org-todo-kwd-priority-p nil
498 "Do TODO items have priorities?")
499 (make-variable-buffer-local 'org-todo-kwd-priority-p)
500 (defvar org-todo-kwd-max-priority nil
501 "Maximum priority of TODO items.")
502 (make-variable-buffer-local 'org-todo-kwd-max-priority)
503 (defvar org-ds-keyword-length 12
504 "Maximum length of the Deadline and SCHEDULED keywords.")
505 (make-variable-buffer-local 'org-ds-keyword-length)
506 (defvar org-done-string nil
507 "The last string in `org-todo-keywords', indicating an item is DONE.")
508 (make-variable-buffer-local 'org-done-string)
509 (defvar org-todo-regexp nil
510 "Matches any of the TODO state keywords.")
511 (make-variable-buffer-local 'org-todo-regexp)
512 (defvar org-not-done-regexp nil
513 "Matches any of the TODO state keywords except the last one.")
514 (make-variable-buffer-local 'org-not-done-regexp)
515 (defvar org-todo-line-regexp nil
516 "Matches a headline and puts TODO state into group 2 if present.")
517 (make-variable-buffer-local 'org-todo-line-regexp)
518 (defvar org-nl-done-regexp nil
519 "Matches newline followed by a headline with the DONE keyword.")
520 (make-variable-buffer-local 'org-nl-done-regexp)
521 (defvar org-looking-at-done-regexp nil
522 "Matches the DONE keyword a point.")
523 (make-variable-buffer-local 'org-looking-at-done-regexp)
524 (defvar org-deadline-regexp nil
525 "Matches the DEADLINE keyword.")
526 (make-variable-buffer-local 'org-deadline-regexp)
527 (defvar org-deadline-time-regexp nil
528 "Matches the DEADLINE keyword together with a time stamp.")
529 (make-variable-buffer-local 'org-deadline-time-regexp)
530 (defvar org-deadline-line-regexp nil
531 "Matches the DEADLINE keyword and the rest of the line.")
532 (make-variable-buffer-local 'org-deadline-line-regexp)
533 (defvar org-scheduled-regexp nil
534 "Matches the SCHEDULED keyword.")
535 (make-variable-buffer-local 'org-scheduled-regexp)
536 (defvar org-scheduled-time-regexp nil
537 "Matches the SCHEDULED keyword together with a time stamp.")
538 (make-variable-buffer-local 'org-scheduled-time-regexp)
540 (defvar org-category nil
541 "Variable used by org files to set a category for agenda display.
542 Such files should use a file variable to set it, for example
544 -*- mode: org; org-category: \"ELisp\"
546 or contain a special line
550 If the file does not specify a category, then file's base name
552 (make-variable-buffer-local 'org-category)
554 (defgroup org-time nil
555 "Options concerning time stamps and deadlines in Org-mode."
559 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
560 "Formats for `format-time-string' which are used for time stamps.
561 It is not recommended to change this constant.")
564 (defcustom org-deadline-warning-days 30
565 "No. of days before expiration during which a deadline becomes active.
566 This variable governs the display in the org file."
570 (defcustom org-popup-calendar-for-date-prompt t
571 "Non-nil means, pop up a calendar when prompting for a date.
572 In the calendar, the date can be selected with mouse-1. However, the
573 minibuffer will also be active, and you can simply enter the date as well.
574 When nil, only the minibuffer will be available."
578 (defcustom org-calendar-follow-timestamp-change t
579 "Non-nil means, make the calendar window follow timestamp changes.
580 When a timestamp is modified and the calendar window is visible, it will be
581 moved to the new date."
585 (defcustom org-log-done nil
586 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
587 When the state of an entry is changed from nothing to TODO, remove a previous
592 (defgroup org-agenda nil
593 "Options concerning agenda display Org-mode."
597 (defcustom org-agenda-files nil
598 "A list of org files for agenda/diary display.
599 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
600 \\[org-remove-file]. You can also use customize to edit the list."
602 :type '(repeat file))
604 (defcustom org-agenda-custom-commands
605 '(("w" todo "WAITING")
606 ("u" tags "+WORK+URGENT-BOSS"))
607 "Custom commands for the agenda.
608 These commands will be offered on the splash screen displayed by the
609 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
611 key The key (as a string) to be associated with the command.
612 type The command type, either `todo' for a todo list with a specific
613 todo keyword, or `tags' for a tags search.
614 match What to search for. Either a TODO keyword, or a tags match query."
617 (list (string :tag "Key")
618 (choice :tag "Type" (const tags) (const todo))
619 (string :tag "Match"))))
621 (defcustom org-select-timeline-window t
622 "Non-nil means, after creating a timeline, move cursor into Timeline window.
623 When nil, cursor will remain in the current window."
627 (defcustom org-select-agenda-window t
628 "Non-nil means, after creating an agenda, move cursor into Agenda window.
629 When nil, cursor will remain in the current window."
633 (defcustom org-fit-agenda-window t
634 "Non-nil means, change window size of agenda to fit content."
638 (defcustom org-agenda-show-all-dates t
639 "Non-nil means, `org-agenda' shows every day in the selected range.
640 When nil, only the days which actually have entries are shown."
644 ;; FIXME: First day of month works only for current month because it would
645 ;; require a variable ndays treatment.
646 (defcustom org-agenda-start-on-weekday 1
647 "Non-nil means, start the overview always on the specified weekday.
648 0 Denotes Sunday, 1 denotes Monday etc.
649 When nil, always start on the current day."
651 :type '(choice (const :tag "Today" nil)
652 (const :tag "First day of month" t)
653 (number :tag "Weekday No.")))
655 (defcustom org-agenda-ndays 7
656 "Number of days to include in overview display."
660 (defcustom org-agenda-include-all-todo t
661 "Non-nil means, the agenda will always contain all TODO entries.
662 When nil, date-less entries will only be shown if `org-agenda' is called
663 with a prefix argument.
664 When non-nil, the TODO entries will be listed at the top of the agenda, before
665 the entries for specific days."
669 (defcustom org-agenda-include-diary nil
670 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
674 (defcustom org-calendar-to-agenda-key [?c]
675 "The key to be installed in `calendar-mode-map' for switching to the agenda.
676 The command `org-calendar-goto-agenda' will be bound to this key. The
677 default is the character `c' because then`c' can be used to switch back and
678 force between agenda and calendar."
682 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
683 "Sorting structure for the agenda items of a single day.
684 This is a list of symbols which will be used in sequence to determine
685 if an entry should be listed before another entry. The following
686 symbols are recognized.
688 time-up Put entries with time-of-day indications first, early first
689 time-down Put entries with time-of-day indications first, late first
690 category-keep Keep the default order of categories, corresponding to the
691 sequence in `org-agenda-files'.
692 category-up Sort alphabetically by category, A-Z.
693 category-down Sort alphabetically by category, Z-A.
694 priority-up Sort numerically by priority, high priority last.
695 priority-down Sort numerically by priority, high priority first.
697 The different possibilities will be tried in sequence, and testing stops
698 if one comparison returns a \"not-equal\". For example, the default
699 '(time-up category-keep priority-down)
700 means: Pull out all entries having a specified time of day and sort them,
701 in order to make a time schedule for the current day the first thing in the
702 agenda listing for the day. Of the entries without a time indication, keep
703 the grouped in categories, don't sort the categories, but keep them in
704 the sequence given in `org-agenda-files'. Within each category sort by
707 Leaving out `category-keep' would mean that items will be sorted across
708 categories by priority."
714 (const category-keep)
716 (const category-down)
718 (const priority-down))))
720 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
721 "Format specification for the prefix of items in the agenda buffer.
722 This format works similar to a printf format, with the following meaning:
724 %c the category of the item, \"Diary\" for entries from the diary, or
725 as given by the CATEGORY keyword or derived from the file name.
726 %t the time-of-day specification if one applies to the entry, in the
728 %s Scheduling/Deadline information, a short string
730 All specifiers work basically like the standard `%s' of printf, but may
731 contain two additional characters: A question mark just after the `%' and
732 a whitespace/punctuation character just before the final letter.
734 If the first character after `%' is a question mark, the entire field
735 will only be included if the corresponding value applies to the
736 current entry. This is useful for fields which should have fixed
737 width when present, but zero width when absent. For example,
738 \"%?-12t\" will result in a 12 character time field if a time of the
739 day is specified, but will completely disappear in entries which do
742 If there is punctuation or whitespace character just before the final
743 format letter, this character will be appended to the field value if
744 the value is not empty. For example, the format \"%-12:c\" leads to
745 \"Diary: \" if the category is \"Diary\". If the category were be
746 empty, no additional colon would be interted.
748 The default value of this option is \" %-12:c%?-12t% s\", meaning:
749 - Indent the line with two space characters
750 - Give the category in a 12 chars wide field, padded with whitespace on
751 the right (because of `-'). Append a colon if there is a category
753 - If there is a time-of-day, put it into a 12 chars wide field. If no
754 time, don't put in an empty field, just skip it (because of '?').
755 - Finally, put the scheduling information and append a whitespace.
757 As another example, if you don't want the time-of-day of entries in
758 the prefix, you could use:
760 (setq org-agenda-prefix-format \" %-11:c% s\")
762 See also the variable `org-agenda-remove-times-when-in-prefix'."
766 (defcustom org-timeline-prefix-format " % s"
767 "Like `org-agenda-prefix-format', but for the timeline of a single file."
771 (defvar org-prefix-format-compiled nil
772 "The compiled version of the most recently used prefix format.
773 Depending on which command was used last, this may be the compiled version
774 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
776 (defcustom org-agenda-use-time-grid t
777 "Non-nil means, show a time grid in the agenda schedule.
778 A time grid is a set of lines for specific times (like every two hours between
779 8:00 and 20:00. The items scheduled for a day at specific times are
780 sorted in between these lines.
781 For deails about when the grid will be shown, and what it will look like, see
782 the variable `org-agenda-time-grid'."
786 (defcustom org-agenda-time-grid
787 '((daily today require-timed)
789 (800 1000 1200 1400 1600 1800 2000))
791 "The settings for time grid for agenda display.
792 This is a list of three items. The first item is again a list. It contains
793 symbols specifying conditions when the grid should be displayed:
795 daily if the agenda shows a single day
796 weekly if the agenda shows an entire week
797 today show grid on current date, independent of daily/weekly display
798 require-timed show grid only if at least on item has a time specification
800 The second item is a string which will be places behing the grid time.
802 The third item is a list of integers, indicating the times that should have
807 (set :greedy t :tag "Grid Display Options"
808 (const :tag "Show grid in single day agenda display" daily)
809 (const :tag "Show grid in weekly agenda display" weekly)
810 (const :tag "Always show grid for today" today)
811 (const :tag "Show grid only if any timed entries are present"
813 (const :tag "Skip grid times already present in an entry"
815 (string :tag "Grid String")
816 (repeat :tag "Grid Times" (integer :tag "Time"))))
818 (defcustom org-agenda-remove-times-when-in-prefix t
819 "Non-nil means, remove duplicate time specifications in agenda items.
820 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
821 time-of-day specification in a headline or diary entry is extracted and
822 placed into the prefix. If this option is non-nil, the original specification
823 \(a timestamp or -range, or just a plain time(range) specification like
824 11:30-4pm) will be removed for agenda display. This makes the agenda less
826 The option can be t or nil. It may also be the symbol `beg', indicating
827 that the time should only be removed what it is located at the beginning of
828 the headline/diary entry."
831 (const :tag "Always" t)
832 (const :tag "Never" nil)
833 (const :tag "When at beginning of entry" beg)))
835 (defcustom org-sort-agenda-notime-is-late t
836 "Non-nil means, items without time are considered late.
837 This is only relevant for sorting. When t, items which have no explicit
838 time like 15:30 will be considered as 24:01, i.e. later than any items which
839 do have a time. When nil, the default time is before 0:00. You can use this
840 option to decide if the schedule for today should come before or after timeless
845 (defgroup org-structure nil
846 "Options concerning structure editing in Org-mode."
850 (defcustom org-cycle-include-plain-lists nil
851 "Non-nil means, include plain lists into visibility cycling.
852 This means that during cycling, plain list items will *temporarily* be
853 interpreted as outline headlines with a level given by 1000+i where i is the
854 indentation of the bullet. In all other operations, plain list items are
855 not seen as headlines. For example, you cannot assign a TODO keyword to
857 :group 'org-structure
860 (defcustom org-cycle-emulate-tab t
861 "Where should `org-cycle' emulate TAB.
863 white Only in completely white lines
864 t Everywhere except in headlines"
865 :group 'org-structure
866 :type '(choice (const :tag "Never" nil)
867 (const :tag "Only in completely white lines" white)
868 (const :tag "Everywhere except in headlines" t)
871 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
872 "Hook that is run after `org-cycle' has changed the buffer visibility.
873 The function(s) in this hook must accept a single argument which indicates
874 the new state that was set by the most recent `org-cycle' command. The
875 argument is a symbol. After a global state change, it can have the values
876 `overview', `content', or `all'. After a local state change, it can have
877 the values `folded', `children', or `subtree'."
878 :group 'org-structure
881 (defcustom org-highlight-sparse-tree-matches t
882 "Non-nil means, highlight all matches that define a sparse tree.
883 The highlights will automatically disappear the next time the buffer is
884 changed by an edit command."
885 :group 'org-structure
888 (defcustom org-show-hierarchy-above t
889 "Non-nil means, show full hierarchy when showing a spot in the tree.
890 Turning this off makes sparse trees more compact, but also less clear."
891 :group 'org-structure
894 (defcustom org-show-following-heading t
895 "Non-nil means, show heading following match in `org-occur'.
896 When doing an `org-occur' it is useful to show the headline which
897 follows the match, even if they do not match the regexp. This makes it
898 easier to edit directly inside the sparse tree. However, if you use
899 org-occur mainly as an overview, the following headlines are
900 unnecessary clutter."
901 :group 'org-structure
904 (defcustom org-occur-hook '(org-first-headline-recenter)
905 "Hook that is run after `org-occur' has constructed a sparse tree.
906 This can be used to recenter the window to show as much of the structure
908 :group 'org-structure
911 (defcustom org-level-color-stars-only nil
912 "Non-nil means fontify only the stars in each headline.
913 When nil, the entire headline is fontified.
914 After changin this, requires restart of Emacs to become effective."
915 :group 'org-structure
918 (defcustom org-adapt-indentation t
919 "Non-nil means, adapt indentation when promoting and demoting.
920 When this is set and the *entire* text in an entry is indented, the
921 indentation is increased by one space in a demotion command, and
922 decreased by one in a promotion command. If any line in the entry
923 body starts at column 0, indentation is not changed at all."
924 :group 'org-structure
927 (defcustom org-plain-list-ordered-item-terminator t
928 "The character that makes a line with leading number an ordered list item.
929 Valid values are ?. and ?\). To get both terminators, use t. While
930 ?. may look nicer, it creates the danger that a line with leading
931 number may be incorrectly interpreted as an item. ?\) therefore is
933 :group 'org-structure
934 :type '(choice (const :tag "dot like in \"2.\"" ?.)
935 (const :tag "paren like in \"2)\"" ?\))
936 (const :tab "both" t)))
938 (defcustom org-auto-renumber-ordered-lists t
939 "Non-nil means, automatically renumber ordered plain lists.
940 Renumbering happens when the sequence have been changed with
941 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
942 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
943 :group 'org-structure
946 (defcustom org-enable-fixed-width-editor t
947 "Non-nil means, lines starting with \":\" are treated as fixed-width.
948 This currently only means, they are never auto-wrapped.
949 When nil, such lines will be treated like ordinary lines.
950 See also the QUOTE keyword."
951 :group 'org-structure
954 (defcustom org-archive-location "%s_archive::"
955 "The location where subtrees should be archived.
956 This string consists of two parts, separated by a double-colon.
958 The first part is a file name - when omitted, archiving happens in the same
959 file. %s will be replaced by the current file name (without directory part).
960 Archiving to a different file is useful to keep archived entries from
961 contributing to the Org-mode Agenda.
963 The part after the double colon is a headline. The archived entries will be
964 filed under that headline. When omitted, the subtrees are simply filed away
965 at the end of the file, as top-level entries.
967 Here are a few examples:
969 If the current file is Projects.org, archive in file
970 Projects.org_archive, as top-level trees. This is the default.
972 \"::* Archived Tasks\"
973 Archive in the current file, under the top-level headline
974 \"* Archived Tasks\".
976 \"~/org/archive.org::\"
977 Archive in file ~/org/archive.org (absolute path), as top-level trees.
979 \"basement::** Finished Tasks\"
980 Archive in file ./basement (relative path), as level 3 trees
981 below the level 2 heading \"** Finished Tasks\".
983 You may set this option on a per-file basis by adding to the buffer a
986 #+ARCHIVE: basement::** Finished Tasks"
987 :group 'org-structure
990 (defcustom org-archive-mark-done t
991 "Non-nil means, mark archived entries as DONE."
992 :group 'org-structure
995 (defcustom org-archive-stamp-time t
996 "Non-nil means, add a time stamp to archived entries.
997 The time stamp will be added directly after the TODO state keyword in the
998 first line, so it is probably best to use this in combinations with
999 `org-archive-mark-done'."
1000 :group 'org-structure
1003 (defgroup org-tags nil
1004 "Options concerning startup of Org-mode."
1008 (defcustom org-tags-column 48
1009 "The column to which tags should be indented in a headline.
1010 If this number is positive, it specified the column. If it is negative,
1011 it means that the tags should be flushright to that column. For example,
1012 -79 works well for a normal 80 character screen."
1016 (defcustom org-auto-align-tags t
1017 "Non-nil means, realign tags after pro/demotion of TODO state change.
1018 These operations change the length of a headline and therefore shift
1019 the tags around. With this options turned on, after each such operation
1020 the tags are again aligned to `org-tags-column'."
1024 (defcustom org-use-tag-inheritance t
1025 "Non-nil means, tags in levels apply also for sublevels.
1026 When nil, only the tags directly give in a specific line apply there.
1027 If you turn off this option, you very likely want to turn on the
1028 companion option `org-tags-match-list-sublevels'."
1032 (defcustom org-tags-match-list-sublevels nil
1033 "Non-nil means list also sublevels of headlines matching tag search.
1034 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1035 the sublevels of a headline matching a tag search often also match
1036 the same search. Listing all of them can create very long lists.
1037 Setting this variable to nil causes subtrees to be skipped.
1038 This option is off by default, because inheritance in on. If you turn
1039 inheritance off, you very likely want to turn this option on."
1043 (defvar org-tags-history nil
1044 "History of minibuffer reads for tags.")
1045 (defvar org-last-tags-completion-table nil
1046 "The last used completion table for tags.")
1048 (defgroup org-link nil
1049 "Options concerning links in Org-mode."
1053 (defcustom org-tab-follows-link nil
1054 "Non-nil means, on links TAB will follow the link.
1055 Needs to be set before org.el is loaded."
1059 (defcustom org-return-follows-link nil
1060 "Non-nil means, on links RET will follow the link.
1061 Needs to be set before org.el is loaded."
1065 (defcustom org-link-format "<%s>"
1066 "Default format for linkes in the buffer.
1067 This is a format string for printf, %s will be replaced by the link text.
1068 If you want to make sure that your link is always properly terminated,
1069 include angle brackets into this format, like \"<%s>\". Some people also
1070 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
1073 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
1074 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
1075 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
1076 (string :tag "Other" :value "<%s>")))
1078 (defcustom org-allow-space-in-links t
1079 "Non-nil means, file names in links may contain space characters.
1080 When nil, it becomes possible to put several links into a line.
1081 Note that in tables, a link never extends accross fields, so in a table
1082 it is always possible to put several links into a line.
1083 Changing this varable requires a re-launch of Emacs of become effective."
1087 (defcustom org-context-in-file-links t
1088 "Non-nil means, file links from `org-store-link' contain context.
1089 The line number will be added to the file name with :: as separator and
1090 used to find the context when the link is activated by the command
1091 `org-open-at-point'.
1092 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1093 negates this setting for the duration of the command."
1097 (defcustom org-keep-stored-link-after-insertion nil
1098 "Non-nil means, keep link in list for entire session.
1100 The command `org-store-link' adds a link pointing to the current
1101 location to an internal list. These links accumulate during a session.
1102 The command `org-insert-link' can be used to insert links into any
1103 Org-mode file (offering completion for all stored links). When this
1104 option is nil, every link which has been inserted once using \\[org-insert-link]
1105 will be removed from the list, to make completing the unused links
1110 (defcustom org-link-frame-setup
1111 '((vm . vm-visit-folder-other-frame)
1112 (gnus . gnus-other-frame)
1113 (file . find-file-other-window))
1114 "Setup the frame configuration for following links.
1115 When following a link with Emacs, it may often be useful to display
1116 this link in another window or frame. This variable can be used to
1117 set this up for the different types of links.
1120 `vm-visit-folder-other-frame'
1121 For Gnus, use any of
1124 For FILE, use any of
1126 `find-file-other-window'
1127 `find-file-other-frame'
1128 For the calendar, use the variable `calendar-setup'.
1129 For BBDB, it is currently only possible to display the matches in
1135 (const vm-visit-folder)
1136 (const vm-visit-folder-other-window)
1137 (const vm-visit-folder-other-frame)))
1141 (const gnus-other-frame)))
1145 (const find-file-other-window)
1146 (const find-file-other-frame)))))
1148 (defcustom org-usenet-links-prefer-google nil
1149 "Non-nil means, `org-store-link' will create web links to google groups.
1150 When nil, Gnus will be used for such links.
1151 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1152 negates this setting for the duration of the command."
1156 (defcustom org-open-non-existing-files nil
1157 "Non-nil means, `org-open-file' will open non-existing file.
1158 When nil, an error will be generated."
1162 (defcustom org-confirm-shell-links t
1163 "Non-nil means, ask for confirmation before executing shell links.
1164 The default is true, to keep new users from shooting into their own foot."
1168 (defconst org-file-apps-defaults-gnu
1180 ("eps.gz" . "gv %s")
1182 ("mpeg" . "plaympeg %s")
1183 ("mp3" . "plaympeg %s")
1185 ("pdf" . "acroread %s")
1186 ("doc" . "soffice %s")
1187 ("ppt" . "soffice %s")
1188 ("pps" . "soffice %s")
1189 ("html" . "netscape -remote openURL(%s,new-window)")
1190 ("htm" . "netscape -remote openURL(%s,new-window)")
1191 ("xs" . "soffice %s"))
1192 "Default file applications on a UNIX/LINUX system.
1193 See `org-file-apps'.")
1195 (defconst org-file-apps-defaults-macosx
1200 ("eps.gz" . "gv %s")
1202 ("fig" . "xfig %s"))
1203 "Default file applications on a MacOS X system.
1204 The system \"open\" is known as a default, but we use X11 applications
1205 for some files for which the OS does not have a good default.
1206 See `org-file-apps'.")
1208 (defconst org-file-apps-defaults-windowsnt
1209 '((t . (w32-shell-execute "open" file)))
1210 "Default file applications on a Windows NT system.
1211 The system \"open\" is used for most files.
1212 See `org-file-apps'.")
1214 (defcustom org-file-apps
1222 "External applications for opening `file:path' items in a document.
1223 Org-mode uses system defaults for different file types, but
1224 you can use this variable to set the application for a given file
1225 extension. The entries in this list are cons cells with a file extension
1226 and the corresponding command. Possible values for the command are:
1227 `emacs' The file will be visited by the current Emacs process.
1228 `default' Use the default application for this file type.
1229 string A command to be executed by a shell; %s will be replaced
1230 by the path to the file.
1231 sexp A Lisp form which will be evaluated. The file path will
1232 be available in the Lisp variable `file'.
1233 For more examples, see the system specific constants
1234 `org-file-apps-defaults-macosx'
1235 `org-file-apps-defaults-windowsnt'
1236 `org-file-apps-defaults-gnu'."
1239 (cons (string :tag "Extension")
1241 (const :tag "Visit with Emacs" 'emacs)
1242 (const :tag "Use system default" 'default)
1243 (string :tag "Command")
1244 (sexp :tag "Lisp form")))))
1247 (defgroup org-remember nil
1248 "Options concerning interaction with remember.el."
1252 (defcustom org-directory "~/org"
1253 "Directory with org files.
1254 This directory will be used as default to prompt for org files.
1255 Used by the hooks for remember.el."
1256 :group 'org-remember
1259 (defcustom org-default-notes-file "~/.notes"
1260 "Default target for storing notes.
1261 Used by the hooks for remember.el. This can be a string, or nil to mean
1262 the value of `remember-data-file'."
1263 :group 'org-remember
1265 (const :tag "Default from remember-data-file" nil)
1268 (defcustom org-reverse-note-order nil
1269 "Non-nil means, store new notes at the beginning of a file or entry.
1270 When nil, new notes will be filed to the end of a file or entry."
1271 :group 'org-remember
1273 (const :tag "Reverse always" t)
1274 (const :tag "Reverse never" nil)
1275 (repeat :tag "By file name regexp"
1276 (cons regexp boolean))))
1278 (defgroup org-table nil
1279 "Options concerning tables in Org-mode."
1283 (defcustom org-enable-table-editor 'optimized
1284 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1285 When nil, such lines will be treated like ordinary lines.
1287 When equal to the symbol `optimized', the table editor will be optimized to
1289 - Use automatic overwrite mode in front of whitespace in table fields.
1290 This make the structure of the table stay in tact as long as the edited
1291 field does not exceed the column width.
1292 - Minimize the number of realigns. Normally, the table is aligned each time
1293 TAB or RET are pressed to move to another field. With optimization this
1294 happens only if changes to a field might have changed the column width.
1295 Optimization requires replacing the functions `self-insert-command',
1296 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1297 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1298 very good at guessing when a re-align will be necessary, but you can always
1299 force one with \\[org-ctrl-c-ctrl-c].
1301 If you would like to use the optimized version in Org-mode, but the
1302 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1304 This variable can be used to turn on and off the table editor during a session,
1305 but in order to toggle optimization, a restart is required.
1307 See also the variable `org-table-auto-blank-field'."
1310 (const :tag "off" nil)
1312 (const :tag "on, optimized" optimized)))
1314 ;; FIXME: We could have a third option which makes it jump only over the first
1315 ;; hline in a table.
1316 (defcustom org-table-tab-jumps-over-hlines t
1317 "Non-nil means, tab in the last column of a table with jump over a hline.
1318 If a horizontal separator line is following the current line,
1319 `org-table-next-field' can either create a new row before that line, or jump
1320 over the line. When this option is nil, a new line will be created before
1325 (defcustom org-table-auto-blank-field t
1326 "Non-nil means, automatically blank table field when starting to type into it.
1327 This only happens when typing immediately after a field motion
1328 command (TAB, S-TAB or RET).
1329 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1333 (defcustom org-table-default-size "5x2"
1334 "The default size for newly created tables, Columns x Rows."
1338 (defcustom org-table-automatic-realign t
1339 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1340 When nil, aligning is only done with \\[org-table-align], or after column
1345 (defcustom org-table-spaces-around-separators '(1 . 1)
1346 "The number of spaces to be placed before and after separators."
1348 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1350 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1351 "The number of spaces to be placed before and after separators.
1352 This option applies when the column separators have been made invisible."
1354 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1356 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1357 "Regular expression for recognizing numbers in table columns.
1358 If a table column contains mostly numbers, it will be aligned to the
1359 right. If not, it will be aligned to the left.
1361 The default value of this option is a regular expression which allows
1362 anything which looks remotely like a number as used in scientific
1363 context. For example, all of the following will be considered a
1365 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1367 Other options offered by the customize interface are more restrictive."
1370 (const :tag "Positive Integers"
1372 (const :tag "Integers"
1374 (const :tag "Floating Point Numbers"
1375 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1376 (const :tag "Floating Point Number or Integer"
1377 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1378 (const :tag "Exponential, Floating point, Integer"
1379 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1380 (const :tag "Very General Number-Like"
1381 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1382 (string :tag "Regexp:")))
1384 (defcustom org-table-number-fraction 0.5
1385 "Fraction of numbers in a column required to make the column align right.
1386 In a column all non-white fields are considered. If at least this
1387 fraction of fields is matched by `org-table-number-fraction',
1388 alignment to the right border applies."
1392 (defcustom org-export-highlight-first-table-line t
1393 "Non-nil means, highlight the first table line.
1394 In HTML export, this means use <th> instead of <td>.
1395 In tables created with table.el, this applies to the first table line.
1396 In Org-mode tables, all lines before the first horizontal separator
1397 line will be formatted with <th> tags."
1401 (defcustom org-table-tab-recognizes-table.el t
1402 "Non-nil means, TAB will automatically notice a table.el table.
1403 When it sees such a table, it moves point into it and - if necessary -
1404 calls `table-recognize-table'."
1408 (defgroup org-table-calculation nil
1409 "Options concerning tables in Org-mode."
1410 :tag "Org Table Calculation"
1413 (defcustom org-table-copy-increment t
1414 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1415 :group 'org-table-calculation
1418 (defcustom org-calc-default-modes
1419 '(calc-internal-prec 12
1420 calc-float-format (float 5)
1422 calc-prefer-frac nil
1423 calc-symbolic-mode nil
1424 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1425 calc-display-working-message t
1427 "List with Calc mode settings for use in calc-eval for table formulas.
1428 The list must contain alternating symbols (calc modes variables and values.
1429 Don't remove any of the default settings, just change the values. Org-mode
1430 relies on the variables to be present in the list."
1431 :group 'org-table-calculation
1434 (defcustom org-table-formula-evaluate-inline t
1435 "Non-nil means, TAB and RET evaluate a formula in current table field.
1436 If the current field starts with an equal sign, it is assumed to be a formula
1437 which should be evaluated as described in the manual and in the documentation
1438 string of the command `org-table-eval-formula'. This feature requires the
1440 When this variable is nil, formula calculation is only available through
1441 the command \\[org-table-eval-formula]."
1442 :group 'org-table-calculation
1446 (defcustom org-table-formula-use-constants t
1447 "Non-nil means, interpret constants in formulas in tables.
1448 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1449 by the value given in `org-table-formula-constants', or by a value obtained
1450 from the `constants.el' package."
1451 :group 'org-table-calculation
1454 (defcustom org-table-formula-constants nil
1455 "Alist with constant names and values, for use in table formulas.
1456 The car of each element is a name of a constant, without the `$' before it.
1457 The cdr is the value as a string. For example, if you'd like to use the
1458 speed of light in a formula, you would configure
1460 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1462 and then use it in an equation like `$1*$c'."
1463 :group 'org-table-calculation
1465 (cons (string :tag "name")
1466 (string :tag "value"))))
1468 (defcustom org-table-formula-numbers-only nil
1469 "Non-nil means, calculate only with numbers in table formulas.
1470 Then all input fields will be converted to a number, and the result
1471 must also be a number. When nil, calc's full potential is available
1472 in table calculations, including symbolics etc."
1473 :group 'org-table-calculation
1476 (defcustom org-table-allow-automatic-line-recalculation t
1477 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1478 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1479 :group 'org-table-calculation
1482 (defgroup org-export nil
1483 "Options for exporting org-listings."
1487 (defcustom org-export-language-setup
1488 '(("en" "Author" "Date" "Table of Contents")
1489 ("da" "Ophavsmand" "Dato" "Indhold")
1490 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1491 ("es" "Autor" "Fecha" "\xccndice")
1492 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1493 ("it" "Autore" "Data" "Indice")
1494 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1495 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1496 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1497 "Terms used in export text, translated to different languages.
1498 Use the variable `org-export-default-language' to set the language,
1499 or use the +OPTION lines for a per-file setting."
1503 (string :tag "HTML language tag")
1504 (string :tag "Author")
1505 (string :tag "Date")
1506 (string :tag "Table of Contents"))))
1508 (defcustom org-export-default-language "en"
1509 "The default language of HTML export, as a string.
1510 This should have an association in `org-export-language-setup'."
1514 (defcustom org-export-html-style
1515 "<style type=\"text/css\">
1517 font-family: Times, serif;
1520 .title { text-align: center; }
1521 .todo, .deadline { color: red; }
1522 .done { color: green; }
1524 border: 1pt solid #AEBDCC;
1525 background-color: #F3F5F7;
1527 font-family: courier, monospace;
1529 table { border-collapse: collapse; }
1531 vertical-align: top;
1532 border: 1pt solid #ADB9CC;
1535 "The default style specification for exported HTML files.
1536 Since there are different ways of setting style information, this variable
1537 needs to contain the full HTML structure to provide a style, including the
1538 surrounding HTML tags. The style specifications should include definiitons
1539 for new classes todo, done, title, and deadline. For example, legal values
1542 <style type=\"text/css\">
1543 p {font-weight: normal; color: gray; }
1545 .title { text-align: center; }
1546 .todo, .deadline { color: red; }
1547 .done { color: green; }
1550 or, if you want to keep the style in a file,
1552 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1554 As the value of this option simply gets inserted into the HTML <head> header,
1555 you can \"misuse\" it to add arbitrary text to the header."
1559 (defcustom org-export-headline-levels 3
1560 "The last level which is still exported as a headline.
1561 Inferior levels will produce itemize lists when exported.
1562 Note that a numeric prefix argument to an exporter function overrides
1565 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1569 (defcustom org-export-with-section-numbers t
1570 "Non-nil means, add section numbers to headlines when exporting.
1572 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1576 (defcustom org-export-with-toc t
1577 "Non-nil means, create a table of contents in exported files.
1578 The TOC contains headlines with levels up to`org-export-headline-levels'.
1580 Headlines which contain any TODO items will be marked with \"(*)\" in
1581 ASCII export, and with red color in HTML output.
1583 In HTML output, the TOC will be clickable.
1585 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1589 (defcustom org-export-plain-list-max-depth 20
1590 "Maximum depth of hand-formatted lists in HTML export.
1592 Org-mode parses hand-formatted enumeration and bullet lists and
1593 transforms them to HTML open export. Different indentation of the
1594 bullet or number indicates different list nesting levels. To avoid
1595 confusion, only a single level is allowed by default. When this is
1596 larger than 1, deeper indentation leads to deeper list nesting. For
1597 example, the default value of 3 allows the following list to be
1598 formatted correctly in HTML:
1604 2. from South America
1611 (defcustom org-export-preserve-breaks nil
1612 "Non-nil means, preserve all line breaks when exporting.
1613 Normally, in HTML output paragraphs will be reformatted. In ASCII
1614 export, line breaks will always be preserved, regardless of this variable.
1616 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1620 (defcustom org-export-html-inline-images t
1621 "Non-nil means, inline images into exported HTML pages.
1622 The link will still be to the original location of the image file.
1623 So if you are moving the page, lets say to your public HTML site,
1624 you will have to move the image and maybe change the link."
1628 (defcustom org-export-html-expand t
1629 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1630 When nil, these tags will be exported as plain text and therefore
1631 not be interpreted by a browser.
1633 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1637 (defcustom org-export-with-fixed-width t
1638 "Non-nil means, lines starting with \":\" will be in fixed width font.
1639 This can be used to have pre-formatted text, fragments of code etc. For
1641 : ;; Some Lisp examples
1644 will be looking just like this in also HTML. In ASCII export, this option
1647 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1651 (defcustom org-export-with-tables t
1652 "If non-nil, lines starting with \"|\" define a table.
1655 | Name | Address | Birthday |
1656 |-------------+----------+-----------|
1657 | Arthur Dent | England | 29.2.2100 |
1659 In ASCII export, this option has no effect.
1661 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1665 (defcustom org-export-prefer-native-exporter-for-tables nil
1666 "Non-nil means, always export tables created with table.el natively.
1667 Natively means, use the HTML code generator in table.el.
1668 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1669 the table does not use row- or column-spanning). This has the
1670 advantage, that the automatic HTML conversions for math symbols and
1671 sub/superscripts can be applied. Org-mode's HTML generator is also
1676 (defcustom org-export-html-table-tag
1677 "<table border=1 cellspacing=0 cellpadding=6>"
1678 "The HTML tag used to start a table.
1679 This must be a <table> tag, but you may change the options like
1680 borders and spacing."
1684 (defcustom org-export-with-emphasize t
1685 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1686 If the export target supports emphasizing text, the word will be
1687 typeset in bold, italic, or underlined, respectively. Works only for
1688 single words, but you can say: I *really* *mean* *this*.
1689 In ASCII export, this option has no effect.
1691 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1695 (defcustom org-match-sexp-depth 3
1696 "Number of stacked braces for sub/superscript matching.
1697 This has to be set before loading org.el to be effective."
1701 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1702 (defcustom org-export-with-sub-superscripts t
1703 "Non-nil means, interpret \"_\" and \"^\" for export.
1704 When this option is turned on, you can use TeX-like syntax for sub- and
1705 superscripts. Several characters after \"_\" or \"^\" will be
1706 considered as a single item - so grouping with {} is normally not
1707 needed. For example, the following things will be parsed as single
1708 sub- or superscripts.
1710 10^24 or 10^tau several digits will be considered 1 item
1711 10^-12 or 10^-tau a leading sign with digits or a word
1712 x^2-y^3 will be read as x^2 - y^3, because items are
1713 terminated by almost any nonword/nondigit char.
1714 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1716 Still, ambiguity is possible - so when in doubt use {} to enclose the
1718 In ASCII export, this option has no effect.
1720 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1724 (defcustom org-export-with-TeX-macros t
1725 "Non-nil means, interpret simple TeX-like macros when exporting.
1726 For example, HTML export converts \\alpha to α and \\AA to Å.
1727 No only real TeX macros will work here, but the standard HTML entities
1728 for math can be used as macro names as well. For a list of supported
1729 names in HTML export, see the constant `org-html-entities'.
1730 In ASCII export, this option has no effect.
1732 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1736 (defcustom org-export-html-with-timestamp nil
1737 "If non-nil, write `org-export-html-html-helper-timestamp'
1738 into the exported html text. Otherwise, the buffer will just be saved
1743 (defcustom org-export-html-html-helper-timestamp
1744 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1745 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1749 (defcustom org-export-ascii-show-new-buffer t
1750 "Non-nil means, popup buffer containing the exported ASCII text.
1751 Otherwise the buffer will just be saved to a file and stay hidden."
1755 (defcustom org-export-html-show-new-buffer nil
1756 "Non-nil means, popup buffer containing the exported html text.
1757 Otherwise, the buffer will just be saved to a file and stay hidden."
1761 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1762 "The file name for the iCalendar file covering all agenda files.
1763 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1767 (defcustom org-icalendar-include-todo nil
1768 "Non-nil means, export to iCalendar files should also cover TODO items."
1772 (defcustom org-icalendar-combined-name "OrgMode"
1773 "Calendar name for the combined iCalendar representing all agenda files."
1777 (defgroup org-faces nil
1778 "Faces for highlighting in Org-mode."
1782 (defface org-level-1 ;; font-lock-function-name-face
1783 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1784 (((class color) (background light)) (:foreground "Blue"))
1785 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1786 (t (:inverse-video t :bold t)))
1787 "Face used for level 1 headlines."
1790 (defface org-level-2 ;; font-lock-variable-name-face
1791 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1792 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1793 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1794 (t (:bold t :italic t)))
1795 "Face used for level 2 headlines."
1798 (defface org-level-3 ;; font-lock-keyword-face
1799 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1800 (((class color) (background light)) (:foreground "Purple"))
1801 (((class color) (background dark)) (:foreground "Cyan"))
1803 "Face used for level 3 headlines."
1806 (defface org-level-4 ;; font-lock-comment-face
1807 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1808 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1809 (((class color) (background light)) (:foreground "Firebrick"))
1810 (((class color) (background dark)) (:foreground "chocolate1"))
1811 (t (:bold t :italic t)))
1812 "Face used for level 4 headlines."
1815 (defface org-level-5 ;; font-lock-type-face
1816 '((((type tty) (class color)) (:foreground "green"))
1817 (((class color) (background light)) (:foreground "ForestGreen"))
1818 (((class color) (background dark)) (:foreground "PaleGreen"))
1819 (t (:bold t :underline t)))
1820 "Face used for level 5 headlines."
1823 (defface org-level-6 ;; font-lock-constant-face
1824 '((((type tty) (class color)) (:foreground "magenta"))
1825 (((class color) (background light)) (:foreground "CadetBlue"))
1826 (((class color) (background dark)) (:foreground "Aquamarine"))
1827 (t (:bold t :underline t)))
1828 "Face used for level 6 headlines."
1831 (defface org-level-7 ;; font-lock-builtin-face
1832 '((((type tty) (class color)) (:foreground "blue" :weight light))
1833 (((class color) (background light)) (:foreground "Orchid"))
1834 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1836 "Face used for level 7 headlines."
1839 (defface org-level-8 ;; font-lock-string-face
1840 '((((type tty) (class color)) (:foreground "green"))
1841 (((class color) (background light)) (:foreground "RosyBrown"))
1842 (((class color) (background dark)) (:foreground "LightSalmon"))
1844 "Face used for level 8 headlines."
1847 (defface org-special-keyword ;; font-lock-string-face
1848 '((((type tty) (class color)) (:foreground "green"))
1849 (((class color) (background light)) (:foreground "RosyBrown"))
1850 (((class color) (background dark)) (:foreground "LightSalmon"))
1852 "Face used for level 8 headlines."
1855 (defface org-warning ;; font-lock-warning-face
1856 '((((type tty) (class color)) (:foreground "red"))
1857 (((class color) (background light)) (:foreground "Red" :bold t))
1858 (((class color) (background dark)) (:foreground "Red1" :bold t))
1859 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1860 (t (:inverse-video t :bold t)))
1861 "Face for deadlines and TODO keywords."
1864 (defcustom org-fontify-done-headline nil
1865 "Non-nil means, change the face of a headline if it is marked DONE.
1866 Normally, only the TODO/DONE keyword indicates the state of a headline.
1867 When this is non-nil, the headline after the keyword is set to the
1868 `org-headline-done' as an additional indication."
1872 (defface org-headline-done ;; font-lock-string-face
1873 '((((type tty) (class color)) (:foreground "green"))
1874 (((class color) (background light)) (:foreground "RosyBrown"))
1875 (((class color) (background dark)) (:foreground "LightSalmon"))
1877 "Face used to indicate that a headline is DONE. See also the variable
1878 `org-fontify-done-headline'."
1881 ;; Inheritance does not yet work for xemacs. So we just copy...
1883 (defface org-deadline-announce
1884 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1885 (((class color) (background light)) (:foreground "Blue"))
1886 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1887 (t (:inverse-video t :bold t)))
1888 "Face for upcoming deadlines."
1891 (defface org-scheduled-today
1892 '((((type tty) (class color)) (:foreground "green"))
1893 (((class color) (background light)) (:foreground "DarkGreen"))
1894 (((class color) (background dark)) (:foreground "PaleGreen"))
1895 (t (:bold t :underline t)))
1896 "Face for items scheduled for a certain day."
1899 (defface org-scheduled-previously
1900 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1901 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1902 (((class color) (background light)) (:foreground "Firebrick"))
1903 (((class color) (background dark)) (:foreground "chocolate1"))
1904 (t (:bold t :italic t)))
1905 "Face for items scheduled previously, and not yet done."
1908 (defface org-formula
1909 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1910 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1911 (((class color) (background light)) (:foreground "Firebrick"))
1912 (((class color) (background dark)) (:foreground "chocolate1"))
1913 (t (:bold t :italic t)))
1914 "Face for items scheduled previously, and not yet done."
1918 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1919 (((class color) (background light)) (:foreground "Purple"))
1920 (((class color) (background dark)) (:foreground "Cyan"))
1925 (defface org-done ;; font-lock-type-face
1926 '((((type tty) (class color)) (:foreground "green"))
1927 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1928 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1929 (t (:bold t :underline t)))
1930 "Face used for DONE."
1933 (defface org-table ;; font-lock-function-name-face
1934 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1935 (((class color) (background light)) (:foreground "Blue"))
1936 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1937 (t (:inverse-video t :bold t)))
1938 "Face used for tables."
1941 (defface org-time-grid ;; font-lock-variable-name-face
1942 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1943 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1944 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1945 (t (:bold t :italic t)))
1946 "Face used for level 2 headlines."
1949 (defvar org-level-faces
1960 (defvar org-n-levels (length org-level-faces))
1962 (defun org-set-regexps-and-options ()
1963 "Precompute regular expressions for current buffer."
1964 (when (eq major-mode 'org-mode)
1965 (let ((re (org-make-options-regexp
1966 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1967 "STARTUP" "ARCHIVE")))
1969 kwds int key value cat arch)
1973 (goto-char (point-min))
1974 (while (re-search-forward re nil t)
1975 (setq key (match-string 1) value (match-string 2))
1977 ((equal key "CATEGORY")
1978 (if (string-match "[ \t]+$" value)
1979 (setq value (replace-match "" t t value)))
1980 (setq cat (intern value)))
1981 ((equal key "SEQ_TODO")
1983 kwds (append kwds (org-split-string value splitre))))
1984 ((equal key "PRI_TODO")
1986 kwds (append kwds (org-split-string value splitre))))
1987 ((equal key "TYP_TODO")
1989 kwds (append kwds (org-split-string value splitre))))
1990 ((equal key "STARTUP")
1991 (let ((opts (org-split-string value splitre))
1992 (set '(("fold" org-startup-folded t)
1993 ("nofold" org-startup-folded nil)
1994 ("content" org-startup-folded content)
1995 ("dlcheck" org-startup-with-deadline-check t)
1996 ("nodlcheck" org-startup-with-deadline-check nil)))
1998 (while (setq l (assoc (pop opts) set))
1999 (setq var (nth 1 l) val (nth 2 l))
2000 (set (make-local-variable var) val))))
2001 ((equal key "ARCHIVE")
2002 (string-match " *$" value)
2003 (setq arch (replace-match "" t t value))
2004 (remove-text-properties 0 (length arch)
2005 '(face t fontified t) arch)))
2007 (and cat (set (make-local-variable 'org-category) cat))
2008 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2009 (and arch (set (make-local-variable 'org-archive-location) arch))
2010 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2011 ;; Compute the regular expressions and other local variables
2012 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2013 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2014 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2015 (length org-scheduled-string)))
2017 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2019 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2023 (mapconcat 'regexp-quote
2024 (nreverse (cdr (reverse org-todo-keywords)))
2027 org-todo-line-regexp
2028 (concat "^\\(\\*+\\)[ \t]*\\("
2029 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2032 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2033 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2034 org-deadline-regexp (concat "\\<" org-deadline-string)
2035 org-deadline-time-regexp
2036 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2037 org-deadline-line-regexp
2038 (concat "\\<\\(" org-deadline-string "\\).*")
2039 org-scheduled-regexp
2040 (concat "\\<" org-scheduled-string)
2041 org-scheduled-time-regexp
2042 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2043 (org-set-font-lock-defaults)))
2045 ;; Tell the compiler about dynamically scoped variables,
2046 ;; and variables from other packages
2048 (defvar zmacs-regions)
2049 (defvar original-date)
2050 (defvar org-transient-mark-mode)
2051 (defvar org-old-auto-fill-inhibit-regexp)
2052 (defvar orgtbl-mode-menu)
2053 (defvar org-html-entities)
2054 (defvar org-goto-start-pos)
2055 (defvar org-cursor-color)
2056 (defvar org-time-was-given)
2057 (defvar org-ts-what)
2058 (defvar mark-active)
2060 (defvar levels-open)
2071 (defvar starting-day)
2072 (defvar include-all-loc)
2073 (defvar vm-message-pointer)
2074 (defvar vm-folder-directory)
2075 (defvar wl-summary-buffer-elmo-folder)
2076 (defvar wl-summary-buffer-folder-name)
2077 (defvar gnus-group-name)
2078 (defvar gnus-article-current)
2079 (defvar w3m-current-url)
2080 (defvar org-selected-point)
2081 (defvar calendar-mode-map)
2082 (defvar remember-save-after-remembering)
2083 (defvar remember-data-file))
2088 (defvar org-mode-map (copy-keymap outline-mode-map)
2089 "Keymap for Org-mode.")
2091 (defvar org-struct-menu)
2092 (defvar org-org-menu)
2093 (defvar org-tbl-menu)
2095 ;; We use a before-change function to check if a table might need
2097 (defvar org-table-may-need-update t
2098 "Indicates of a table might need an update.
2099 This variable is set by `org-before-change-function'. `org-table-align'
2100 sets it back to nil.")
2101 (defvar org-mode-hook nil)
2102 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2103 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2107 (define-derived-mode org-mode outline-mode "Org"
2108 "Outline-based notes management and organizer, alias
2109 \"Carstens outline-mode for keeping track of everything.\"
2111 Org-mode develops organizational tasks around a NOTES file which
2112 contains information about projects as plain text. Org-mode is
2113 implemented on top of outline-mode, which is ideal to keep the content
2114 of large files well structured. It supports ToDo items, deadlines and
2115 time stamps, which magically appear in the diary listing of the Emacs
2116 calendar. Tables are easily created with a built-in table editor.
2117 Plain text URL-like links connect to websites, emails (VM), Usenet
2118 messages (Gnus), BBDB entries, and any files related to the project.
2119 For printing and sharing of notes, an Org-mode file (or a part of it)
2120 can be exported as a structured ASCII or HTML file.
2122 The following commands are available:
2125 (easy-menu-add org-org-menu)
2126 (easy-menu-add org-tbl-menu)
2127 (org-install-agenda-files-menu)
2128 (setq outline-regexp "\\*+")
2129 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2130 (setq outline-level 'org-outline-level)
2131 (if org-startup-truncated (setq truncate-lines t))
2132 (org-set-regexps-and-options)
2133 (set (make-local-variable 'font-lock-unfontify-region-function)
2134 'org-unfontify-region)
2135 ;; Activate before-change-function
2136 (set (make-local-variable 'org-table-may-need-update) t)
2137 (make-local-hook 'before-change-functions) ;; needed for XEmacs
2138 (add-hook 'before-change-functions 'org-before-change-function nil
2140 ;; Paragraphs and auto-filling
2141 (org-set-autofill-regexps)
2142 ;; Settings for Calc embedded mode
2143 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2144 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2145 (if (and org-insert-mode-line-in-empty-file
2147 (= (point-min) (point-max)))
2148 (insert " -*- mode: org -*-\n\n"))
2150 ;; Get rid of Outline menus, they are not needed
2151 ;; Need to do this here because define-derived-mode sets up
2152 ;; the keymap so late.
2155 (delete-menu-item '("Headings"))
2156 (delete-menu-item '("Show"))
2157 (delete-menu-item '("Hide"))
2158 (set-menubar-dirty-flag))
2159 (define-key org-mode-map [menu-bar headings] 'undefined)
2160 (define-key org-mode-map [menu-bar hide] 'undefined)
2161 (define-key org-mode-map [menu-bar show] 'undefined))
2163 (unless org-inhibit-startup
2164 (if org-startup-with-deadline-check
2165 (call-interactively 'org-check-deadlines)
2167 ((eq org-startup-folded t)
2169 ((eq org-startup-folded 'content)
2170 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2171 (org-cycle '(4)) (org-cycle '(4))))))))
2173 (defsubst org-current-line (&optional pos)
2174 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2178 (defvar org-mouse-map (make-sparse-keymap))
2179 (define-key org-mouse-map
2180 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2181 (define-key org-mouse-map
2182 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2183 (when org-tab-follows-link
2184 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2185 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2186 (when org-return-follows-link
2187 (define-key org-mouse-map [(return)] 'org-open-at-point)
2188 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2190 (require 'font-lock)
2192 (defconst org-non-link-chars "\t\n\r|<>\000")
2193 (defconst org-link-regexp
2194 (if org-allow-space-in-links
2196 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2198 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2200 "Regular expression for matching links.")
2201 (defconst org-link-maybe-angles-regexp
2202 (concat "<?\\(" org-link-regexp "\\)>?")
2203 "Matches a link and optionally surrounding angle brackets.")
2204 (defconst org-protected-link-regexp
2205 (concat "\000" org-link-regexp "\000")
2206 "Matches a link and optionally surrounding angle brackets.")
2208 (defconst org-ts-lengths
2209 (cons (length (format-time-string (car org-time-stamp-formats)))
2210 (length (format-time-string (cdr org-time-stamp-formats))))
2211 "This holds the lengths of the two different time formats.")
2212 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2213 "Regular expression for fast time stamp matching.")
2214 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2215 "Regular expression for fast time stamp matching.")
2216 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2217 "Regular expression matching time strings for analysis.")
2218 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2219 "Regular expression matching time stamps, with groups.")
2220 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2221 "Regular expression matching a time stamp range.")
2222 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2223 org-ts-regexp "\\)?")
2224 "Regular expression matching a time stamp or time stamp range.")
2226 (defun org-activate-links (limit)
2227 "Run through the buffer and add overlays to links."
2228 (if (re-search-forward org-link-regexp limit t)
2230 (add-text-properties (match-beginning 0) (match-end 0)
2231 (list 'mouse-face 'highlight
2232 'keymap org-mouse-map))
2235 (defun org-activate-dates (limit)
2236 "Run through the buffer and add overlays to dates."
2237 (if (re-search-forward org-tsr-regexp limit t)
2239 (add-text-properties (match-beginning 0) (match-end 0)
2240 (list 'mouse-face 'highlight
2241 'keymap org-mouse-map))
2244 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2245 "Matches CamelCase words, possibly with a star before it.")
2246 (defun org-activate-camels (limit)
2247 "Run through the buffer and add overlays to dates."
2248 (if (re-search-forward org-camel-regexp limit t)
2250 (add-text-properties (match-beginning 0) (match-end 0)
2251 (list 'mouse-face 'highlight
2252 'keymap org-mouse-map))
2255 (defun org-activate-tags (limit)
2256 (if (re-search-forward "[ \t]\\(:[A-Za-z_:]+:\\)[ \r\n]" limit t)
2258 (add-text-properties (match-beginning 1) (match-end 1)
2259 (list 'mouse-face 'highlight
2260 'keymap org-mouse-map))
2263 (defun org-font-lock-level ()
2265 (org-back-to-heading t)
2266 (- (match-end 0) (match-beginning 0))))
2268 (defun org-outline-level ()
2270 (looking-at outline-regexp)
2271 (if (match-beginning 1)
2272 (+ (org-get-string-indentation (match-string 1)) 1000)
2273 (- (match-end 0) (match-beginning 0)))))
2275 (defvar org-font-lock-keywords nil)
2277 (defun org-set-font-lock-defaults ()
2278 (let ((org-font-lock-extra-keywords
2280 '(org-activate-links (0 'org-link t))
2281 '(org-activate-dates (0 'org-link t))
2282 '(org-activate-camels (0 'org-link t))
2283 '(org-activate-tags (1 'org-link t))
2284 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2285 '(1 'org-warning t))
2286 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2287 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2288 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2289 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2290 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2292 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2294 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2296 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2297 ; '(1 'org-warning t))
2298 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2299 "\\|" org-quote-string "\\)\\>")
2300 '(1 'org-special-keyword t))
2301 '("^#.*" (0 'font-lock-comment-face t))
2302 (if org-fontify-done-headline
2303 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2304 '(1 'org-done t) '(2 'org-headline-done t))
2305 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2307 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2309 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2310 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2311 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2313 (set (make-local-variable 'org-font-lock-keywords)
2315 (if org-noutline-p ; FIXME: I am not sure if eval will work
2316 ; on XEmacs if noutline is ever ported
2317 `((eval . (list "^\\(\\*+\\).*"
2318 ,(if org-level-color-stars-only 1 0)
2320 (% (- (match-end 1) (match-beginning 1) 1)
2324 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2325 (,(if org-level-color-stars-only 2 0)
2326 (nth (% (- (match-end 2) (match-beginning 2) 1)
2330 org-font-lock-extra-keywords))
2331 (set (make-local-variable 'font-lock-defaults)
2332 '(org-font-lock-keywords t nil nil backward-paragraph))
2333 (kill-local-variable 'font-lock-keywords) nil))
2335 (defun org-unfontify-region (beg end &optional maybe_loudly)
2336 "Remove fontification and activation overlays from links."
2337 (font-lock-default-unfontify-region beg end)
2338 (let* ((buffer-undo-list t)
2339 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2340 (inhibit-modification-hooks t)
2341 deactivate-mark buffer-file-name buffer-file-truename)
2342 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2344 ;;; Visibility cycling
2346 (defvar org-cycle-global-status nil)
2347 (defvar org-cycle-subtree-status nil)
2348 (defun org-cycle (&optional arg)
2349 "Visibility cycling for Org-mode.
2351 - When this function is called with a prefix argument, rotate the entire
2352 buffer through 3 states (global cycling)
2353 1. OVERVIEW: Show only top-level headlines.
2354 2. CONTENTS: Show all headlines of all levels, but no body text.
2355 3. SHOW ALL: Show everything.
2357 - When point is at the beginning of a headline, rotate the subtree started
2358 by this line through 3 different states (local cycling)
2359 1. FOLDED: Only the main headline is shown.
2360 2. CHILDREN: The main headline and the direct children are shown. From
2361 this state, you can move to one of the children and
2363 3. SUBTREE: Show the entire subtree, including body text.
2365 - When there is a numeric prefix, go up to a heading with level ARG, do
2366 a `show-subtree' and return to the previous cursor position. If ARG
2367 is negative, go up that many levels.
2369 - When point is not at the beginning of a headline, execute
2370 `indent-relative', like TAB normally does. See the option
2371 `org-cycle-emulate-tab' for details.
2373 - Special case: if point is the the beginning of the buffer and there is
2374 no headline in line 1, this function will act as if called with prefix arg."
2377 (if (or (and (bobp) (not (looking-at outline-regexp)))
2379 ;; special case: use global cycling
2382 (let ((outline-regexp
2383 (if org-cycle-include-plain-lists
2384 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2389 ((org-at-table-p 'any)
2390 ;; Enter the table or move to the next field in the table
2391 (or (org-table-recognize-table.el)
2393 (org-table-justify-field-maybe)
2394 (org-table-next-field))))
2396 ((eq arg t) ;; Global cycling
2399 ((and (eq last-command this-command)
2400 (eq org-cycle-global-status 'overview))
2401 ;; We just created the overview - now do table of contents
2402 ;; This can be slow in very large buffers, so indicate action
2403 (message "CONTENTS...")
2405 ;; Visit all headings and show their offspring
2406 (goto-char (point-max))
2408 (while (and (progn (condition-case nil
2409 (outline-previous-visible-heading 1)
2410 (error (goto-char (point-min))))
2412 (looking-at outline-regexp))
2414 (if (bobp) (throw 'exit nil))))
2415 (message "CONTENTS...done"))
2416 (setq org-cycle-global-status 'contents)
2417 (run-hook-with-args 'org-cycle-hook 'contents))
2419 ((and (eq last-command this-command)
2420 (eq org-cycle-global-status 'contents))
2421 ;; We just showed the table of contents - now show everything
2423 (message "SHOW ALL")
2424 (setq org-cycle-global-status 'all)
2425 (run-hook-with-args 'org-cycle-hook 'all))
2428 ;; Default action: go to overview
2430 (message "OVERVIEW")
2431 (setq org-cycle-global-status 'overview)
2432 (run-hook-with-args 'org-cycle-hook 'overview))))
2435 ;; Show-subtree, ARG levels up from here.
2437 (org-back-to-heading)
2438 (outline-up-heading (if (< arg 0) (- arg)
2439 (- (outline-level) arg)))
2440 (org-show-subtree)))
2442 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2443 ;; At a heading: rotate between three different views
2444 (org-back-to-heading)
2445 (let ((goal-column 0) eoh eol eos)
2446 ;; First, some boundaries
2448 (org-back-to-heading)
2450 (beginning-of-line 2)
2451 (while (and (not (eobp)) ;; this is like `next-line'
2452 (get-char-property (1- (point)) 'invisible))
2453 (beginning-of-line 2)) (setq eol (point)))
2454 (outline-end-of-heading) (setq eoh (point))
2455 (outline-end-of-subtree) (setq eos (point))
2456 (outline-next-heading))
2457 ;; Find out what to do next and set `this-command'
2460 ;; Nothing is hidden behind this heading
2461 (message "EMPTY ENTRY")
2462 (setq org-cycle-subtree-status nil))
2464 ;; Entire subtree is hidden in one line: open it
2467 (message "CHILDREN")
2468 (setq org-cycle-subtree-status 'children)
2469 (run-hook-with-args 'org-cycle-hook 'children))
2470 ((and (eq last-command this-command)
2471 (eq org-cycle-subtree-status 'children))
2472 ;; We just showed the children, now show everything.
2475 (setq org-cycle-subtree-status 'subtree)
2476 (run-hook-with-args 'org-cycle-hook 'subtree))
2478 ;; Default action: hide the subtree.
2481 (setq org-cycle-subtree-status 'folded)
2482 (run-hook-with-args 'org-cycle-hook 'folded)))))
2485 (buffer-read-only (org-back-to-heading))
2486 ((if (and (eq org-cycle-emulate-tab 'white)
2487 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2489 (eq org-cycle-emulate-tab t))
2490 (if (and (looking-at "[ \n\r\t]")
2491 (string-match "^[ \t]*$" (buffer-substring
2492 (point-at-bol) (point))))
2494 (beginning-of-line 1)
2495 (and (looking-at "[ \t]+") (replace-match ""))))
2499 (org-back-to-heading)
2502 (defun org-optimize-window-after-visibility-change (state)
2503 "Adjust the window after a change in outline visibility.
2504 This function is the default value of the hook `org-cycle-hook'."
2506 ((eq state 'overview) (org-first-headline-recenter 1))
2507 ((eq state 'content) nil)
2508 ((eq state 'all) nil)
2509 ((eq state 'folded) nil)
2510 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2511 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2513 (defun org-subtree-end-visible-p ()
2514 "Is the end of the current subtree visible?"
2515 (pos-visible-in-window-p
2516 (save-excursion (outline-end-of-subtree) (point))))
2518 (defun org-first-headline-recenter (&optional N)
2519 "Move cursor to the first headline and recenter the headline.
2520 Optional argument N means, put the headline into the Nth line of the window."
2521 (goto-char (point-min))
2522 (when (re-search-forward (concat "^" outline-regexp) nil t)
2524 (recenter (prefix-numeric-value N))))
2526 (defvar org-goto-window-configuration nil)
2527 (defvar org-goto-marker nil)
2528 (defvar org-goto-map (make-sparse-keymap))
2529 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2530 (while (setq cmd (pop cmds))
2531 (substitute-key-definition cmd cmd org-goto-map global-map)))
2532 (define-key org-goto-map "\C-m" 'org-goto-ret)
2533 (define-key org-goto-map [(left)] 'org-goto-left)
2534 (define-key org-goto-map [(right)] 'org-goto-right)
2535 (define-key org-goto-map [(?q)] 'org-goto-quit)
2536 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2537 (define-key org-goto-map "\C-i" 'org-cycle)
2538 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2539 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2540 (define-key org-goto-map "n" 'outline-next-visible-heading)
2541 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2542 (define-key org-goto-map "f" 'outline-forward-same-level)
2543 (define-key org-goto-map "b" 'outline-backward-same-level)
2544 (define-key org-goto-map "u" 'outline-up-heading)
2545 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2546 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2547 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2548 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2549 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2550 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2551 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2553 (defconst org-goto-help
2554 "Select a location to jump to, press RET
2555 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2558 "Go to a different location of the document, keeping current visibility.
2560 When you want to go to a different location in a document, the fastest way
2561 is often to fold the entire buffer and then dive into the tree. This
2562 method has the disadvantage, that the previous location will be folded,
2563 which may not be what you want.
2565 This command works around this by showing a copy of the current buffer in
2566 overview mode. You can dive into the tree in that copy, to find the
2567 location you want to reach. When pressing RET, the command returns to the
2568 original buffer in which the visibility is still unchanged. It then jumps
2569 to the new location, making it and the headline hierarchy above it visible."
2571 (let* ((org-goto-start-pos (point))
2573 (org-get-location (current-buffer) org-goto-help)))
2576 (goto-char selected-point)
2577 (if (org-invisible-p) (org-show-hierarchy-above)))
2580 (defun org-get-location (buf help)
2581 "Let the user select a location in the Org-mode buffer BUF.
2582 This function uses a recursive edit. It returns the selected position
2584 (let (org-selected-point)
2586 (save-window-excursion
2587 (delete-other-windows)
2588 (switch-to-buffer (get-buffer-create "*org-goto*"))
2589 (with-output-to-temp-buffer "*Help*"
2591 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2592 (setq buffer-read-only nil)
2594 (insert-buffer-substring buf)
2595 (let ((org-startup-truncated t)
2596 (org-startup-folded t)
2597 (org-startup-with-deadline-check nil))
2599 (setq buffer-read-only t)
2600 (if (boundp 'org-goto-start-pos)
2601 (goto-char org-goto-start-pos)
2602 (goto-char (point-min)))
2603 (org-beginning-of-line)
2604 (message "Select location and press RET")
2605 ;; now we make sure that during selection, ony very few keys work
2606 ;; and that it is impossible to switch to another window.
2607 (let ((gm (current-global-map))
2608 (overriding-local-map org-goto-map))
2611 (use-global-map org-goto-map)
2613 (use-global-map gm)))))
2614 (kill-buffer "*org-goto*")
2615 org-selected-point))
2617 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2618 (defun org-goto-ret (&optional arg)
2619 "Finish org-goto by going to the new location."
2621 (setq org-selected-point (point)
2622 current-prefix-arg arg)
2625 (defun org-goto-left ()
2626 "Finish org-goto by going to the new location."
2628 (if (org-on-heading-p)
2630 (beginning-of-line 1)
2631 (setq org-selected-point (point)
2632 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2634 (error "Not on a heading")))
2636 (defun org-goto-right ()
2637 "Finish org-goto by going to the new location."
2639 (if (org-on-heading-p)
2641 (outline-end-of-subtree)
2642 (or (eobp) (forward-char 1))
2643 (setq org-selected-point (point)
2644 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2646 (error "Not on a heading")))
2648 (defun org-goto-quit ()
2649 "Finish org-goto without cursor motion."
2651 (setq org-selected-point nil)
2654 ;;; Promotion, Demotion, Inserting new headlines
2656 (defvar org-ignore-region nil
2657 "To temporarily disable the active region.")
2659 (defun org-insert-heading (&optional force-heading)
2660 "Insert a new heading or item with same depth at point.
2663 (when (or force-heading (not (org-insert-item)))
2664 (let* ((head (save-excursion
2666 (org-back-to-heading)
2667 (error (outline-next-heading)))
2668 (prog1 (match-string 0)
2669 (funcall outline-level)))))
2670 (unless (bolp) (newline))
2673 (save-excursion (newline-and-indent)))
2674 (unless (equal (char-before) ?\ )
2676 (run-hooks 'org-insert-heading-hook))))
2678 (defun org-insert-item ()
2679 "Insert a new item at the current level.
2680 Return t when tings worked, nil when we are not in an item."
2681 (when (save-excursion
2684 (org-beginning-of-item)
2688 (unless (bolp) (newline))
2689 (insert (match-string 0))
2690 (org-maybe-renumber-ordered-list)
2693 (defun org-insert-todo-heading (arg)
2694 "Insert a new heading with the same level and TODO state as current heading.
2695 If the heading has no TODO state, or if the state is DONE, use the first
2696 state (TODO by default). Also with prefix arg, force first state."
2698 (org-insert-heading)
2700 (org-back-to-heading)
2701 (outline-previous-heading)
2702 (looking-at org-todo-line-regexp))
2704 (not (match-beginning 2))
2705 (equal (match-string 2) org-done-string))
2706 (insert (car org-todo-keywords) " ")
2707 (insert (match-string 2) " ")))
2709 (defun org-promote-subtree ()
2710 "Promote the entire subtree.
2711 See also `org-promote'."
2714 (org-map-tree 'org-promote)))
2716 (defun org-demote-subtree ()
2717 "Demote the entire subtree. See `org-demote'.
2718 See also `org-promote'."
2721 (org-map-tree 'org-demote)))
2723 (defun org-do-promote ()
2724 "Promote the current heading higher up the tree.
2725 If the region is active in `transient-mark-mode', promote all headings
2729 (if (org-region-active-p)
2730 (org-map-region 'org-promote (region-beginning) (region-end))
2732 (org-fix-position-after-promote))
2734 (defun org-do-demote ()
2735 "Demote the current heading lower down the tree.
2736 If the region is active in `transient-mark-mode', demote all headings
2740 (if (org-region-active-p)
2741 (org-map-region 'org-demote (region-beginning) (region-end))
2743 (org-fix-position-after-promote))
2745 (defun org-fix-position-after-promote ()
2746 "Make sure that after pro/demotion cursor position is right."
2747 (and (equal (char-after) ?\ )
2748 (equal (char-before) ?*)
2751 (defun org-promote ()
2752 "Promote the current heading higher up the tree.
2753 If the region is active in `transient-mark-mode', promote all headings
2755 (org-back-to-heading t)
2756 (let* ((level (save-match-data (funcall outline-level)))
2757 (up-head (make-string (1- level) ?*)))
2758 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2759 (replace-match up-head nil t)
2760 ;; Fixup tag positioning
2761 (and org-auto-align-tags (org-set-tags nil t))
2762 (if org-adapt-indentation
2763 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2765 (defun org-demote ()
2766 "Demote the current heading lower down the tree.
2767 If the region is active in `transient-mark-mode', demote all headings
2769 (org-back-to-heading t)
2770 (let* ((level (save-match-data (funcall outline-level)))
2771 (down-head (make-string (1+ level) ?*)))
2772 (replace-match down-head nil t)
2773 ;; Fixup tag positioning
2774 (and org-auto-align-tags (org-set-tags nil t))
2775 (if org-adapt-indentation
2776 (org-fixup-indentation "^ " " " "^\\S-"))))
2778 (defun org-map-tree (fun)
2779 "Call FUN for every heading underneath the current one."
2780 (org-back-to-heading)
2781 (let ((level (outline-level)))
2785 (outline-next-heading)
2786 (> (funcall outline-level) level))
2790 (defun org-map-region (fun beg end)
2791 "Call FUN for every heading between BEG and END."
2792 (let ((org-ignore-region t))
2794 (setq end (copy-marker end))
2796 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2800 (outline-next-heading)
2805 (defun org-fixup-indentation (from to prohibit)
2806 "Change the indentation in the current entry by re-replacing FROM with TO.
2807 However, if the regexp PROHIBIT matches at all, don't do anything.
2808 This is being used to change indentation along with the length of the
2809 heading marker. But if there are any lines which are not indented, nothing
2812 (let ((end (save-excursion (outline-next-heading)
2814 (unless (save-excursion (re-search-forward prohibit end t))
2815 (while (re-search-forward from end t)
2817 (beginning-of-line 2)))
2818 (move-marker end nil))))
2820 ;;; Vertical tree motion, cutting and pasting of subtrees
2822 (defun org-move-subtree-up (&optional arg)
2823 "Move the current subtree up past ARG headlines of the same level."
2825 (org-move-subtree-down (- (prefix-numeric-value arg))))
2827 (defun org-move-subtree-down (&optional arg)
2828 "Move the current subtree down past ARG headlines of the same level."
2830 (setq arg (prefix-numeric-value arg))
2831 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2832 'outline-get-last-sibling))
2833 (ins-point (make-marker))
2837 (org-back-to-heading)
2840 (save-excursion (outline-end-of-heading)
2841 (setq folded (org-invisible-p)))
2842 (outline-end-of-subtree))
2843 (outline-next-heading)
2845 ;; Find insertion point, with error handling
2848 (or (and (funcall movfunc) (looking-at outline-regexp))
2849 (progn (goto-char beg)
2850 (error "Cannot move past superior level or buffer limit")))
2851 (setq cnt (1- cnt)))
2853 ;; Moving forward - still need to move over subtree
2854 (progn (outline-end-of-subtree)
2855 (outline-next-heading)
2856 (if (not (or (looking-at (concat "^" outline-regexp))
2859 (move-marker ins-point (point))
2860 (setq txt (buffer-substring beg end))
2861 (delete-region beg end)
2863 (goto-char ins-point)
2864 (if folded (hide-subtree))
2865 (move-marker ins-point nil)))
2867 (defvar org-subtree-clip ""
2868 "Clipboard for cut and paste of subtrees.
2869 This is actually only a copy of the kill, because we use the normal kill
2870 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2872 (defvar org-subtree-clip-folded nil
2873 "Was the last copied subtree folded?
2874 This is used to fold the tree back after pasting.")
2876 (defun org-cut-subtree ()
2877 "Cut the current subtree into the clipboard.
2878 This is a short-hand for marking the subtree and then cutting it."
2880 (org-copy-subtree 'cut))
2882 (defun org-copy-subtree (&optional cut)
2883 "Cut the current subtree into the clipboard.
2884 This is a short-hand for marking the subtree and then copying it.
2885 If CUT is non nil, actually cut the subtree."
2887 (let (beg end folded)
2888 (org-back-to-heading)
2891 (save-excursion (outline-end-of-heading)
2892 (setq folded (org-invisible-p)))
2893 (outline-end-of-subtree))
2894 (if (equal (char-after) ?\n) (forward-char 1))
2898 (setq org-subtree-clip-folded folded)
2899 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2900 (setq org-subtree-clip (current-kill 0))
2901 (message "%s: Subtree with %d characters"
2902 (if cut "Cut" "Copied")
2903 (length org-subtree-clip)))))
2905 (defun org-paste-subtree (&optional level tree)
2906 "Paste the clipboard as a subtree, with modification of headline level.
2907 The entire subtree is promoted or demoted in order to match a new headline
2908 level. By default, the new level is derived from the visible headings
2909 before and after the insertion point, and taken to be the inferior headline
2910 level of the two. So if the previous visible heading is level 3 and the
2911 next is level 4 (or vice versa), level 4 will be used for insertion.
2912 This makes sure that the subtree remains an independent subtree and does
2913 not swallow low level entries.
2915 You can also force a different level, either by using a numeric prefix
2916 argument, or by inserting the heading marker by hand. For example, if the
2917 cursor is after \"*****\", then the tree will be shifted to level 5.
2919 If you want to insert the tree as is, just use \\[yank].
2921 If optional TREE is given, use this text instead of the kill ring."
2923 (unless (org-kill-is-subtree-p tree)
2925 (substitute-command-keys
2926 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2927 (let* ((txt (or tree (current-kill 0)))
2928 (^re (concat "^\\(" outline-regexp "\\)"))
2929 (re (concat "\\(" outline-regexp "\\)"))
2930 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2932 (old-level (if (string-match ^re txt)
2933 (- (match-end 0) (match-beginning 0))
2935 (force-level (cond (level (prefix-numeric-value level))
2937 ^re_ (buffer-substring (point-at-bol) (point)))
2938 (- (match-end 0) (match-beginning 0)))
2940 (previous-level (save-excursion
2943 (outline-previous-visible-heading 1)
2945 (- (match-end 0) (match-beginning 0))
2948 (next-level (save-excursion
2951 (outline-next-visible-heading 1)
2953 (- (match-end 0) (match-beginning 0))
2956 (new-level (or force-level (max previous-level next-level)))
2957 (shift (if (or (= old-level -1)
2959 (= old-level new-level))
2961 (- new-level old-level)))
2963 (delta (if (> shift 0) -1 1))
2964 (func (if (> shift 0) 'org-demote 'org-promote))
2966 ;; Remove the forces level indicator
2968 (delete-region (point-at-bol) (point)))
2969 ;; Make sure we start at the beginning of an empty line
2970 (if (not (bolp)) (insert "\n"))
2971 (if (not (looking-at "[ \t]*$"))
2972 (progn (insert "\n") (backward-char 1)))
2978 ;; Shift if necessary
2980 (message "Pasted at level %d, without shift" new-level)
2982 (narrow-to-region beg end)
2983 (while (not (= shift 0))
2984 (org-map-region func (point-min) (point-max))
2985 (setq shift (+ delta shift)))
2986 (goto-char (point-min))
2987 (message "Pasted at level %d, with shift by %d levels"
2989 (if (and (eq org-subtree-clip (current-kill 0))
2990 org-subtree-clip-folded)
2991 ;; The tree was folded before it was killed/copied
2994 (defun org-kill-is-subtree-p (&optional txt)
2995 "Check if the current kill is an outline subtree, or a set of trees.
2996 Returns nil if kill does not start with a headline, or if the first
2997 headline level is not the largest headline level in the tree.
2998 So this will actually accept several entries of equal levels as well,
2999 which is OK for `org-paste-subtree'.
3000 If optional TXT is given, check this string instead of the current kill."
3001 (let* ((kill (or txt (current-kill 0) ""))
3002 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3003 (- (match-end 0) (match-beginning 0))))
3004 (re (concat "^" outline-regexp))
3006 (if (not start-level)
3007 nil ;; does not even start with a heading
3009 (while (setq start (string-match re kill (1+ start)))
3010 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3014 ;;; Plain list items
3016 (defun org-at-item-p ()
3017 "Is point in a line starting a hand-formatted item?"
3018 (let ((llt org-plain-list-ordered-item-terminator))
3020 (goto-char (point-at-bol))
3023 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3024 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3025 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3026 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3028 (defun org-get-indentation ()
3029 "Get the indentation of the current line, ionterpreting tabs."
3031 (beginning-of-line 1)
3032 (skip-chars-forward " \t")
3035 (defun org-beginning-of-item ()
3036 "Go to the beginning of the current hand-formatted item.
3037 If the cursor is not in an item, throw an error."
3039 (limit (save-excursion (org-back-to-heading)
3040 (beginning-of-line 2) (point)))
3043 (beginning-of-line 1)
3044 (beginning-of-line 1)
3045 (skip-chars-forward " \t")
3046 (setq ind (current-column))
3049 (beginning-of-line 0)
3050 (if (< (point) limit) (throw 'exit nil))
3051 (unless (looking-at " \t]*$")
3052 (skip-chars-forward " \t")
3053 (setq ind1 (current-column))
3055 (throw 'exit (org-at-item-p))))))
3058 (error "Not in an item")))))
3060 (defun org-end-of-item ()
3061 "Go to the beginning of the current hand-formatted item.
3062 If the cursor is not in an item, throw an error."
3064 (limit (save-excursion (outline-next-heading) (point)))
3065 (ind (save-excursion
3066 (org-beginning-of-item)
3067 (skip-chars-forward " \t")
3072 (beginning-of-line 2)
3073 (if (>= (point) limit) (throw 'exit t))
3074 (unless (looking-at "[ \t]*$")
3075 (skip-chars-forward " \t")
3076 (setq ind1 (current-column))
3077 (if (<= ind1 ind) (throw 'exit t)))))
3078 (beginning-of-line 1)
3080 (error "Not in an item"))))
3082 (defun org-move-item-down (arg)
3083 "Move the plain list item at point down, i.e. swap with following item.
3084 Subitems (items with larger indentation are considered part of the item,
3085 so this really moves item trees."
3087 (let (beg end ind ind1 (pos (point)) txt)
3088 (org-beginning-of-item)
3090 (setq ind (org-get-indentation))
3093 (setq ind1 (org-get-indentation))
3094 (if (and (org-at-item-p) (= ind ind1))
3097 (setq txt (buffer-substring beg end))
3099 (delete-region beg end))
3103 (org-maybe-renumber-ordered-list))
3105 (error "Cannot move this item further down"))))
3107 (defun org-move-item-up (arg)
3108 "Move the plain list item at point up, i.e. swap with previous item.
3109 Subitems (items with larger indentation are considered part of the item,
3110 so this really moves item trees."
3112 (let (beg end ind ind1 (pos (point)) txt)
3113 (org-beginning-of-item)
3115 (setq ind (org-get-indentation))
3121 (beginning-of-line 0)
3122 (if (looking-at "[ \t]*$")
3124 (if (<= (setq ind1 (org-get-indentation)) ind)
3127 (org-beginning-of-item)
3128 (error (goto-char beg)
3129 (error "Cannot move this item further up")))
3130 (setq ind1 (org-get-indentation))
3131 (if (and (org-at-item-p) (= ind ind1))
3133 (setq txt (buffer-substring beg end))
3135 (delete-region beg end))
3139 (org-maybe-renumber-ordered-list))
3141 (error "Cannot move this item further up"))))
3143 (defun org-maybe-renumber-ordered-list ()
3144 "Renumber the ordered list at point if setup allows it.
3145 This tests the user option `org-auto-renumber-ordered-lists' before
3146 doing the renumbering."
3147 (and org-auto-renumber-ordered-lists
3150 (org-renumber-ordered-list 1)))
3152 (defun org-get-string-indentation (s)
3153 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3154 (let ((n -1) (i 0) (w tab-width) c)
3156 (while (< (setq n (1+ n)) (length s))
3158 (cond ((= c ?\ ) (setq i (1+ i)))
3159 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3160 (t (throw 'exit t)))))
3163 (defun org-renumber-ordered-list (arg)
3164 "Renumber an ordered plain list.
3165 Cursor neext to be in the first line of an item, the line that starts
3166 with something like \"1.\" or \"2)\"."
3168 (unless (and (org-at-item-p)
3169 (match-beginning 3))
3170 (error "This is not an ordered list"))
3171 (let ((line (org-current-line))
3172 (col (current-column))
3173 (ind (org-get-string-indentation
3174 (buffer-substring (point-at-bol) (match-beginning 3))))
3175 ;; (term (substring (match-string 3) -1))
3177 ;; find where this list begins
3181 (beginning-of-line 0)
3182 (if (looking-at "[ \t]*$") (throw 'next t))
3183 (skip-chars-forward " \t") (setq ind1 (current-column))
3184 (if (or (< ind1 ind)
3186 (not (org-at-item-p))))
3188 ;; Walk forward and replace these numbers
3192 (beginning-of-line 2)
3193 (if (eobp) (throw 'exit nil))
3194 (if (looking-at "[ \t]*$") (throw 'next nil))
3195 (skip-chars-forward " \t") (setq ind1 (current-column))
3196 (if (> ind1 ind) (throw 'next t))
3197 (if (< ind1 ind) (throw 'exit t))
3198 (if (not (org-at-item-p)) (throw 'exit nil))
3199 (if (not (match-beginning 3))
3200 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3201 (delete-region (match-beginning 3) (1- (match-end 3)))
3202 (goto-char (match-beginning 3))
3203 (insert (format "%d" (setq n (1+ n)))))))
3205 (move-to-column col)))
3207 (defvar org-last-indent-begin-marker (make-marker))
3208 (defvar org-last-indent-end-marker (make-marker))
3211 (defun org-outdent-item (arg)
3212 "Outdent a local list item."
3214 (org-indent-item (- arg)))
3216 (defun org-indent-item (arg)
3217 "Indent a local list item."
3219 (unless (org-at-item-p)
3220 (error "Not on an item"))
3221 (let (beg end ind ind1)
3222 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3223 (setq beg org-last-indent-begin-marker
3224 end org-last-indent-end-marker)
3225 (org-beginning-of-item)
3226 (setq beg (move-marker org-last-indent-begin-marker (point)))
3228 (setq end (move-marker org-last-indent-end-marker (point))))
3230 (skip-chars-forward " \t") (setq ind (current-column))
3231 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3232 (while (< (point) end)
3233 (beginning-of-line 1)
3234 (skip-chars-forward " \t") (setq ind1 (current-column))
3235 (delete-region (point-at-bol) (point))
3236 (indent-to-column (+ ind1 arg))
3237 (beginning-of-line 2))
3242 (defun org-archive-subtree ()
3243 "Move the current subtree to the archive.
3244 The archive can be a certain top-level heading in the current file, or in
3245 a different file. The tree will be moved to that location, the subtree
3246 heading be marked DONE, and the current time will be added."
3248 ;; Save all relevant TODO keyword-relatex variables
3249 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3250 (tr-org-todo-keywords org-todo-keywords)
3251 (tr-org-todo-interpretation org-todo-interpretation)
3252 (tr-org-done-string org-done-string)
3253 (tr-org-todo-regexp org-todo-regexp)
3254 (tr-org-todo-line-regexp org-todo-line-regexp)
3255 (this-buffer (current-buffer))
3256 file heading buffer level newfile-p)
3257 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3259 (setq file (format (match-string 1 org-archive-location)
3260 (file-name-nondirectory (buffer-file-name)))
3261 heading (match-string 2 org-archive-location)))
3262 (error "Invalid `org-archive-location'"))
3263 (if (> (length file) 0)
3264 (setq newfile-p (not (file-exists-p file))
3265 buffer (find-file-noselect file))
3266 (setq buffer (current-buffer)))
3268 (error "Cannot access file \"%s\"" file))
3269 (if (and (> (length heading) 0)
3270 (string-match "^\\*+" heading))
3271 (setq level (match-end 0))
3272 (setq heading nil level 0))
3274 ;; We first only copy, in case something goes wrong
3275 ;; we need to protect this-command, to avoid kill-region sets it,
3276 ;; which would lead to duplication of subtrees
3277 (let (this-command) (org-copy-subtree))
3279 ;; Enforce org-mode for the archive buffer
3280 (if (not (eq major-mode 'org-mode))
3281 ;; Force the mode for future visits.
3282 (let ((org-insert-mode-line-in-empty-file t))
3283 (call-interactively 'org-mode)))
3285 (goto-char (point-max))
3286 (insert (format "\nArchived entries from file %s\n\n"
3287 (buffer-file-name this-buffer))))
3288 ;; Force the TODO keywords of the original buffer
3289 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3290 (org-todo-keywords tr-org-todo-keywords)
3291 (org-todo-interpretation tr-org-todo-interpretation)
3292 (org-done-string tr-org-done-string)
3293 (org-todo-regexp tr-org-todo-regexp)
3294 (org-todo-line-regexp tr-org-todo-line-regexp))
3295 (goto-char (point-min))
3298 (if (re-search-forward
3299 (concat "\\(^\\|\r\\)"
3300 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3302 (goto-char (match-end 0))
3303 ;; Heading not found, just insert it at the end
3304 (goto-char (point-max))
3305 (or (bolp) (insert "\n"))
3306 (insert "\n" heading "\n")
3308 ;; Make the heading visible, and the following as well
3309 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3310 (if (re-search-forward
3311 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3313 (progn (goto-char (match-beginning 0)) (insert "\n")
3314 (beginning-of-line 0))
3315 (goto-char (point-max)) (insert "\n")))
3316 (goto-char (point-max)) (insert "\n"))
3318 (org-paste-subtree (1+ level))
3319 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3320 (if org-archive-mark-done
3321 (org-todo (length org-todo-keywords)))
3322 ;; Move cursor to right after the TODO keyword
3323 (when org-archive-stamp-time
3324 (beginning-of-line 1)
3325 (looking-at org-todo-line-regexp)
3326 (goto-char (or (match-end 2) (match-beginning 3)))
3327 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3330 ;; Save the buffer, if it is not the same buffer.
3331 (if (not (eq this-buffer buffer)) (save-buffer))))
3332 ;; Here we are back in the original buffer. Everything seems to have
3333 ;; worked. So now cut the tree and finish up.
3334 (let (this-command) (org-cut-subtree))
3335 (if (looking-at "[ \t]*$") (kill-line))
3336 (message "Subtree archived %s"
3337 (if (eq this-buffer buffer)
3338 (concat "under heading: " heading)
3339 (concat "in file: " (abbreviate-file-name file))))))
3343 (defun org-complete (&optional arg)
3344 "Perform completion on word at point.
3345 At the beginning of a headline, this completes TODO keywords as given in
3346 `org-todo-keywords'.
3347 If the current word is preceded by a backslash, completes the TeX symbols
3348 that are supported for HTML support.
3349 If the current word is preceded by \"#+\", completes special words for
3350 setting file options.
3351 At all other locations, this simply calls `ispell-complete-word'."
3354 (let* ((end (point))
3355 (beg1 (save-excursion
3356 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3357 (skip-chars-backward "a-zA-Z_")
3359 (beg (save-excursion
3360 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3361 (skip-chars-backward "a-zA-Z0-9_:$")
3363 (camel (equal (char-before beg) ?*))
3364 (tag (equal (char-before beg1) ?:))
3365 (texp (equal (char-before beg) ?\\))
3366 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3369 (completion-ignore-case opt)
3376 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3377 (cons (match-string 2 x) (match-string 1 x)))
3378 (org-split-string (org-get-current-options) "\n")))
3382 ((string-match "\\`\\*+[ \t]*\\'"
3383 (buffer-substring (point-at-bol) beg))
3385 (mapcar 'list org-todo-keywords))
3389 (goto-char (point-min))
3390 (while (re-search-forward org-todo-line-regexp nil t)
3391 (push (list (org-make-org-heading-camel (match-string 3)))
3394 (tag (setq type :tag beg beg1)
3395 (org-get-buffer-tags))
3396 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3397 (pattern (buffer-substring-no-properties beg end))
3398 (completion (try-completion pattern table)))
3399 (cond ((eq completion t)
3400 (if (equal type :opt)
3401 (insert (substring (cdr (assoc (upcase pattern) table))
3402 (length pattern)))))
3404 (message "Can't find completion for \"%s\"" pattern)
3406 ((not (string= pattern completion))
3407 (delete-region beg end)
3408 (if (string-match " +$" completion)
3409 (setq completion (replace-match "" t t completion)))
3411 (if (get-buffer-window "*Completions*")
3412 (delete-window (get-buffer-window "*Completions*")))
3413 (if (assoc completion table)
3414 (if (eq type :todo) (insert " ")
3415 (if (eq type :tag) (insert ":"))))
3416 (if (and (equal type :opt) (assoc completion table))
3417 (message "%s" (substitute-command-keys
3418 "Press \\[org-complete] again to insert example settings"))))
3420 (message "Making completion list...")
3421 (let ((list (sort (all-completions pattern table) 'string<)))
3422 (with-output-to-temp-buffer "*Completions*"
3423 (display-completion-list list)))
3424 (message "Making completion list...%s" "done"))))))
3426 ;;; Comments, TODO and DEADLINE
3428 (defun org-toggle-comment ()
3429 "Change the COMMENT state of an entry."
3432 (org-back-to-heading)
3433 (if (looking-at (concat outline-regexp
3434 "\\( +\\<" org-comment-string "\\>\\)"))
3435 (replace-match "" t t nil 1)
3436 (if (looking-at outline-regexp)
3438 (goto-char (match-end 0))
3439 (insert " " org-comment-string))))))
3441 (defvar org-last-todo-state-is-todo nil
3442 "This is non-nil when the last TODO state change led to a TODO state.
3443 If the last change removed the TODO tag or switched to DONE, then
3446 (defun org-todo (&optional arg)
3447 "Change the TODO state of an item.
3448 The state of an item is given by a keyword at the start of the heading,
3450 *** TODO Write paper
3453 The different keywords are specified in the variable `org-todo-keywords'. By
3454 default the available states are \"TODO\" and \"DONE\".
3455 So for this example: when the item starts with TODO, it is changed to DONE.
3456 When it starts with DONE, the DONE is removed. And when neither TODO nor
3457 DONE are present, add TODO at the beginning of the heading.
3459 With prefix arg, use completion to determined the new state. With numeric
3460 prefix arg, switch to that state."
3463 (org-back-to-heading)
3464 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3465 (or (looking-at (concat " +" org-todo-regexp " *"))
3467 (let* ((this (match-string 1))
3468 (completion-ignore-case t)
3469 (member (member this org-todo-keywords))
3473 ;; Read a state with completion
3474 (completing-read "State: " (mapcar (lambda(x) (list x))
3479 (if tail (car tail) nil)
3480 (car org-todo-keywords)))
3482 (if (equal member org-todo-keywords)
3485 (nth (- (length org-todo-keywords) (length tail) 2)
3489 ;; user requests a specific state
3490 (nth (1- (prefix-numeric-value arg))
3492 ((null member) (car org-todo-keywords))
3493 ((null tail) nil) ;; -> first entry
3494 ((eq org-todo-interpretation 'sequence)
3496 ((memq org-todo-interpretation '(type priority))
3497 (if (eq this-command last-command)
3499 (if (> (length tail) 0) org-done-string nil)))
3501 (next (if state (concat " " state " ") " ")))
3502 (replace-match next t t)
3503 (setq org-last-todo-state-is-todo
3504 (not (equal state org-done-string)))
3506 (if (equal state org-done-string)
3510 ;; Fixup tag positioning
3511 (and org-auto-align-tags (org-set-tags nil t))
3512 (run-hooks 'org-after-todo-state-change-hook)))
3513 ;; Fixup cursor location if close to the keyword
3514 (if (and (outline-on-heading-p)
3516 (save-excursion (beginning-of-line 1)
3517 (looking-at org-todo-line-regexp))
3518 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3520 (goto-char (or (match-end 2) (match-end 1)))
3523 (defun org-log-done (&optional undone)
3524 "Add a time stamp logging that a TODO entry has been closed.
3525 When UNDONE is non-nil, remove such a time stamg again."
3529 (org-back-to-heading t)
3531 (looking-at (concat outline-regexp " *"))
3532 (goto-char (match-end 0))
3533 (setq col (current-column))
3534 (outline-next-heading)
3537 (when (re-search-forward (concat
3539 (regexp-quote org-closed-string)
3540 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3541 (delete-region (match-beginning 1) (match-end 1)))
3543 (org-back-to-heading t)
3544 (skip-chars-forward "^\n\r")
3545 (goto-char (min (1+ (point)) (point-max)))
3546 (when (not (member (char-before) '(?\r ?\n)))
3549 (insert org-closed-string " "
3551 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3555 (defun org-show-todo-tree (arg)
3556 "Make a compact tree which shows all headlines marked with TODO.
3557 The tree will show the lines where the regexp matches, and all higher
3558 headlines above the match.
3559 With \\[universal-argument] prefix, also show the DONE entries.
3560 With a numeric prefix N, construct a sparse tree for the Nth element
3561 of `org-todo-keywords'."
3563 (let ((case-fold-search nil)
3565 (cond ((null arg) org-not-done-regexp)
3566 ((equal arg '(4)) org-todo-regexp)
3567 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3568 (regexp-quote (nth (1- (prefix-numeric-value arg))
3569 org-todo-keywords)))
3570 (t (error "Invalid prefix argument: %s" arg)))))
3571 (message "%d TODO entries found"
3572 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3574 (defun org-deadline ()
3575 "Insert the DEADLINE: string to make a deadline.
3576 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3577 to modify it to the correct date."
3580 org-deadline-string " "
3581 (format-time-string (car org-time-stamp-formats)
3582 (org-read-date nil 'to-time)))
3583 (message "%s" (substitute-command-keys
3584 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3586 (defun org-schedule ()
3587 "Insert the SCHEDULED: string to schedule a TODO item.
3588 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3589 to modify it to the correct date."
3592 org-scheduled-string " "
3593 (format-time-string (car org-time-stamp-formats)
3594 (org-read-date nil 'to-time)))
3595 (message "%s" (substitute-command-keys
3596 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3599 (defun org-occur (regexp &optional callback)
3600 "Make a compact tree which shows all matches of REGEXP.
3601 The tree will show the lines where the regexp matches, and all higher
3602 headlines above the match. It will also show the heading after the match,
3603 to make sure editing the matching entry is easy.
3604 if CALLBACK is non-nil, it is a function which is called to confirm
3605 that the match should indeed be shown."
3606 (interactive "sRegexp: ")
3607 (org-remove-occur-highlights nil nil t)
3608 (setq regexp (org-check-occur-regexp regexp))
3611 (goto-char (point-min))
3613 (while (re-search-forward regexp nil t)
3614 (when (or (not callback)
3615 (save-match-data (funcall callback)))
3617 (org-highlight-new-match (match-beginning 0) (match-end 0))
3618 (org-show-hierarchy-above))))
3619 (make-local-hook 'before-change-functions) ; needed for XEmacs
3620 (add-hook 'before-change-functions 'org-remove-occur-highlights
3622 (run-hooks 'org-occur-hook)
3624 (message "%d match(es) for regexp %s" cnt regexp))
3627 (defun org-show-hierarchy-above ()
3628 "Make sure point and the headings hierarchy above is visible."
3629 (if (org-on-heading-p t)
3630 (org-flag-heading nil) ; only show the heading
3631 (and (org-invisible-p) (org-show-hidden-entry))) ; show entire entry
3633 (and org-show-following-heading
3634 (outline-next-heading)
3635 (org-flag-heading nil))) ; show the next heading
3636 (when org-show-hierarchy-above
3637 (save-excursion ; show all higher headings
3638 (while (condition-case nil
3639 (progn (org-up-heading-all 1) t)
3641 (org-flag-heading nil)))))
3643 (defvar org-occur-highlights nil)
3644 (defun org-highlight-new-match (beg end)
3645 "Highlight from BEG to END and mark the highlight is an occur headline."
3646 (let ((ov (make-overlay beg end)))
3647 (overlay-put ov 'face 'secondary-selection)
3648 (push ov org-occur-highlights)))
3650 (defun org-remove-occur-highlights (&optional beg end noremove)
3651 "Remove the occur highlights from the buffer.
3652 BEG and END are ignored. If NOREMOVE is nil, remove this function
3653 from the before-change-functions in the current buffer."
3655 (mapc 'delete-overlay org-occur-highlights)
3656 (setq org-occur-highlights nil)
3658 (remove-hook 'before-change-functions
3659 'org-remove-occur-highlights 'local)))
3663 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3664 "Regular expression matching the priority indicator.")
3666 (defvar org-remove-priority-next-time nil)
3668 (defun org-priority-up ()
3669 "Increase the priority of the current item."
3673 (defun org-priority-down ()
3674 "Decrease the priority of the current item."
3676 (org-priority 'down))
3678 (defun org-priority (&optional action)
3679 "Change the priority of an item by ARG.
3680 ACTION can be set, up, or down."
3682 (setq action (or action 'set))
3683 (let (current new news have remove)
3685 (org-back-to-heading)
3686 (if (looking-at org-priority-regexp)
3687 (setq current (string-to-char (match-string 2))
3689 (setq current org-default-priority))
3692 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3693 (setq new (read-char-exclusive))
3694 (cond ((equal new ?\ ) (setq remove t))
3695 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3696 (error "Priority must be between `%c' and `%c'"
3697 ?A org-lowest-priority))))
3699 (setq new (1- current)))
3701 (setq new (1+ current)))
3702 (t (error "Invalid action")))
3703 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3704 (setq news (format "%c" new))
3707 (replace-match "" t t nil 1)
3708 (replace-match news t t nil 2))
3710 (error "No priority cookie found in line")
3711 (looking-at org-todo-line-regexp)
3714 (goto-char (match-end 2))
3715 (insert " [#" news "]"))
3716 (goto-char (match-beginning 3))
3717 (insert "[#" news "] ")))))
3719 (message "Priority removed")
3720 (message "Priority of current item set to %s" news))))
3723 (defun org-get-priority (s)
3724 "Find priority cookie and return priority."
3726 (if (not (string-match org-priority-regexp s))
3727 (* 1000 (- org-lowest-priority org-default-priority))
3728 (* 1000 (- org-lowest-priority
3729 (string-to-char (match-string 2 s)))))))
3733 (defvar org-last-changed-timestamp nil)
3735 (defun org-time-stamp (arg)
3736 "Prompt for a date/time and insert a time stamp.
3737 If the user specifies a time like HH:MM, or if this command is called
3738 with a prefix argument, the time stamp will contain date and time.
3739 Otherwise, only the date will be included. All parts of a date not
3740 specified by the user will be filled in from the current date/time.
3741 So if you press just return without typing anything, the time stamp
3742 will represent the current date/time. If there is already a timestamp
3743 at the cursor, it will be modified."
3745 (let ((fmt (if arg (cdr org-time-stamp-formats)
3746 (car org-time-stamp-formats)))
3747 (org-time-was-given nil)
3750 ((and (org-at-timestamp-p)
3751 (eq last-command 'org-time-stamp)
3752 (eq this-command 'org-time-stamp))
3754 (setq time (let ((this-command this-command))
3755 (org-read-date arg 'totime)))
3756 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3757 (insert (format-time-string fmt time)))
3758 ((org-at-timestamp-p)
3759 (setq time (let ((this-command this-command))
3760 (org-read-date arg 'totime)))
3761 (and (org-at-timestamp-p) (replace-match
3762 (setq org-last-changed-timestamp
3763 (format-time-string fmt time))
3765 (message "Timestamp updated"))
3767 (setq time (let ((this-command this-command))
3768 (org-read-date arg 'totime)))
3769 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3770 (insert (format-time-string fmt time))))))
3772 (defun org-time-stamp-inactive (&optional arg)
3773 "Insert an inactive time stamp.
3774 An inactive time stamp is enclosed in square brackets instead of angle
3775 brackets. It is inactive in the sense that it does not trigger agenda entries,
3776 does not link to the calendar and cannot be changed with the S-cursor keys.
3777 So these are more for recording a certain time/date."
3778 ;; FIXME: Would it be better not to ask for a date/time here?
3780 (let ((fmt (if arg (cdr org-time-stamp-formats)
3781 (car org-time-stamp-formats)))
3782 (org-time-was-given nil)
3784 (setq time (org-read-date arg 'totime))
3785 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3786 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3787 (insert (format-time-string fmt time))))
3789 ;;; FIXME: Make the function take "Fri" as "next friday"
3790 ;;; because these are mostly being used to record the current time.
3791 (defun org-read-date (&optional with-time to-time)
3792 "Read a date and make things smooth for the user.
3793 The prompt will suggest to enter an ISO date, but you can also enter anything
3794 which will at least partially be understood by `parse-time-string'.
3795 Unrecognized parts of the date will default to the current day, month ,year,
3796 hour and minute. For example,
3797 3-2-5 --> 2003-02-05
3798 feb 15 --> currentyear-02-15
3799 sep 12 9 --> 2009-09-12
3800 12:45 --> today 12:45
3801 22 sept 0:34 --> currentyear-09-22 0:34
3802 12 --> currentyear-currentmonth-12
3804 The function understands only English month and weekday abbreviations,
3805 but this can be configured with the variables `parse-time-months' and
3806 `parse-time-weekdays'.
3808 While prompting, a calendar is popped up - you can also select the
3809 date with the mouse (button 1). The calendar shows a period of three
3810 month. To scroll it to other months, use the keys `>' and `<'.
3811 If you don't like the calendar, turn it off with
3812 \(setq org-popup-calendar-for-date-prompt nil).
3814 With optional argument TO-TIME, the date will immediately be converted
3815 to an internal time.
3816 With an optional argument WITH-TIME, the prompt will suggest to also
3817 insert a time. Note that when WITH-TIME is not set, you can still
3818 enter a time, and this function will inform the calling routine about
3819 this change. The calling routine may then choose to change the format
3820 used to insert the time stamp into the buffer to include the time."
3821 (let* ((default-time
3822 ;; Default time is either today, or, when entering a range,
3826 (concat org-ts-regexp "--\\=")
3830 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3831 (parse-time-string (match-string 1))))
3833 (calendar-move-hook nil)
3834 (view-diary-entries-initially nil)
3835 (timestr (format-time-string
3836 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3837 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3839 second minute hour day month year tl)
3841 (if org-popup-calendar-for-date-prompt
3842 ;; Also show a calendar for date selection
3843 ;; Copied (with modifications) from planner.el by John Wiegley
3845 (save-window-excursion
3847 (calendar-forward-day (- (time-to-days default-time)
3848 (calendar-absolute-from-gregorian
3849 (calendar-current-date))))
3850 (let* ((old-map (current-local-map))
3851 (map (copy-keymap calendar-mode-map))
3852 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3853 (define-key map (kbd "RET") 'org-calendar-select)
3854 (define-key map (if org-xemacs-p [button1] [mouse-1])
3855 'org-calendar-select)
3856 (define-key minibuffer-local-map [(meta shift left)]
3857 (lambda () (interactive)
3858 (org-eval-in-calendar '(calendar-backward-month 1))))
3859 (define-key minibuffer-local-map [(meta shift right)]
3860 (lambda () (interactive)
3861 (org-eval-in-calendar '(calendar-forward-month 1))))
3862 (define-key minibuffer-local-map [(shift up)]
3863 (lambda () (interactive)
3864 (org-eval-in-calendar '(calendar-backward-week 1))))
3865 (define-key minibuffer-local-map [(shift down)]
3866 (lambda () (interactive)
3867 (org-eval-in-calendar '(calendar-forward-week 1))))
3868 (define-key minibuffer-local-map [(shift left)]
3869 (lambda () (interactive)
3870 (org-eval-in-calendar '(calendar-backward-day 1))))
3871 (define-key minibuffer-local-map [(shift right)]
3872 (lambda () (interactive)
3873 (org-eval-in-calendar '(calendar-forward-day 1))))
3874 (define-key minibuffer-local-map ">"
3875 (lambda () (interactive)
3876 (org-eval-in-calendar '(scroll-calendar-left 1))))
3877 (define-key minibuffer-local-map "<"
3878 (lambda () (interactive)
3879 (org-eval-in-calendar '(scroll-calendar-right 1))))
3883 (setq ans (read-string prompt "" nil nil))
3884 (setq ans (or ans1 ans2 ans)))
3885 (use-local-map old-map)))))
3886 ;; Naked prompt only
3887 (setq ans (read-string prompt "" nil timestr)))
3890 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3892 (setq year (if (match-end 2)
3893 (string-to-number (match-string 2 ans))
3894 (string-to-number (format-time-string "%Y")))
3895 month (string-to-number (match-string 3 ans))
3896 day (string-to-number (match-string 4 ans)))
3897 (if (< year 100) (setq year (+ 2000 year)))
3898 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3900 (setq tl (parse-time-string ans)
3901 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3902 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3903 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3904 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3905 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3906 second (or (nth 0 tl) 0))
3907 (if (and (boundp 'org-time-was-given)
3909 (setq org-time-was-given t))
3910 (if (< year 100) (setq year (+ 2000 year)))
3912 (encode-time second minute hour day month year)
3913 (if (or (nth 1 tl) (nth 2 tl))
3914 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3915 (format "%04d-%02d-%02d" year month day)))))
3917 (defun org-eval-in-calendar (form)
3918 "Eval FORM in the calendar window and return to current window.
3919 Also, store the cursor date in variable ans2."
3920 (let ((sw (selected-window)))
3921 (select-window (get-buffer-window "*Calendar*"))
3923 (when (calendar-cursor-to-date)
3924 (let* ((date (calendar-cursor-to-date))
3925 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3926 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3927 (and org-xemacs-p (sit-for .2))
3928 (select-window sw)))
3930 (defun org-calendar-select ()
3931 "Return to `org-read-date' with the date currently selected.
3932 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3934 (when (calendar-cursor-to-date)
3935 (let* ((date (calendar-cursor-to-date))
3936 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3937 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3938 (if (active-minibuffer-window) (exit-minibuffer))))
3940 (defun org-check-deadlines (ndays)
3941 "Check if there are any deadlines due or past due.
3942 A deadline is considered due if it happens within `org-deadline-warning-days'
3943 days from today's date. If the deadline appears in an entry marked DONE,
3944 it is not shown. The prefix arg NDAYS can be used to test that many
3945 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3947 (let* ((org-warn-days
3949 ((equal ndays '(4)) 100000)
3950 (ndays (prefix-numeric-value ndays))
3951 (t org-deadline-warning-days)))
3952 (case-fold-search nil)
3953 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3956 (and (let ((d1 (time-to-days (current-time)))
3958 (org-time-string-to-time (match-string 1)))))
3959 (< (- d2 d1) org-warn-days))
3960 (not (org-entry-is-done-p))))))
3961 (message "%d deadlines past-due or due within %d days"
3962 (org-occur regexp callback)
3965 (defun org-evaluate-time-range (&optional to-buffer)
3966 "Evaluate a time range by computing the difference between start and end.
3967 Normally the result is just printed in the echo area, but with prefix arg
3968 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3969 If the time range is actually in a table, the result is inserted into the
3971 For time difference computation, a year is assumed to be exactly 365
3972 days in order to avoid rounding problems."
3975 (unless (org-at-date-range-p)
3976 (goto-char (point-at-bol))
3977 (re-search-forward org-tr-regexp (point-at-eol) t))
3978 (if (not (org-at-date-range-p))
3979 (error "Not at a time-stamp range, and none found in current line")))
3980 (let* ((ts1 (match-string 1))
3981 (ts2 (match-string 2))
3982 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3983 (match-end (match-end 0))
3984 (time1 (org-time-string-to-time ts1))
3985 (time2 (org-time-string-to-time ts2))
3986 (t1 (time-to-seconds time1))
3987 (t2 (time-to-seconds time2))
3988 (diff (abs (- t2 t1)))
3989 (negative (< (- t2 t1) 0))
3990 ;; (ys (floor (* 365 24 60 60)))
3993 (fy "%dy %dd %02d:%02d")
3995 (fd "%dd %02d:%02d")
3999 ;; FIXME: Should I re-introduce years, make year refer to same date?
4000 ;; This would be the only useful way to have years, actually.
4002 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4004 d (floor (/ diff ds)) diff (mod diff ds)
4005 h (floor (/ diff hs)) diff (mod diff hs)
4006 m (floor (/ diff 60)))
4007 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4009 d (floor (+ (/ diff ds) 0.5))
4012 (message (org-make-tdiff-string y d h m))
4013 (when (org-at-table-p)
4014 (goto-char match-end)
4016 (and (looking-at " *|") (goto-char (match-end 0))))
4018 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4020 (if negative (insert " -"))
4021 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4022 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4023 (insert " " (format fh h m))))
4024 (if align (org-table-align))
4025 (message "Time difference inserted"))))
4027 (defun org-make-tdiff-string (y d h m)
4030 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4032 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4034 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4036 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4038 (apply 'format fmt (nreverse l))))
4040 (defun org-time-string-to-time (s)
4041 (apply 'encode-time (org-parse-time-string s)))
4043 (defun org-parse-time-string (s &optional nodefault)
4044 "Parse the standard Org-mode time string.
4045 This should be a lot faster than the normal `parse-time-string'.
4046 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4047 hour and minute fields will be nil if not given."
4048 (if (string-match org-ts-regexp1 s)
4050 (if (or (match-beginning 8) (not nodefault))
4051 (string-to-number (or (match-string 8 s) "0")))
4052 (if (or (match-beginning 7) (not nodefault))
4053 (string-to-number (or (match-string 7 s) "0")))
4054 (string-to-number (match-string 4 s))
4055 (string-to-number (match-string 3 s))
4056 (string-to-number (match-string 2 s))
4060 (defun org-timestamp-up (&optional arg)
4061 "Increase the date item at the cursor by one.
4062 If the cursor is on the year, change the year. If it is on the month or
4063 the day, change that.
4064 With prefix ARG, change by that many units."
4066 (org-timestamp-change (prefix-numeric-value arg)))
4068 (defun org-timestamp-down (&optional arg)
4069 "Decrease the date item at the cursor by one.
4070 If the cursor is on the year, change the year. If it is on the month or
4071 the day, change that.
4072 With prefix ARG, change by that many units."
4074 (org-timestamp-change (- (prefix-numeric-value arg))))
4076 (defun org-timestamp-up-day (&optional arg)
4077 "Increase the date in the time stamp by one day.
4078 With prefix ARG, change that many days."
4080 (if (and (not (org-at-timestamp-p))
4083 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4085 (defun org-timestamp-down-day (&optional arg)
4086 "Decrease the date in the time stamp by one day.
4087 With prefix ARG, change that many days."
4089 (if (and (not (org-at-timestamp-p))
4092 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4094 (defsubst org-pos-in-match-range (pos n)
4095 (and (match-beginning n)
4096 (<= (match-beginning n) pos)
4097 (>= (match-end n) pos)))
4099 (defun org-at-timestamp-p ()
4100 "Determine if the cursor is in or at a timestamp."
4102 (let* ((tsr org-ts-regexp2)
4104 (ans (or (looking-at tsr)
4106 (skip-chars-backward "^<\n\r\t")
4107 (if (> (point) 1) (backward-char 1))
4108 (and (looking-at tsr)
4109 (> (- (match-end 0) pos) -1))))))
4110 (and (boundp 'org-ts-what)
4113 ((org-pos-in-match-range pos 2) 'year)
4114 ((org-pos-in-match-range pos 3) 'month)
4115 ((org-pos-in-match-range pos 7) 'hour)
4116 ((org-pos-in-match-range pos 8) 'minute)
4117 ((or (org-pos-in-match-range pos 4)
4118 (org-pos-in-match-range pos 5)) 'day)
4122 (defun org-timestamp-change (n &optional what)
4123 "Change the date in the time stamp at point.
4124 The date will be changed by N times WHAT. WHAT can be `day', `month',
4125 `year', `minute', `second'. If WHAT is not given, the cursor position
4126 in the timestamp determines what will be changed."
4127 (let ((fmt (car org-time-stamp-formats))
4131 (if (not (org-at-timestamp-p))
4132 (error "Not at a timestamp"))
4133 (setq org-ts-what (or what org-ts-what))
4134 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4135 (- (match-end 0) (match-beginning 0))))
4137 (cdr org-time-stamp-formats)
4138 (car org-time-stamp-formats)))
4139 (setq ts (match-string 0))
4141 (setq time0 (org-parse-time-string ts))
4145 (list (or (car time0) 0))
4146 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4147 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4148 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4149 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4150 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4152 (if (eq what 'calendar)
4156 (set-buffer "*Calendar*")
4157 (calendar-cursor-to-date)))))
4158 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4159 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4160 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4161 (setcar time0 (or (car time0) 0))
4162 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4163 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4164 (setq time (apply 'encode-time time0))))
4165 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4167 ;; Try to recenter the calendar window, if any
4168 (if (and org-calendar-follow-timestamp-change
4169 (get-buffer-window "*Calendar*" t)
4170 (memq org-ts-what '(day month year)))
4171 (org-recenter-calendar (time-to-days time)))))
4173 (defun org-recenter-calendar (date)
4174 "If the calendar is visible, recenter it to DATE."
4175 (let* ((win (selected-window))
4176 (cwin (get-buffer-window "*Calendar*" t))
4177 (calendar-move-hook nil))
4179 (select-window cwin)
4180 (calendar-goto-date (if (listp date) date
4181 (calendar-gregorian-from-absolute date)))
4182 (select-window win))))
4184 (defun org-goto-calendar (&optional arg)
4185 "Go to the Emacs calendar at the current date.
4186 If there is a time stamp in the current line, go to that date.
4187 A prefix ARG can be used force the current date."
4189 (let ((tsr org-ts-regexp) diff
4190 (calendar-move-hook nil)
4191 (view-diary-entries-initially nil))
4192 (if (or (org-at-timestamp-p)
4194 (beginning-of-line 1)
4195 (looking-at (concat ".*" tsr))))
4196 (let ((d1 (time-to-days (current-time)))
4198 (org-time-string-to-time (match-string 1)))))
4199 (setq diff (- d2 d1))))
4201 (calendar-goto-today)
4202 (if (and diff (not arg)) (calendar-forward-day diff))))
4204 (defun org-date-from-calendar ()
4205 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4206 If there is already a time stamp at the cursor position, update it."
4208 (org-timestamp-change 0 'calendar))
4210 ;;; Agenda, and Diary Integration
4214 (defvar org-agenda-mode-map (make-sparse-keymap)
4215 "Keymap for `org-agenda-mode'.")
4217 (defvar org-agenda-menu)
4218 (defvar org-agenda-follow-mode nil)
4219 (defvar org-agenda-show-log nil)
4220 (defvar org-agenda-buffer-name "*Org Agenda*")
4221 (defvar org-agenda-redo-command nil)
4222 (defvar org-agenda-mode-hook nil)
4224 (defvar org-agenda-force-single-file nil)
4227 (defun org-agenda-mode ()
4228 "Mode for time-sorted view on action items in Org-mode files.
4230 The following commands are available:
4232 \\{org-agenda-mode-map}"
4234 (kill-all-local-variables)
4235 (setq major-mode 'org-agenda-mode)
4236 (setq mode-name "Org-Agenda")
4237 (use-local-map org-agenda-mode-map)
4238 (easy-menu-add org-agenda-menu)
4239 (if org-startup-truncated (setq truncate-lines t))
4240 (make-local-hook 'post-command-hook) ; Needed for XEmacs
4241 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4242 (make-local-hook 'pre-command-hook) ; Needed for XEmacs
4243 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4244 (unless org-agenda-keep-modes
4245 (setq org-agenda-follow-mode nil
4246 org-agenda-show-log nil))
4248 '("Agenda") "Agenda Files"
4252 (if (get 'org-agenda-files 'org-restrict)
4253 "Restricted to single file"
4255 '(customize-variable 'org-agenda-files)
4256 (not (get 'org-agenda-files 'org-restrict)))
4258 (mapcar 'org-file-menu-entry (org-agenda-files))))
4259 (org-agenda-set-mode-name)
4261 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4262 (list 'org-agenda-mode-hook)))
4264 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4265 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4266 (define-key org-agenda-mode-map " " 'org-agenda-show)
4267 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4268 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4269 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4270 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4271 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4272 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4273 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4274 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4275 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4276 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4277 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4278 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4280 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4281 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4282 (while l (define-key org-agenda-mode-map
4283 (int-to-string (pop l)) 'digit-argument)))
4285 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4286 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4287 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4288 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4289 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4290 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4291 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4292 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4293 (define-key org-agenda-mode-map "n" 'next-line)
4294 (define-key org-agenda-mode-map "p" 'previous-line)
4295 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4296 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4297 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4298 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4299 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4300 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4301 (eval-after-load "calendar"
4302 '(define-key calendar-mode-map org-calendar-to-agenda-key
4303 'org-calendar-goto-agenda))
4304 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4305 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4306 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4307 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4308 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4309 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4310 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4311 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4312 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4313 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4314 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4315 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4316 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4317 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4318 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4319 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4320 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4321 "Local keymap for agenda entries from Org-mode.")
4323 (define-key org-agenda-keymap
4324 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4325 (define-key org-agenda-keymap
4326 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4328 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4332 ["Show" org-agenda-show t]
4333 ["Go To (other window)" org-agenda-goto t]
4334 ["Go To (one window)" org-agenda-switch-to t]
4335 ["Follow Mode" org-agenda-follow-mode
4336 :style toggle :selected org-agenda-follow-mode :active t]
4338 ["Cycle TODO" org-agenda-todo t]
4339 ["Set Tags" org-agenda-set-tags t]
4341 ["Reschedule +1 day" org-agenda-date-later t]
4342 ["Reschedule -1 day" org-agenda-date-earlier t]
4344 ["Reschedule to ..." org-agenda-date-prompt t])
4346 ["Set Priority" org-agenda-priority t]
4347 ["Increase Priority" org-agenda-priority-up t]
4348 ["Decrease Priority" org-agenda-priority-down t]
4349 ["Show Priority" org-agenda-show-priority t])
4351 ["Rebuild buffer" org-agenda-redo t]
4352 ["Goto Today" org-agenda-goto-today t]
4353 ["Next Dates" org-agenda-later (local-variable-p 'starting-day (current-buffer))]
4354 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day (current-buffer))]
4356 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day (current-buffer))
4357 :style radio :selected (equal org-agenda-ndays 1)]
4358 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day (current-buffer))
4359 :style radio :selected (equal org-agenda-ndays 7)]
4361 ["Show Logbook entries" org-agenda-log-mode
4362 :style toggle :selected org-agenda-show-log :active t]
4363 ["Include Diary" org-agenda-toggle-diary
4364 :style toggle :selected org-agenda-include-diary :active t]
4365 ["Use Time Grid" org-agenda-toggle-time-grid
4366 :style toggle :selected org-agenda-use-time-grid :active t]
4368 ["New Diary Entry" org-agenda-diary-entry t]
4369 ("Calendar Commands"
4370 ["Goto Calendar" org-agenda-goto-calendar t]
4371 ["Phases of the Moon" org-agenda-phases-of-moon t]
4372 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
4373 ["Holidays" org-agenda-holidays t]
4374 ["Convert" org-agenda-convert-date t])
4375 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4377 ["Quit" org-agenda-quit t]
4378 ["Exit and Release Buffers" org-agenda-exit t]
4382 (defun org-agenda (arg)
4383 "Dispatch agenda commands to collect entries to the agenda buffer.
4384 Prompts for a character to select a command. Any prefix arg will be passed
4385 on to the selected command. The default selections are:
4387 a Call `org-agenda' to display the agenda for the current day or week.
4388 t Call `org-todo-list' to display the global todo list.
4389 T Call `org-todo-list' to display the global todo list, put
4390 select only entries with a specific TODO keyword.
4391 m Call `org-tags-view' to display headlines with tags matching
4392 a condition. The tags condition is a list of positive and negative
4393 selections, like `+WORK+URGENT-WITHBOSS'.
4394 M like `m', but select only TODO entries, no ordinary headlines.
4396 More commands can be added by configuring the variable
4397 `org-agenda-custom-commands'.
4399 If the current buffer is in Org-mode and visiting a file, you can also
4400 first press `1' to indicate that the agenda should be temporarily
4401 restricted to the current file."
4404 (let ((restrict-ok (and (buffer-file-name) (eq major-mode 'org-mode)))
4405 (custom org-agenda-custom-commands)
4406 c entry key type string)
4407 (put 'org-agenda-files 'org-restrict nil)
4408 (save-window-excursion
4409 (delete-other-windows)
4410 (switch-to-buffer-other-window " *Agenda Commands*")
4413 "Press key for an agenda command:
4414 --------------------------------
4415 a Agenda for current week or day
4416 t List of all TODO entries T Entries with special TODO kwd
4417 m Match a TAGS query M Like m, but only TODO entries.
4418 C Configure your own agenda commands")
4419 (while (setq entry (pop custom))
4420 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4421 (insert (format "\n%-4s%-12s: %s"
4423 (if (eq type 'tags) "Tags query" "TODO keyword")
4425 (goto-char (point-min))
4426 (fit-window-to-buffer)
4427 (message "Press key for agenda command%s"
4428 (if restrict-ok ", or [1] to restrict to current file" ""))
4429 (setq c (read-char-exclusive))
4433 (put 'org-agenda-files 'org-restrict (list (buffer-file-name)))
4434 (error "Cannot restrict agenda to current buffer"))
4435 (message "Press key for agenda command%s"
4436 (if restrict-ok " (restricted to current file)" ""))
4437 (setq c (read-char-exclusive))
4439 (require 'calendar) ; FIXME: can we avoid this for some commands?
4441 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4442 ((equal c ?a) (call-interactively 'org-agenda-list))
4443 ((equal c ?t) (call-interactively 'org-todo-list))
4445 (setq current-prefix-arg (or arg '(4)))
4446 (call-interactively 'org-todo-list))
4447 ((equal c ?m) (call-interactively 'org-tags-view))
4449 (setq current-prefix-arg (or arg '(4)))
4450 (call-interactively 'org-tags-view))
4451 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4452 (setq type (nth 1 entry) string (nth 2 entry))
4455 (org-tags-view current-prefix-arg string))
4457 (org-todo-list string))
4458 (t (error "Invalid custom agenda command type %s" type))))
4459 (t (error "Invalid key"))))))
4461 (defun org-fit-agenda-window ()
4462 "Fit the window to the buffer size."
4463 (and org-fit-agenda-window
4464 (fboundp 'fit-window-to-buffer)
4465 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4466 (/ (frame-height) 2))))
4468 (defun org-agenda-files ()
4469 "Get the list of agenda files."
4470 (or (get 'org-agenda-files 'org-restrict)
4473 (defvar org-agenda-markers nil
4474 "List of all currently active markers created by `org-agenda'.")
4475 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4476 "Creation time of the last agenda marker.")
4478 (defun org-agenda-new-marker (&optional pos)
4479 "Return a new agenda marker.
4480 Org-mode keeps a list of these markers and resets them when they are
4482 (let ((m (copy-marker (or pos (point)))))
4483 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4484 (push m org-agenda-markers)
4487 (defun org-agenda-maybe-reset-markers (&optional force)
4488 "Reset markers created by `org-agenda'. But only if they are old enough."
4490 (> (- (time-to-seconds (current-time))
4491 org-agenda-last-marker-time)
4493 (while org-agenda-markers
4494 (move-marker (pop org-agenda-markers) nil))))
4496 (defvar org-agenda-new-buffers nil
4497 "Buffers created to visit agenda files.")
4499 (defun org-get-agenda-file-buffer (file)
4500 "Get a buffer visiting FILE. If the buffer needs to be created, add
4501 it to the list of buffers which might be released later."
4502 (let ((buf (find-buffer-visiting file)))
4504 buf ; just return it
4505 ;; Make a new buffer and remember it
4506 (setq buf (find-file-noselect file))
4507 (if buf (push buf org-agenda-new-buffers))
4510 (defun org-release-buffers (blist)
4511 "Release all buffers in list, asking the user for confirmation when needed.
4512 When a buffer is unmodified, it is just killed. When modified, it is saved
4513 \(if the user agrees) and then killed."
4515 (while (setq buf (pop blist))
4516 (setq file (buffer-file-name buf))
4517 (when (and (buffer-modified-p buf)
4519 (y-or-n-p (format "Save file %s? " file)))
4520 (with-current-buffer buf (save-buffer)))
4521 (kill-buffer buf))))
4523 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4525 (defun org-timeline (&optional include-all keep-modes)
4526 "Show a time-sorted view of the entries in the current org file.
4527 Only entries with a time stamp of today or later will be listed. With
4528 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4529 under the current date.
4530 If the buffer contains an active region, only check the region for
4534 (org-agenda-maybe-reset-markers 'force)
4535 (org-compile-prefix-format org-timeline-prefix-format)
4537 (dotodo include-all)
4538 (doclosed org-agenda-show-log)
4539 (org-agenda-keep-modes keep-modes)
4540 (entry (buffer-file-name))
4541 (org-agenda-files (list (buffer-file-name)))
4542 (date (calendar-current-date))
4543 (win (selected-window))
4545 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4546 (end (if (org-region-active-p) (region-end) (point-max)))
4547 (day-numbers (org-get-all-dates beg end 'no-ranges
4548 t doclosed)) ; always include today
4549 (today (time-to-days (current-time)))
4550 (org-respect-restriction t)
4554 (setq org-agenda-redo-command
4556 (list 'switch-to-buffer-other-window (current-buffer))
4557 (list 'org-timeline (list 'quote include-all) t)))
4559 ;; Remove past dates from the list of dates.
4560 (setq day-numbers (delq nil (mapcar (lambda(x)
4561 (if (>= x today) x nil))
4563 (switch-to-buffer-other-window
4564 (get-buffer-create org-agenda-buffer-name))
4565 (setq buffer-read-only nil)
4567 (org-agenda-mode) (setq buffer-read-only nil)
4568 (if doclosed (push :closed args))
4569 (push :timestamp args)
4570 (if dotodo (push :todo args))
4571 (while (setq d (pop day-numbers))
4572 (if (and (>= d today)
4577 (insert (make-string 79 ?-) "\n")))
4578 (setq date (calendar-gregorian-from-absolute d))
4580 (setq rtn (apply 'org-agenda-get-day-entries
4582 (if (or rtn (equal d today))
4584 (insert (calendar-day-name date) " "
4585 (number-to-string (extract-calendar-day date)) " "
4586 (calendar-month-name (extract-calendar-month date)) " "
4587 (number-to-string (extract-calendar-year date)) "\n")
4588 (put-text-property s (1- (point)) 'face
4591 (put-text-property s (1- (point)) 'org-today t))
4592 (insert (org-finalize-agenda-entries rtn) "\n")
4593 (put-text-property s (1- (point)) 'day d))))
4594 (goto-char (point-min))
4595 (setq buffer-read-only t)
4596 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4598 (when (not org-select-timeline-window)
4603 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4604 "Produce a weekly view from all files in variable `org-agenda-files'.
4605 The view will be for the current week, but from the overview buffer you
4606 will be able to go to other weeks.
4607 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4608 also be shown, under the current date.
4609 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4610 on the days are also shown. See the variable `org-log-done' for how
4612 START-DAY defaults to TODAY, or to the most recent match for the weekday
4613 given in `org-agenda-start-on-weekday'.
4614 NDAYS defaults to `org-agenda-ndays'."
4616 (org-agenda-maybe-reset-markers 'force)
4617 (org-compile-prefix-format org-agenda-prefix-format)
4619 (let* ((org-agenda-start-on-weekday
4620 (if (or (equal ndays 1)
4621 (and (null ndays) (equal 1 org-agenda-ndays)))
4622 nil org-agenda-start-on-weekday))
4623 (org-agenda-keep-modes keep-modes)
4624 (files (copy-sequence (org-agenda-files)))
4625 (win (selected-window))
4626 (today (time-to-days (current-time)))
4627 (sd (or start-day today))
4628 (start (if (or (null org-agenda-start-on-weekday)
4629 (< org-agenda-ndays 7))
4631 (let* ((nt (calendar-day-of-week
4632 (calendar-gregorian-from-absolute sd)))
4633 (n1 org-agenda-start-on-weekday)
4635 (- sd (+ (if (< d 0) 7 0) d)))))
4636 (day-numbers (list start))
4637 (inhibit-redisplay t)
4638 s e rtn rtnall file date d start-pos end-pos todayp nd)
4639 (setq org-agenda-redo-command
4640 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4641 ;; Make the list of days
4642 (setq ndays (or ndays org-agenda-ndays)
4645 (push (1+ (car day-numbers)) day-numbers)
4646 (setq ndays (1- ndays)))
4647 (setq day-numbers (nreverse day-numbers))
4648 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4650 (delete-other-windows)
4651 (switch-to-buffer-other-window
4652 (get-buffer-create org-agenda-buffer-name))))
4653 (setq buffer-read-only nil)
4655 (org-agenda-mode) (setq buffer-read-only nil)
4656 (set (make-local-variable 'starting-day) (car day-numbers))
4657 (set (make-local-variable 'include-all-loc) include-all)
4658 (when (and (or include-all org-agenda-include-all-todo)
4659 (member today day-numbers))
4660 (setq files (org-agenda-files)
4662 (while (setq file (pop files))
4664 (org-check-agenda-file file)
4665 (setq date (calendar-gregorian-from-absolute today)
4666 rtn (org-agenda-get-day-entries
4668 (setq rtnall (append rtnall rtn))))
4670 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4671 (add-text-properties (point-min) (1- (point))
4672 (list 'face 'org-link))
4673 (insert (org-finalize-agenda-entries rtnall) "\n")))
4674 (while (setq d (pop day-numbers))
4675 (setq date (calendar-gregorian-from-absolute d)
4677 (if (or (setq todayp (= d today))
4678 (and (not start-pos) (= d sd)))
4679 (setq start-pos (point))
4680 (if (and start-pos (not end-pos))
4681 (setq end-pos (point))))
4682 (setq files (org-agenda-files)
4684 (while (setq file (pop files))
4686 (org-check-agenda-file file)
4687 (if org-agenda-show-log
4688 (setq rtn (org-agenda-get-day-entries
4690 :deadline :scheduled :timestamp :closed))
4691 (setq rtn (org-agenda-get-day-entries
4693 :deadline :scheduled :timestamp)))
4694 (setq rtnall (append rtnall rtn))))
4695 (if org-agenda-include-diary
4697 (require 'diary-lib)
4698 (setq rtn (org-get-entries-from-diary date))
4699 (setq rtnall (append rtnall rtn))))
4700 (if (or rtnall org-agenda-show-all-dates)
4702 (insert (format "%-9s %2d %s %4d\n"
4703 (calendar-day-name date)
4704 (extract-calendar-day date)
4705 (calendar-month-name (extract-calendar-month date))
4706 (extract-calendar-year date)))
4707 (put-text-property s (1- (point)) 'face
4710 (org-finalize-agenda-entries
4711 (org-agenda-add-time-grid-maybe
4714 (put-text-property s (1- (point)) 'day d))))
4715 (goto-char (point-min))
4716 (setq buffer-read-only t)
4717 (org-fit-agenda-window)
4718 (unless (and (pos-visible-in-window-p (point-min))
4719 (pos-visible-in-window-p (point-max)))
4720 (goto-char (1- (point-max)))
4722 (if (not (pos-visible-in-window-p (or start-pos 1)))
4724 (goto-char (or start-pos 1))
4726 (goto-char (or start-pos 1))
4727 (if (not org-select-agenda-window) (select-window win))
4730 (defvar org-select-this-todo-keyword nil)
4733 (defun org-todo-list (arg &optional keep-modes)
4734 "Show all TODO entries from all agenda file in a single list.
4735 The prefix arg can be used to select a specific TODO keyword and limit
4736 the list to these. When using \\[universal-argument], you will be prompted
4737 for a keyword. A numeric prefix directly selects the Nth keyword in
4738 `org-todo-keywords'."
4740 (org-agenda-maybe-reset-markers 'force)
4741 (org-compile-prefix-format org-agenda-prefix-format)
4742 (let* ((org-agenda-keep-modes keep-modes)
4743 (today (time-to-days (current-time)))
4744 (date (calendar-gregorian-from-absolute today))
4745 (win (selected-window))
4746 (kwds org-todo-keywords)
4747 (completion-ignore-case t)
4748 (org-select-this-todo-keyword
4749 (if (stringp arg) arg
4750 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4751 rtn rtnall files file pos)
4752 (when (equal arg '(4))
4753 (setq org-select-this-todo-keyword
4754 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4756 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4757 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4759 (delete-other-windows)
4760 (switch-to-buffer-other-window
4761 (get-buffer-create org-agenda-buffer-name))))
4762 (setq buffer-read-only nil)
4764 (org-agenda-mode) (setq buffer-read-only nil)
4765 (set (make-local-variable 'last-arg) arg)
4766 (set (make-local-variable 'org-todo-keywords) kwds)
4767 (set (make-local-variable 'org-agenda-redo-command)
4768 '(org-todo-list (or current-prefix-arg last-arg) t))
4769 (setq files (org-agenda-files)
4771 (while (setq file (pop files))
4773 (org-check-agenda-file file)
4774 (setq rtn (org-agenda-get-day-entries file date :todo))
4775 (setq rtnall (append rtnall rtn))))
4776 (insert "Global list of TODO items of type: ")
4777 (add-text-properties (point-min) (1- (point))
4778 (list 'face 'org-link))
4780 (insert (or org-select-this-todo-keyword "ALL") "\n")
4781 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4784 "Available with `N r': (0)ALL "
4786 (mapconcat (lambda (x)
4787 (format "(%d)%s" (setq n (1+ n)) x))
4788 org-todo-keywords " "))
4790 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4792 (insert (org-finalize-agenda-entries rtnall) "\n"))
4793 (goto-char (point-min))
4794 (setq buffer-read-only t)
4795 (org-fit-agenda-window)
4796 (if (not org-select-agenda-window) (select-window win))))
4798 (defun org-check-agenda-file (file)
4799 "Make sure FILE exists. If not, ask user what to do."
4800 ;; FIXME: this does not correctly change the menus
4801 ;; Could probably be fixed by explicitly going to the buffer.
4802 (when (not (file-exists-p file))
4803 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4805 (let ((r (downcase (read-char-exclusive))))
4808 (org-remove-file file)
4809 (throw 'nextfile t))
4810 (t (error "Abort"))))))
4812 (defun org-agenda-quit ()
4813 "Exit agenda by removing the window or the buffer."
4815 (let ((buf (current-buffer)))
4816 (if (not (one-window-p)) (delete-window))
4818 (org-agenda-maybe-reset-markers 'force)))
4820 (defun org-agenda-exit ()
4821 "Exit agenda by removing the window or the buffer.
4822 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4823 Org-mode buffers visited directly by the user will not be touched."
4825 (org-release-buffers org-agenda-new-buffers)
4826 (setq org-agenda-new-buffers nil)
4829 (defun org-agenda-redo ()
4831 When this is the global TODO list, a prefix argument will be interpreted."
4833 (eval org-agenda-redo-command))
4835 (defun org-agenda-goto-today ()
4838 (if (boundp 'starting-day)
4839 (let ((cmd (car org-agenda-redo-command))
4840 (iall (nth 1 org-agenda-redo-command))
4841 (nday (nth 3 org-agenda-redo-command))
4842 (keep (nth 4 org-agenda-redo-command)))
4843 (eval (list cmd iall nil nday keep)))
4844 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4847 (defun org-agenda-later (arg)
4848 "Go forward in time by `org-agenda-ndays' days.
4849 With prefix ARG, go forward that many times `org-agenda-ndays'."
4851 (unless (boundp 'starting-day)
4852 (error "Not allowed"))
4853 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4854 (+ starting-day (* arg org-agenda-ndays)) nil t))
4856 (defun org-agenda-earlier (arg)
4857 "Go back in time by `org-agenda-ndays' days.
4858 With prefix ARG, go back that many times `org-agenda-ndays'."
4860 (unless (boundp 'starting-day)
4861 (error "Not allowed"))
4862 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4863 (- starting-day (* arg org-agenda-ndays)) nil t))
4865 (defun org-agenda-week-view ()
4866 "Switch to weekly view for agenda."
4868 (unless (boundp 'starting-day)
4869 (error "Not allowed"))
4870 (setq org-agenda-ndays 7)
4871 (org-agenda-list include-all-loc
4872 (or (get-text-property (point) 'day)
4875 (org-agenda-set-mode-name)
4876 (message "Switched to week view"))
4878 (defun org-agenda-day-view ()
4879 "Switch to weekly view for agenda."
4881 (unless (boundp 'starting-day)
4882 (error "Not allowed"))
4883 (setq org-agenda-ndays 1)
4884 (org-agenda-list include-all-loc
4885 (or (get-text-property (point) 'day)
4888 (org-agenda-set-mode-name)
4889 (message "Switched to day view"))
4891 (defun org-agenda-next-date-line (&optional arg)
4892 "Jump to the next line indicating a date in agenda buffer."
4894 (beginning-of-line 1)
4895 (if (looking-at "^\\S-") (forward-char 1))
4896 (if (not (re-search-forward "^\\S-" nil t arg))
4899 (error "No next date after this line in this buffer")))
4900 (goto-char (match-beginning 0)))
4902 (defun org-agenda-previous-date-line (&optional arg)
4903 "Jump to the next line indicating a date in agenda buffer."
4905 (beginning-of-line 1)
4906 (if (not (re-search-backward "^\\S-" nil t arg))
4907 (error "No previous date before this line in this buffer")))
4909 ;; Initialize the highlight
4910 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
4911 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
4914 (defun org-highlight (begin end &optional buffer)
4915 "Highlight a region with overlay."
4916 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4917 org-hl begin end (or buffer (current-buffer))))
4919 (defun org-unhighlight ()
4920 "Detach overlay INDEX."
4921 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4924 (defun org-agenda-follow-mode ()
4925 "Toggle follow mode in an agenda buffer."
4927 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4928 (org-agenda-set-mode-name)
4929 (message "Follow mode is %s"
4930 (if org-agenda-follow-mode "on" "off")))
4932 (defun org-agenda-log-mode ()
4933 "Toggle follow mode in an agenda buffer."
4935 (setq org-agenda-show-log (not org-agenda-show-log))
4936 (org-agenda-set-mode-name)
4938 (message "Log mode is %s"
4939 (if org-agenda-show-log "on" "off")))
4941 (defun org-agenda-toggle-diary ()
4942 "Toggle follow mode in an agenda buffer."
4944 (setq org-agenda-include-diary (not org-agenda-include-diary))
4946 (org-agenda-set-mode-name)
4947 (message "Diary inclusion turned %s"
4948 (if org-agenda-include-diary "on" "off")))
4950 (defun org-agenda-toggle-time-grid ()
4951 "Toggle follow mode in an agenda buffer."
4953 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4955 (org-agenda-set-mode-name)
4956 (message "Time-grid turned %s"
4957 (if org-agenda-use-time-grid "on" "off")))
4959 (defun org-agenda-set-mode-name ()
4960 "Set the mode name to indicate all the small mode settings."
4962 (concat "Org-Agenda"
4963 (if (equal org-agenda-ndays 1) " Day" "")
4964 (if (equal org-agenda-ndays 7) " Week" "")
4965 (if org-agenda-follow-mode " Follow" "")
4966 (if org-agenda-include-diary " Diary" "")
4967 (if org-agenda-use-time-grid " Grid" "")
4968 (if org-agenda-show-log " Log" "")))
4969 (force-mode-line-update))
4971 (defun org-agenda-post-command-hook ()
4972 (and (eolp) (not (bolp)) (backward-char 1))
4973 (if (and org-agenda-follow-mode
4974 (get-text-property (point) 'org-marker))
4977 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4979 (defun org-get-entries-from-diary (date)
4980 "Get the (Emacs Calendar) diary entries for DATE."
4981 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4982 (diary-display-hook '(fancy-diary-display))
4983 (list-diary-entries-hook
4984 (cons 'org-diary-default-entry list-diary-entries-hook))
4985 (diary-file-name-prefix-function nil) ; turn this feature off
4986 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4988 (org-disable-agenda-to-diary t))
4990 (save-window-excursion
4991 (list-diary-entries date 1)))
4992 (if (not (get-buffer fancy-diary-buffer))
4994 (with-current-buffer fancy-diary-buffer
4995 (setq buffer-read-only nil)
4996 (if (= (point-max) 1)
4999 ;; Omit the date and other unnecessary stuff
5000 (org-agenda-cleanup-fancy-diary)
5001 ;; Add prefix to each line and extend the text properties
5002 (if (= (point-max) 1)
5004 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5005 (set-buffer-modified-p nil)
5006 (kill-buffer fancy-diary-buffer)))
5008 (setq entries (org-split-string entries "\n"))
5012 (setq x (org-format-agenda-item "" x "Diary" 'time))
5013 ;; Extend the text properties to the beginning of the line
5014 (add-text-properties
5016 (text-properties-at (1- (length x)) x)
5021 (defun org-agenda-cleanup-fancy-diary ()
5022 "Remove unwanted stuff in buffer created by fancy-diary-display.
5023 This gets rid of the date, the underline under the date, and
5024 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5025 date. Itt also removes lines that contain only whitespace."
5026 (goto-char (point-min))
5027 (if (looking-at ".*?:[ \t]*")
5030 (re-search-forward "\n=+$" nil t)
5032 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5033 (re-search-forward "\n=+$" nil t)
5034 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5035 (goto-char (point-min))
5036 (while (re-search-forward "^ +\n" nil t)
5038 (goto-char (point-min))
5039 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5040 (replace-match "")))
5042 ;; Make sure entries from the diary have the right text properties.
5043 (eval-after-load "diary-lib"
5044 '(if (boundp 'diary-modify-entry-list-string-function)
5045 ;; We can rely on the hook, nothing to do
5047 ;; Hook not avaiable, must use advice to make this work
5048 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5049 "Make the position visible."
5050 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5053 (setq string (org-modify-diary-entry-string string))))))
5055 (defun org-modify-diary-entry-string (string)
5056 "Add text properties to string, allowing org-mode to act on it."
5057 (add-text-properties
5059 (list 'mouse-face 'highlight
5060 'keymap org-agenda-keymap
5063 "mouse-2 or RET jump to diary file %s"
5064 (abbreviate-file-name (buffer-file-name)))
5065 'org-agenda-diary-link t
5066 'org-marker (org-agenda-new-marker (point-at-bol)))
5070 (defun org-diary-default-entry ()
5071 "Add a dummy entry to the diary.
5072 Needed to avoid empty dates which mess up holiday display."
5073 ;; Catch the error if dealing with the new add-to-diary-alist
5074 (when org-disable-agenda-to-diary
5076 (add-to-diary-list original-date "Org-mode dummy" "")
5078 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5080 (defun org-cycle-agenda-files ()
5081 "Cycle through the files in `org-agenda-files'.
5082 If the current buffer visits an agenda file, find the next one in the list.
5083 If the current buffer does not, find the first agenda file."
5085 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5086 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
5088 (unless files (error "No agenda files"))
5090 (while (setq file (pop files))
5091 (if (equal (file-truename file) tcf)
5093 (find-file (car files))
5095 (find-file (car org-agenda-files)))))
5097 (defun org-agenda-file-to-end (&optional file)
5098 "Move/add the current file to the end of the agenda fiole list.
5099 I the file is not present in the list, it is appended ot the list. If it is
5100 present, it is moved there."
5102 (org-agenda-file-to-front 'to-end file))
5104 (defun org-agenda-file-to-front (&optional to-end file)
5105 "Move/add the current file to the top of the agenda file list.
5106 If the file is not present in the list, it is added to the front. If it is
5107 present, it is moved there. With optional argument TO-END, add/move to the
5110 (let ((file-alist (mapcar (lambda (x)
5111 (cons (file-truename x) x))
5113 (ctf (file-truename (buffer-file-name)))
5115 (setq x (assoc ctf file-alist) had x)
5117 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
5119 (setq file-alist (append (delq x file-alist) (list x)))
5120 (setq file-alist (cons x (delq x file-alist))))
5121 (setq org-agenda-files (mapcar 'cdr file-alist))
5122 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5123 (customize-save-variable 'org-agenda-files org-agenda-files))
5124 (org-install-agenda-files-menu)
5125 (message "File %s to %s of agenda file list"
5126 (if had "moved" "added") (if to-end "end" "front"))))
5128 (defun org-remove-file (&optional file)
5129 "Remove current file from the list of files in variable `org-agenda-files'.
5130 These are the files which are being checked for agenda entries.
5131 Optional argument FILE means, use this file instead of the current."
5133 (let* ((file (or file (buffer-file-name)))
5134 (true-file (file-truename file))
5135 (afile (abbreviate-file-name file))
5136 (files (delq nil (mapcar
5138 (if (equal true-file
5141 org-agenda-files))))
5142 (if (not (= (length files) (length org-agenda-files)))
5144 (setq org-agenda-files files)
5145 (customize-save-variable 'org-agenda-files org-agenda-files)
5146 (org-install-agenda-files-menu)
5147 (message "Removed file: %s" afile))
5148 (message "File was not in list: %s" afile))))
5150 (defun org-file-menu-entry (file)
5151 (vector file (list 'find-file file) t))
5152 ;; FIXME: Maybe we removed a buffer visited through the menu from
5153 ;; org-agenda-new-buffers, so that the buffer will not be removed
5154 ;; when exiting the agenda????
5156 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5157 "Return a list of all relevant day numbers from BEG to END buffer positions.
5158 If NO-RANGES is non-nil, include only the start and end dates of a range,
5159 not every single day in the range. If FORCE-TODAY is non-nil, make
5160 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5161 inactive time stamps (those in square brackets) are included."
5162 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5163 dates date day day1 day2 ts1 ts2)
5165 (setq dates (list (time-to-days (current-time)))))
5168 (while (re-search-forward re end t)
5169 (setq day (time-to-days (org-time-string-to-time
5170 (substring (match-string 1) 0 10))))
5171 (or (memq day dates) (push day dates)))
5174 (while (re-search-forward org-tr-regexp end t)
5175 (setq ts1 (substring (match-string 1) 0 10)
5176 ts2 (substring (match-string 2) 0 10)
5177 day1 (time-to-days (org-time-string-to-time ts1))
5178 day2 (time-to-days (org-time-string-to-time ts2)))
5179 (while (< (setq day1 (1+ day1)) day2)
5180 (or (memq day1 dates) (push day1 dates)))))
5184 (defun org-diary (&rest args)
5185 "Return diary information from org-files.
5186 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5187 It accesses org files and extracts information from those files to be
5188 listed in the diary. The function accepts arguments specifying what
5189 items should be listed. The following arguments are allowed:
5191 :timestamp List the headlines of items containing a date stamp or
5192 date range matching the selected date. Deadlines will
5193 also be listed, on the expiration day.
5195 :deadline List any deadlines past due, or due within
5196 `org-deadline-warning-days'. The listing occurs only
5197 in the diary for *today*, not at any other date. If
5198 an entry is marked DONE, it is no longer listed.
5200 :scheduled List all items which are scheduled for the given date.
5201 The diary for *today* also contains items which were
5202 scheduled earlier and are not yet marked DONE.
5204 :todo List all TODO items from the org-file. This may be a
5205 long list - so this is not turned on by default.
5206 Like deadlines, these entries only show up in the
5207 diary for *today*, not at any other date.
5209 The call in the diary file should look like this:
5211 &%%(org-diary) ~/path/to/some/orgfile.org
5213 Use a separate line for each org file to check. Or, if you omit the file name,
5214 all files listed in `org-agenda-files' will be checked automatically:
5218 If you don't give any arguments (as in the example above), the default
5219 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5222 &%%(org-diary :deadline :timestamp :scheduled)
5224 The function expects the lisp variables `entry' and `date' to be provided
5225 by the caller, because this is how the calendar works. Don't use this
5226 function from a program - use `org-agenda-get-day-entries' instead."
5227 (org-agenda-maybe-reset-markers)
5228 (org-compile-prefix-format org-agenda-prefix-format)
5229 (setq args (or args '(:deadline :scheduled :timestamp)))
5230 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5234 ;; If this is called during org-agenda, don't return any entries to
5235 ;; the calendar. Org Agenda will list these entries itself.
5236 (if org-disable-agenda-to-diary (setq files nil))
5237 (while (setq file (pop files))
5238 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5239 (setq results (append results rtn)))
5241 (concat (org-finalize-agenda-entries results) "\n"))))
5242 (defvar org-category-table nil)
5243 (defun org-get-category-table ()
5244 "Get the table of categories and positions in current buffer."
5247 (goto-char (point-min))
5248 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5249 (push (cons (point) (org-trim (match-string 2))) tbl)))
5251 (defun org-get-category (&optional pos)
5252 "Get the category applying to position POS."
5253 (if (not org-category-table)
5255 ((null org-category)
5257 (if (buffer-file-name)
5258 (file-name-sans-extension
5259 (file-name-nondirectory (buffer-file-name)))
5261 ((symbolp org-category) (symbol-name org-category))
5263 (let ((tbl org-category-table)
5264 (pos (or pos (point))))
5265 (while (and tbl (> (caar tbl) pos))
5267 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5268 org-category-table))))))
5270 (defun org-agenda-get-day-entries (file date &rest args)
5271 "Does the work for `org-diary' and `org-agenda'.
5272 FILE is the path to a file to be checked for entries. DATE is date like
5273 the one returned by `calendar-current-date'. ARGS are symbols indicating
5274 which kind of entries should be extracted. For details about these, see
5275 the documentation of `org-diary'."
5276 (setq args (or args '(:deadline :scheduled :timestamp)))
5277 (let* ((org-startup-with-deadline-check nil)
5278 (org-startup-folded nil)
5279 (buffer (if (file-exists-p file)
5280 (org-get-agenda-file-buffer file)
5281 (error "No such file %s" file)))
5284 ;; If file does not exist, make sure an error message ends up in diary
5285 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5286 (with-current-buffer buffer
5287 (unless (eq major-mode 'org-mode)
5288 (error "Agenda file %s is not in `org-mode'" file))
5289 (setq org-category-table (org-get-category-table))
5290 (let ((case-fold-search nil))
5293 (if org-respect-restriction
5294 (if (org-region-active-p)
5295 ;; Respect a region to restrict search
5296 (narrow-to-region (region-beginning) (region-end)))
5297 ;; If we work for the calendar or many files,
5298 ;; get rid of any restriction
5300 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5301 (while (setq arg (pop args))
5303 ((and (eq arg :todo)
5304 (equal date (calendar-current-date)))
5305 (setq rtn (org-agenda-get-todos))
5306 (setq results (append results rtn)))
5307 ((eq arg :timestamp)
5308 (setq rtn (org-agenda-get-blocks))
5309 (setq results (append results rtn))
5310 (setq rtn (org-agenda-get-timestamps))
5311 (setq results (append results rtn)))
5312 ((eq arg :scheduled)
5313 (setq rtn (org-agenda-get-scheduled))
5314 (setq results (append results rtn)))
5316 (setq rtn (org-agenda-get-closed))
5317 (setq results (append results rtn)))
5318 ((and (eq arg :deadline)
5319 (equal date (calendar-current-date)))
5320 (setq rtn (org-agenda-get-deadlines))
5321 (setq results (append results rtn))))))))
5324 (defun org-entry-is-done-p ()
5325 "Is the current entry marked DONE?"
5327 (and (re-search-backward "[\r\n]\\*" nil t)
5328 (looking-at org-nl-done-regexp))))
5330 (defun org-at-date-range-p ()
5331 "Is the cursor inside a date range?"
5335 (let ((pos (point)))
5336 (skip-chars-backward "^<\r\n")
5337 (skip-chars-backward "<")
5338 (and (looking-at org-tr-regexp)
5339 (>= (match-end 0) pos)
5341 (skip-chars-backward "^<\r\n")
5342 (skip-chars-backward "<")
5343 (and (looking-at org-tr-regexp)
5344 (>= (match-end 0) pos)
5348 (defun org-agenda-get-todos ()
5349 "Return the TODO information for agenda display."
5350 (let* ((props (list 'face nil
5351 'done-face 'org-done
5352 'mouse-face 'highlight
5353 'keymap org-agenda-keymap
5355 (format "mouse-2 or RET jump to org file %s"
5356 (abbreviate-file-name (buffer-file-name)))))
5357 (regexp (concat "[\n\r]\\*+ *\\("
5358 (if org-select-this-todo-keyword
5359 (concat "\\<\\(" org-select-this-todo-keyword
5361 org-not-done-regexp)
5363 marker priority category
5365 (goto-char (point-min))
5366 (while (re-search-forward regexp nil t)
5367 (goto-char (match-beginning 1))
5368 (setq marker (org-agenda-new-marker (point-at-bol))
5369 category (org-get-category)
5370 txt (org-format-agenda-item "" (match-string 1) category)
5372 (+ (org-get-priority txt)
5373 (if org-todo-kwd-priority-p
5374 (- org-todo-kwd-max-priority -2
5376 (member (match-string 2) org-todo-keywords)))
5378 (add-text-properties
5379 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5380 'priority priority 'category category)
5384 (goto-char (match-end 1)))
5387 (defconst org-agenda-no-heading-message
5388 "No heading for this item in buffer or region")
5390 (defun org-agenda-get-timestamps ()
5391 "Return the date stamp information for agenda display."
5392 (let* ((props (list 'face nil
5393 'mouse-face 'highlight
5394 'keymap org-agenda-keymap
5396 (format "mouse-2 or RET jump to org file %s"
5397 (abbreviate-file-name (buffer-file-name)))))
5398 (regexp (regexp-quote
5401 (car org-time-stamp-formats)
5402 (apply 'encode-time ; DATE bound by calendar
5403 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5405 marker hdmarker deadlinep scheduledp donep tmp priority category
5407 (goto-char (point-min))
5408 (while (re-search-forward regexp nil t)
5409 (if (not (save-match-data (org-at-date-range-p)))
5411 (setq marker (org-agenda-new-marker (match-beginning 0))
5412 category (org-get-category (match-beginning 0))
5413 tmp (buffer-substring (max (point-min)
5414 (- (match-beginning 0)
5415 org-ds-keyword-length))
5416 (match-beginning 0))
5417 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5418 deadlinep (string-match org-deadline-regexp tmp)
5419 scheduledp (string-match org-scheduled-regexp tmp)
5420 donep (org-entry-is-done-p))
5421 (if (string-match ">" timestr)
5422 ;; substring should only run to end of time stamp
5423 (setq timestr (substring timestr 0 (match-end 0))))
5425 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5427 (goto-char (match-end 1))
5428 (setq hdmarker (org-agenda-new-marker))
5429 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5430 (setq txt (org-format-agenda-item
5432 (if deadlinep "Deadline: " "")
5433 (if scheduledp "Scheduled: " ""))
5434 (match-string 1) category timestr)))
5435 (setq txt org-agenda-no-heading-message))
5436 (setq priority (org-get-priority txt))
5437 (add-text-properties
5438 0 (length txt) (append (list 'org-marker marker
5439 'org-hd-marker hdmarker) props)
5442 (add-text-properties
5445 (if donep 'org-done 'org-warning)
5446 'undone-face 'org-warning
5447 'done-face 'org-done
5449 'priority (+ 100 priority))
5452 (add-text-properties
5454 (list 'face 'org-scheduled-today
5455 'undone-face 'org-scheduled-today
5456 'done-face 'org-done
5458 priority (+ 99 priority))
5460 (add-text-properties
5462 (list 'priority priority 'category category) txt)))
5464 (outline-next-heading))))
5467 (defun org-agenda-get-closed ()
5468 "Return the loggedd TODO entries for agenda display."
5469 (let* ((props (list 'mouse-face 'highlight
5470 'keymap org-agenda-keymap
5472 (format "mouse-2 or RET jump to org file %s"
5473 (abbreviate-file-name (buffer-file-name)))))
5475 "\\<" org-closed-string " *\\["
5479 (car org-time-stamp-formats)
5480 (apply 'encode-time ; DATE bound by calendar
5481 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5483 marker hdmarker priority category
5485 (goto-char (point-min))
5486 (while (re-search-forward regexp nil t)
5487 (if (not (save-match-data (org-at-date-range-p)))
5489 (setq marker (org-agenda-new-marker (match-beginning 0))
5490 category (org-get-category (match-beginning 0))
5491 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5492 ;; donep (org-entry-is-done-p)
5494 (if (string-match "\\]" timestr)
5495 ;; substring should only run to end of time stamp
5496 (setq timestr (substring timestr 0 (match-end 0))))
5498 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5500 (goto-char (match-end 1))
5501 (setq hdmarker (org-agenda-new-marker))
5502 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5503 (setq txt (org-format-agenda-item
5505 (match-string 1) category timestr)))
5506 (setq txt org-agenda-no-heading-message))
5507 (setq priority 100000)
5508 (add-text-properties
5509 0 (length txt) (append (list 'org-marker marker
5510 'org-hd-marker hdmarker
5514 'undone-face 'org-warning
5515 'done-face 'org-done) props)
5518 (outline-next-heading))))
5521 (defun org-agenda-get-deadlines ()
5522 "Return the deadline information for agenda display."
5523 (let* ((wdays org-deadline-warning-days)
5524 (props (list 'mouse-face 'highlight
5525 'keymap org-agenda-keymap
5527 (format "mouse-2 or RET jump to org file %s"
5528 (abbreviate-file-name (buffer-file-name)))))
5529 (regexp org-deadline-time-regexp)
5530 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5531 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5532 d2 diff pos pos1 category
5534 (goto-char (point-min))
5535 (while (re-search-forward regexp nil t)
5536 (setq pos (1- (match-beginning 1))
5538 (org-time-string-to-time (match-string 1)))
5540 ;; When to show a deadline in the calendar:
5541 ;; If the expiration is within wdays warning time.
5542 ;; Past-due deadlines are only shown on the current date
5543 (if (and (< diff wdays) todayp (not (= diff 0)))
5545 (setq category (org-get-category))
5546 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5548 (goto-char (match-end 0))
5549 (setq pos1 (match-end 1))
5550 (setq head (buffer-substring-no-properties
5552 (progn (skip-chars-forward "^\r\n")
5554 (if (string-match org-looking-at-done-regexp head)
5556 (setq txt (org-format-agenda-item
5557 (format "In %3d d.: " diff) head category))))
5558 (setq txt org-agenda-no-heading-message))
5560 (add-text-properties
5563 (list 'org-marker (org-agenda-new-marker pos)
5564 'org-hd-marker (org-agenda-new-marker pos1)
5565 'priority (+ (- 10 diff) (org-get-priority txt))
5567 'face (cond ((<= diff 0) 'org-warning)
5568 ((<= diff 5) 'org-scheduled-previously)
5571 ((<= diff 0) 'org-warning)
5572 ((<= diff 5) 'org-scheduled-previously)
5574 'done-face 'org-done)
5580 (defun org-agenda-get-scheduled ()
5581 "Return the scheduled information for agenda display."
5582 (let* ((props (list 'face 'org-scheduled-previously
5583 'undone-face 'org-scheduled-previously
5584 'done-face 'org-done
5585 'mouse-face 'highlight
5586 'keymap org-agenda-keymap
5588 (format "mouse-2 or RET jump to org file %s"
5589 (abbreviate-file-name (buffer-file-name)))))
5590 (regexp org-scheduled-time-regexp)
5591 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5592 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5593 d2 diff pos pos1 category
5595 (goto-char (point-min))
5596 (while (re-search-forward regexp nil t)
5597 (setq pos (1- (match-beginning 1))
5599 (org-time-string-to-time (match-string 1)))
5601 ;; When to show a scheduled item in the calendar:
5602 ;; If it is on or past the date.
5603 (if (and (< diff 0) todayp)
5605 (setq category (org-get-category))
5606 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5608 (goto-char (match-end 0))
5609 (setq pos1 (match-end 1))
5610 (setq head (buffer-substring-no-properties
5612 (progn (skip-chars-forward "^\r\n") (point))))
5613 (if (string-match org-looking-at-done-regexp head)
5615 (setq txt (org-format-agenda-item
5616 (format "Sched.%2dx: " (- 1 diff)) head
5618 (setq txt org-agenda-no-heading-message))
5620 (add-text-properties
5622 (append (list 'org-marker (org-agenda-new-marker pos)
5623 'org-hd-marker (org-agenda-new-marker pos1)
5624 'priority (+ (- 5 diff) (org-get-priority txt))
5630 (defun org-agenda-get-blocks ()
5631 "Return the date-range information for agenda display."
5632 (let* ((props (list 'face nil
5633 'mouse-face 'highlight
5634 'keymap org-agenda-keymap
5636 (format "mouse-2 or RET jump to org file %s"
5637 (abbreviate-file-name (buffer-file-name)))))
5638 (regexp org-tr-regexp)
5639 (d0 (calendar-absolute-from-gregorian date))
5640 marker hdmarker ee txt d1 d2 s1 s2 timestr category)
5641 (goto-char (point-min))
5642 (while (re-search-forward regexp nil t)
5643 (setq timestr (match-string 0)
5646 d1 (time-to-days (org-time-string-to-time s1))
5647 d2 (time-to-days (org-time-string-to-time s2)))
5648 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5649 ;; Only allow days between the limits, because the normal
5650 ;; date stamps will catch the limits.
5652 (setq marker (org-agenda-new-marker (point)))
5653 (setq category (org-get-category))
5654 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5656 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5657 (goto-char (match-end 1))
5658 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5659 (setq txt (org-format-agenda-item
5660 (format (if (= d1 d2) "" "(%d/%d): ")
5661 (1+ (- d0 d1)) (1+ (- d2 d1)))
5662 (match-string 1) category
5663 (if (= d0 d1) timestr))))
5664 (setq txt org-agenda-no-heading-message))
5665 (add-text-properties
5666 0 (length txt) (append (list 'org-marker marker
5667 'org-hd-marker hdmarker
5668 'priority (org-get-priority txt)
5673 (outline-next-heading))
5674 ;; Sort the entries by expiration date.
5677 (defconst org-plain-time-of-day-regexp
5680 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5683 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5685 "Regular expression to match a plain time or time range.
5686 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5687 groups carry important information:
5689 1 the first time, range or not
5690 8 the second time, if it is a range.")
5692 (defconst org-stamp-time-of-day-regexp
5694 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5695 "\\([012][0-9]:[0-5][0-9]\\)>"
5697 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5698 "Regular expression to match a timestamp time or time range.
5699 After a match, the following groups carry important information:
5701 1 date plus weekday, for backreferencing to make sure both times on same day
5702 2 the first time, range or not
5703 4 the second time, if it is a range.")
5705 (defvar org-prefix-has-time nil
5706 "A flag, set by `org-compile-prefix-format'.
5707 The flag is set if the currently compiled format contains a `%t'.")
5709 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
5710 "Format TXT to be inserted into the agenda buffer.
5711 In particular, it adds the prefix and corresponding text properties. EXTRA
5712 must be a string and replaces the `%s' specifier in the prefix format.
5713 CATEGORY (string, symbol or nil) may be used to overule the default
5714 category taken from local variable or file name. It will replace the `%c'
5715 specifier in the format. DOTIME, when non-nil, indicates that a
5716 time-of-day should be extracted from TXT for sorting of this entry, and for
5717 the `%t' specifier in the format. When DOTIME is a string, this string is
5718 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5719 only the correctly processes TXT should be returned - this is used by
5720 `org-agenda-change-all-lines'."
5722 ;; Diary entries sometimes have extra whitespace at the beginning
5723 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5724 (let* ((category (or category
5726 (if (buffer-file-name)
5727 (file-name-sans-extension
5728 (file-name-nondirectory (buffer-file-name)))
5730 time ;; needed for the eval of the prefix format
5731 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5732 (time-of-day (and dotime (org-get-time-of-day ts)))
5733 stamp plain s0 s1 s2 rtn)
5734 (when (and dotime time-of-day org-prefix-has-time)
5735 ;; Extract starting and ending time and move them to prefix
5736 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5737 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5738 (setq s0 (match-string 0 ts)
5739 s1 (match-string (if plain 1 2) ts)
5740 s2 (match-string (if plain 8 4) ts))
5742 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5743 ;; them, we might want to remove them there to avoid duplication.
5744 ;; The user can turn this off with a variable.
5745 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5746 (string-match (concat (regexp-quote s0) " *") txt)
5747 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5748 (= (match-beginning 0) 0)
5750 (setq txt (replace-match "" nil nil txt))))
5751 ;; Normalize the time(s) to 24 hour
5752 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5753 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5755 ;; Create the final string
5758 ;; Prepare the variables needed in the eval of the compiled format
5759 (setq time (cond (s2 (concat s1 "-" s2))
5760 (s1 (concat s1 "......"))
5763 category (if (symbolp category) (symbol-name category) category))
5764 ;; Evaluate the compiled format
5765 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5767 ;; And finally add the text properties
5768 (add-text-properties
5769 0 (length rtn) (list 'category (downcase category)
5770 'prefix-length (- (length rtn) (length txt))
5771 'time-of-day time-of-day
5776 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5778 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5779 ((and todayp (member 'today (car org-agenda-time-grid))))
5780 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5781 ((member 'weekly (car org-agenda-time-grid)))
5782 (t (throw 'exit list)))
5783 (let* ((have (delq nil (mapcar
5784 (lambda (x) (get-text-property 1 'time-of-day x))
5786 (string (nth 1 org-agenda-time-grid))
5787 (gridtimes (nth 2 org-agenda-time-grid))
5788 (req (car org-agenda-time-grid))
5789 (remove (member 'remove-match req))
5791 (if (and (member 'require-timed req) (not have))
5792 ;; don't show empty grid
5794 (while (setq time (pop gridtimes))
5795 (unless (and remove (member time have))
5796 (setq time (int-to-string time))
5797 (push (org-format-agenda-item
5798 nil string "" ;; FIXME: put a category for the grid?
5799 (concat (substring time 0 -2) ":" (substring time -2)))
5802 1 (length (car new)) 'face 'org-time-grid (car new))))
5803 (if (member 'time-up org-agenda-sorting-strategy)
5805 (append list new)))))
5807 (defun org-compile-prefix-format (format)
5808 "Compile the prefix format into a Lisp form that can be evaluated.
5809 The resulting form is returned and stored in the variable
5810 `org-prefix-format-compiled'."
5811 (setq org-prefix-has-time nil)
5812 (let ((start 0) varform vars var (s format) c f opt)
5813 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5815 (setq var (cdr (assoc (match-string 4 s)
5816 '(("c" . category) ("t" . time) ("s" . extra))))
5817 c (or (match-string 3 s) "")
5818 opt (match-beginning 1)
5819 start (1+ (match-beginning 0)))
5820 (if (equal var 'time) (setq org-prefix-has-time t))
5821 (setq f (concat "%" (match-string 2 s) "s"))
5824 `(if (equal "" ,var)
5826 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5827 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5828 (setq s (replace-match "%s" t nil s))
5829 (push varform vars))
5830 (setq vars (nreverse vars))
5831 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5833 (defun org-get-time-of-day (s &optional string)
5834 "Check string S for a time of day.
5835 If found, return it as a military time number between 0 and 2400.
5836 If not found, return nil.
5837 The optional STRING argument forces conversion into a 5 character wide string
5843 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5845 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5846 (let* ((t0 (+ (* 100
5847 (+ (string-to-number (match-string 1 s))
5848 (if (and (match-beginning 4)
5849 (equal (downcase (match-string 4 s)) "pm"))
5851 (if (match-beginning 3)
5852 (string-to-number (match-string 3 s))
5854 (t1 (concat " " (int-to-string t0))))
5855 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5857 (defun org-finalize-agenda-entries (list)
5858 "Sort and concatenate the agenda items."
5859 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5861 (defsubst org-cmp-priority (a b)
5862 "Compare the priorities of string a and b."
5863 (let ((pa (or (get-text-property 1 'priority a) 0))
5864 (pb (or (get-text-property 1 'priority b) 0)))
5865 (cond ((> pa pb) +1)
5869 (defsubst org-cmp-category (a b)
5870 "Compare the string values of categories of strings a and b."
5871 (let ((ca (or (get-text-property 1 'category a) ""))
5872 (cb (or (get-text-property 1 'category b) "")))
5873 (cond ((string-lessp ca cb) -1)
5874 ((string-lessp cb ca) +1)
5877 (defsubst org-cmp-time (a b)
5878 "Compare the time-of-day values of strings a and b."
5879 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5880 (ta (or (get-text-property 1 'time-of-day a) def))
5881 (tb (or (get-text-property 1 'time-of-day b) def)))
5882 (cond ((< ta tb) -1)
5886 (defun org-entries-lessp (a b)
5887 "Predicate for sorting agenda entries."
5888 ;; The following variables will be used when the form is evaluated.
5889 (let* ((time-up (org-cmp-time a b))
5890 (time-down (if time-up (- time-up) nil))
5891 (priority-up (org-cmp-priority a b))
5892 (priority-down (if priority-up (- priority-up) nil))
5893 (category-up (org-cmp-category a b))
5894 (category-down (if category-up (- category-up) nil))
5895 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
5897 (eval (cons 'or org-agenda-sorting-strategy))
5898 '((-1 . t) (1 . nil) (nil . nil))))))
5900 (defun org-agenda-show-priority ()
5901 "Show the priority of the current item.
5902 This priority is composed of the main priority given with the [#A] cookies,
5903 and by additional input from the age of a schedules or deadline entry."
5905 (let* ((pri (get-text-property (point-at-bol) 'priority)))
5906 (message "Priority is %d" (if pri pri -1000))))
5908 (defun org-agenda-goto (&optional highlight)
5909 "Go to the Org-mode file which contains the item at point."
5911 (let* ((marker (or (get-text-property (point) 'org-marker)
5912 (org-agenda-error)))
5913 (buffer (marker-buffer marker))
5914 (pos (marker-position marker)))
5915 (switch-to-buffer-other-window buffer)
5918 (when (eq major-mode 'org-mode)
5919 (org-show-hidden-entry)
5921 (and (outline-next-heading)
5922 (org-flag-heading nil)))) ; show the next heading
5923 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
5925 (defun org-agenda-switch-to ()
5926 "Go to the Org-mode file which contains the item at point."
5928 (let* ((marker (or (get-text-property (point) 'org-marker)
5929 (org-agenda-error)))
5930 (buffer (marker-buffer marker))
5931 (pos (marker-position marker)))
5932 (switch-to-buffer buffer)
5933 (delete-other-windows)
5936 (when (eq major-mode 'org-mode)
5937 (org-show-hidden-entry)
5939 (and (outline-next-heading)
5940 (org-flag-heading nil)))))) ; show the next heading
5942 (defun org-agenda-goto-mouse (ev)
5943 "Go to the Org-mode file which contains the item at the mouse click."
5945 (mouse-set-point ev)
5948 (defun org-agenda-show ()
5949 "Display the Org-mode file which contains the item at point."
5951 (let ((win (selected-window)))
5953 (select-window win)))
5955 (defun org-agenda-recenter (arg)
5956 "Display the Org-mode file which contains the item at point and recenter."
5958 (let ((win (selected-window)))
5961 (select-window win)))
5963 (defun org-agenda-show-mouse (ev)
5964 "Display the Org-mode file which contains the item at the mouse click."
5966 (mouse-set-point ev)
5969 (defun org-agenda-check-no-diary ()
5970 "Check if the entry is a diary link and abort if yes."
5971 (if (get-text-property (point) 'org-agenda-diary-link)
5972 (org-agenda-error)))
5974 (defun org-agenda-error ()
5975 (error "Command not allowed in this line"))
5977 (defvar org-last-heading-marker (make-marker)
5978 "Marker pointing to the headline that last changed its TODO state
5979 by a remote command from the agenda.")
5981 (defun org-agenda-todo (&optional arg)
5982 "Cycle TODO state of line at point, also in Org-mode file.
5983 This changes the line at point, all other lines in the agenda referring to
5984 the same tree node, and the headline of the tree node in the Org-mode file."
5986 (org-agenda-check-no-diary)
5987 (let* ((col (current-column))
5988 (marker (or (get-text-property (point) 'org-marker)
5989 (org-agenda-error)))
5990 (buffer (marker-buffer marker))
5991 (pos (marker-position marker))
5992 (hdmarker (get-text-property (point) 'org-hd-marker))
5993 (buffer-read-only nil)
5995 (with-current-buffer buffer
5998 (org-show-hidden-entry)
6000 (and (outline-next-heading)
6001 (org-flag-heading nil))) ; show the next heading
6004 (setq newhead (org-get-heading))
6006 (org-back-to-heading)
6007 (move-marker org-last-heading-marker (point))))
6008 (beginning-of-line 1)
6010 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6011 (move-to-column col)))
6013 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6014 "Change all lines in the agenda buffer which match hdmarker.
6015 The new content of the line will be NEWHEAD (as modified by
6016 `org-format-agenda-item'). HDMARKER is checked with
6017 `equal' against all `org-hd-marker' text properties in the file.
6018 If FIXFACE is non-nil, the face of each item is modified acording to
6019 the new TODO state."
6020 (let* (props m pl undone-face done-face finish new dotime cat)
6021 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6023 (goto-char (point-max))
6024 (beginning-of-line 1)
6026 (setq finish (bobp))
6027 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6029 (setq props (text-properties-at (point))
6030 dotime (get-text-property (point) 'dotime)
6031 cat (get-text-property (point) 'category)
6032 new (org-format-agenda-item "x" newhead cat dotime 'noprefix)
6033 pl (get-text-property (point) 'prefix-length)
6034 undone-face (get-text-property (point) 'undone-face)
6035 done-face (get-text-property (point) 'done-face))
6037 (if (looking-at ".*")
6039 (replace-match new t t)
6040 (beginning-of-line 1)
6041 (add-text-properties (point-at-bol) (point-at-eol) props)
6043 (add-text-properties
6044 (point-at-bol) (point-at-eol)
6046 (if org-last-todo-state-is-todo
6047 undone-face done-face))))
6048 (beginning-of-line 1))
6049 (error "Line update did not work")))
6050 (beginning-of-line 0)))))
6052 (defun org-agenda-priority-up ()
6053 "Increase the priority of line at point, also in Org-mode file."
6055 (org-agenda-priority 'up))
6057 (defun org-agenda-priority-down ()
6058 "Decrease the priority of line at point, also in Org-mode file."
6060 (org-agenda-priority 'down))
6062 (defun org-agenda-priority (&optional force-direction)
6063 "Set the priority of line at point, also in Org-mode file.
6064 This changes the line at point, all other lines in the agenda referring to
6065 the same tree node, and the headline of the tree node in the Org-mode file."
6067 (org-agenda-check-no-diary)
6068 (let* ((marker (or (get-text-property (point) 'org-marker)
6069 (org-agenda-error)))
6070 (buffer (marker-buffer marker))
6071 (pos (marker-position marker))
6072 (hdmarker (get-text-property (point) 'org-hd-marker))
6073 (buffer-read-only nil)
6075 (with-current-buffer buffer
6078 (org-show-hidden-entry)
6080 (and (outline-next-heading)
6081 (org-flag-heading nil))) ; show the next heading
6082 (funcall 'org-priority force-direction)
6084 (setq newhead (org-get-heading)))
6085 (org-agenda-change-all-lines newhead hdmarker)
6086 (beginning-of-line 1)))
6088 (defun org-agenda-set-tags ()
6089 "Set tags for the current headline."
6091 (org-agenda-check-no-diary)
6092 (let* ((marker (or (get-text-property (point) 'org-marker)
6093 (org-agenda-error)))
6094 (hdmarker (get-text-property (point) 'org-hd-marker))
6095 (buffer (marker-buffer hdmarker))
6096 (pos (marker-position hdmarker))
6097 (buffer-read-only nil)
6099 (with-current-buffer buffer
6102 (org-show-hidden-entry)
6104 (and (outline-next-heading)
6105 (org-flag-heading nil))) ; show the next heading
6106 (call-interactively 'org-set-tags)
6108 (setq newhead (org-get-heading)))
6109 (org-agenda-change-all-lines newhead hdmarker)
6110 (beginning-of-line 1)))
6112 (defun org-agenda-date-later (arg &optional what)
6113 "Change the date of this item to one day later."
6115 (org-agenda-check-no-diary)
6116 (let* ((marker (or (get-text-property (point) 'org-marker)
6117 (org-agenda-error)))
6118 (buffer (marker-buffer marker))
6119 (pos (marker-position marker)))
6120 (with-current-buffer buffer
6123 (if (not (org-at-timestamp-p))
6124 (error "Cannot find time stamp"))
6125 (org-timestamp-change arg (or what 'day))
6126 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6128 (defun org-agenda-date-earlier (arg &optional what)
6129 "Change the date of this item to one day earlier."
6131 (org-agenda-date-later (- arg) what))
6133 (defun org-agenda-date-prompt (arg)
6134 "Change the date of this item. Date is prompted for, with default today.
6135 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6136 be used to request time specification in the time stamp."
6138 (org-agenda-check-no-diary)
6139 (let* ((marker (or (get-text-property (point) 'org-marker)
6140 (org-agenda-error)))
6141 (buffer (marker-buffer marker))
6142 (pos (marker-position marker)))
6143 (with-current-buffer buffer
6146 (if (not (org-at-timestamp-p))
6147 (error "Cannot find time stamp"))
6148 (org-time-stamp arg)
6149 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6151 (defun org-get-heading ()
6152 "Return the heading of the current entry, without the stars."
6154 (and (bolp) (end-of-line 1))
6155 (if (and (re-search-backward "[\r\n]\\*" nil t)
6156 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
6160 (defun org-agenda-diary-entry ()
6161 "Make a diary entry, like the `i' command from the calendar.
6162 All the standard commands work: block, weekly etc"
6164 (require 'diary-lib)
6166 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6167 (read-char-exclusive)))
6168 (cmd (cdr (assoc char
6169 '((?d . insert-diary-entry)
6170 (?w . insert-weekly-diary-entry)
6171 (?m . insert-monthly-diary-entry)
6172 (?y . insert-yearly-diary-entry)
6173 (?a . insert-anniversary-diary-entry)
6174 (?b . insert-block-diary-entry)
6175 (?c . insert-cyclic-diary-entry)))))
6176 (oldf (symbol-function 'calendar-cursor-to-date))
6178 (mark (or (mark t) (point))))
6180 (error "No command associated with <%c>" char))
6181 (unless (and (get-text-property point 'day)
6182 (or (not (equal ?b char))
6183 (get-text-property mark 'day)))
6184 (error "Don't know which date to use for diary entry"))
6185 ;; We implement this by hacking the `calendar-cursor-to-date' function
6186 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6187 (let ((calendar-mark-ring
6188 (list (calendar-gregorian-from-absolute
6189 (or (get-text-property mark 'day)
6190 (get-text-property point 'day))))))
6193 (fset 'calendar-cursor-to-date
6194 (lambda (&optional error)
6195 (calendar-gregorian-from-absolute
6196 (get-text-property point 'day))))
6197 (call-interactively cmd))
6198 (fset 'calendar-cursor-to-date oldf)))))
6201 (defun org-agenda-execute-calendar-command (cmd)
6202 "Execute a calendar command from the agenda, with the date associated to
6203 the cursor position."
6204 (require 'diary-lib)
6205 (unless (get-text-property (point) 'day)
6206 (error "Don't know which date to use for calendar command"))
6207 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6209 (date (calendar-gregorian-from-absolute
6210 (get-text-property point 'day)))
6211 (displayed-day (extract-calendar-day date))
6212 (displayed-month (extract-calendar-month date))
6213 (displayed-year (extract-calendar-year date)))
6216 (fset 'calendar-cursor-to-date
6217 (lambda (&optional error)
6218 (calendar-gregorian-from-absolute
6219 (get-text-property point 'day))))
6220 (call-interactively cmd))
6221 (fset 'calendar-cursor-to-date oldf))))
6223 (defun org-agenda-phases-of-moon ()
6224 "Display the phases of the moon for the 3 months around the cursor date."
6226 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6228 (defun org-agenda-holidays ()
6229 "Display the holidays for the 3 months around the cursor date."
6231 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6233 (defun org-agenda-sunrise-sunset (arg)
6234 "Display sunrise and sunset for the cursor date.
6235 Latitude and longitude can be specified with the variables
6236 `calendar-latitude' and `calendar-longitude'. When called with prefix
6237 argument, latitude and longitude will be prompted for."
6239 (let ((calendar-longitude (if arg nil calendar-longitude))
6240 (calendar-latitude (if arg nil calendar-latitude))
6241 (calendar-location-name
6242 (if arg "the given coordinates" calendar-location-name)))
6243 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6245 (defun org-agenda-goto-calendar ()
6246 "Open the Emacs calendar with the date at the cursor."
6248 (let* ((day (or (get-text-property (point) 'day)
6249 (error "Don't know which date to open in calendar")))
6250 (date (calendar-gregorian-from-absolute day))
6251 (calendar-move-hook nil)
6252 (view-diary-entries-initially nil))
6254 (calendar-goto-date date)))
6256 (defun org-calendar-goto-agenda ()
6257 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6258 This is a command that has to be installed in `calendar-mode-map'."
6260 (org-agenda-list nil (calendar-absolute-from-gregorian
6261 (calendar-cursor-to-date))
6264 (defun org-agenda-convert-date ()
6266 (let ((day (get-text-property (point) 'day))
6269 (error "Don't know which date to convert"))
6270 (setq date (calendar-gregorian-from-absolute day))
6272 "Gregorian: " (calendar-date-string date) "\n"
6273 "ISO: " (calendar-iso-date-string date) "\n"
6274 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6275 "Julian: " (calendar-julian-date-string date) "\n"
6276 "Astron. JD: " (calendar-astro-date-string date)
6277 " (Julian date number at noon UTC)\n"
6278 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6279 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6280 "French: " (calendar-french-date-string date) "\n"
6281 "Mayan: " (calendar-mayan-date-string date) "\n"
6282 "Coptic: " (calendar-coptic-date-string date) "\n"
6283 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6284 "Persian: " (calendar-persian-date-string date) "\n"
6285 "Chinese: " (calendar-chinese-date-string date) "\n"))
6286 (with-output-to-temp-buffer "*Dates*"
6288 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
6292 (defun org-scan-tags (action matcher &optional todo-only)
6293 "Scan headline tags with inheritance and produce output ACTION.
6294 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6295 evaluated, testing if a given set of tags qualifies a headline for
6296 inclusion. When TODO-ONLY is non-nil, only lines with a TDOD keyword
6297 d are included in the output."
6298 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6299 (mapconcat 'regexp-quote
6300 (nreverse (cdr (reverse org-todo-keywords)))
6302 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_:]+:\\)?[ \t]*[\n\r]"))
6303 (props (list 'face nil
6304 'done-face 'org-done
6306 'mouse-face 'highlight
6307 'keymap org-agenda-keymap
6309 (format "mouse-2 or RET jump to org file %s"
6310 (abbreviate-file-name (buffer-file-name)))))
6311 tags tags-list tags-alist (llast 0) rtn level category i txt
6315 (goto-char (point-min))
6316 (when (eq action 'sparse-tree) (hide-sublevels 1))
6317 (while (re-search-forward re nil t)
6318 (setq todo (if (match-end 1) (match-string 2))
6319 tags (if (match-end 4) (match-string 4)))
6320 (goto-char (1+ (match-beginning 0)))
6321 (setq level (outline-level)
6322 category (org-get-category))
6323 (setq i llast llast level)
6324 ;; remove tag lists from same and sublevels
6326 (when (setq entry (assoc i tags-alist))
6327 (setq tags-alist (delete entry tags-alist)))
6331 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6333 (cons (cons level tags) tags-alist)))
6334 ;; compile tags for current headline
6336 (if org-use-tag-inheritance
6337 (apply 'append (mapcar 'cdr tags-alist))
6339 (when (and (or (not todo-only) todo)
6341 ;; list this headline
6342 (if (eq action 'sparse-tree)
6344 (org-show-hierarchy-above))
6345 (setq txt (org-format-agenda-item
6348 (if org-tags-match-list-sublevels
6349 (make-string (1- level) ?.) "")
6352 (setq marker (org-agenda-new-marker))
6353 (add-text-properties
6355 (append (list 'org-marker marker 'org-hd-marker marker
6360 ;; if we are to skip sublevels, jump to end of subtree
6361 (or org-tags-match-list-sublevels (outline-end-of-subtree)))))
6364 (defun org-tags-sparse-tree (&optional arg match)
6365 "Create a sparse tree according to tags search string MATCH.
6366 MATCH can contain positive and negative selection of tags, like
6367 \"+WORK+URGENT-WITHBOSS\"."
6369 (let ((org-show-following-heading nil)
6370 (org-show-hierarchy-above nil))
6371 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6373 (defun org-make-tags-matcher (match)
6374 "Create the TAGS matcher form for the tags-selecting string MATCH."
6376 ;; Get a new match request, with completion
6377 (setq org-last-tags-completion-table
6378 (or (org-get-buffer-tags)
6379 org-last-tags-completion-table))
6380 (setq match (completing-read
6381 "Tags: " 'org-tags-completion-function nil nil nil
6382 'org-tags-history)))
6383 ;; parse the string and create a lisp form
6384 (let ((match0 match) minus tag mm matcher orterms term orlist)
6385 (setq orterms (org-split-string match "|"))
6386 (while (setq term (pop orterms))
6387 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_]+\\)" term)
6388 (setq minus (and (match-end 1)
6389 (equal (match-string 1 term) "-"))
6390 tag (match-string 2 term)
6391 term (substring term (match-end 0))
6392 mm (list 'member (downcase tag) 'tags-list)
6393 mm (if minus (list 'not mm) mm))
6395 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6398 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6399 ;; Return the string and lisp forms of the matcher
6400 (cons match0 matcher)))
6402 ;;(org-make-tags-matcher "&hello&-you")
6406 (defun org-tags-view (&optional todo-only match keep-modes)
6407 "Show all headlines for all `org-agenda-files' matching a TAGS criterions.
6408 The prefix arg TODO-ONLY limits the search to TODO entries."
6410 (org-agenda-maybe-reset-markers 'force)
6411 (org-compile-prefix-format org-agenda-prefix-format)
6412 (let* ((org-agenda-keep-modes keep-modes)
6413 (win (selected-window))
6414 (completion-ignore-case t)
6415 rtn rtnall files file pos matcher
6417 (setq matcher (org-make-tags-matcher match)
6418 match (car matcher) matcher (cdr matcher))
6419 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6421 (delete-other-windows)
6422 (switch-to-buffer-other-window
6423 (get-buffer-create org-agenda-buffer-name))))
6424 (setq buffer-read-only nil)
6426 (org-agenda-mode) (setq buffer-read-only nil)
6427 (set (make-local-variable 'org-agenda-redo-command)
6428 '(call-interactively 'org-tags-view))
6429 (setq files (org-agenda-files)
6431 (while (setq file (pop files))
6433 (org-check-agenda-file file)
6434 (setq buffer (if (file-exists-p file)
6435 (org-get-agenda-file-buffer file)
6436 (error "No such file %s" file)))
6438 ;; If file does not exist, merror message to agenda
6440 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6441 rtnall (append rtnall rtn))
6442 (with-current-buffer buffer
6443 (unless (eq major-mode 'org-mode)
6444 (error "Agenda file %s is not in `org-mode'" file))
6447 (if org-respect-restriction
6448 (if (org-region-active-p)
6449 ;; Respect a region to restrict search
6450 (narrow-to-region (region-beginning) (region-end)))
6451 ;; If we work for the calendar or many files,
6452 ;; get rid of any restriction
6454 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6455 (setq rtnall (append rtnall rtn))))))))
6456 (insert "Headlines with TAGS match: ")
6457 (add-text-properties (point-min) (1- (point))
6458 (list 'face 'org-link))
6461 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6463 (insert (mapconcat 'identity rtnall "\n")))
6464 (goto-char (point-min))
6465 (setq buffer-read-only t)
6466 (org-fit-agenda-window)
6467 (if (not org-select-agenda-window) (select-window win))))
6469 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6470 (defun org-set-tags (&optional arg just-align)
6471 "Set the tags for the current headline.
6472 With prefix ARG, realign all tags in headings in the current buffer."
6474 (let* (;(inherit (org-get-inherited-tags))
6475 (re (concat "^" outline-regexp))
6476 (col (current-column))
6477 (current (org-get-tags))
6481 (goto-char (point-min))
6482 (while (re-search-forward re nil t)
6483 (org-set-tags nil t))
6484 (message "All tags realigned to column %d" org-tags-column))
6487 (setq org-last-tags-completion-table
6488 (or (org-get-buffer-tags)
6489 org-last-tags-completion-table))
6491 (let ((org-add-colon-after-tag-completion t))
6492 (completing-read "Tags: " 'org-tags-completion-function
6493 nil nil current 'org-tags-history)))
6494 (while (string-match "[-+&]+" tags)
6495 (setq tags (replace-match ":" t t tags)))
6496 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6497 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
6498 (if (equal current "")
6500 (beginning-of-line 1)
6501 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6502 (setq hd (match-string 1))
6503 (delete-region (match-beginning 0) (match-end 0))
6504 (insert (org-trim hd) " "))
6505 (unless (equal tags "")
6506 (move-to-column (max (current-column)
6507 (if (> org-tags-column 0)
6509 (- (- org-tags-column) (length tags))))
6512 (move-to-column col))))
6514 (defun org-tags-completion-function (string predicate &optional flag)
6515 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6516 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6517 (setq s1 (match-string 1 string)
6518 s2 (match-string 2 string))
6519 (setq s1 "" s2 string))
6523 (setq rtn (try-completion s2 ctable))
6525 (concat s1 s2 (substring rtn (length s2))
6526 (if (and org-add-colon-after-tag-completion
6532 (all-completions s2 ctable)
6539 (defun org-get-tags ()
6540 "Get the TAGS string in the current headline."
6541 (unless (org-on-heading-p)
6542 (error "Not on a heading"))
6544 (beginning-of-line 1)
6545 (if (looking-at ".*[ \t]\\(:[A-Za-z_:]+:\\)[ \t]*\\(\r\\|$\\)")
6549 (defun org-get-buffer-tags ()
6550 "Get a table of all tags used in the buffer, for completion."
6553 (goto-char (point-min))
6554 (while (re-search-forward "[ \t]:\\([A-Za-z_:]+\\):[ \t\r\n]" nil t)
6555 (mapc (lambda (x) (add-to-list 'tags x))
6556 (org-split-string (match-string-no-properties 1) ":"))))
6557 (mapcar 'list tags)))
6561 (defun org-find-file-at-mouse (ev)
6562 "Open file link or URL at mouse."
6564 (mouse-set-point ev)
6565 (org-open-at-point 'in-emacs))
6567 (defun org-open-at-mouse (ev)
6568 "Open file link or URL at mouse."
6570 (mouse-set-point ev)
6571 (org-open-at-point))
6573 (defun org-open-at-point (&optional in-emacs)
6574 "Open link at or after point.
6575 If there is no link at point, this function will search forward up to
6576 the end of the current subtree.
6577 Normally, files will be opened by an appropriate application. If the
6578 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6580 (org-remove-occur-highlights nil nil t)
6581 (if (org-at-timestamp-p)
6582 (org-agenda-list nil (time-to-days (org-time-string-to-time
6583 (substring (match-string 1) 0 10)))
6585 (let (type path line search (pos (point)))
6588 (skip-chars-backward
6589 (concat (if org-allow-space-in-links "^" "^ ")
6590 org-non-link-chars))
6591 (when (looking-at org-link-regexp)
6592 (setq type (match-string 1)
6593 path (match-string 2))
6596 (skip-chars-backward "^ \t\n\r")
6597 (when (looking-at "\\(:[A-Za-z_:]+\\):[ \t\r\n]")
6599 path (match-string 1))
6600 (while (string-match ":" path)
6601 (setq path (replace-match "+" t t path)))
6604 (skip-chars-backward "a-zA-Z_")
6605 (when (looking-at org-camel-regexp)
6606 (setq type "camel" path (match-string 0))
6607 (if (equal (char-before) ?*)
6608 (setq path (concat "*" path))))
6611 (when (re-search-forward
6615 (progn (outline-end-of-subtree) (max pos (point)))
6616 (error (end-of-line 1) (point))))
6618 (setq type (match-string 1)
6619 path (match-string 2)))))
6621 (error "No link found"))
6622 ;; Remove any trailing spaces in path
6623 (if (string-match " +\\'" path)
6624 (setq path (replace-match "" t t path)))
6628 ((string= type "tags")
6629 (org-tags-view path in-emacs))
6630 ((string= type "camel")
6633 (cond ((equal in-emacs '(4)) 'occur)
6634 ((equal in-emacs '(16)) 'org-occur)
6637 ((string= type "file")
6638 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6639 (setq line (string-to-number (match-string 1 path))
6640 path (substring path 0 (match-beginning 0)))
6641 (if (string-match "::\\(.+\\)\\'" path)
6642 (setq search (match-string 1 path)
6643 path (substring path 0 (match-beginning 0)))))
6644 (org-open-file path in-emacs line search))
6646 ((string= type "news")
6647 (org-follow-gnus-link path))
6649 ((string= type "bbdb")
6650 (org-follow-bbdb-link path))
6652 ((string= type "gnus")
6653 (let (group article)
6654 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6655 (error "Error in Gnus link"))
6656 (setq group (match-string 1 path)
6657 article (match-string 3 path))
6658 (org-follow-gnus-link group article)))
6660 ((string= type "vm")
6661 (let (folder article)
6662 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6663 (error "Error in VM link"))
6664 (setq folder (match-string 1 path)
6665 article (match-string 3 path))
6666 ;; in-emacs is the prefix arg, will be interpreted as read-only
6667 (org-follow-vm-link folder article in-emacs)))
6669 ((string= type "wl")
6670 (let (folder article)
6671 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6672 (error "Error in Wanderlust link"))
6673 (setq folder (match-string 1 path)
6674 article (match-string 3 path))
6675 (org-follow-wl-link folder article)))
6677 ((string= type "rmail")
6678 (let (folder article)
6679 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6680 (error "Error in RMAIL link"))
6681 (setq folder (match-string 1 path)
6682 article (match-string 3 path))
6683 (org-follow-rmail-link folder article)))
6685 ((string= type "shell")
6687 (while (string-match "@{" cmd)
6688 (setq cmd (replace-match "<" t t cmd)))
6689 (while (string-match "@}" cmd)
6690 (setq cmd (replace-match ">" t t cmd)))
6691 (if (or (not org-confirm-shell-links)
6692 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6697 (browse-url-at-point))))))
6699 (defun org-link-search (s &optional type)
6700 "Search for a link search option.
6701 When S is a CamelCaseWord, search for a target, or for a sentence containing
6702 the words. If S is surrounded by forward slashes, it is interpreted as a
6703 regular expression. In org-mode files, this will create an `org-occur'
6704 sparse tree. In ordinary files, `occur' will be used to list matched.
6705 If the current buffer is in `dired-mode', grep will be used to search
6707 (let ((case-fold-search t)
6711 words re0 re1 re2 re3 re4 re5 reall)
6712 (cond ((string-match "^/\\(.*\\)/$" s)
6713 ;; A regular expression
6715 ((eq major-mode 'org-mode)
6716 (org-occur (match-string 1 s)))
6717 ;;((eq major-mode 'dired-mode)
6718 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6719 (t (org-do-occur (match-string 1 s)))))
6720 ((string-match (concat "^" org-camel-regexp) s)
6722 (if (equal (string-to-char s) ?*)
6723 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6726 (remove-text-properties
6728 '(face nil mouse-face nil keymap nil fontified nil) s)
6729 ;; Make a series of regular expressions to find a match
6730 (setq words (org-camel-to-words s)
6731 re0 (concat "<<" (regexp-quote s0) ">>")
6732 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6733 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6734 re1 (concat pre re2 post)
6735 re3 (concat pre re4 post)
6736 re5 (concat pre ".*" re4)
6737 re2 (concat pre re2)
6738 re4 (concat pre re4)
6739 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6740 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6744 ((eq type 'org-occur) (org-occur reall))
6745 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6746 (t (goto-char (point-min))
6747 (if (or (re-search-forward re0 nil t)
6748 (re-search-forward re1 nil t)
6749 (re-search-forward re2 nil t)
6750 (re-search-forward re3 nil t)
6751 (re-search-forward re4 nil t)
6752 (re-search-forward re5 nil t))
6753 (goto-char (match-beginning 0))
6755 (error "No match")))))
6757 ;; Normal string-search
6758 (goto-char (point-min))
6759 (if (search-forward s nil t)
6760 (goto-char (match-beginning 0))
6761 (error "No match"))))))
6763 (defun org-do-occur (regexp &optional cleanup)
6764 "Call the Emacs command `occur'.
6765 If CLEANUP is non-nil, remove the printout of the regular expression
6766 in the *Occur* buffer. This is useful if the regex is long and not useful
6770 (let ((cwin (selected-window)) win beg end)
6771 (when (setq win (get-buffer-window "*Occur*"))
6772 (select-window win))
6773 (goto-char (point-min))
6774 (when (re-search-forward "match[a-z]+" nil t)
6775 (setq beg (match-end 0))
6776 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6777 (setq end (1- (match-beginning 0)))))
6778 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
6779 (goto-char (point-min))
6780 (select-window cwin))))
6782 (defun org-camel-to-words (s)
6783 "Split \"CamelCaseWords\" to (\"Camel \" \"Case\" \"Words\")."
6784 (let ((case-fold-search nil)
6786 (while (string-match "[a-z][A-Z]" s)
6787 (push (substring s 0 (1+ (match-beginning 0))) words)
6788 (setq s (substring s (1+ (match-beginning 0)))))
6789 (nreverse (cons s words))))
6791 (defun org-follow-bbdb-link (name)
6792 "Follow a BBDB link to NAME."
6794 (let ((inhibit-redisplay t))
6796 ;; Exact match on name
6797 (bbdb-name (concat "\\`" name "\\'") nil)
6798 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6799 ;; Exact match on name
6800 (bbdb-company (concat "\\`" name "\\'") nil)
6801 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6802 ;; Partial match on name
6803 (bbdb-name name nil)
6804 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6805 ;; Partial match on company
6806 (bbdb-company name nil)
6807 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6808 ;; General match including network address and notes
6810 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
6811 (delete-window (get-buffer-window "*BBDB*"))
6812 (error "No matching BBDB record")))))
6814 (defun org-follow-gnus-link (&optional group article)
6815 "Follow a Gnus link to GROUP and ARTICLE."
6817 (funcall (cdr (assq 'gnus org-link-frame-setup)))
6818 (if group (gnus-fetch-group group))
6820 (or (gnus-summary-goto-article article nil 'force)
6821 (if (fboundp 'gnus-summary-insert-cached-articles)
6823 (gnus-summary-insert-cached-articles)
6824 (gnus-summary-goto-article article nil 'force))
6825 (message "Message could not be found.")))))
6827 (defun org-follow-vm-link (&optional folder article readonly)
6828 "Follow a VM link to FOLDER and ARTICLE."
6830 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
6831 ;; ange-ftp or efs or tramp access
6832 (let ((user (or (match-string 1 folder) (user-login-name)))
6833 (host (match-string 2 folder))
6834 (file (match-string 3 folder)))
6837 ;; use tramp to access the file
6839 (setq folder (format "[%s@%s]%s" user host file))
6840 (setq folder (format "/%s@%s:%s" user host file))))
6842 ;; use ange-ftp or efs
6843 (require (if org-xemacs-p 'efs 'ange-ftp))
6844 (setq folder (format "/%s@%s:%s" user host file))))))
6846 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
6849 (vm-select-folder-buffer)
6851 (let ((case-fold-search t))
6852 (goto-char (point-min))
6853 (if (not (re-search-forward
6854 (concat "^" "message-id: *" (regexp-quote article))))
6855 (error "Could not find the specified message in this folder"))
6858 (vm-beginning-of-message)
6861 (defun org-follow-wl-link (folder article)
6862 "Follow a Wanderlust link to FOLDER and ARTICLE."
6863 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
6864 (if article (wl-summary-jump-to-msg-by-message-id article))
6865 (wl-summary-redisplay))
6867 (defun org-follow-rmail-link (folder article)
6868 "Follow an RMAIL link to FOLDER and ARTICLE."
6869 (let (message-number)
6871 (save-window-excursion
6872 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6873 (setq message-number
6876 (goto-char (point-max))
6877 (if (re-search-backward
6878 (concat "^Message-ID:\\s-+" (regexp-quote
6881 (rmail-what-message))))))
6884 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6885 (rmail-show-message message-number)
6887 (error "Message not found"))))
6889 (defun org-open-file (path &optional in-emacs line search)
6890 "Open the file at PATH.
6891 First, this expands any special file name abbreviations. Then the
6892 configuration variable `org-file-apps' is checked if it contains an
6893 entry for this file type, and if yes, the corresponding command is launched.
6894 If no application is found, Emacs simply visits the file.
6895 With optional argument IN-EMACS, Emacs will visit the file.
6896 Optional LINE specifies a line to go to, optional SEARCH a string to
6897 search for. If LINE or SEARCH is given, the file will always be
6899 If the file does not exist, an error is thrown."
6900 (setq in-emacs (or in-emacs line search))
6901 (let* ((file (if (equal path "")
6903 (convert-standard-filename (org-expand-file-name path))))
6904 (dfile (downcase file))
6906 (if (and (not (file-exists-p file))
6907 (not org-open-non-existing-files))
6908 (error "No such file: %s" file))
6909 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
6910 (setq ext (match-string 1 dfile))
6911 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
6912 (setq ext (match-string 1 dfile))))
6913 (setq apps (append org-file-apps (org-default-apps)))
6916 (setq cmd (or (cdr (assoc ext apps))
6917 (cdr (assoc t apps)))))
6919 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
6920 (setq cmd (format cmd (concat "\"" file "\"")))
6921 (save-window-excursion
6922 (shell-command (concat cmd " & &"))))
6925 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
6926 (funcall (cdr (assq 'file org-link-frame-setup)) file))
6927 (if line (goto-line line)
6928 (if search (org-link-search search))))
6931 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
6933 (defun org-default-apps ()
6934 "Return the default applications for this operating system."
6936 ((eq system-type 'darwin)
6937 org-file-apps-defaults-macosx)
6938 ((eq system-type 'windows-nt)
6939 org-file-apps-defaults-windowsnt)
6940 (t org-file-apps-defaults-gnu)))
6942 (defun org-expand-file-name (path)
6943 "Replace special path abbreviations and expand the file name."
6944 (expand-file-name path))
6947 (defvar org-insert-link-history nil
6948 "Minibuffer history for links inserted with `org-insert-link'.")
6950 (defvar org-stored-links nil
6951 "Contains the links stored with `org-store-link'.")
6954 (defun org-store-link (arg)
6955 "\\<org-mode-map>Store an org-link to the current location.
6956 This link can later be inserted into an org-buffer with
6957 \\[org-insert-link].
6958 For some link types, a prefix arg is interpreted:
6959 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6960 For file links, arg negates `org-context-in-file-links'."
6965 ((eq major-mode 'bbdb-mode)
6966 (setq cpltxt (concat
6968 (or (bbdb-record-name (bbdb-current-record))
6969 (bbdb-record-company (bbdb-current-record))))
6970 link (org-make-link cpltxt)))
6972 ((eq major-mode 'calendar-mode)
6973 (let ((cd (calendar-cursor-to-date)))
6976 (car org-time-stamp-formats)
6978 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6981 ((or (eq major-mode 'vm-summary-mode)
6982 (eq major-mode 'vm-presentation-mode))
6983 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
6984 (vm-follow-summary-cursor)
6986 (vm-select-folder-buffer)
6987 (let* ((message (car vm-message-pointer))
6988 (folder (buffer-file-name))
6989 (subject (vm-su-subject message))
6990 (author (vm-su-full-name message))
6991 (message-id (vm-su-message-id message)))
6992 (setq folder (abbreviate-file-name folder))
6993 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
6995 (setq folder (replace-match "" t t folder)))
6996 (setq cpltxt (concat author " on: " subject))
6997 (setq link (concat cpltxt "\n "
6999 "vm:" folder "#" message-id))))))
7001 ((eq major-mode 'wl-summary-mode)
7002 (let* ((msgnum (wl-summary-message-number))
7003 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7004 msgnum 'message-id))
7005 (wl-message-entity (elmo-msgdb-overview-get-entity
7006 msgnum (wl-summary-buffer-msgdb)))
7007 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7008 (subject "???")) ; FIXME: How to get subject of email?
7009 (setq cpltxt (concat author " on: " subject))
7010 (setq link (concat cpltxt "\n "
7012 "wl:" wl-summary-buffer-folder-name
7015 ((eq major-mode 'rmail-mode)
7018 (rmail-narrow-to-non-pruned-header)
7019 (let ((folder (buffer-file-name))
7020 (message-id (mail-fetch-field "message-id"))
7021 (author (mail-fetch-field "from"))
7022 (subject (mail-fetch-field "subject")))
7023 (setq cpltxt (concat author " on: " subject))
7024 (setq link (concat cpltxt "\n "
7026 "rmail:" folder "#" message-id)))))))
7028 ((eq major-mode 'gnus-group-mode)
7029 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7030 (gnus-group-group-name)) ; version
7031 ((fboundp 'gnus-group-name)
7034 (setq cpltxt (concat
7035 (if (org-xor arg org-usenet-links-prefer-google)
7036 "http://groups.google.com/groups?group="
7039 link (org-make-link cpltxt))))
7041 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7042 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7043 (gnus-summary-beginning-of-article)
7044 (let* ((group (car gnus-article-current))
7045 (article (cdr gnus-article-current))
7046 (header (gnus-summary-article-header article))
7047 (author (mail-header-from header))
7048 (message-id (mail-header-id header))
7049 (date (mail-header-date header))
7050 (subject (gnus-summary-subject-string)))
7051 (setq cpltxt (concat author " on: " subject))
7052 (if (org-xor arg org-usenet-links-prefer-google)
7056 (format "http://groups.google.com/groups?as_umsgid=%s"
7057 (org-fixup-message-id-for-http message-id))))
7058 (setq link (concat cpltxt "\n"
7061 "#" (number-to-string article)))))))
7063 ((eq major-mode 'w3-mode)
7064 (setq cpltxt (url-view-url t)
7065 link (org-make-link cpltxt)))
7066 ((eq major-mode 'w3m-mode)
7067 (setq cpltxt w3m-current-url
7068 link (org-make-link cpltxt)))
7070 ((eq major-mode 'org-mode)
7071 ;; Just link to current headline
7072 (setq cpltxt (concat "file:"
7073 (abbreviate-file-name (buffer-file-name))))
7074 ;; Add a context search string
7075 (when (org-xor org-context-in-file-links arg)
7077 (skip-chars-backward "a-zA-Z<")
7078 (looking-at (concat "<<\\(" org-camel-regexp "\\)>>")))
7079 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7082 (org-make-org-heading-camel
7084 ((org-on-heading-p) nil)
7085 ((org-region-active-p)
7086 (buffer-substring (region-beginning) (region-end)))
7087 (t (buffer-substring (point-at-bol) (point-at-eol))))
7089 (setq link (org-make-link cpltxt)))
7092 ;; Just link to this file here.
7093 (setq cpltxt (concat "file:"
7094 (abbreviate-file-name (buffer-file-name))))
7095 ;; Add a context string
7096 (when (org-xor org-context-in-file-links arg)
7099 (org-make-org-heading-camel
7100 (if (org-region-active-p)
7101 (buffer-substring (region-beginning) (region-end))
7102 (buffer-substring (point-at-bol) (point-at-eol)))))))
7103 (setq link (org-make-link cpltxt)))
7106 (error "Cannot link to a buffer which is not visiting a file"))
7108 (t (setq link nil)))
7110 (if (and (interactive-p) link)
7112 (setq org-stored-links
7113 (cons (cons (or cpltxt link) link) org-stored-links))
7114 (message "Stored: %s" (or cpltxt link)))
7117 (defun org-make-org-heading-camel (&optional string)
7118 "Make a CamelCase string for S or the current headline."
7120 (let ((s (or string (org-get-heading))))
7122 ;; We are using a headline, clean up garbage in there.
7123 (if (string-match org-todo-regexp s)
7124 (setq s (replace-match "" t t s)))
7125 (setq s (org-trim s))
7126 (if (string-match (concat "^\\(" org-quote-string "\\|"
7127 org-comment-string "\\)") s)
7128 (setq s (replace-match "" t t s)))
7129 (while (string-match org-ts-regexp s)
7130 (setq s (replace-match "" t t s))))
7131 (while (string-match "[^a-zA-Z_ \t]+" s)
7132 (setq s (replace-match " " t t s)))
7133 (or string (setq s (concat "*" s))) ; Add * for headlines
7134 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7136 (defun org-make-link (&rest strings)
7137 "Concatenate STRINGS, format resulting string with `org-link-format'."
7138 (format org-link-format (apply 'concat strings)))
7140 (defun org-xor (a b)
7144 (defun org-get-header (header)
7145 "Find a header field in the current buffer."
7147 (goto-char (point-min))
7148 (let ((case-fold-search t) s)
7151 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7152 (setq s (match-string 1)))
7153 (while (string-match "\"" s)
7154 (setq s (replace-match "" t t s)))
7155 (if (string-match "[<(].*" s)
7156 (setq s (replace-match "" t t s))))
7157 ((eq header 'message-id)
7158 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7159 (setq s (match-string 1))))
7160 ((eq header 'subject)
7161 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7162 (setq s (match-string 1)))))
7163 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7164 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7168 (defun org-fixup-message-id-for-http (s)
7169 "Replace special characters in a message id, so it can be used in an http query."
7170 (while (string-match "<" s)
7171 (setq s (replace-match "%3C" t t s)))
7172 (while (string-match ">" s)
7173 (setq s (replace-match "%3E" t t s)))
7174 (while (string-match "@" s)
7175 (setq s (replace-match "%40" t t s)))
7178 (defun org-insert-link (&optional complete-file)
7179 "Insert a link. At the prompt, enter the link.
7181 Completion can be used to select a link previously stored with
7182 `org-store-link'. When the empty string is entered (i.e. if you just
7183 press RET at the prompt), the link defaults to the most recently
7184 stored link. As SPC triggers completion in the minibuffer, you need to
7185 use M-SPC or C-q SPC to force the insertion of a space character.
7187 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7188 selected using completion. The path to the file will be relative to
7189 the current directory if the file is in the current directory or a
7190 subdirectory. Otherwise, the link will be the absolute path as
7191 completed in the minibuffer (i.e. normally ~/path/to/file).
7193 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7194 is in the current directory or below."
7196 (let ((link (if complete-file
7197 (read-file-name "File: ")
7199 "Link: " org-stored-links nil nil nil
7200 org-insert-link-history
7201 (or (car (car org-stored-links))))))
7203 (if (or (not link) (equal link ""))
7204 (error "No links available"))
7206 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7208 ((equal complete-file '(16))
7211 "file:" (abbreviate-file-name (expand-file-name link)))))
7212 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7213 (expand-file-name link))
7216 "file:" (match-string 1 (expand-file-name link)))))
7217 (t (insert (org-make-link "file:" link)))))
7218 (setq linktxt (cdr (assoc link org-stored-links)))
7219 (if (not org-keep-stored-link-after-insertion)
7220 (setq org-stored-links (delq (assoc link org-stored-links)
7222 (if (not linktxt) (setq link (org-make-link link)))
7223 (setq link (or linktxt link))
7224 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7225 (let* ((path (match-string 1 link))
7226 (case-fold-search nil)
7227 (search (match-string 2 link)))
7228 (when (save-match-data
7229 (equal (file-truename (buffer-file-name))
7230 (file-truename path)))
7231 (if (save-match-data
7232 (string-match (concat "^" org-camel-regexp "$") search))
7233 (setq link (replace-match search t t link)
7235 (setq link (replace-match (concat "<file:::" search ">")
7237 (let ((lines (org-split-string link "\n")))
7238 (insert (car lines))
7239 (setq matched (or matched (string-match org-link-regexp (car lines))))
7240 (setq lines (cdr lines))
7244 (beginning-of-line 0)
7245 (looking-at "[ \t]+\\S-"))
7247 (setq matched (or matched
7248 (string-match org-link-regexp (car lines))))
7249 (insert (car lines))
7250 (setq lines (cdr lines))))
7252 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7254 ;;; Hooks for remember.el
7256 (defun org-remember-annotation ()
7257 "Return a link to the current location as an annotation for remember.el.
7258 If you are using Org-mode files as target for data storage with
7259 remember.el, then the annotations should include a link compatible with the
7260 conventions in Org-mode. This function returns such a link."
7261 (org-store-link nil))
7263 (defconst org-remember-help
7264 "Select a destination location for the note.
7265 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7266 RET at beg-of-buf -> Append to file as level 2 headline
7267 RET on headline -> Store as sublevel entry to current headline
7268 <left>/<right> -> before/after current headline, same headings level")
7271 (defun org-remember-handler ()
7272 "Store stuff from remember.el into an org file.
7273 First prompts for an org file. If the user just presses return, the value
7274 of `org-default-notes-file' is used.
7275 Then the command offers the headings tree of the selected file in order to
7276 file the text at a specific location.
7277 You can either immediately press RET to get the note appended to the
7278 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
7279 find a better place. Then press RET or <left> or <right> in insert the note.
7281 Key Cursor position Note gets inserted
7282 -----------------------------------------------------------------------------
7283 RET buffer-start as level 2 heading at end of file
7284 RET on headline as sublevel of the heading at cursor
7285 RET no heading at cursor position, level taken from context.
7286 Or use prefix arg to specify level manually.
7287 <left> on headline as same level, before current heading
7288 <right> on headline as same level, after current heading
7290 So the fastest way to store the note is to press RET RET to append it to
7291 the default file. This way your current train of thought is not
7292 interrupted, in accordance with the principles of remember.el. But with
7293 little extra effort, you can push it directly to the correct location.
7295 Before being stored away, the function ensures that the text has a
7296 headline, i.e. a first line that starts with a \"*\". If not, a headline
7297 is constructed from the current date and some additional data.
7299 If the variable `org-adapt-indentation' is non-nil, the entire text is
7300 also indented so that it starts in the same column as the headline
7301 \(i.e. after the stars).
7303 See also the variable `org-reverse-note-order'."
7305 (let* ((txt (buffer-substring (point-min) (point-max)))
7306 (fastp current-prefix-arg)
7307 (file (if fastp org-default-notes-file (org-get-org-file)))
7308 (visiting (find-buffer-visiting file))
7309 (org-startup-with-deadline-check nil)
7310 (org-startup-folded nil)
7311 spos level indent reversed)
7312 ;; Modify text so that it becomes a nice subtree which can be inserted
7313 ;; into an org tree.
7314 (let* ((lines (split-string txt "\n"))
7316 (lines (cdr lines)))
7317 (if (string-match "^\\*+" first)
7318 ;; Is already a headline
7319 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7321 ;; We need to add a headline: Use time and first buffer line
7322 (setq lines (cons first lines)
7323 first (concat "* " (current-time-string)
7324 " (" (remember-buffer-desc) ")")
7326 (if org-adapt-indentation
7327 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7328 (setq txt (concat first "\n"
7329 (mapconcat 'identity lines "\n"))))
7332 (find-file-noselect file))
7333 (with-current-buffer (get-file-buffer file)
7334 (setq reversed (org-notes-order-reversed-p))
7338 ;; Ask the User for a location
7339 (setq spos (if fastp 1 (org-get-location
7341 org-remember-help)))
7342 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7343 ; not handle this note
7346 ;; Put it at the start or end, as level 2
7349 (goto-char (if reversed (point-min) (point-max)))
7350 (if (not (bolp)) (newline))
7351 (org-paste-subtree (or current-prefix-arg 2) txt)))
7352 ((and (org-on-heading-p nil) (not current-prefix-arg))
7353 ;; Put it below this entry, at the beg/end of the subtree
7354 (org-back-to-heading)
7355 (setq level (outline-level))
7357 (outline-end-of-heading)
7358 (outline-end-of-subtree))
7359 (if (not (bolp)) (newline))
7360 (beginning-of-line 1)
7361 (org-paste-subtree (1+ level) txt))
7363 ;; Put it right there, with automatic level determined by
7364 ;; org-paste-subtree or from prefix arg
7365 (org-paste-subtree current-prefix-arg txt)))
7366 (when remember-save-after-remembering
7368 (if (not visiting) (kill-buffer (current-buffer)))))))))
7369 t) ;; return t to indicate that we took care of this note.
7371 (defun org-get-org-file ()
7372 "Read a filename, with default directory `org-directory'."
7373 (let ((default (or org-default-notes-file remember-data-file)))
7374 (read-file-name (format "File name [%s]: " default)
7375 (file-name-as-directory org-directory)
7378 (defun org-notes-order-reversed-p ()
7379 "Check if the current file should receive notes in reversed order."
7381 ((not org-reverse-note-order) nil)
7382 ((eq t org-reverse-note-order) t)
7383 ((not (listp org-reverse-note-order)) nil)
7385 (let ((all org-reverse-note-order)
7387 (while (setq entry (pop all))
7388 (if (string-match (car entry) (buffer-file-name))
7389 (throw 'exit (cdr entry))))
7394 ;; Watch out: Here we are talking about two different kind of tables.
7395 ;; Most of the code is for the tables created with the Org-mode table editor.
7396 ;; Sometimes, we talk about tables created and edited with the table.el
7397 ;; Emacs package. We call the former org-type tables, and the latter
7398 ;; table.el-type tables.
7401 (defun org-before-change-function (beg end)
7402 "Every change indicates that a table might need an update."
7403 (setq org-table-may-need-update t))
7405 (defconst org-table-line-regexp "^[ \t]*|"
7406 "Detects an org-type table line.")
7407 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7408 "Detects an org-type table line.")
7409 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7410 "Detects a table line marked for automatic recalculation.")
7411 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7412 "Detects a table line marked for automatic recalculation.")
7413 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7414 "Detects a table line marked for automatic recalculation.")
7415 (defconst org-table-hline-regexp "^[ \t]*|-"
7416 "Detects an org-type table hline.")
7417 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7418 "Detects a table-type table hline.")
7419 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7420 "Detects an org-type or table-type table.")
7421 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7422 "Searching from within a table (any type) this finds the first line
7423 outside the table.")
7424 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7425 "Searching from within a table (any type) this finds the first line
7426 outside the table.")
7428 (defun org-table-create-with-table.el ()
7429 "Use the table.el package to insert a new table.
7430 If there is already a table at point, convert between Org-mode tables
7431 and table.el tables."
7435 ((org-at-table.el-p)
7436 (if (y-or-n-p "Convert table to Org-mode table? ")
7437 (org-table-convert)))
7439 (if (y-or-n-p "Convert table to table.el table? ")
7440 (org-table-convert)))
7441 (t (call-interactively 'table-insert))))
7443 (defun org-table-create (&optional size)
7444 "Query for a size and insert a table skeleton.
7445 SIZE is a string Columns x Rows like for example \"3x2\"."
7448 (setq size (read-string
7449 (concat "Table size Columns x Rows [e.g. "
7450 org-table-default-size "]: ")
7451 "" nil org-table-default-size)))
7453 (let* ((pos (point))
7454 (indent (make-string (current-column) ?\ ))
7455 (split (org-split-string size " *x *"))
7456 (rows (string-to-number (nth 1 split)))
7457 (columns (string-to-number (car split)))
7458 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7460 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7461 (point-at-bol) (point)))
7462 (beginning-of-line 1)
7464 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7465 (dotimes (i rows) (insert line))
7468 ;; Insert a hline after the first row.
7475 (defun org-table-convert-region (beg0 end0 nspace)
7476 "Convert region to a table.
7477 The region goes from BEG0 to END0, but these borders will be moved
7478 slightly, to make sure a beginning of line in the first line is included.
7479 When NSPACE is non-nil, it indicates the minimum number of spaces that
7480 separate columns (default: just one space)"
7481 (let* ((beg (min beg0 end0))
7482 (end (max beg0 end0))
7486 (beginning-of-line 1)
7487 (setq beg (move-marker (make-marker) (point)))
7489 (if (bolp) (backward-char 1) (end-of-line 1))
7490 (setq end (move-marker (make-marker) (point)))
7491 ;; Lets see if this is tab-separated material. If every nonempty line
7492 ;; contains a tab, we will assume that it is tab-separated material
7496 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7497 (if nspace (setq tabsep nil))
7500 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7501 (max 1 (prefix-numeric-value nspace)))))
7503 (while (re-search-forward re end t)
7504 (replace-match "|" t t))
7509 (defun org-table-import (file arg)
7510 "Import FILE as a table.
7511 The file is assumed to be tab-separated. Such files can be produced by most
7512 spreadsheet and database applications. If no tabs (at least one per line)
7513 are found, lines will be split on whitespace into fields."
7514 (interactive "f\nP")
7515 (or (bolp) (newline))
7518 (insert-file-contents file)
7519 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7521 (defun org-table-export ()
7522 "Export table as a tab-separated file.
7523 Such a file can be imported into a spreadsheet program like Excel."
7525 (let* ((beg (org-table-begin))
7526 (end (org-table-end))
7527 (table (buffer-substring beg end))
7528 (file (read-file-name "Export table to: "))
7530 (unless (or (not (file-exists-p file))
7531 (y-or-n-p (format "Overwrite file %s? " file)))
7533 (with-current-buffer (find-file-noselect file)
7534 (setq buf (current-buffer))
7538 (goto-char (point-min))
7539 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7540 (replace-match "" t t)
7542 (goto-char (point-min))
7543 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7544 (replace-match "" t t)
7545 (goto-char (min (1+ (point)) (point-max))))
7546 (goto-char (point-min))
7547 (while (re-search-forward "^-[-+]*$" nil t)
7549 (if (looking-at "\n")
7551 (goto-char (point-min))
7552 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7553 (replace-match "\t" t t))
7557 (defvar org-table-aligned-begin-marker (make-marker)
7558 "Marker at the beginning of the table last aligned.
7559 Used to check if cursor still is in that table, to minimize realignment.")
7560 (defvar org-table-aligned-end-marker (make-marker)
7561 "Marker at the end of the table last aligned.
7562 Used to check if cursor still is in that table, to minimize realignment.")
7563 (defvar org-table-last-alignment nil
7564 "List of flags for flushright alignment, from the last re-alignment.
7565 This is being used to correctly align a single field after TAB or RET.")
7566 ;; FIXME: The following is currently not used.
7567 (defvar org-table-last-column-widths nil
7568 "List of max width of fields in each column.
7569 This is being used to correctly align a single field after TAB or RET.")
7571 (defvar org-last-recalc-line nil)
7573 (defun org-table-align ()
7574 "Align the table at point by aligning all vertical bars."
7576 ;; (message "align") (sit-for 2)
7579 (beg (org-table-begin))
7580 (end (org-table-end))
7581 ;; Current cursor position
7582 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7583 (colpos (org-table-current-column))
7584 (winstart (window-start))
7585 text lines (new "") lengths l typenums ty fields maxfields i
7587 (indent "") cnt frac
7589 (spaces (if (org-in-invisibility-spec-p '(org-table))
7590 org-table-spaces-around-invisible-separators
7591 org-table-spaces-around-separators))
7595 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7597 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7600 ;; (message "Aligning table...")
7602 (setq lines (org-split-string
7603 (buffer-substring-no-properties beg end) "\n"))
7604 ;; Store the indentation of the first line
7605 (if (string-match "^ *" (car lines))
7606 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7608 (setq lines (mapcar (lambda (l)
7609 (if (string-match "^ *|-" l)
7611 (if (string-match "[ \t]+$" l)
7612 (substring l 0 (match-beginning 0))
7615 ;; Get the data fields
7616 (setq fields (mapcar
7618 (org-split-string l " *| *"))
7619 (delq nil (copy-sequence lines))))
7620 ;; How many fields in the longest line?
7622 (setq maxfields (apply 'max (mapcar 'length fields)))
7624 (kill-region beg end)
7625 (org-table-create org-table-default-size)
7626 (error "Empty table - created default table")))
7627 ;; A list of empty string to fill any short rows on output
7628 (setq emptystrings (make-list maxfields ""))
7629 ;; Get the maximum length of a field and the most common datatype
7632 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7633 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7635 (push (apply 'max 1 (mapcar 'length column)) lengths)
7636 ;; compute the fraction stepwise, ignoring empty fields
7637 (setq cnt 0 frac 0.0)
7642 (setq frac ( / (+ (* frac cnt)
7643 (if (string-match org-table-number-regexp x) 1 0))
7644 (setq cnt (1+ cnt))))))
7646 (push (>= frac org-table-number-fraction) typenums))
7647 (setq lengths (nreverse lengths)
7648 typenums (nreverse typenums))
7649 (setq org-table-last-alignment typenums
7650 org-table-last-column-widths lengths)
7651 ;; Compute the formats needed for output of the table
7652 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7653 (while (setq l (pop lengths))
7654 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7655 (setq rfmt (concat rfmt (format rfmt1 ty l))
7656 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7657 (setq rfmt (concat rfmt "\n")
7658 hfmt (concat (substring hfmt 0 -1) "|\n"))
7659 ;; Produce the new table
7661 ;; (setq l (pop lines))
7663 ;; (setq new (concat new (apply 'format rfmt
7664 ;; (append (pop fields) emptystrings))))
7665 ;; (setq new (concat new hfmt))))
7666 (setq new (mapconcat
7668 (if l (apply 'format rfmt
7669 (append (pop fields) emptystrings))
7672 ;; Replace the old one
7673 (delete-region beg end)
7674 (move-marker end nil)
7675 (move-marker org-table-aligned-begin-marker (point))
7677 (move-marker org-table-aligned-end-marker (point))
7678 ;; Try to move to the old location (approximately)
7680 (set-window-start (selected-window) winstart 'noforce)
7681 (org-table-goto-column colpos)
7682 (setq org-table-may-need-update nil)
7683 (if (org-in-invisibility-spec-p '(org-table))
7684 (org-table-add-invisible-to-vertical-lines))
7687 (defun org-table-begin (&optional table-type)
7688 "Find the beginning of the table and return its position.
7689 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7691 (if (not (re-search-backward
7692 (if table-type org-table-any-border-regexp
7693 org-table-border-regexp)
7695 (error "Can't find beginning of table")
7696 (goto-char (match-beginning 0))
7697 (beginning-of-line 2)
7700 (defun org-table-end (&optional table-type)
7701 "Find the end of the table and return its position.
7702 With argument TABLE-TYPE, go to the end of a table.el-type table."
7704 (if (not (re-search-forward
7705 (if table-type org-table-any-border-regexp
7706 org-table-border-regexp)
7708 (goto-char (point-max))
7709 (goto-char (match-beginning 0)))
7712 (defun org-table-justify-field-maybe (&optional new)
7713 "Justify the current field, text to left, number to right.
7714 Optional argument NEW may specify text to replace the current field content."
7716 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7717 ((org-at-table-hline-p)
7718 ;; FIXME: I used to enforce realign here, but I think this is not needed.
7719 ;; (setq org-table-may-need-update t)
7722 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7724 (< (point) org-table-aligned-begin-marker)
7725 (>= (point) org-table-aligned-end-marker)))
7726 ;; This is not the same table, force a full re-align
7727 (setq org-table-may-need-update t))
7728 (t ;; realign the current field, based on previous full realign
7729 (let* ((pos (point)) s
7730 (col (org-table-current-column))
7731 (num (nth (1- col) org-table-last-alignment))
7734 (skip-chars-backward "^|\n")
7735 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7737 (setq s (match-string 1)
7739 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7740 e (not (= (match-beginning 2) (match-end 2))))
7741 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7742 l (if e "|" (setq org-table-may-need-update t) ""))
7745 (if (<= (length new) l)
7746 (setq n (format f new t t)) ;; FIXME: why t t?????
7747 (setq n (concat new "|") org-table-may-need-update t)))
7749 (let (org-table-may-need-update)
7750 (replace-match n))))
7751 (setq org-table-may-need-update t))
7752 (goto-char pos))))))
7754 (defun org-table-next-field ()
7755 "Go to the next field in the current table, creating new lines as needed.
7756 Before doing so, re-align the table if necessary."
7758 (org-table-maybe-eval-formula)
7759 (org-table-maybe-recalculate-line)
7760 (if (and org-table-automatic-realign
7761 org-table-may-need-update)
7763 (let ((end (org-table-end)))
7764 (if (org-at-table-hline-p)
7768 (re-search-forward "|" end)
7769 (if (looking-at "[ \t]*$")
7770 (re-search-forward "|" end))
7771 (if (and (looking-at "-")
7772 org-table-tab-jumps-over-hlines
7773 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7774 (goto-char (match-beginning 1)))
7775 (if (looking-at "-")
7777 (beginning-of-line 0)
7778 (org-table-insert-row 'below))
7779 (if (looking-at " ") (forward-char 1))))
7781 (org-table-insert-row 'below)))))
7783 (defun org-table-previous-field ()
7784 "Go to the previous field in the table.
7785 Before doing so, re-align the table if necessary."
7787 (org-table-justify-field-maybe)
7788 (org-table-maybe-recalculate-line)
7789 (if (and org-table-automatic-realign
7790 org-table-may-need-update)
7792 (if (org-at-table-hline-p)
7794 (re-search-backward "|" (org-table-begin))
7795 (re-search-backward "|" (org-table-begin))
7796 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7797 (re-search-backward "|" (org-table-begin)))
7798 (if (looking-at "| ?")
7799 (goto-char (match-end 0))))
7801 (defun org-table-next-row ()
7802 "Go to the next row (same column) in the current table.
7803 Before doing so, re-align the table if necessary."
7805 (org-table-maybe-eval-formula)
7806 (org-table-maybe-recalculate-line)
7807 (if (or (looking-at "[ \t]*$")
7808 (save-excursion (skip-chars-backward " \t") (bolp)))
7810 (if (and org-table-automatic-realign
7811 org-table-may-need-update)
7813 (let ((col (org-table-current-column)))
7814 (beginning-of-line 2)
7815 (if (or (not (org-at-table-p))
7816 (org-at-table-hline-p))
7818 (beginning-of-line 0)
7819 (org-table-insert-row 'below)))
7820 (org-table-goto-column col)
7821 (skip-chars-backward "^|\n\r")
7822 (if (looking-at " ") (forward-char 1)))))
7824 (defun org-table-copy-down (n)
7825 "Copy a field down in the current column.
7826 If the field at the cursor is empty, copy into it the content of the nearest
7827 non-empty field above. With argument N, use the Nth non-empty field.
7828 If the current field is not empty, it is copied down to the next row, and
7829 the cursor is moved with it. Therefore, repeating this command causes the
7830 column to be filled row-by-row.
7831 If the variable `org-table-copy-increment' is non-nil and the field is an
7832 integer, it will be incremented while copying."
7834 (let* ((colpos (org-table-current-column))
7835 (field (org-table-get-field))
7836 (non-empty (string-match "[^ \t]" field))
7837 (beg (org-table-begin))
7839 (org-table-check-inside-data-field)
7842 (setq txt (org-trim field))
7843 (org-table-next-row)
7844 (org-table-blank-field))
7848 (while (progn (beginning-of-line 1)
7849 (re-search-backward org-table-dataline-regexp
7851 (org-table-goto-column colpos t)
7852 (if (and (looking-at
7853 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7854 (= (setq n (1- n)) 0))
7855 (throw 'exit (match-string 1))))))))
7858 (if (and org-table-copy-increment
7859 (string-match "^[0-9]+$" txt))
7860 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7862 (org-table-maybe-recalculate-line)
7864 (error "No non-empty field found"))))
7866 (defun org-table-check-inside-data-field ()
7867 "Is point inside a table data field?
7868 I.e. not on a hline or before the first or after the last column?
7869 This actually throws an error, so it aborts the current command."
7870 (if (or (not (org-at-table-p))
7871 (= (org-table-current-column) 0)
7872 (org-at-table-hline-p)
7873 (looking-at "[ \t]*$"))
7874 (error "Not in table data field")))
7876 (defvar org-table-clip nil
7877 "Clipboard for table regions.")
7879 (defun org-table-blank-field ()
7880 "Blank the current table field or active region."
7882 (org-table-check-inside-data-field)
7883 (if (and (interactive-p) (org-region-active-p))
7884 (let (org-table-clip)
7885 (org-table-cut-region (region-beginning) (region-end)))
7886 (skip-chars-backward "^|")
7888 (if (looking-at "|[^|\n]+")
7889 (let* ((pos (match-beginning 0))
7890 (match (match-string 0))
7891 (len (length match)))
7892 (replace-match (concat "|" (make-string (1- len) ?\ )))
7893 (goto-char (+ 2 pos))
7894 (substring match 1)))))
7896 (defun org-table-get-field (&optional n replace)
7897 "Return the value of the field in column N of current row.
7898 N defaults to current field.
7899 If REPLACE is a string, replace field with this value. The return value
7900 is always the old value."
7901 (and n (org-table-goto-column n))
7902 (skip-chars-backward "^|\n")
7904 (if (looking-at "|[^|\r\n]*")
7905 (let* ((pos (match-beginning 0))
7906 (val (buffer-substring (1+ pos) (match-end 0))))
7908 (replace-match (concat "|" replace)))
7909 (goto-char (min (point-at-eol) (+ 2 pos)))
7911 (forward-char 1) ""))
7913 (defun org-table-current-column ()
7914 "Find out which column we are in.
7915 When called interactively, column is also displayed in echo area."
7917 (if (interactive-p) (org-table-check-inside-data-field))
7919 (let ((cnt 0) (pos (point)))
7920 (beginning-of-line 1)
7921 (while (search-forward "|" pos t)
7922 (setq cnt (1+ cnt)))
7923 (if (interactive-p) (message "This is table column %d" cnt))
7926 (defun org-table-goto-column (n &optional on-delim force)
7927 "Move the cursor to the Nth column in the current table line.
7928 With optional argument ON-DELIM, stop with point before the left delimiter
7930 If there are less than N fields, just go to after the last delimiter.
7931 However, when FORCE is non-nil, create new columns if necessary."
7933 (let ((pos (point-at-eol)))
7934 (beginning-of-line 1)
7936 (while (and (> (setq n (1- n)) -1)
7937 (or (search-forward "|" pos t)
7939 (progn (end-of-line 1)
7940 (skip-chars-backward "^|")
7942 ; (backward-char 2) t)))))
7943 (when (and force (not (looking-at ".*|")))
7944 (save-excursion (end-of-line 1) (insert " | ")))
7947 (if (looking-at " ") (forward-char 1))))))
7949 (defun org-at-table-p (&optional table-type)
7950 "Return t if the cursor is inside an org-type table.
7951 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7952 (if org-enable-table-editor
7954 (beginning-of-line 1)
7955 (looking-at (if table-type org-table-any-line-regexp
7956 org-table-line-regexp)))
7959 (defun org-at-table.el-p ()
7960 "Return t if and only if we are at a table.el table."
7961 (and (org-at-table-p 'any)
7963 (goto-char (org-table-begin 'any))
7964 (looking-at org-table1-hline-regexp))))
7966 (defun org-table-recognize-table.el ()
7967 "If there is a table.el table nearby, recognize it and move into it."
7968 (if org-table-tab-recognizes-table.el
7969 (if (org-at-table.el-p)
7971 (beginning-of-line 1)
7972 (if (looking-at org-table-dataline-regexp)
7974 (if (looking-at org-table1-hline-regexp)
7976 (beginning-of-line 2)
7977 (if (looking-at org-table-any-border-regexp)
7978 (beginning-of-line -1)))))
7979 (if (re-search-forward "|" (org-table-end t) t)
7982 (if (table--at-cell-p (point))
7984 (message "recognizing table.el table...")
7985 (table-recognize-table)
7986 (message "recognizing table.el table...done")))
7987 (error "This should not happen..."))
7992 (defun org-at-table-hline-p ()
7993 "Return t if the cursor is inside a hline in a table."
7994 (if org-enable-table-editor
7996 (beginning-of-line 1)
7997 (looking-at org-table-hline-regexp))
8000 (defun org-table-insert-column ()
8001 "Insert a new column into the table."
8003 (if (not (org-at-table-p))
8004 (error "Not at a table"))
8005 (org-table-find-dataline)
8006 (let* ((col (max 1 (org-table-current-column)))
8007 (beg (org-table-begin))
8008 (end (org-table-end))
8009 ;; Current cursor position
8010 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8013 (while (< (point) end)
8014 (if (org-at-table-hline-p)
8016 (org-table-goto-column col t)
8018 (beginning-of-line 2))
8019 (move-marker end nil)
8021 (org-table-goto-column colpos)
8023 (org-table-modify-formulas 'insert col)))
8025 (defun org-table-find-dataline ()
8026 "Find a dataline in the current table, which is needed for column commands."
8027 (if (and (org-at-table-p)
8028 (not (org-at-table-hline-p)))
8030 (let ((col (current-column))
8031 (end (org-table-end)))
8032 (move-to-column col)
8033 (while (and (< (point) end)
8034 (or (not (= (current-column) col))
8035 (org-at-table-hline-p)))
8036 (beginning-of-line 2)
8037 (move-to-column col))
8038 (if (and (org-at-table-p)
8039 (not (org-at-table-hline-p)))
8042 "Please position cursor in a data line for column operations")))))
8044 (defun org-table-delete-column ()
8045 "Delete a column into the table."
8047 (if (not (org-at-table-p))
8048 (error "Not at a table"))
8049 (org-table-find-dataline)
8050 (org-table-check-inside-data-field)
8051 (let* ((col (org-table-current-column))
8052 (beg (org-table-begin))
8053 (end (org-table-end))
8054 ;; Current cursor position
8055 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8058 (while (< (point) end)
8059 (if (org-at-table-hline-p)
8061 (org-table-goto-column col t)
8062 (and (looking-at "|[^|\n]+|")
8063 (replace-match "|")))
8064 (beginning-of-line 2))
8065 (move-marker end nil)
8067 (org-table-goto-column colpos)
8069 (org-table-modify-formulas 'remove col)))
8071 (defun org-table-move-column-right ()
8072 "Move column to the right."
8074 (org-table-move-column nil))
8075 (defun org-table-move-column-left ()
8076 "Move column to the left."
8078 (org-table-move-column 'left))
8080 (defun org-table-move-column (&optional left)
8081 "Move the current column to the right. With arg LEFT, move to the left."
8083 (if (not (org-at-table-p))
8084 (error "Not at a table"))
8085 (org-table-find-dataline)
8086 (org-table-check-inside-data-field)
8087 (let* ((col (org-table-current-column))
8088 (col1 (if left (1- col) col))
8089 (beg (org-table-begin))
8090 (end (org-table-end))
8091 ;; Current cursor position
8092 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8093 (colpos (if left (1- col) (1+ col))))
8094 (if (and left (= col 1))
8095 (error "Cannot move column further left"))
8096 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8097 (error "Cannot move column further right"))
8099 (while (< (point) end)
8100 (if (org-at-table-hline-p)
8102 (org-table-goto-column col1 t)
8103 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8104 (replace-match "|\\2|\\1|")))
8105 (beginning-of-line 2))
8106 (move-marker end nil)
8108 (org-table-goto-column colpos)
8110 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8112 (defun org-table-move-row-down ()
8113 "move table row down."
8115 (org-table-move-row nil))
8116 (defun org-table-move-row-up ()
8117 "move table row up."
8119 (org-table-move-row 'up))
8121 (defun org-table-move-row (&optional up)
8122 "Move the current table line down. With arg UP, move it up."
8124 (let ((col (current-column))
8128 (beginning-of-line tonew)
8129 (if (not (org-at-table-p))
8132 (error "Cannot move row further")))
8134 (beginning-of-line 1)
8136 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8137 (delete-region (point) (1+ (point-at-eol)))
8138 (beginning-of-line tonew)
8140 (beginning-of-line 0)
8141 (move-to-column col)))
8143 (defun org-table-insert-row (&optional arg)
8144 "Insert a new row above the current line into the table.
8145 With prefix ARG, insert below the current line."
8147 (if (not (org-at-table-p))
8148 (error "Not at a table"))
8149 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
8151 (if (string-match "^[ \t]*|-" line)
8152 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8153 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8154 ;; Fix the first field if necessary
8155 (setq new (concat new))
8156 (if (string-match "^[ \t]*| *[#$] *|" line)
8157 (setq new (replace-match (match-string 0 line) t t new)))
8158 (beginning-of-line (if arg 2 1))
8159 (let (org-table-may-need-update)
8160 (insert-before-markers new)
8161 (insert-before-markers "\n"))
8162 (beginning-of-line 0)
8163 (re-search-forward "| ?" (point-at-eol) t)
8164 (and org-table-may-need-update (org-table-align))))
8166 (defun org-table-insert-hline (&optional arg)
8167 "Insert a horizontal-line below the current line into the table.
8168 With prefix ARG, insert above the current line."
8170 (if (not (org-at-table-p))
8171 (error "Not at a table"))
8172 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
8173 (col (current-column))
8175 (if (string-match "^[ \t]*|-" line)
8177 (mapcar (lambda (x) (if (member x '(?| ?+))
8178 (prog1 (if start ?+ ?|) (setq start t))
8182 (mapcar (lambda (x) (if (equal x ?|)
8183 (prog1 (if start ?+ ?|) (setq start t))
8186 (beginning-of-line (if arg 1 2))
8187 (apply 'insert line)
8188 (if (equal (char-before (point)) ?+)
8189 (progn (backward-delete-char 1) (insert "|")))
8191 (beginning-of-line 0)
8192 (move-to-column col)))
8194 (defun org-table-kill-row ()
8195 "Delete the current row or horizontal line from the table."
8197 (if (not (org-at-table-p))
8198 (error "Not at a table"))
8199 (let ((col (current-column)))
8200 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8201 (if (not (org-at-table-p)) (beginning-of-line 0))
8202 (move-to-column col)))
8204 (defun org-table-sort-lines (beg end numericp)
8205 "Sort table lines in region.
8206 Point and mark define the first and last line to include. Both point and
8207 mark should be in the column that is used for sorting. For example, to
8208 sort according to column 3, put the mark in the first line to sort, in
8209 table column 3. Put point into the last line to be included in the sorting,
8210 also in table column 3. The command will prompt for the sorting method (n for
8211 numerical, a for alphanumeric)."
8212 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8213 (setq numericp (string-match "[nN]" numericp))
8214 (org-table-align) ;; Just to be safe
8215 (let* (bcol ecol cmp column lns)
8217 (org-table-check-inside-data-field)
8218 (setq column (org-table-current-column)
8219 beg (move-marker (make-marker) (point-at-bol)))
8221 (org-table-check-inside-data-field)
8222 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8225 (org-table-goto-column column)
8226 (skip-chars-backward "^|")
8227 (setq bcol (current-column))
8228 (org-table-goto-column (1+ column))
8229 (skip-chars-backward "^|")
8230 (setq ecol (1- (current-column)))
8231 (setq cmp (if numericp
8232 (lambda (a b) (< (car a) (car b)))
8233 (lambda (a b) (string< (car a) (car b)))))
8234 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8235 (split-string (buffer-substring beg end) "\n")))
8237 (setq lns (mapcar (lambda(x)
8238 (cons (string-to-number (car x)) (cdr x)))
8240 (delete-region beg end)
8241 (move-marker beg nil)
8242 (move-marker end nil)
8243 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8244 (message "%d lines sorted %s based on column %d"
8246 (if numericp "numerically" "alphabetically") column)))
8248 (defun org-table-cut-region (beg end)
8249 "Copy region in table to the clipboard and blank all relevant fields."
8251 (org-table-copy-region beg end 'cut))
8253 (defun org-table-copy-region (beg end &optional cut)
8254 "Copy rectangular region in table to clipboard.
8255 A special clipboard is used which can only be accessed
8256 with `org-table-paste-rectangle'"
8258 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8260 (rpl (if cut " " nil)))
8262 (org-table-check-inside-data-field)
8263 (setq l01 (count-lines (point-min) (point))
8264 c01 (org-table-current-column))
8266 (org-table-check-inside-data-field)
8267 (setq l02 (count-lines (point-min) (point))
8268 c02 (org-table-current-column))
8269 (setq l1 (min l01 l02) l2 (max l01 l02)
8270 c1 (min c01 c02) c2 (max c01 c02))
8274 (if (> l1 l2) (throw 'exit t))
8276 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8277 (setq cols nil ic1 c1 ic2 c2)
8278 (while (< ic1 (1+ ic2))
8279 (push (org-table-get-field ic1 rpl) cols)
8280 (setq ic1 (1+ ic1)))
8281 (push (nreverse cols) region)
8282 (setq l1 (1+ l1)))))
8283 (setq org-table-clip (nreverse region))
8284 (if cut (org-table-align))
8287 (defun org-table-paste-rectangle ()
8288 "Paste a rectangular region into a table.
8289 The upper right corner ends up in the current field. All involved fields
8290 will be overwritten. If the rectangle does not fit into the present table,
8291 the table is enlarged as needed. The process ignores horizontal separator
8294 (unless (and org-table-clip (listp org-table-clip))
8295 (error "First cut/copy a region to paste!"))
8296 (org-table-check-inside-data-field)
8297 (let* ((clip org-table-clip)
8298 (line (count-lines (point-min) (point)))
8299 (col (org-table-current-column))
8300 (org-enable-table-editor t)
8301 (org-table-automatic-realign nil)
8303 (while (setq cols (pop clip))
8304 (while (org-at-table-hline-p) (beginning-of-line 2))
8305 (if (not (org-at-table-p))
8306 (progn (end-of-line 0) (org-table-next-field)))
8308 (while (setq field (pop cols))
8309 (org-table-goto-column c nil 'force)
8310 (org-table-get-field nil field)
8312 (beginning-of-line 2))
8314 (org-table-goto-column col)
8317 (defun org-table-convert ()
8318 "Convert from `org-mode' table to table.el and back.
8319 Obviously, this only works within limits. When an Org-mode table is
8320 converted to table.el, all horizontal separator lines get lost, because
8321 table.el uses these as cell boundaries and has no notion of horizontal lines.
8322 A table.el table can be converted to an Org-mode table only if it does not
8323 do row or column spanning. Multiline cells will become multiple cells.
8324 Beware, Org-mode does not test if the table can be successfully converted - it
8325 blindly applies a recipe that works for simple tables."
8328 (if (org-at-table.el-p)
8329 ;; convert to Org-mode table
8330 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8331 (end (move-marker (make-marker) (org-table-end t))))
8332 (table-unrecognize-region beg end)
8334 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8337 (if (org-at-table-p)
8338 ;; convert to table.el table
8339 (let ((beg (move-marker (make-marker) (org-table-begin)))
8340 (end (move-marker (make-marker) (org-table-end))))
8341 ;; first, get rid of all horizontal lines
8343 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8345 ;; insert a hline before first
8347 (org-table-insert-hline 'above)
8348 ;; insert a hline after each line
8349 (while (progn (beginning-of-line 2) (< (point) end))
8350 (org-table-insert-hline))
8352 (setq end (move-marker end (org-table-end)))
8353 ;; replace "+" at beginning and ending of hlines
8354 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8355 (replace-match "\\1+-"))
8357 (while (re-search-forward "-|[ \t]*$" end t)
8358 (replace-match "-+"))
8361 (defun org-table-wrap-region (arg)
8362 "Wrap several fields in a column like a paragraph.
8363 This is useful if you'd like to spread the contents of a field over several
8364 lines, in order to keep the table compact.
8366 If there is an active region, and both point and mark are in the same column,
8367 the text in the column is wrapped to minimum width for the given number of
8368 lines. Generally, this makes the table more compact. A prefix ARG may be
8369 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8370 formats the selected text to two lines. If the region was longer than 2
8371 lines, the remaining lines remain empty. A negative prefix argument reduces
8372 the current number of lines by that amount. The wrapped text is pasted back
8373 into the table. If you formatted it to more lines than it was before, fields
8374 further down in the table get overwritten - so you might need to make space in
8377 If there is no region, the current field is split at the cursor position and
8378 the text fragment to the right of the cursor is prepended to the field one
8381 If there is no region, but you specify a prefix ARG, the current field gets
8382 blank, and the content is appended to the field above."
8384 (org-table-check-inside-data-field)
8385 (if (org-region-active-p)
8386 ;; There is a region: fill as a paragraph
8387 (let ((beg (region-beginning))
8389 (org-table-cut-region (region-beginning) (region-end))
8390 (if (> (length (car org-table-clip)) 1)
8391 (error "Region must be limited to single column"))
8392 (setq nlines (if arg
8394 (+ (length org-table-clip) arg)
8396 (length org-table-clip)))
8397 (setq org-table-clip
8398 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8401 (org-table-paste-rectangle))
8402 ;; No region, split the current field at point
8404 ;; combine with field above
8405 (let ((s (org-table-blank-field))
8406 (col (org-table-current-column)))
8407 (beginning-of-line 0)
8408 (while (org-at-table-hline-p) (beginning-of-line 0))
8409 (org-table-goto-column col)
8410 (skip-chars-forward "^|")
8411 (skip-chars-backward " ")
8412 (insert " " (org-trim s))
8415 (when (looking-at "\\([^|]+\\)+|")
8416 (let ((s (match-string 1)))
8417 (replace-match " |")
8418 (goto-char (match-beginning 0))
8419 (org-table-next-row)
8420 (insert (org-trim s) " ")
8421 (org-table-align))))))
8424 "Remove whitespace at beginning and end of string."
8425 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8426 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8429 (defun org-wrap (string &optional width lines)
8430 "Wrap string to either a number of lines, or a width in characters.
8431 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8432 that costs. If there is a word longer than WIDTH, the text is actually
8433 wrapped to the length of that word.
8434 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8435 many lines, whatever width that takes.
8436 The return value is a list of lines, without newlines at the end."
8437 (let* ((words (org-split-string string "[ \t\n]+"))
8438 (maxword (apply 'max (mapcar 'length words)))
8441 (org-do-wrap words (max maxword width)))
8444 (setq ll (org-do-wrap words maxword))
8445 (if (<= (length ll) lines)
8448 (while (> (length ll) lines)
8450 (setq ll (org-do-wrap words w)))
8452 (t (error "Cannot wrap this")))))
8455 (defun org-do-wrap (words width)
8456 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8459 (setq line (pop words))
8460 (while (and words (< (+ (length line) (length (car words))) width))
8461 (setq line (concat line " " (pop words))))
8462 (setq lines (push line lines)))
8465 ;; FIXME: I think I can make this more efficient
8466 (defun org-split-string (string &optional separators)
8467 "Splits STRING into substrings at SEPARATORS.
8468 No empty strings are returned if there are matches at the beginning
8470 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8474 (while (and (string-match rexp string
8476 (= start (match-beginning 0))
8477 (< start (length string)))
8479 (< (match-beginning 0) (length string)))
8481 (or (eq (match-beginning 0) 0)
8482 (and (eq (match-beginning 0) (match-end 0))
8483 (eq (match-beginning 0) start))
8485 (cons (substring string start (match-beginning 0))
8487 (setq start (match-end 0)))
8488 (or (eq start (length string))
8490 (cons (substring string start)
8494 (defun org-table-add-invisible-to-vertical-lines ()
8495 "Add an `invisible' property to vertical lines of current table."
8497 (let* ((beg (org-table-begin))
8498 (end (org-table-end))
8502 (while (< (point) end)
8503 (setq end1 (point-at-eol))
8504 (if (looking-at org-table-dataline-regexp)
8505 (while (re-search-forward "|" end1 t)
8506 (add-text-properties (1- (point)) (point)
8507 '(invisible org-table)))
8508 (while (re-search-forward "[+|]" end1 t)
8509 (add-text-properties (1- (point)) (point)
8510 '(invisible org-table))))
8511 (beginning-of-line 2)))))
8513 (defun org-table-toggle-vline-visibility (&optional arg)
8514 "Toggle the visibility of table vertical lines.
8515 The effect is immediate and on all tables in the file.
8516 With prefix ARG, make lines invisible when ARG is positive, make lines
8517 visible when ARG is not positive"
8520 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
8521 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
8522 (t (if (org-in-invisibility-spec-p '(org-table))
8525 (if (eq action 'off)
8527 (org-remove-from-invisibility-spec '(org-table))
8528 (org-table-map-tables 'org-table-align)
8529 (message "Vertical table lines visible")
8530 (if (org-at-table-p)
8532 (org-add-to-invisibility-spec '(org-table))
8533 (org-table-map-tables 'org-table-align)
8534 (message "Vertical table lines invisible"))
8535 (redraw-frame (selected-frame))))
8537 (defun org-table-map-tables (function)
8538 "Apply FUNCTION to the start of all tables in the buffer."
8542 (goto-char (point-min))
8543 (while (re-search-forward org-table-any-line-regexp nil t)
8544 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8545 (beginning-of-line 1)
8546 (if (looking-at org-table-line-regexp)
8547 (save-excursion (funcall function)))
8548 (re-search-forward org-table-any-border-regexp nil 1)))))
8550 (defun org-table-sum (&optional beg end nlast)
8551 "Sum numbers in region of current table column.
8552 The result will be displayed in the echo area, and will be available
8553 as kill to be inserted with \\[yank].
8555 If there is an active region, it is interpreted as a rectangle and all
8556 numbers in that rectangle will be summed. If there is no active
8557 region and point is located in a table column, sum all numbers in that
8560 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8561 numbers are assumed to be times as well (in decimal hours) and the
8562 numbers are added as such.
8564 If NLAST is a number, only the NLAST fields will actually be summed."
8567 (let (col (timecnt 0) diff h m s org-table-clip)
8569 ((and beg end)) ; beg and end given explicitly
8570 ((org-region-active-p)
8571 (setq beg (region-beginning) end (region-end)))
8573 (setq col (org-table-current-column))
8574 (goto-char (org-table-begin))
8575 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8576 (error "No table data"))
8577 (org-table-goto-column col)
8578 ;not needed? (skip-chars-backward "^|")
8580 (goto-char (org-table-end))
8581 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8582 (error "No table data"))
8583 (org-table-goto-column col)
8584 ;not needed? (skip-chars-forward "^|")
8585 (setq end (point))))
8586 (let* ((items (apply 'append (org-table-copy-region beg end)))
8587 (items1 (cond ((not nlast) items)
8588 ((>= nlast (length items)) items)
8589 (t (setq items (reverse items))
8590 (setcdr (nthcdr (1- nlast) items) nil)
8592 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8594 (res (apply '+ numbers))
8595 (sres (if (= timecnt 0)
8597 (setq diff (* 3600 res)
8598 h (floor (/ diff 3600)) diff (mod diff 3600)
8599 m (floor (/ diff 60)) diff (mod diff 60)
8601 (format "%d:%02d:%02d" h m s))))
8605 (substitute-command-keys
8606 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8607 (length numbers) sres))))
8610 (defun org-table-get-number-for-summing (s)
8612 (if (string-match "^ *|? *" s)
8613 (setq s (replace-match "" nil nil s)))
8614 (if (string-match " *|? *$" s)
8615 (setq s (replace-match "" nil nil s)))
8616 (setq n (string-to-number s))
8618 ((and (string-match "0" s)
8619 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8620 ((string-match "\\`[ \t]+\\'" s) nil)
8621 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8622 (let ((h (string-to-number (or (match-string 1 s) "0")))
8623 (m (string-to-number (or (match-string 2 s) "0")))
8624 (s (string-to-number (or (match-string 4 s) "0"))))
8625 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
8626 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8630 (defun org-table-get-vertical-vector (desc &optional tbeg col)
8631 "Get a calc vector from a column, accorting to desctiptor DESC.
8632 Optional arguments TBEG and COL can give the beginning of the table and
8633 the current column, to avoid unnecessary parsing."
8635 (or tbeg (setq tbeg (org-table-begin)))
8636 (or col (setq col (org-table-current-column)))
8637 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
8639 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
8640 (setq n1 (- (match-end 1) (match-beginning 1)))
8641 (if (match-beginning 3)
8642 (setq n2 (- (match-end 2) (match-beginning 3))))
8643 (setq n (if n2 (max n1 n2) n1))
8644 (setq n1 (if n2 (min n1 n2)))
8646 (while (and (> nn 0)
8647 (re-search-backward org-table-hline-regexp tbeg t))
8648 (push (org-current-line) hline-list)
8650 (setq hline-list (nreverse hline-list))
8651 (goto-line (nth (1- n) hline-list))
8652 (when (re-search-forward org-table-dataline-regexp)
8653 (org-table-goto-column col)
8655 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
8656 (when (re-search-backward org-table-dataline-regexp)
8657 (org-table-goto-column col)
8659 (setq l (apply 'append (org-table-copy-region beg end)))
8660 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
8661 (if (equal x "") "0" x))
8663 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
8664 (setq n1 (string-to-number (match-string 1 desc))
8665 n2 (string-to-number (match-string 2 desc)))
8666 (beginning-of-line 1)
8668 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
8669 (org-table-goto-column col)
8670 (setq beg (point))))
8671 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
8672 (org-table-goto-column col)
8674 (setq l (apply 'append (org-table-copy-region beg end)))
8675 (concat "[" (mapconcat
8676 (lambda (x) (setq x (org-trim x))
8677 (if (equal x "") "0" x))
8679 ((string-match "\\([0-9]+\\)" desc)
8680 (beginning-of-line 1)
8681 (when (re-search-backward org-table-dataline-regexp tbeg t
8682 (string-to-number (match-string 0 desc)))
8683 (org-table-goto-column col)
8684 (org-trim (org-table-get-field))))))))
8686 (defvar org-table-formula-history nil)
8688 (defvar org-table-column-names nil
8689 "Alist with column names, derived from the `!' line.")
8690 (defvar org-table-column-name-regexp nil
8691 "Regular expression matching the current column names.")
8692 (defvar org-table-local-parameters nil
8693 "Alist with parameter names, derived from the `$' line.")
8694 (defvar org-table-named-field-locations nil
8695 "Alist with locations of named fields.")
8697 (defun org-table-get-formula (&optional equation named)
8698 "Read a formula from the minibuffer, offer stored formula as default."
8699 (let* ((name (car (rassoc (list (org-current-line)
8700 (org-table-current-column))
8701 org-table-named-field-locations)))
8704 (error "Not in a named field"))
8705 (int-to-string (org-table-current-column))))
8706 (dummy (and name (not named)
8707 (not (y-or-n-p "Replace named-field formula with column equation? " ))
8709 (org-table-may-need-update nil)
8710 (stored-list (org-table-get-stored-formulas))
8711 (stored (cdr (assoc scol stored-list)))
8713 ((and stored equation (string-match "^ *=? *$" equation))
8718 (format "%s formula $%s=" (if named "Field" "Column") scol)
8719 (or stored "") 'org-table-formula-history
8723 (when (not (string-match "\\S-" eq))
8725 (setq stored-list (delq (assoc scol stored-list) stored-list))
8726 (org-table-store-formulas stored-list)
8727 (error "Formula removed"))
8728 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8729 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8730 (if (and name (not named))
8731 ;; We set the column equation, delete the named one.
8732 (setq stored-list (delq (assoc name stored-list) stored-list)
8735 (setcdr (assoc scol stored-list) eq)
8736 (setq stored-list (cons (cons scol eq) stored-list)))
8737 (if (or mustsave (not (equal stored eq)))
8738 (org-table-store-formulas stored-list))
8741 (defun org-table-store-formulas (alist)
8742 "Store the list of formulas below the current table."
8743 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
8745 (goto-char (org-table-end))
8746 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
8747 (delete-region (point) (match-end 0)))
8749 (mapconcat (lambda (x)
8750 (concat "$" (car x) "=" (cdr x)))
8754 (defun org-table-get-stored-formulas ()
8755 "Return an alist with the t=stored formulas directly after current table."
8757 (let (scol eq eq-alist strings string seen)
8759 (goto-char (org-table-end))
8760 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8761 (setq strings (org-split-string (match-string 2) " *:: *"))
8762 (while (setq string (pop strings))
8763 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
8764 (setq scol (match-string 1 string)
8765 eq (match-string 2 string)
8766 eq-alist (cons (cons scol eq) eq-alist))
8767 (if (member scol seen)
8768 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8769 (push scol seen))))))
8770 (nreverse eq-alist)))
8772 (defun org-table-modify-formulas (action &rest columns)
8773 "Modify the formulas stored below the current table.
8774 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
8775 expected, for the other action only a single column number is needed."
8776 (let ((list (org-table-get-stored-formulas))
8777 (nmax (length (org-split-string
8778 (buffer-substring (point-at-bol) (point-at-eol))
8780 col col1 col2 scol si sc1 sc2)
8782 ((null list)) ; No action needed if there are no stored formulas
8783 ((eq action 'remove)
8784 (setq col (car columns)
8785 scol (int-to-string col))
8786 (org-table-replace-in-formulas list scol "INVALID")
8787 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
8788 (loop for i from (1+ col) upto nmax by 1 do
8789 (setq si (int-to-string i))
8790 (org-table-replace-in-formulas list si (int-to-string (1- i)))
8791 (if (assoc si list) (setcar (assoc si list)
8792 (int-to-string (1- i))))))
8793 ((eq action 'insert)
8794 (setq col (car columns))
8795 (loop for i from nmax downto col by 1 do
8796 (setq si (int-to-string i))
8797 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
8798 (if (assoc si list) (setcar (assoc si list)
8799 (int-to-string (1+ i))))))
8801 (setq col1 (car columns) col2 (nth 1 columns)
8802 sc1 (int-to-string col1) sc2 (int-to-string col2))
8803 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
8804 (org-table-replace-in-formulas list sc1 "ZqZ")
8805 (org-table-replace-in-formulas list sc2 sc1)
8806 (org-table-replace-in-formulas list "ZqZ" sc2)
8807 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
8808 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
8809 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
8810 (t (error "Invalid action in `org-table-modify-formulas'")))
8811 (if list (org-table-store-formulas list))))
8813 (defun org-table-replace-in-formulas (list s1 s2)
8815 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
8816 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
8817 re (concat (regexp-quote s1) "\\>"))
8818 (while (setq elt (pop list))
8820 (while (string-match re s)
8821 (setq s (replace-match s2 t t s)))
8824 (defun org-table-get-specials ()
8825 "Get the column nmaes and local parameters for this table."
8827 (let ((beg (org-table-begin)) (end (org-table-end))
8828 names name fields fields1 field cnt c v line col)
8829 (setq org-table-column-names nil
8830 org-table-local-parameters nil
8831 org-table-named-field-locations nil)
8833 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8834 (setq names (org-split-string (match-string 1) " *| *")
8836 (while (setq name (pop names))
8838 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8839 (push (cons name (int-to-string cnt)) org-table-column-names))))
8840 (setq org-table-column-names (nreverse org-table-column-names))
8841 (setq org-table-column-name-regexp
8842 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8844 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8845 (setq fields (org-split-string (match-string 1) " *| *"))
8846 (while (setq field (pop fields))
8847 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8848 (push (cons (match-string 1 field) (match-string 2 field))
8849 org-table-local-parameters))))
8851 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8852 (setq c (match-string 1)
8853 fields (org-split-string (match-string 2) " *| *"))
8855 (beginning-of-line (if (equal c "_") 2 0))
8856 (setq line (org-current-line) col 1)
8857 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8858 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8859 (while (and fields1 (setq field (pop fields)))
8860 (setq v (pop fields1) col (1+ col))
8861 (when (and (stringp field) (stringp v)
8862 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8863 (push (cons field v) org-table-local-parameters)
8864 (push (list field line col) org-table-named-field-locations)))))))
8866 (defun org-this-word ()
8867 ;; Get the current word
8869 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
8870 (end (progn (skip-chars-forward "^ \t\n") (point))))
8871 (buffer-substring-no-properties beg end))))
8873 (defun org-table-maybe-eval-formula ()
8874 "Check if the current field starts with \"=\" or \":=\".
8875 If yes, store the formula and apply it."
8876 ;; We already know we are in a table. Get field will only return a formula
8877 ;; when appropriate. It might return a separator line, but no problem.
8878 (when org-table-formula-evaluate-inline
8879 (let* ((field (org-trim (or (org-table-get-field) "")))
8881 (when (string-match "^:?=\\(.*\\)" field)
8882 (setq named (equal (string-to-char field) ?:)
8883 eq (match-string 1 field))
8884 (if (fboundp 'calc-eval)
8885 (org-table-eval-formula (if named '(4) nil) eq))))))
8887 (defvar org-recalc-commands nil
8888 "List of commands triggering the reccalculation of a line.
8889 Will be filled automatically during use.")
8891 (defvar org-recalc-marks
8892 '((" " . "Unmarked: no special line, no automatic recalculation")
8893 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8894 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8895 ("!" . "Column name definition line. Reference in formula as $name.")
8896 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8897 ("_" . "Names for values in row below this one.")
8898 ("^" . "Names for values in row above this one.")))
8900 (defun org-table-rotate-recalc-marks (&optional newchar)
8901 "Rotate the recalculation mark in the first column.
8902 If in any row, the first field is not consistent with a mark,
8903 insert a new column for the makers.
8904 When there is an active region, change all the lines in the region,
8905 after prompting for the marking character.
8906 After each change, a message will be displayed indication the meaning
8909 (unless (org-at-table-p) (error "Not at a table"))
8910 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8911 (beg (org-table-begin))
8912 (end (org-table-end))
8913 (l (org-current-line))
8914 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8915 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8919 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8920 (col (org-table-current-column))
8921 (forcenew (car (assoc newchar org-recalc-marks)))
8924 (message "Change region to what mark? Type # * ! $ or SPC: ")
8925 (setq newchar (char-to-string (read-char-exclusive))
8926 forcenew (car (assoc newchar org-recalc-marks))))
8927 (if (and newchar (not forcenew))
8928 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8930 (if l1 (goto-line l1))
8932 (beginning-of-line 1)
8933 (unless (looking-at org-table-dataline-regexp)
8934 (error "Not at a table data line")))
8936 (org-table-goto-column 1)
8937 (org-table-insert-column)
8938 (org-table-goto-column (1+ col)))
8939 (setq epos (point-at-eol))
8941 (beginning-of-line 1)
8942 (org-table-get-field
8943 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8945 (setq new (or forcenew
8946 (cadr (member (match-string 1) marks))))
8952 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8953 (and (looking-at org-table-dataline-regexp)
8954 (org-table-get-field 1 (concat " " new " "))))
8956 (if (not (= epos (point-at-eol))) (org-table-align))
8958 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8960 (defun org-table-maybe-recalculate-line ()
8961 "Recompute the current line if marked for it, and if we haven't just done it."
8963 (and org-table-allow-automatic-line-recalculation
8964 (not (and (memq last-command org-recalc-commands)
8965 (equal org-last-recalc-line (org-current-line))))
8966 (save-excursion (beginning-of-line 1)
8967 (looking-at org-table-auto-recalculate-regexp))
8968 (fboundp 'calc-eval)
8969 (org-table-recalculate) t))
8971 (defvar org-table-formula-debug nil
8972 "Non-nil means, debug table formulas.
8973 When nil, simply write \"#ERROR\" in corrupted fields.")
8976 (defsubst org-set-calc-mode (var &optional value)
8978 (setq var (assoc var '(("D" calc-angle-mode deg)
8979 ("R" calc-angle-mode rad)
8980 ("F" calc-prefer-frac t)
8981 ("S" calc-symbolic-mode t)))
8982 value (nth 2 var) var (nth 1 var)))
8983 (if (memq var modes)
8984 (setcar (cdr (memq var modes)) value)
8985 (cons var (cons value modes)))
8988 (defun org-table-eval-formula (&optional arg equation
8989 suppress-align suppress-const
8991 "Replace the table field value at the cursor by the result of a calculation.
8993 This function makes use of Dave Gillespie's calc package, in my view the
8994 most exciting program ever written for GNU Emacs. So you need to have calc
8995 installed in order to use this function.
8997 In a table, this command replaces the value in the current field with the
8998 result of a formula. It also installes the formula as the \"current\" column
8999 formula, by storing it in a special line below the table. When called
9000 with a `C-u' prefix, the current field must ba a named field, and the
9001 formula is installed as valid in only this specific field.
9003 When called, the command first prompts for a formula, which is read in
9004 the minibuffer. Previously entered formulas are available through the
9005 history list, and the last used formula is offered as a default.
9006 These stored formulas are adapted correctly when moving, inserting, or
9007 deleting columns with the corresponding commands.
9009 The formula can be any algebraic expression understood by the calc package.
9010 For details, see the Org-mode manual.
9012 This function can also be called from Lisp programs and offers
9013 additional Arguments: EQUATION can be the formula to apply. If this
9014 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9015 used to speed-up recursive calls by by-passing unnecessary aligns.
9016 SUPPRESS-CONST suppresses the interpretation of constants in the
9017 formula, assuming that this has been done already outside the fuction.
9018 SUPPRESS-STORE means the formula should not be stored, either because
9019 it is already stored, or because it is a modified equation that should
9020 not overwrite the stored one."
9023 (org-table-check-inside-data-field)
9024 (org-table-get-specials)
9026 (ndown (if (integerp arg) arg 1))
9027 (org-table-automatic-realign nil)
9028 (case-fold-search nil)
9030 (formula (if (and equation suppress-store)
9032 (org-table-get-formula equation (equal arg '(4)))))
9033 (n0 (org-table-current-column))
9034 (modes (copy-sequence org-calc-default-modes))
9035 n form fmt x ev orig c)
9036 ;; Parse the format string. Since we have a lot of modes, this is
9037 ;; a lot of work. However, I think calc still uses most of the time.
9038 (if (string-match ";" formula)
9039 (let ((tmp (org-split-string formula ";")))
9040 (setq formula (car tmp)
9041 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9043 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9044 (setq c (string-to-char (match-string 1 fmt))
9045 n (string-to-number (or (match-string 1 fmt) "")))
9046 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9047 (setq modes (org-set-calc-mode
9049 (list (cdr (assoc c '((?n. float) (?f. fix)
9050 (?s. sci) (?e. eng))))
9052 (setq fmt (replace-match "" t t fmt)))
9053 (while (string-match "[DRFS]" fmt)
9054 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9055 (setq fmt (replace-match "" t t fmt)))
9056 (unless (string-match "\\S-" fmt)
9058 (if (and (not suppress-const) org-table-formula-use-constants)
9059 (setq formula (org-table-formula-substitute-names formula)))
9060 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9062 (setq fields (org-split-string
9064 (point-at-bol) (point-at-eol)) " *| *"))
9065 (if org-table-formula-numbers-only
9066 (setq fields (mapcar
9067 (lambda (x) (number-to-string (string-to-number x)))
9069 (setq ndown (1- ndown))
9070 (setq form (copy-sequence formula))
9071 ;; Insert the references to fields in same row
9072 (while (string-match "\\$\\([0-9]+\\)?" form)
9073 (setq n (if (match-beginning 1)
9074 (string-to-number (match-string 1 form))
9076 x (nth (1- n) fields))
9077 (unless x (error "Invalid field specifier \"%s\""
9078 (match-string 0 form)))
9079 (if (equal x "") (setq x "0"))
9080 (setq form (replace-match (concat "(" x ")") t t form)))
9081 ;; Insert ranges in current column
9082 (while (string-match "\\&[-I0-9]+" form)
9083 (setq form (replace-match
9085 (org-table-get-vertical-vector (match-string 0 form)
9088 (setq ev (calc-eval (cons form modes)
9089 (if org-table-formula-numbers-only 'num)))
9091 (when org-table-formula-debug
9092 (with-output-to-temp-buffer "*Help*"
9093 (princ (format "Substitution history of formula
9096 $1-> %s\n" orig formula form))
9098 (princ (format " %s^\nError: %s"
9099 (make-string (car ev) ?\-) (nth 1 ev)))
9100 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9102 (if fmt (format fmt (string-to-number ev)) ev)))))
9103 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9104 (unless (and (interactive-p) (not ndown))
9105 (unless (let (inhibit-redisplay)
9106 (y-or-n-p "Debugging Formula. Continue to next? "))
9109 (delete-window (get-buffer-window "*Help*"))
9111 (if (listp ev) (setq fmt nil ev "#ERROR"))
9112 (org-table-justify-field-maybe
9113 (if fmt (format fmt (string-to-number ev)) ev))
9114 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9115 (call-interactively 'org-return)
9117 (and down (org-table-maybe-recalculate-line))
9118 (or suppress-align (and org-table-may-need-update
9119 (org-table-align)))))
9121 (defun org-table-recalculate (&optional all noalign)
9122 "Recalculate the current table line by applying all stored formulas."
9124 (or (memq this-command org-recalc-commands)
9125 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9126 (unless (org-at-table-p) (error "Not at a table"))
9127 (org-table-get-specials)
9128 (let* ((eqlist (sort (org-table-get-stored-formulas)
9129 (lambda (a b) (string< (car a) (car b)))))
9130 (inhibit-redisplay t)
9131 (line-re org-table-dataline-regexp)
9132 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9133 (thiscol (org-table-current-column))
9134 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9135 ;; Insert constants in all formulas
9138 (setcdr x (org-table-formula-substitute-names (cdr x)))
9141 ;; Split the equation list
9142 (while (setq eq (pop eqlist))
9143 (if (<= (string-to-char (car eq)) ?9)
9146 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9149 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9150 (goto-char (setq beg (org-table-begin)))
9151 (if (re-search-forward org-table-calculate-mark-regexp end t)
9152 ;; This is a table with marked lines, only compute selected lines
9153 (setq line-re org-table-recalculate-regexp)
9154 ;; Move forward to the first non-header line
9155 (if (and (re-search-forward org-table-dataline-regexp end t)
9156 (re-search-forward org-table-hline-regexp end t)
9157 (re-search-forward org-table-dataline-regexp end t))
9158 (setq beg (match-beginning 0))
9159 nil))) ;; just leave beg where it is
9160 (setq beg (point-at-bol)
9161 end (move-marker (make-marker) (1+ (point-at-eol)))))
9163 (and all (message "Re-applying formulas to full table..."))
9164 (while (re-search-forward line-re end t)
9165 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9166 ;; Unprotected line, recalculate
9167 (and all (message "Re-applying formulas to full table...(line %d)"
9168 (setq cnt (1+ cnt))))
9169 (setq org-last-recalc-line (org-current-line))
9171 (while (setq entry (pop eql))
9172 (goto-line org-last-recalc-line)
9173 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9174 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9175 (goto-line thisline)
9176 (org-table-goto-column thiscol)
9177 (or noalign (and org-table-may-need-update (org-table-align))
9178 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9179 ;; Now do the names fields
9180 (while (setq eq (pop eqlname))
9182 a (assoc name org-table-named-field-locations))
9184 (message "Re-applying formula to named field: %s" name)
9185 (goto-line (nth 1 a))
9186 (org-table-goto-column (nth 2 a))
9187 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9188 ;; back to initial position
9189 (goto-line thisline)
9190 (org-table-goto-column thiscol)
9191 (or noalign (and org-table-may-need-update (org-table-align))
9192 (and all (message "Re-applying formulas...done")))))
9194 (defun org-table-formula-substitute-names (f)
9195 "Replace $const with values in string F."
9196 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9197 ;; First, check for column names
9198 (while (setq start (string-match org-table-column-name-regexp f start))
9199 (setq start (1+ start))
9200 (setq a (assoc (match-string 1 f) org-table-column-names))
9201 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9202 ;; Expand ranges to vectors
9203 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9204 (setq n1 (string-to-number (match-string 1 f))
9205 n2 (string-to-number (match-string 2 f))
9206 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9207 s (concat "[($" (number-to-string (1- nn1)) ")"))
9208 (loop for i from nn1 upto nn2 do
9209 (setq s (concat s ",($" (int-to-string i) ")")))
9210 (setq s (concat s "]"))
9211 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9212 (setq f (replace-match s t t f)))
9213 ;; Parameters and constants
9215 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9216 (setq start (1+ start))
9217 (if (setq a (save-match-data
9218 (org-table-get-constant (match-string 1 f))))
9219 (setq f (replace-match (concat "(" a ")") t t f))))
9220 (if org-table-formula-debug
9221 (put-text-property 0 (length f) :orig-formula f1 f))
9224 (defun org-table-get-constant (const)
9225 "Find the value for a parameter or constant in a formula.
9226 Parameters get priority."
9227 (or (cdr (assoc const org-table-local-parameters))
9228 (cdr (assoc const org-table-formula-constants))
9229 (and (fboundp 'constants-get) (constants-get const))
9232 (defvar org-edit-formulas-map (make-sparse-keymap))
9233 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9234 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9235 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9238 (defvar org-window-configuration)
9240 (defun org-table-edit-formulas ()
9241 "Edit the formulas of the current table in a separate buffer."
9243 (unless (org-at-table-p)
9244 (error "Not at a table"))
9245 (org-table-get-specials)
9246 (let ((eql (org-table-get-stored-formulas))
9247 (pos (move-marker (make-marker) (point)))
9248 (wc (current-window-configuration))
9250 (switch-to-buffer-other-window "*Edit Formulas*")
9253 (set (make-local-variable 'org-pos) pos)
9254 (set (make-local-variable 'org-window-configuration) wc)
9255 (use-local-map org-edit-formulas-map)
9256 (setq s "# Edit formulas and finish with `C-c C-c'.
9257 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9258 # Use `C-c ?' to get information about $name at point.
9259 # To cancel editing, press `C-c C-q'.\n")
9260 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9262 (while (setq entry (pop eql))
9263 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9264 (setq s (format "# Named formula, referring to column %d in line %d\n"
9265 (nth 2 loc) (nth 1 loc)))
9266 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9268 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9269 (remove-text-properties 0 (length s) '(face nil) s)
9271 (goto-char (point-min))
9272 (message "Edit formulas and finish with `C-c C-c'.")))
9274 (defun org-show-variable ()
9275 "Show the location/value of the $ expression at point."
9277 (let (var (pos org-pos) (win (selected-window)) e)
9279 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9280 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9281 (setq var (match-string 1))
9282 (error "No variable at point")))
9284 ((setq e (assoc var org-table-named-field-locations))
9285 (switch-to-buffer-other-window (marker-buffer pos))
9286 (goto-line (nth 1 e))
9287 (org-table-goto-column (nth 2 e))
9289 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9290 ((setq e (assoc var org-table-column-names))
9291 (switch-to-buffer-other-window (marker-buffer pos))
9293 (goto-char (org-table-begin))
9294 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9297 (goto-char (match-beginning 1))
9298 (message "Named column (column %s)" (cdr e)))
9299 (error "Column name not found"))
9300 (select-window win))
9301 ((string-match "^[0-9]$" var)
9303 (switch-to-buffer-other-window (marker-buffer pos))
9305 (goto-char (org-table-begin))
9307 (if (re-search-forward org-table-dataline-regexp
9310 (goto-char (match-beginning 0))
9311 (org-table-goto-column (string-to-number var))
9312 (message "Column %s" var))
9313 (error "Column name not found"))
9314 (select-window win))
9315 ((setq e (assoc var org-table-local-parameters))
9316 (switch-to-buffer-other-window (marker-buffer pos))
9318 (goto-char (org-table-begin))
9319 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9321 (goto-char (match-beginning 1))
9322 (message "Local parameter."))
9323 (error "Parameter not found"))
9324 (select-window win))
9327 ((setq e (assoc var org-table-formula-constants))
9328 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9329 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9330 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9331 (t (error "Undefined name $%s" var)))))))
9333 (defun org-finish-edit-formulas (&optional arg)
9334 "Parse the buffer for formula definitions and install them.
9335 With prefix ARG, apply the new formulas to the table."
9337 (let ((pos org-pos) eql)
9338 (goto-char (point-min))
9339 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9340 (push (cons (match-string 1) (match-string 2)) eql))
9341 (set-window-configuration org-window-configuration)
9342 (select-window (get-buffer-window (marker-buffer pos)))
9344 (unless (org-at-table-p)
9345 (error "Lost table position - cannot install formulae"))
9346 (org-table-store-formulas eql)
9347 (move-marker pos nil)
9348 (kill-buffer "*Edit Formulas*")
9350 (org-table-recalculate 'all)
9351 (message "New formulas installed - press C-u C-c C-c to apply."))))
9353 (defun org-abort-edit-formulas ()
9354 "Abort editing formulas, without installing the changes."
9356 (let ((pos org-pos))
9357 (set-window-configuration org-window-configuration)
9358 (select-window (get-buffer-window (marker-buffer pos)))
9360 (message "Formula editing aborted without installing changes")))
9362 ;;; The orgtbl minor mode
9364 ;; Define a minor mode which can be used in other modes in order to
9365 ;; integrate the org-mode table editor.
9367 ;; This is really a hack, because the org-mode table editor uses several
9368 ;; keys which normally belong to the major mode, for example the TAB and
9369 ;; RET keys. Here is how it works: The minor mode defines all the keys
9370 ;; necessary to operate the table editor, but wraps the commands into a
9371 ;; function which tests if the cursor is currently inside a table. If that
9372 ;; is the case, the table editor command is executed. However, when any of
9373 ;; those keys is used outside a table, the function uses `key-binding' to
9374 ;; look up if the key has an associated command in another currently active
9375 ;; keymap (minor modes, major mode, global), and executes that command.
9376 ;; There might be problems if any of the keys used by the table editor is
9377 ;; otherwise used as a prefix key.
9379 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9380 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9381 ;; addresses this by checking explicitly for both bindings.
9383 ;; The optimized version (see variable `orgtbl-optimized') takes over
9384 ;; all keys which are bound to `self-insert-command' in the *global map*.
9385 ;; Some modes bind other commands to simple characters, for example
9386 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9387 ;; active, this binding is ignored inside tables and replaced with a
9388 ;; modified self-insert.
9390 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9391 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9392 In the optimized version, the table editor takes over all simple keys that
9393 normally just insert a character. In tables, the characters are inserted
9394 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9395 for empty fields). Outside tables, the correct binding of the keys is
9398 The default for this option is t if the optimized version is also used in
9399 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9400 this variable requires a restart of Emacs to become effective."
9404 (defvar orgtbl-mode nil
9405 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9406 table editor in arbitrary modes.")
9407 (make-variable-buffer-local 'orgtbl-mode)
9409 (defvar orgtbl-mode-map (make-keymap)
9410 "Keymap for `orgtbl-mode'.")
9413 (defun turn-on-orgtbl ()
9414 "Unconditionally turn on `orgtbl-mode'."
9418 (defun orgtbl-mode (&optional arg)
9419 "The `org-mode' table editor as a minor mode for use in other modes."
9421 (if (eq major-mode 'org-mode)
9422 ;; Exit without error, in case some hook functions calls this
9423 ;; by accident in org-mode.
9424 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9426 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9429 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9430 ;; Make sure we are first in minor-mode-map-alist
9431 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9432 (and c (setq minor-mode-map-alist
9433 (cons c (delq c minor-mode-map-alist)))))
9434 (set (make-local-variable (quote org-table-may-need-update)) t)
9435 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
9436 (add-hook 'before-change-functions 'org-before-change-function
9438 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9439 auto-fill-inhibit-regexp)
9440 (set (make-local-variable 'auto-fill-inhibit-regexp)
9441 (if auto-fill-inhibit-regexp
9442 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9444 (easy-menu-add orgtbl-mode-menu)
9445 (run-hooks 'orgtbl-mode-hook))
9446 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9447 (remove-hook 'before-change-functions 'org-before-change-function t)
9448 (easy-menu-remove orgtbl-mode-menu)
9449 (force-mode-line-update 'all))))
9451 ;; Install it as a minor mode.
9452 (put 'orgtbl-mode :included t)
9453 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9454 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9456 (defun orgtbl-make-binding (fun n &rest keys)
9457 "Create a function for binding in the table minor mode.
9458 FUN is the command to call inside a table. N is used to create a unique
9459 command name. KEYS are keys that should be checked in for a command
9460 to execute outside of tables."
9463 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9465 (concat "In tables, run `" (symbol-name fun) "'.\n"
9466 "Outside of tables, run the binding of `"
9467 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9472 (list 'call-interactively (list 'quote fun))
9473 (list 'let '(orgtbl-mode)
9474 (list 'call-interactively
9477 (list 'key-binding k))
9479 '('orgtbl-error))))))))
9481 (defun orgtbl-error ()
9482 "Error when there is no default binding for a table key."
9484 (error "This key is has no function outside tables"))
9486 (defun orgtbl-setup ()
9487 "Setup orgtbl keymaps."
9491 '([(meta shift left)] org-table-delete-column)
9492 '([(meta left)] org-table-move-column-left)
9493 '([(meta right)] org-table-move-column-right)
9494 '([(meta shift right)] org-table-insert-column)
9495 '([(meta shift up)] org-table-kill-row)
9496 '([(meta shift down)] org-table-insert-row)
9497 '([(meta up)] org-table-move-row-up)
9498 '([(meta down)] org-table-move-row-down)
9499 '("\C-c\C-w" org-table-cut-region)
9500 '("\C-c\M-w" org-table-copy-region)
9501 '("\C-c\C-y" org-table-paste-rectangle)
9502 '("\C-c-" org-table-insert-hline)
9503 ; '([(shift tab)] org-table-previous-field)
9504 '("\C-m" org-table-next-row)
9505 (list (org-key 'S-return) 'org-table-copy-down)
9506 '([(meta return)] org-table-wrap-region)
9507 '("\C-c\C-q" org-table-wrap-region)
9508 '("\C-c?" org-table-current-column)
9509 '("\C-c " org-table-blank-field)
9510 '("\C-c+" org-table-sum)
9511 '("\C-c|" org-table-toggle-vline-visibility)
9512 '("\C-c=" org-table-eval-formula)
9513 '("\C-c'" org-table-edit-formulas)
9514 '("\C-c*" org-table-recalculate)
9515 '("\C-c^" org-table-sort-lines)
9516 '([(control ?#)] org-table-rotate-recalc-marks)))
9518 (while (setq elt (pop bindings))
9519 (setq nfunc (1+ nfunc))
9522 cmd (orgtbl-make-binding fun nfunc key))
9523 (define-key orgtbl-mode-map key cmd))
9524 ;; Special treatment needed for TAB and RET
9525 (define-key orgtbl-mode-map [(return)]
9526 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9527 (define-key orgtbl-mode-map "\C-m"
9528 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9529 (define-key orgtbl-mode-map [(tab)]
9530 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9531 (define-key orgtbl-mode-map "\C-i"
9532 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
9533 (define-key orgtbl-mode-map "\C-i"
9534 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
9535 (define-key orgtbl-mode-map "\C-c\C-c"
9536 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
9537 (when orgtbl-optimized
9538 ;; If the user wants maximum table support, we need to hijack
9539 ;; some standard editing functions
9540 (org-remap orgtbl-mode-map
9541 'self-insert-command 'orgtbl-self-insert-command
9542 'delete-char 'orgtbl-delete-char
9543 'delete-backward-char 'orgtbl-delete-backward-char)
9544 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
9545 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9547 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9548 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9549 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9550 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9552 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9553 ["Copy Field from Above"
9554 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9557 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9558 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9559 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9560 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9562 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9563 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9564 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9565 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
9566 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
9568 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
9570 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
9571 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
9572 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
9573 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
9575 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
9576 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9577 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
9578 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
9579 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
9580 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
9581 ["Sum Column/Rectangle" org-table-sum
9582 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
9583 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
9585 (setq org-table-formula-debug (not org-table-formula-debug))
9586 :style toggle :selected org-table-formula-debug]
9590 (defun orgtbl-tab ()
9591 "Justification and field motion for `orgtbl-mode'."
9593 (org-table-justify-field-maybe)
9594 (org-table-next-field))
9596 (defun orgtbl-ret ()
9597 "Justification and field motion for `orgtbl-mode'."
9599 (org-table-justify-field-maybe)
9600 (org-table-next-row))
9602 (defun orgtbl-self-insert-command (N)
9603 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9604 If the cursor is in a table looking at whitespace, the whitespace is
9605 overwritten, and the table is not marked as requiring realignment."
9607 (if (and (org-at-table-p)
9609 (and org-table-auto-blank-field
9610 (member last-command
9611 '(orgtbl-hijacker-command-100
9612 orgtbl-hijacker-command-101
9613 orgtbl-hijacker-command-102
9614 orgtbl-hijacker-command-103
9615 orgtbl-hijacker-command-104
9616 orgtbl-hijacker-command-105))
9617 (org-table-blank-field))
9620 (looking-at "[^|\n]* +|"))
9621 (let (org-table-may-need-update)
9622 (goto-char (1- (match-end 0)))
9623 (delete-backward-char 1)
9624 (goto-char (match-beginning 0))
9625 (self-insert-command N))
9626 (setq org-table-may-need-update t)
9628 (call-interactively (key-binding (vector last-input-event))))))
9630 (defun org-force-self-insert (N)
9631 "Needed to enforce self-insert under remapping."
9633 (self-insert-command N))
9635 (defun orgtbl-delete-backward-char (N)
9636 "Like `delete-backward-char', insert whitespace at field end in tables.
9637 When deleting backwards, in tables this function will insert whitespace in
9638 front of the next \"|\" separator, to keep the table aligned. The table will
9639 still be marked for re-alignment, because a narrow field may lead to a
9640 reduced column width."
9642 (if (and (org-at-table-p)
9644 (string-match "|" (buffer-substring (point-at-bol) (point)))
9645 (looking-at ".*?|"))
9646 (let ((pos (point)))
9647 (backward-delete-char N)
9648 (skip-chars-forward "^|")
9650 (goto-char (1- pos)))
9651 (delete-backward-char N)))
9653 (defun orgtbl-delete-char (N)
9654 "Like `delete-char', but insert whitespace at field end in tables.
9655 When deleting characters, in tables this function will insert whitespace in
9656 front of the next \"|\" separator, to keep the table aligned. The table
9657 will still be marked for re-alignment, because a narrow field may lead to
9658 a reduced column width."
9660 (if (and (org-at-table-p)
9662 (not (= (char-after) ?|))
9664 (if (looking-at ".*?|")
9665 (let ((pos (point)))
9666 (replace-match (concat
9667 (substring (match-string 0) 1 -1)
9674 (defconst org-level-max 20)
9676 (defun org-export-find-first-heading-line (list)
9677 "Remove all lines from LIST which are before the first headline."
9678 (let ((orig-list list)
9679 (re (concat "^" outline-regexp)))
9681 (not (string-match re (car list))))
9683 (or list orig-list)))
9685 (defun org-skip-comments (lines)
9686 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
9687 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
9688 (re2 "^\\(\\*+\\)[ \t\n\r]")
9690 (while (setq line (pop lines))
9692 ((and (string-match re1 line)
9693 (setq level (- (match-end 1) (match-beginning 1))))
9694 ;; Beginning of a COMMENT subtree. Skip it.
9695 (while (and (setq line (pop lines))
9696 (or (not (string-match re2 line))
9697 (> (- (match-end 1) (match-beginning 1)) level))))
9698 (setq lines (cons line lines)))
9699 ((string-match "^#" line)
9700 ;; an ordinary comment line
9702 (t (setq rtn (cons line rtn)))))
9707 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
9708 "Characters for underlining headings in ASCII export.")
9710 (defconst org-html-entities
9750 ("Aring") ("AA"."Å")
9839 ("varepsilon"."ε")
9852 ("sigmaf") ("varsigma"."ς")
9860 ("thetasym") ("vartheta"."ϑ")
9863 ("bull") ("bullet"."•")
9864 ("hellip") ("dots"."…")
9874 ("larr") ("leftarrow"."←") ("gets"."←")
9875 ("uarr") ("uparrow"."↑")
9876 ("rarr") ("to"."→") ("rightarrow"."→")
9877 ("darr")("downarrow"."↓")
9878 ("harr") ("leftrightarrow"."↔")
9879 ("crarr") ("hookleftarrow"."↵") ; has round hook, not quite CR
9880 ("lArr") ("Leftarrow"."⇐")
9881 ("uArr") ("Uparrow"."⇑")
9882 ("rArr") ("Rightarrow"."⇒")
9883 ("dArr") ("Downarrow"."⇓")
9884 ("hArr") ("Leftrightarrow"."⇔")
9886 ("part") ("partial"."∂")
9887 ("exist") ("exists"."∃")
9888 ("empty") ("emptyset"."∅")
9890 ("isin") ("in"."∈")
9896 ("lowast") ("ast"."∗")
9898 ("prop") ("proptp"."∝")
9899 ("infin") ("infty"."∞")
9900 ("ang") ("angle"."∠")
9901 ("and") ("vee"."∧")
9902 ("or") ("wedge"."∨")
9908 ("cong") ("simeq"."≅")
9909 ("asymp")("approx"."≈")
9910 ("ne") ("neq"."≠")
9914 ("sub") ("subset"."⊂")
9915 ("sup") ("supset"."⊃")
9922 ("sdot") ("cdot"."⋅")
9929 ("loz") ("Diamond"."◊")
9930 ("spades") ("spadesuit"."♠")
9931 ("clubs") ("clubsuit"."♣")
9932 ("hearts") ("diamondsuit"."♥")
9933 ("diams") ("diamondsuit"."♦")
10000 "Entities for TeX->HTML translation.
10001 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10002 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10003 In that case, \"\\ent\" will be translated to \"&other;\".
10004 The list contains HTML entities for Latin-1, Greek and other symbols.
10005 It is supplemented by a number of commonly used TeX macros with appropriate
10006 translations. There is currently no way for users to extend this.")
10008 (defvar org-last-level nil) ; dynamically scoped variable
10010 (defun org-export-as-ascii (arg)
10011 "Export the outline as a pretty ASCII file.
10012 If there is an active region, export only the region.
10013 The prefix ARG specifies how many levels of the outline should become
10014 underlined headlines. The default is 3."
10016 (setq-default org-todo-line-regexp org-todo-line-regexp)
10019 (if (org-region-active-p) (region-beginning) (point-min))
10020 (if (org-region-active-p) (region-end) (point-max))))
10021 (lines (org-export-find-first-heading-line
10022 (org-skip-comments (org-split-string region "[\r\n]"))))
10023 (org-startup-with-deadline-check nil)
10026 (case-fold-search nil)
10027 (filename (concat (file-name-sans-extension (buffer-file-name))
10029 (buffer (find-file-noselect filename))
10030 (levels-open (make-vector org-level-max nil))
10031 (date (format-time-string "%Y/%m/%d" (current-time)))
10032 (time (format-time-string "%X" (current-time)))
10033 (author user-full-name)
10034 (title (buffer-name))
10036 (email user-mail-address)
10037 (language org-export-default-language)
10042 (setq org-last-level 1)
10043 (org-init-section-numbers)
10045 (find-file-noselect filename)
10047 ;; Search for the export key lines
10048 (org-parse-key-lines)
10050 (setq lang-words (or (assoc language org-export-language-setup)
10051 (assoc "en" org-export-language-setup)))
10052 (if org-export-ascii-show-new-buffer
10053 (switch-to-buffer-other-window buffer)
10054 (set-buffer buffer))
10057 (if options (org-parse-export-options options))
10058 (setq umax (if arg (prefix-numeric-value arg)
10059 org-export-headline-levels))
10062 (if title (org-insert-centered title ?=))
10064 (if (or author email)
10065 (insert (concat (nth 1 lang-words) ": " (or author "")
10066 (if email (concat " <" email ">") "")
10068 (if (and date time)
10069 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10070 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10074 (if org-export-with-toc
10076 (insert (nth 3 lang-words) "\n"
10077 (make-string (length (nth 3 lang-words)) ?=) "\n")
10078 (mapcar '(lambda (line)
10079 (if (string-match org-todo-line-regexp
10081 ;; This is a headline
10083 (setq level (- (match-end 1) (match-beginning 1))
10084 txt (match-string 3 line)
10086 (or (and (match-beginning 2)
10087 (not (equal (match-string 2 line)
10090 (and (= level umax)
10091 (org-search-todo-below
10092 line lines level))))
10093 (setq txt (org-html-expand-for-ascii txt))
10095 (if org-export-with-section-numbers
10096 (setq txt (concat (org-section-number level)
10098 (if (<= level umax)
10101 (make-string (* (1- level) 4) ?\ )
10102 (format (if todo "%s (*)\n" "%s\n") txt))
10103 (setq org-last-level level))
10107 (org-init-section-numbers)
10108 (while (setq line (pop lines))
10109 ;; Remove the quoted HTML tags.
10110 (setq line (org-html-expand-for-ascii line))
10112 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10114 (setq level (- (match-end 1) (match-beginning 1))
10115 txt (match-string 2 line))
10116 (org-ascii-level-start level txt umax))
10117 (t (insert line "\n"))))
10120 (goto-char (point-min))))
10122 (defun org-search-todo-below (line lines level)
10123 "Search the subtree below LINE for any TODO entries."
10124 (let ((rest (cdr (memq line lines)))
10125 (re org-todo-line-regexp)
10128 (while (setq line (pop rest))
10129 (if (string-match re line)
10131 (setq lv (- (match-end 1) (match-beginning 1))
10132 todo (and (match-beginning 2)
10133 (not (equal (match-string 2 line)
10134 org-done-string))))
10136 (if (<= lv level) (throw 'exit nil))
10137 (if todo (throw 'exit t))))))))
10139 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10140 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10141 (defun org-html-expand-for-ascii (line)
10142 "Handle quoted HTML for ASCII export."
10143 (if org-export-html-expand
10144 (while (string-match "@<[^<>\n]*>" line)
10145 ;; We just remove the tags for now.
10146 (setq line (replace-match "" nil nil line))))
10149 (defun org-insert-centered (s &optional underline)
10150 "Insert the string S centered and underline it with character UNDERLINE."
10151 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10152 (insert (make-string ind ?\ ) s "\n")
10154 (insert (make-string ind ?\ )
10155 (make-string (length s) underline)
10158 (defun org-ascii-level-start (level title umax)
10159 "Insert a new level in ASCII export."
10162 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10163 (if (or (not (equal (char-before) ?\n))
10164 (not (equal (char-before (1- (point))) ?\n)))
10166 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10167 (if org-export-with-section-numbers
10168 (setq title (concat (org-section-number level) " " title)))
10169 (insert title "\n" (make-string (string-width title) char) "\n"))))
10171 (defun org-export-copy-visible ()
10172 "Copy the visible part of the buffer to another buffer, for printing.
10173 Also removes the first line of the buffer if it specifies a mode,
10174 and all options lines."
10176 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
10178 (buffer (find-file-noselect filename))
10180 (org-make-options-regexp
10181 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10182 "STARTUP" "ARCHIVE"
10183 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10184 (if org-noutline-p "\\(\n\\|$\\)" "")))
10186 (with-current-buffer buffer
10190 (setq s (goto-char (point-min)))
10191 (while (not (= (point) (point-max)))
10192 (goto-char (org-find-invisible))
10193 (append-to-buffer buffer s (point))
10194 (setq s (goto-char (org-find-visible)))))
10195 (switch-to-buffer-other-window buffer)
10197 (goto-char (point-min))
10198 (if (looking-at ".*-\\*- mode:.*\n")
10199 (replace-match ""))
10200 (while (re-search-forward ore nil t)
10201 (replace-match ""))
10202 (goto-char (point-min))))
10204 (defun org-find-visible ()
10205 (if (featurep 'noutline)
10207 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10208 (get-char-property s 'invisible)))
10210 (skip-chars-forward "^\n")
10212 (defun org-find-invisible ()
10213 (if (featurep 'noutline)
10215 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10216 (not (get-char-property s 'invisible))))
10218 (skip-chars-forward "^\r")
10223 (defun org-get-current-options ()
10224 "Return a string with current options as keyword options.
10225 Does include HTML export options as well as TODO and CATEGORY stuff."
10231 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10232 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10239 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10240 org-export-headline-levels
10241 org-export-with-section-numbers
10242 org-export-with-toc
10243 org-export-preserve-breaks
10244 org-export-html-expand
10245 org-export-with-fixed-width
10246 org-export-with-tables
10247 org-export-with-sub-superscripts
10248 org-export-with-emphasize
10249 org-export-with-TeX-macros
10250 (file-name-nondirectory (buffer-file-name))
10251 (if (equal org-todo-interpretation 'sequence)
10252 (mapconcat 'identity org-todo-keywords " ")
10253 "TODO FEEDBACK VERIFY DONE")
10254 (if (equal org-todo-interpretation 'type)
10255 (mapconcat 'identity org-todo-keywords " ")
10256 "Me Jason Marie DONE")
10257 (cdr (assoc org-startup-folded
10258 '((nil . "nofold")(t . "fold")(content . "content"))))
10259 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10260 org-archive-location
10263 (defun org-insert-export-options-template ()
10264 "Insert into the buffer a template with information for exporting."
10266 (if (not (bolp)) (newline))
10267 (let ((s (org-get-current-options)))
10268 (and (string-match "#\\+CATEGORY" s)
10269 (setq s (substring s 0 (match-beginning 0))))
10272 (defun org-toggle-fixed-width-section (arg)
10273 "Toggle the fixed-width export.
10274 If there is no active region, the QUOTE keyword at the current headline is
10275 inserted or removed. When present, it causes the text between this headline
10276 and the next to be exported as fixed-width text, and unmodified.
10277 If there is an active region, this command adds or removes a colon as the
10278 first character of this line. If the first character of a line is a colon,
10279 this line is also exported in fixed-width font."
10282 (regionp (org-region-active-p))
10283 (beg (if regionp (region-beginning) (point)))
10284 (end (if regionp (region-end)))
10285 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10286 (re "[ \t]*\\(:\\)")
10291 (setq cc (current-column))
10292 (beginning-of-line 1)
10293 (setq off (looking-at re))
10294 (while (> nlines 0)
10295 (setq nlines (1- nlines))
10296 (beginning-of-line 1)
10299 (move-to-column cc t)
10302 ((and off (looking-at re))
10303 (replace-match "" t t nil 1))
10304 ((not off) (move-to-column cc t) (insert ":")))
10307 (org-back-to-heading)
10308 (if (looking-at (concat outline-regexp
10309 "\\( +\\<" org-quote-string "\\>\\)"))
10310 (replace-match "" t t nil 1)
10311 (if (looking-at outline-regexp)
10313 (goto-char (match-end 0))
10314 (insert " " org-quote-string))))))))
10316 (defun org-export-as-html-and-open (arg)
10317 "Export the outline as HTML and immediately open it with a browser.
10318 If there is an active region, export only the region.
10319 The prefix ARG specifies how many levels of the outline should become
10320 headlines. The default is 3. Lower levels will become bulleted lists."
10322 (org-export-as-html arg 'hidden)
10323 (org-open-file (buffer-file-name)))
10325 (defun org-export-as-html-batch ()
10326 "Call `org-export-as-html', may be used in batch processing as
10328 --load=$HOME/lib/emacs/org.el
10329 --eval \"(setq org-export-headline-levels 2)\"
10330 --visit=MyFile --funcall org-export-as-html-batch"
10331 (org-export-as-html org-export-headline-levels 'hidden))
10333 (defun org-export-as-html (arg &optional hidden)
10334 "Export the outline as a pretty HTML file.
10335 If there is an active region, export only the region.
10336 The prefix ARG specifies how many levels of the outline should become
10337 headlines. The default is 3. Lower levels will become bulleted lists."
10339 (setq-default org-todo-line-regexp org-todo-line-regexp)
10340 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10341 (setq-default org-done-string org-done-string)
10342 (let* ((style org-export-html-style)
10343 (region-p (org-region-active-p))
10346 (if region-p (region-beginning) (point-min))
10347 (if region-p (region-end) (point-max))))
10349 (org-skip-comments (org-split-string region "[\r\n]")))
10350 (lines (org-export-find-first-heading-line all_lines))
10351 (level 0) (line "") (origline "") txt todo
10353 (filename (concat (file-name-sans-extension (buffer-file-name))
10355 (buffer (find-file-noselect filename))
10356 (levels-open (make-vector org-level-max nil))
10357 (date (format-time-string "%Y/%m/%d" (current-time)))
10358 (time (format-time-string "%X" (current-time)))
10359 (author user-full-name)
10360 (title (buffer-name))
10362 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
10365 (in-local-list nil)
10366 (local-list-num nil)
10367 (local-list-indent nil)
10368 (llt org-plain-list-ordered-item-terminator)
10369 (email user-mail-address)
10370 (language org-export-default-language)
10375 ;; FIXME: The following returns always nil under XEmacs
10376 (coding-system (and (fboundp 'coding-system-get)
10377 (boundp 'buffer-file-coding-system)
10378 buffer-file-coding-system))
10379 (coding-system-for-write (or coding-system coding-system-for-write))
10380 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
10381 (charset (and coding-system
10382 (coding-system-get coding-system 'mime-charset)))
10384 table-buffer table-orig-buffer
10385 ind start-is-num starter
10387 (message "Exporting...")
10389 (setq org-last-level 1)
10390 (org-init-section-numbers)
10392 ;; Search for the export key lines
10393 (org-parse-key-lines)
10394 (setq lang-words (or (assoc language org-export-language-setup)
10395 (assoc "en" org-export-language-setup)))
10397 ;; Switch to the output buffer
10398 (if (or hidden (not org-export-html-show-new-buffer))
10399 (set-buffer buffer)
10400 (switch-to-buffer-other-window buffer))
10403 (let ((case-fold-search nil))
10404 (if options (org-parse-export-options options))
10405 (setq umax (if arg (prefix-numeric-value arg)
10406 org-export-headline-levels))
10410 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
10411 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
10412 <html lang=\"%s\"><head>
10414 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
10415 <meta name=generator content=\"Org-mode\">
10416 <meta name=generated content=\"%s %s\">
10417 <meta name=author content=\"%s\">
10421 language (org-html-expand title) (or charset "iso-8859-1")
10422 date time author style))
10423 (if title (insert (concat "<H1 class=\"title\">"
10424 (org-html-expand title) "</H1>\n")))
10425 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
10426 (if email (insert (concat "<a href=\"mailto:" email "\"><"
10427 email "></a>\n")))
10428 (if (or author email) (insert "<br>\n"))
10429 (if (and date time) (insert (concat (nth 2 lang-words) ": "
10430 date " " time "<br>\n")))
10431 (if text (insert (concat "<p>\n" (org-html-expand text))))
10432 (if org-export-with-toc
10434 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
10436 (mapcar '(lambda (line)
10437 (if (string-match org-todo-line-regexp line)
10438 ;; This is a headline
10440 (setq level (- (match-end 1) (match-beginning 1))
10441 txt (save-match-data
10443 (match-string 3 line)))
10445 (or (and (match-beginning 2)
10446 (not (equal (match-string 2 line)
10449 (and (= level umax)
10450 (org-search-todo-below
10451 line lines level))))
10452 (if org-export-with-section-numbers
10453 (setq txt (concat (org-section-number level)
10455 (if (<= level umax)
10457 (setq head-count (+ head-count 1))
10458 (if (> level org-last-level)
10460 (setq cnt (- level org-last-level))
10461 (while (>= (setq cnt (1- cnt)) 0)
10464 (if (< level org-last-level)
10466 (setq cnt (- org-last-level level))
10467 (while (>= (setq cnt (1- cnt)) 0)
10473 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
10474 "<li><a href=\"#sec-%d\">%s</a>\n")
10476 (setq org-last-level level))
10479 (while (> org-last-level 0)
10480 (setq org-last-level (1- org-last-level))
10481 (insert "</ul>\n"))
10483 (setq head-count 0)
10484 (org-init-section-numbers)
10486 (while (setq line (pop lines) origline line)
10489 ;; end of quote section?
10490 (when (and inquote (string-match "^\\*+" line))
10491 (insert "</pre>\n")
10492 (setq inquote nil))
10493 ;; inside a quote section?
10495 (insert (org-html-protect line) "\n")
10496 (throw 'nextline nil))
10499 (when (and org-export-with-fixed-width
10500 (string-match "^[ \t]*:\\(.*\\)" line))
10501 (when (not infixed)
10503 (insert "<pre>\n"))
10504 (insert (org-html-protect (match-string 1 line)) "\n")
10506 (not (string-match "^[ \t]*\\(:.*\\)"
10509 (insert "</pre>\n"))
10510 (throw 'nextline nil))
10512 ;; Protect the links
10514 (while (string-match org-link-maybe-angles-regexp line start)
10515 (setq start (match-end 0))
10516 (setq line (replace-match
10517 (concat "\000" (match-string 1 line) "\000")
10520 ;; replace "&" by "&", "<" and ">" by "<" and ">"
10521 ;; handle @<..> HTML tags (replace "@>..<" by "<..>")
10522 (setq line (org-html-expand line))
10524 ;; Format the links
10526 (while (string-match org-protected-link-regexp line start)
10527 (setq start (- (match-end 0) 2))
10528 (setq type (match-string 1 line))
10530 ((member type '("http" "https" "ftp" "mailto" "news"))
10532 (setq line (replace-match
10533 ; "<a href=\"\\1:\\2\"><\\1:\\2></a>"
10534 "<a href=\"\\1:\\2\">\\1:\\2</a>"
10536 ((string= type "file")
10538 (let* ((filename (match-string 2 line))
10539 (abs-p (file-name-absolute-p filename))
10540 (thefile (if abs-p (expand-file-name filename) filename))
10541 (thefile (save-match-data
10542 (if (string-match ":[0-9]+$" thefile)
10543 (replace-match "" t t thefile)
10547 (string-match (org-image-file-name-regexp) thefile))))
10548 (setq line (replace-match
10549 (if (and org-export-html-inline-images
10551 (concat "<img src=\"" thefile "\"/>")
10552 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
10555 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
10556 (setq line (replace-match
10557 "<i><\\1:\\2></i>" nil nil line)))))
10560 (if (and (string-match org-todo-line-regexp line)
10561 (match-beginning 2))
10562 (if (equal (match-string 2 line) org-done-string)
10563 (setq line (replace-match
10564 "<span class=\"done\">\\2</span>"
10566 (setq line (replace-match "<span class=\"todo\">\\2</span>"
10570 (if (string-match org-deadline-line-regexp line)
10572 (if (save-match-data
10573 (string-match "<a href"
10574 (substring line 0 (match-beginning 0))))
10575 nil ; Don't do the replacement - it is inside a link
10576 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
10577 nil nil line 1)))))
10579 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10580 ;; This is a headline
10581 (setq level (- (match-end 1) (match-beginning 1))
10582 txt (match-string 2 line))
10583 (if (<= level umax) (setq head-count (+ head-count 1)))
10584 (when in-local-list
10585 ;; Close any local lists before inserting a new header line
10586 (while local-list-num
10587 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10588 (pop local-list-num))
10589 (setq local-list-indent nil
10590 in-local-list nil))
10591 (org-html-level-start level txt umax
10592 (and org-export-with-toc (<= level umax))
10595 (when (string-match quote-re line)
10599 ((and org-export-with-tables
10600 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
10601 (if (not table-open)
10602 ;; New table starts
10603 (setq table-open t table-buffer nil table-orig-buffer nil))
10604 ;; Accumulate lines
10605 (setq table-buffer (cons line table-buffer)
10606 table-orig-buffer (cons origline table-orig-buffer))
10607 (when (or (not lines)
10608 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
10610 (setq table-open nil
10611 table-buffer (nreverse table-buffer)
10612 table-orig-buffer (nreverse table-orig-buffer))
10613 (insert (org-format-table-html table-buffer table-orig-buffer))))
10616 (when (and (> org-export-plain-list-max-depth 0)
10619 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10620 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10621 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10622 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
10624 (setq ind (org-get-string-indentation line)
10625 start-is-num (match-beginning 4)
10626 starter (if (match-beginning 2) (match-string 2 line))
10627 line (substring line (match-beginning 5)))
10628 (unless (string-match "[^ \t]" line)
10629 ;; empty line. Pretend indentation is large.
10630 (setq ind (1+ (or (car local-list-indent) 1))))
10631 (while (and in-local-list
10632 (or (and (= ind (car local-list-indent))
10634 (< ind (car local-list-indent))))
10635 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10636 (pop local-list-num) (pop local-list-indent)
10637 (setq in-local-list local-list-indent))
10640 (or (not in-local-list)
10641 (> ind (car local-list-indent)))
10642 (< (length local-list-indent)
10643 org-export-plain-list-max-depth))
10644 ;; Start new (level of ) list
10645 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
10646 (push start-is-num local-list-num)
10647 (push ind local-list-indent)
10648 (setq in-local-list t))
10650 ;; continue current list
10651 (insert "<li>\n"))))
10652 ;; Empty lines start a new paragraph. If hand-formatted lists
10653 ;; are not fully interpreted, lines starting with "-", "+", "*"
10654 ;; also start a new paragraph.
10655 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
10656 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
10658 (if org-export-html-with-timestamp
10659 (insert org-export-html-html-helper-timestamp))
10660 (insert "</body>\n</html>\n")
10663 (goto-char (point-min)))))
10665 (defun org-format-table-html (lines olines)
10666 "Find out which HTML converter to use and return the HTML code."
10667 (if (string-match "^[ \t]*|" (car lines))
10668 ;; A normal org table
10669 (org-format-org-table-html lines)
10670 ;; Table made by table.el - test for spanning
10671 (let* ((hlines (delq nil (mapcar
10673 (if (string-match "^[ \t]*\\+-" x) x
10676 (first (car hlines))
10677 (ll (and (string-match "\\S-+" first)
10678 (match-string 0 first)))
10679 (re (concat "^[ \t]*" (regexp-quote ll)))
10680 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
10682 (if (and (not spanning)
10683 (not org-export-prefer-native-exporter-for-tables))
10684 ;; We can use my own converter with HTML conversions
10685 (org-format-table-table-html lines)
10686 ;; Need to use the code generator in table.el, with the original text.
10687 (org-format-table-table-html-using-table-generate-source olines)))))
10689 (defun org-format-org-table-html (lines)
10690 "Format a table into html."
10691 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10692 (setq lines (nreverse lines))
10693 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10694 (setq lines (nreverse lines))
10695 (let ((head (and org-export-highlight-first-table-line
10697 (lambda (x) (string-match "^[ \t]*|-" x))
10700 (setq html (concat org-export-html-table-tag "\n"))
10701 (while (setq line (pop lines))
10703 (if (string-match "^[ \t]*|-" line)
10705 (setq head nil) ;; head ends here, first time around
10706 ;; ignore this line
10707 (throw 'next-line t)))
10708 ;; Break the line into fields
10709 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10713 (mapconcat (lambda (x)
10715 (concat "<th>" x "</th>")
10716 (concat "<td>" x "</td>")))
10719 (setq html (concat html "</table>\n"))
10722 (defun org-fake-empty-table-line (line)
10723 "Replace everything except \"|\" with spaces."
10724 (let ((i (length line))
10725 (newstr (copy-sequence line)))
10728 (if (not (eq (aref newstr i) ?|))
10729 (aset newstr i ?\ )))
10732 (defun org-format-table-table-html (lines)
10733 "Format a table generated by table.el into html.
10734 This conversion does *not* use `table-generate-source' from table.el.
10735 This has the advantage that Org-mode's HTML conversions can be used.
10736 But it has the disadvantage, that no cell- or row-spanning is allowed."
10737 (let (line field-buffer
10738 (head org-export-highlight-first-table-line)
10740 (setq html (concat org-export-html-table-tag "\n"))
10741 (while (setq line (pop lines))
10742 (setq empty " ")
10744 (if (string-match "^[ \t]*\\+-" line)
10753 (if (equal x "") (setq x empty))
10755 (concat "<th>" x "</th>\n")
10756 (concat "<td>" x "</td>\n")))
10760 (setq field-buffer nil)))
10761 ;; Ignore this line
10762 (throw 'next-line t)))
10763 ;; Break the line into fields and store the fields
10764 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10766 (setq field-buffer (mapcar
10768 (concat x "<br>" (pop fields)))
10770 (setq field-buffer fields))))
10771 (setq html (concat html "</table>\n"))
10774 (defun org-format-table-table-html-using-table-generate-source (lines)
10775 "Format a table into html, using `table-generate-source' from table.el.
10776 This has the advantage that cell- or row-spanning is allowed.
10777 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
10779 (with-current-buffer (get-buffer-create " org-tmp1 ")
10781 (insert (mapconcat 'identity lines "\n"))
10782 (goto-char (point-min))
10783 (if (not (re-search-forward "|[^+]" nil t))
10784 (error "Error processing table"))
10785 (table-recognize-table)
10786 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
10787 (table-generate-source 'html " org-tmp2 ")
10788 (set-buffer " org-tmp2 ")
10789 (buffer-substring (point-min) (point-max))))
10791 (defun org-html-protect (s)
10792 ;; convert & to &, < to < and > to >
10794 (while (string-match "&" s start)
10795 (setq s (replace-match "&" t t s)
10796 start (1+ (match-beginning 0))))
10797 (while (string-match "<" s)
10798 (setq s (replace-match "<" t t s)))
10799 (while (string-match ">" s)
10800 (setq s (replace-match ">" t t s))))
10803 (defun org-html-expand (string)
10804 "Prepare STRING for HTML export. Applies all active conversions."
10805 ;; First check if there is a link in the line - if yes, apply conversions
10806 ;; only before the start of the link.
10807 ;; FIXME: This is no longer correct, because links now have an end.
10808 (let* ((m (string-match org-link-regexp string))
10809 (s (if m (substring string 0 m) string))
10810 (r (if m (substring string m) "")))
10811 ;; convert & to &, < to < and > to >
10812 (setq s (org-html-protect s))
10813 (if org-export-html-expand
10814 (while (string-match "@<\\([^&]*\\)>" s)
10815 (setq s (replace-match "<\\1>" nil nil s))))
10816 (if org-export-with-emphasize
10817 (setq s (org-export-html-convert-emphasize s)))
10818 (if org-export-with-sub-superscripts
10819 (setq s (org-export-html-convert-sub-super s)))
10820 (if org-export-with-TeX-macros
10821 (let ((start 0) wd ass)
10822 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
10823 (setq wd (match-string 1 s))
10824 (if (setq ass (assoc wd org-html-entities))
10825 (setq s (replace-match (or (cdr ass)
10826 (concat "&" (car ass) ";"))
10828 (setq start (+ start (length wd)))))))
10831 (defun org-create-multibrace-regexp (left right n)
10832 "Create a regular expression which will match a balanced sexp.
10833 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
10834 as single character strings.
10835 The regexp returned will match the entire expression including the
10836 delimiters. It will also define a single group which contains the
10837 match except for the outermost delimiters. The maximum depth of
10838 stacked delimiters is N. Escaping delimiters is not possible."
10839 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
10842 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
10845 re (concat re or next)
10846 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
10847 (concat left "\\(" re "\\)" right)))
10849 (defvar org-match-substring-regexp
10851 "\\([^\\]\\)\\([_^]\\)\\("
10852 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
10854 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
10856 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
10857 "The regular expression matching a sub- or superscript.")
10859 (defun org-export-html-convert-sub-super (string)
10860 "Convert sub- and superscripts in STRING to HTML."
10862 (while (string-match org-match-substring-regexp string)
10863 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
10864 (setq c (or (match-string 8 string)
10865 (match-string 6 string)
10866 (match-string 5 string)))
10867 (setq string (replace-match
10868 (concat (match-string 1 string)
10869 "<" key ">" c "</" key ">")
10871 (while (string-match "\\\\\\([_^]\\)" string)
10872 (setq string (replace-match (match-string 1 string) t t string))))
10875 (defun org-export-html-convert-emphasize (string)
10876 (while (string-match
10877 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
10879 (setq string (replace-match
10880 (concat "<b>" (match-string 3 string) "</b>")
10882 (while (string-match
10883 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
10885 (setq string (replace-match
10886 (concat "<i>" (match-string 3 string) "</i>")
10888 (while (string-match
10889 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
10891 (setq string (replace-match
10892 (concat "<u>" (match-string 3 string) "</u>")
10896 (defun org-parse-key-lines ()
10897 "Find the special key lines with the information for exporters."
10900 (let ((re (org-make-options-regexp
10901 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
10903 (while (re-search-forward re nil t)
10904 (setq key (match-string 1))
10905 (cond ((string-equal key "TITLE")
10906 (setq title (match-string 2)))
10907 ((string-equal key "AUTHOR")
10908 (setq author (match-string 2)))
10909 ((string-equal key "EMAIL")
10910 (setq email (match-string 2)))
10911 ((string-equal key "LANGUAGE")
10912 (setq language (match-string 2)))
10913 ((string-equal key "TEXT")
10914 (setq text (concat text "\n" (match-string 2))))
10915 ((string-equal key "OPTIONS")
10916 (setq options (match-string 2))))))))
10918 (defun org-parse-export-options (s)
10919 "Parse the export options line."
10920 (let ((op '(("H" . org-export-headline-levels)
10921 ("num" . org-export-with-section-numbers)
10922 ("toc" . org-export-with-toc)
10923 ("\\n" . org-export-preserve-breaks)
10924 ("@" . org-export-html-expand)
10925 (":" . org-export-with-fixed-width)
10926 ("|" . org-export-with-tables)
10927 ("^" . org-export-with-sub-superscripts)
10928 ("*" . org-export-with-emphasize)
10929 ("TeX" . org-export-with-TeX-macros)))
10931 (while (setq o (pop op))
10932 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
10934 (set (make-local-variable (cdr o))
10935 (car (read-from-string (match-string 1 s))))))))
10937 (defun org-html-level-start (level title umax with-toc head-count)
10938 "Insert a new level in HTML export."
10939 (let ((l (1+ (max level umax))))
10940 (while (<= l org-level-max)
10941 (if (aref levels-open (1- l))
10943 (org-html-level-close l)
10944 (aset levels-open (1- l) nil)))
10948 (if (aref levels-open (1- level))
10949 (insert "<li>" title "<p>\n")
10950 (aset levels-open (1- level) t)
10951 (insert "<ul><li>" title "<p>\n")))
10952 (if org-export-with-section-numbers
10953 (setq title (concat (org-section-number level) " " title)))
10954 (setq level (+ level 1))
10956 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
10957 level head-count title level))
10958 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
10960 (defun org-html-level-close (&rest args)
10961 "Terminate one level in HTML export."
10964 ;; Variable holding the vector with section numbers
10965 (defvar org-section-numbers (make-vector org-level-max 0))
10967 (defun org-init-section-numbers ()
10968 "Initialize the vector for the section numbers."
10970 (numbers (nreverse (org-split-string "" "\\.")))
10971 (depth (1- (length org-section-numbers)))
10972 (i depth) number-string)
10975 (aset org-section-numbers i 0)
10976 (setq number-string (or (car numbers) "0"))
10977 (if (string-match "\\`[A-Z]\\'" number-string)
10978 (aset org-section-numbers i
10979 (- (string-to-char number-string) ?A -1))
10980 (aset org-section-numbers i (string-to-number number-string)))
10984 (defun org-section-number (&optional level)
10985 "Return a string with the current section number.
10986 When LEVEL is non-nil, increase section numbers on that level."
10987 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
10990 (aset org-section-numbers
10991 level (1+ (aref org-section-numbers level))))
10992 (setq idx (1+ level))
10993 (while (<= idx depth)
10994 (if (not (= idx 1))
10995 (aset org-section-numbers idx 0))
10996 (setq idx (1+ idx))))
10998 (while (<= idx depth)
10999 (setq n (aref org-section-numbers idx))
11000 (setq string (concat string (if (not (string= string "")) "." "")
11001 (int-to-string n)))
11002 (setq idx (1+ idx)))
11004 (if (string-match "\\`\\([@0]\\.\\)+" string)
11005 (setq string (replace-match "" nil nil string)))
11006 (if (string-match "\\(\\.0\\)+\\'" string)
11007 (setq string (replace-match "" nil nil string))))
11011 (defun org-export-icalendar-this-file ()
11012 "Export current file as an iCalendar file.
11013 The iCalendar file will be located in the same directory as the Org-mode
11014 file, but with extension `.ics'."
11016 (org-export-icalendar nil (buffer-file-name)))
11019 (defun org-export-icalendar-all-agenda-files ()
11020 "Export all files in `org-agenda-files' to iCalendar .ics files.
11021 Each iCalendar file will be located in the same directory as the Org-mode
11022 file, but with extension `.ics'."
11024 (apply 'org-export-icalendar nil org-agenda-files))
11027 (defun org-export-icalendar-combine-agenda-files ()
11028 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11029 The file is stored under the name `org-combined-agenda-icalendar-file'."
11031 (apply 'org-export-icalendar t org-agenda-files))
11033 (defun org-export-icalendar (combine &rest files)
11034 "Create iCalendar files for all elements of FILES.
11035 If COMBINE is non-nil, combine all calendar entries into a single large
11036 file and store it under the name `org-combined-agenda-icalendar-file'."
11038 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11040 (setq ical-file org-combined-agenda-icalendar-file
11041 ical-buffer (org-get-agenda-file-buffer ical-file))
11042 (set-buffer ical-buffer) (erase-buffer))
11043 (while (setq file (pop files))
11045 (org-check-agenda-file file)
11047 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11048 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11049 (set-buffer ical-buffer) (erase-buffer))
11050 (set-buffer (org-get-agenda-file-buffer file))
11051 (setq category (or org-category
11052 (file-name-sans-extension
11053 (file-name-nondirectory (buffer-file-name)))))
11054 (if (symbolp category) (setq category (symbol-name category)))
11055 (let ((standard-output ical-buffer))
11057 (and (not started) (setq started t)
11058 (org-start-icalendar-file org-icalendar-combined-name))
11059 (org-start-icalendar-file category))
11060 (org-print-icalendar-entries combine category)
11061 (when (or (and combine (not files)) (not combine))
11062 (org-finish-icalendar-file)
11063 (set-buffer ical-buffer)
11065 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11066 (org-release-buffers org-agenda-new-buffers))))
11068 (defvar org-after-save-iCalendar-file-hook nil
11069 "Hook run after an iCalendar file has been saved.
11070 The iCalendar buffer is still current when this hook is run.
11071 A good way to use this is to tell a desktop calenndar application to re-read
11072 the iCalendar file.")
11074 (defun org-print-icalendar-entries (&optional combine category)
11075 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11076 When COMBINE is non nil, add the category to each line."
11077 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11078 (dts (org-ical-ts-to-string
11079 (format-time-string (cdr org-time-stamp-formats) (current-time))
11081 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11083 (goto-char (point-min))
11084 (while (re-search-forward org-ts-regexp nil t)
11085 (setq pos (match-beginning 0)
11086 ts (match-string 0)
11088 hd (org-get-heading))
11089 (if (looking-at re2)
11091 (goto-char (match-end 0))
11092 (setq ts2 (match-string 1) inc nil))
11094 tmp (buffer-substring (max (point-min)
11095 (- pos org-ds-keyword-length))
11097 deadlinep (string-match org-deadline-regexp tmp)
11098 scheduledp (string-match org-scheduled-regexp tmp)
11099 ;; donep (org-entry-is-done-p)
11101 (if (or (string-match org-tr-regexp hd)
11102 (string-match org-ts-regexp hd))
11103 (setq hd (replace-match "" t t hd)))
11105 (setq hd (concat hd " (category " category ")")))
11106 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11107 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11108 (princ (format "BEGIN:VEVENT
11113 (org-ical-ts-to-string ts "DTSTART")
11114 (org-ical-ts-to-string ts2 "DTEND" inc)
11116 (when org-icalendar-include-todo
11117 (goto-char (point-min))
11118 (while (re-search-forward org-todo-line-regexp nil t)
11119 (setq state (match-string 1))
11120 (unless (equal state org-done-string)
11121 (setq hd (match-string 3))
11122 (if (string-match org-priority-regexp hd)
11123 (setq pri (string-to-char (match-string 2 hd))
11124 hd (concat (substring hd 0 (match-beginning 1))
11125 (substring hd (- (match-end 1)))))
11126 (setq pri org-default-priority))
11127 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11128 (- org-lowest-priority ?A))))))
11130 (princ (format "BEGIN:VTODO
11138 (defun org-start-icalendar-file (name)
11139 "Start an iCalendar file by inserting the header."
11140 (let ((user user-full-name)
11141 (name (or name "unknown"))
11142 (timezone (cadr (current-time-zone))))
11144 (format "BEGIN:VCALENDAR
11147 PRODID:-//%s//Emacs with Org-mode//EN
11149 CALSCALE:GREGORIAN\n" name user timezone))))
11151 (defun org-finish-icalendar-file ()
11152 "Finish an iCalendar file by inserting the END statement."
11153 (princ "END:VCALENDAR\n"))
11155 (defun org-ical-ts-to-string (s keyword &optional inc)
11156 "Take a time string S and convert it to iCalendar format.
11157 KEYWORD is added in front, to make a complete line like DTSTART....
11158 When INC is non-nil, increase the hour by two (if time string contains
11159 a time), or the day by one (if it does not contain a time)."
11160 (let ((t1 (org-parse-time-string s 'nodefault))
11161 t2 fmt have-time time)
11162 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11163 (setq t2 t1 have-time t)
11164 (setq t2 (org-parse-time-string s)))
11165 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11166 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11168 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11169 (setq time (encode-time s mi h d m y)))
11170 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11171 (concat keyword (format-time-string fmt time))))
11176 ;; - Bindings in Org-mode map are currently
11177 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11178 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
11179 ;; e (?) useful from outline-mode
11180 ;; i k @ expendable from outline-mode
11181 ;; 0123456789 ! %^& ()_{} " `' free
11183 ;; Make `C-c C-x' a prefix key
11184 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11186 ;; TAB key with modifiers
11187 (define-key org-mode-map "\C-i" 'org-cycle)
11188 (define-key org-mode-map [(meta tab)] 'org-complete)
11189 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11190 ;; The following line is necessary under Suse GNU/Linux
11191 (unless org-xemacs-p
11192 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11193 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11195 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11196 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11197 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11198 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11199 (define-key org-mode-map [(meta return)] 'org-meta-return)
11200 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11201 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11203 ;; Cursor keys with modifiers
11204 (define-key org-mode-map [(meta left)] 'org-metaleft)
11205 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11206 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11207 (define-key org-mode-map [(meta right)] 'org-metaright)
11208 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11209 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11210 (define-key org-mode-map [(meta up)] 'org-metaup)
11211 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11212 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11213 (define-key org-mode-map [(meta down)] 'org-metadown)
11214 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11215 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11217 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11218 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11219 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11220 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11221 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11222 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11223 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11224 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11225 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11226 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11227 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11228 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11229 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11230 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11231 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11232 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11234 ;; All the other keys
11235 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11236 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11237 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11238 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11239 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11240 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11241 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11242 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11243 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11244 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11245 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11246 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11247 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11248 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11249 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11250 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11251 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11252 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11253 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11254 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11255 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11256 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11257 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11258 (define-key org-mode-map "\C-c]" 'org-remove-file)
11259 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11260 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11261 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11262 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11263 (define-key org-mode-map "\C-m" 'org-return)
11264 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11265 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11266 (define-key org-mode-map "\C-c+" 'org-table-sum)
11267 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
11268 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
11269 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
11270 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
11271 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11272 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
11273 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11274 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
11275 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
11276 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
11277 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
11278 ;; OPML support is only an option for the future
11279 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
11280 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
11281 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
11282 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
11283 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
11284 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11285 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
11286 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11287 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
11288 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
11289 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
11291 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11292 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11293 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11295 (defsubst org-table-p () (org-at-table-p))
11297 (defun org-self-insert-command (N)
11298 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11299 If the cursor is in a table looking at whitespace, the whitespace is
11300 overwritten, and the table is not marked as requiring realignment."
11302 (if (and (org-table-p)
11304 (and org-table-auto-blank-field
11305 (member last-command
11306 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11307 (org-table-blank-field))
11310 (looking-at "[^|\n]* +|"))
11311 (let (org-table-may-need-update)
11312 (goto-char (1- (match-end 0)))
11313 (delete-backward-char 1)
11314 (goto-char (match-beginning 0))
11315 (self-insert-command N))
11316 (setq org-table-may-need-update t)
11317 (self-insert-command N)))
11320 ;; The following two functions might still be optimized to trigger
11321 ;; re-alignment less frequently.
11323 (defun org-delete-backward-char (N)
11324 "Like `delete-backward-char', insert whitespace at field end in tables.
11325 When deleting backwards, in tables this function will insert whitespace in
11326 front of the next \"|\" separator, to keep the table aligned. The table will
11327 still be marked for re-alignment, because a narrow field may lead to a
11328 reduced column width."
11330 (if (and (org-table-p)
11332 (string-match "|" (buffer-substring (point-at-bol) (point)))
11333 (looking-at ".*?|"))
11334 (let ((pos (point)))
11335 (backward-delete-char N)
11336 (skip-chars-forward "^|")
11338 (goto-char (1- pos)))
11339 (backward-delete-char N)))
11341 (defun org-delete-char (N)
11342 "Like `delete-char', but insert whitespace at field end in tables.
11343 When deleting characters, in tables this function will insert whitespace in
11344 front of the next \"|\" separator, to keep the table aligned. The table
11345 will still be marked for re-alignment, because a narrow field may lead to
11346 a reduced column width."
11348 (if (and (org-table-p)
11350 (not (= (char-after) ?|))
11352 (if (looking-at ".*?|")
11353 (let ((pos (point)))
11354 (replace-match (concat
11355 (substring (match-string 0) 1 -1)
11360 ;; How to do this: Measure non-white length of current string
11361 ;; If equal to column width, we should realign.
11363 (defun org-remap (map &rest commands)
11364 "In MAP, remap the functions given in COMMANDS.
11365 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11368 (setq old (pop commands) new (pop commands))
11369 (if (fboundp 'command-remapping)
11370 (define-key map (vector 'remap old) new)
11371 (substitute-key-definition old new map global-map)))))
11373 (when (eq org-enable-table-editor 'optimized)
11374 ;; If the user wants maximum table support, we need to hijack
11375 ;; some standard editing functions
11376 (org-remap org-mode-map
11377 'self-insert-command 'org-self-insert-command
11378 'delete-char 'org-delete-char
11379 'delete-backward-char 'org-delete-backward-char)
11380 (define-key org-mode-map "|" 'org-force-self-insert))
11382 (defun org-shiftcursor-error ()
11383 "Throw an error because Shift-Cursor command was applied in wrong context."
11384 (error "This command is active in special context like tables, headlines or timestamps"))
11386 (defun org-shifttab ()
11387 "Global visibility cycling or move to previous table field.
11388 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
11389 See the individual commands for more information."
11392 ((org-at-table-p) (org-table-previous-field))
11393 (t (org-cycle '(4)))))
11395 (defun org-shiftmetaleft ()
11396 "Promote subtree or delete table column.
11397 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
11398 See the individual commands for more information."
11401 ((org-at-table-p) (org-table-delete-column))
11402 ((org-on-heading-p) (org-promote-subtree))
11403 ((org-at-item-p) (call-interactively 'org-outdent-item))
11404 (t (org-shiftcursor-error))))
11406 (defun org-shiftmetaright ()
11407 "Demote subtree or insert table column.
11408 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
11409 See the individual commands for more information."
11412 ((org-at-table-p) (org-table-insert-column))
11413 ((org-on-heading-p) (org-demote-subtree))
11414 ((org-at-item-p) (call-interactively 'org-indent-item))
11415 (t (org-shiftcursor-error))))
11417 (defun org-shiftmetaup (&optional arg)
11418 "Move subtree up or kill table row.
11419 Calls `org-move-subtree-up' or `org-table-kill-row' or
11420 `org-move-item-up' depending on context. See the individual commands
11421 for more information."
11424 ((org-at-table-p) (org-table-kill-row))
11425 ((org-on-heading-p) (org-move-subtree-up arg))
11426 ((org-at-item-p) (org-move-item-up arg))
11427 (t (org-shiftcursor-error))))
11428 (defun org-shiftmetadown (&optional arg)
11429 "Move subtree down or insert table row.
11430 Calls `org-move-subtree-down' or `org-table-insert-row' or
11431 `org-move-item-down', depending on context. See the individual
11432 commands for more information."
11435 ((org-at-table-p) (org-table-insert-row arg))
11436 ((org-on-heading-p) (org-move-subtree-down arg))
11437 ((org-at-item-p) (org-move-item-down arg))
11438 (t (org-shiftcursor-error))))
11440 (defun org-metaleft (&optional arg)
11441 "Promote heading or move table column to left.
11442 Calls `org-do-promote' or `org-table-move-column', depending on context.
11443 With no specific context, calls the Emacs default `backward-word'.
11444 See the individual commands for more information."
11447 ((org-at-table-p) (org-table-move-column 'left))
11448 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
11449 (t (backward-word (prefix-numeric-value arg)))))
11451 (defun org-metaright (&optional arg)
11452 "Demote subtree or move table column to right.
11453 Calls `org-do-demote' or `org-table-move-column', depending on context.
11454 With no specific context, calls the Emacs default `forward-word'.
11455 See the individual commands for more information."
11458 ((org-at-table-p) (org-table-move-column nil))
11459 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
11460 (t (forward-word (prefix-numeric-value arg)))))
11462 (defun org-metaup (&optional arg)
11463 "Move subtree up or move table row up.
11464 Calls `org-move-subtree-up' or `org-table-move-row' or
11465 `org-move-item-up', depending on context. See the individual commands
11466 for more information."
11469 ((org-at-table-p) (org-table-move-row 'up))
11470 ((org-on-heading-p) (org-move-subtree-up arg))
11471 ((org-at-item-p) (org-move-item-up arg))
11472 (t (org-shiftcursor-error))))
11474 (defun org-metadown (&optional arg)
11475 "Move subtree down or move table row down.
11476 Calls `org-move-subtree-down' or `org-table-move-row' or
11477 `org-move-item-down', depending on context. See the individual
11478 commands for more information."
11481 ((org-at-table-p) (org-table-move-row nil))
11482 ((org-on-heading-p) (org-move-subtree-down arg))
11483 ((org-at-item-p) (org-move-item-down arg))
11484 (t (org-shiftcursor-error))))
11486 (defun org-shiftup (&optional arg)
11487 "Increase item in timestamp or increase priority of current item.
11488 Calls `org-timestamp-up' or `org-priority-up', depending on context.
11489 See the individual commands for more information."
11492 ((org-at-timestamp-p) (org-timestamp-up arg))
11493 (t (org-priority-up))))
11495 (defun org-shiftdown (&optional arg)
11496 "Decrease item in timestamp or decrease priority of current item.
11497 Calls `org-timestamp-down' or `org-priority-down', depending on context.
11498 See the individual commands for more information."
11501 ((org-at-timestamp-p) (org-timestamp-down arg))
11502 (t (org-priority-down))))
11504 (defun org-shiftright ()
11505 "Next TODO keyword or timestamp one day later, depending on context."
11508 ((org-at-timestamp-p) (org-timestamp-up-day))
11509 ((org-on-heading-p) (org-todo 'right))
11510 (t (org-shiftcursor-error))))
11512 (defun org-shiftleft ()
11513 "Previous TODO keyword or timestamp one day earlier, depending on context."
11516 ((org-at-timestamp-p) (org-timestamp-down-day))
11517 ((org-on-heading-p) (org-todo 'left))
11518 (t (org-shiftcursor-error))))
11520 (defun org-copy-special ()
11521 "Copy region in table or copy current subtree.
11522 Calls `org-table-copy' or `org-copy-subtree', depending on context.
11523 See the individual commands for more information."
11525 (call-interactively
11526 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
11528 (defun org-cut-special ()
11529 "Cut region in table or cut current subtree.
11530 Calls `org-table-copy' or `org-cut-subtree', depending on context.
11531 See the individual commands for more information."
11533 (call-interactively
11534 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
11536 (defun org-paste-special (arg)
11537 "Paste rectangular region into table, or past subtree relative to level.
11538 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
11539 See the individual commands for more information."
11541 (if (org-at-table-p)
11542 (org-table-paste-rectangle)
11543 (org-paste-subtree arg)))
11545 ;; FIXME: document tags
11546 (defun org-ctrl-c-ctrl-c (&optional arg)
11547 "Call realign table, or recognize a table.el table, or update keywords.
11548 When the cursor is inside a table created by the table.el package,
11549 activate that table. Otherwise, if the cursor is at a normal table
11550 created with org.el, re-align that table. This command works even if
11551 the automatic table editor has been turned off.
11552 If the cursor is in one of the special #+KEYWORD lines, this triggers
11553 scanning the buffer for these lines and updating the information.
11554 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
11556 (let ((org-enable-table-editor t))
11558 ((org-on-heading-p) (org-set-tags arg))
11559 ((org-at-table.el-p)
11561 (beginning-of-line 1)
11562 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
11563 (table-recognize-table))
11565 (org-table-maybe-eval-formula)
11567 (org-table-recalculate t)
11568 (org-table-maybe-recalculate-line))
11571 (org-renumber-ordered-list (prefix-numeric-value arg)))
11572 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
11574 ((equal (match-string 1) "TBLFM")
11575 ;; Recalculate the table before this line
11577 (beginning-of-line 1)
11578 (skip-chars-backward " \r\n\t")
11579 (if (org-at-table-p) (org-table-recalculate t))))
11581 (org-mode-restart))))
11582 ((org-region-active-p)
11583 (org-table-convert-region (region-beginning) (region-end) arg))
11584 ((condition-case nil
11585 (and (region-beginning) (region-end))
11587 (if (y-or-n-p "Convert inactive region to table? ")
11588 (org-table-convert-region (region-beginning) (region-end) arg)
11590 (t (error "C-c C-c can do nothing useful at this location.")))))
11592 (defun org-mode-restart ()
11593 "Restart Org-mode, to scan again for special lines.
11594 Also updates the keyword regular expressions."
11596 (let ((org-inhibit-startup t)) (org-mode))
11597 (message "Org-mode restarted to refresh keyword and special line setup"))
11599 (defun org-return ()
11600 "Goto next table row or insert a newline.
11601 Calls `org-table-next-row' or `newline', depending on context.
11602 See the individual commands for more information."
11606 (org-table-justify-field-maybe)
11607 (org-table-next-row))
11610 (defun org-meta-return (&optional arg)
11611 "Insert a new heading or wrap a region in a table.
11612 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
11613 See the individual commands for more information."
11617 (org-table-wrap-region arg))
11618 (t (org-insert-heading arg))))
11622 ;; Define the Org-mode menus
11623 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
11625 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
11626 ["Next Field" org-cycle (org-at-table-p)]
11627 ["Previous Field" org-shifttab (org-at-table-p)]
11628 ["Next Row" org-return (org-at-table-p)]
11630 ["Blank Field" org-table-blank-field (org-at-table-p)]
11631 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
11634 ["Move Column Left" org-metaleft (org-at-table-p)]
11635 ["Move Column Right" org-metaright (org-at-table-p)]
11636 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
11637 ["Insert Column" org-shiftmetaright (org-at-table-p)])
11639 ["Move Row Up" org-metaup (org-at-table-p)]
11640 ["Move Row Down" org-metadown (org-at-table-p)]
11641 ["Delete Row" org-shiftmetaup (org-at-table-p)]
11642 ["Insert Row" org-shiftmetadown (org-at-table-p)]
11643 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
11645 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
11647 ["Copy Rectangle" org-copy-special (org-at-table-p)]
11648 ["Cut Rectangle" org-cut-special (org-at-table-p)]
11649 ["Paste Rectangle" org-paste-special (org-at-table-p)]
11650 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
11653 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
11654 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11655 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
11657 ["Recalculate line" org-table-recalculate (org-at-table-p)]
11658 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
11659 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
11661 ["Sum Column/Rectangle" org-table-sum
11662 (or (org-at-table-p) (org-region-active-p))]
11663 ["Which Column?" org-table-current-column (org-at-table-p)])
11665 (setq org-table-formula-debug (not org-table-formula-debug))
11666 :style toggle :selected org-table-formula-debug]
11668 ["Invisible Vlines" org-table-toggle-vline-visibility
11669 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
11671 ["Create" org-table-create (and (not (org-at-table-p))
11672 org-enable-table-editor)]
11673 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
11674 ["Import from File" org-table-import (not (org-at-table-p))]
11675 ["Export to File" org-table-export (org-at-table-p)]
11677 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
11679 (easy-menu-define org-org-menu org-mode-map "Org menu"
11681 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
11682 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
11683 ["Sparse Tree" org-occur t]
11684 ["Show All" show-all t]
11686 ["New Heading" org-insert-heading t]
11687 ("Navigate Headings"
11688 ["Up" outline-up-heading t]
11689 ["Next" outline-next-visible-heading t]
11690 ["Previous" outline-previous-visible-heading t]
11691 ["Next Same Level" outline-forward-same-level t]
11692 ["Previous Same Level" outline-backward-same-level t]
11694 ["Jump" org-goto t])
11696 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
11697 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
11699 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
11700 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
11701 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
11703 ["Promote Heading" org-metaleft (not (org-at-table-p))]
11704 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
11705 ["Demote Heading" org-metaright (not (org-at-table-p))]
11706 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
11708 ["Archive Subtree" org-archive-subtree t])
11711 ["TODO/DONE/-" org-todo t]
11712 ["Show TODO Tree" org-show-todo-tree t]
11713 ["Global TODO list" org-todo-list t]
11715 ["Set Priority" org-priority t]
11716 ["Priority Up" org-shiftup t]
11717 ["Priority Down" org-shiftdown t])
11718 ("Dates and Scheduling"
11719 ["Timestamp" org-time-stamp t]
11720 ["Timestamp (inactive)" org-time-stamp-inactive t]
11722 ["1 Day Later" org-timestamp-up-day t]
11723 ["1 Day Earlier" org-timestamp-down-day t]
11724 ["1 ... Later" org-shiftup t]
11725 ["1 ... Earlier" org-shiftdown t])
11726 ["Compute Time Range" org-evaluate-time-range t]
11727 ["Schedule Item" org-schedule t]
11728 ["Deadline" org-deadline t]
11730 ["Goto Calendar" org-goto-calendar t]
11731 ["Date from Calendar" org-date-from-calendar t])
11733 ["Agenda Command" org-agenda t]
11734 ("File List for Agenda")
11735 ("Special views current file"
11736 ["TODO Tree" org-show-todo-tree t]
11737 ["Check Deadlines" org-check-deadlines t]
11738 ["Timeline" org-timeline t]
11739 ["Tags Tree" org-tags-sparse-tree t])
11742 ["Store Link (Global)" org-store-link t]
11743 ["Insert Link" org-insert-link t]
11744 ["Follow Link" org-open-at-point t])
11747 ["ASCII" org-export-as-ascii t]
11748 ["Extract Visible Text" org-export-copy-visible t]
11749 ["HTML" org-export-as-html t]
11750 ["HTML and Open" org-export-as-html-and-open t]
11751 ; ["OPML" org-export-as-opml nil]
11753 ["iCalendar this file" org-export-icalendar-this-file t]
11754 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
11755 :active t :keys "C-c C-x C-i"]
11756 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
11758 ["Option Template" org-insert-export-options-template t]
11759 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
11762 ["Show Version" org-version t]
11763 ["Info Documentation" org-info t])
11765 ["Browse Org Group" org-customize t]
11767 ["Build Full Customize Menu" org-create-customize-menu
11768 (fboundp 'customize-menu-create)])
11770 ["Refresh setup" org-mode-restart t]
11773 (defun org-info (&optional node)
11774 "Read documentation for Org-mode in the info system.
11775 With optional NODE, go directly to that node."
11778 (Info-goto-node (format "(org)%s" (or node ""))))
11780 (defun org-install-agenda-files-menu ()
11782 '("Org") "File List for Agenda"
11785 ["Edit File List" (customize-variable 'org-agenda-files) t]
11786 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
11787 ["Remove Current File from List" org-remove-file t]
11788 ["Cycle through agenda files" org-cycle-agenda-files t]
11790 (mapcar 'org-file-menu-entry org-agenda-files))))
11794 (defun org-customize ()
11795 "Call the customize function with org as argument."
11797 (customize-browse 'org))
11799 (defun org-create-customize-menu ()
11800 "Create a full customization menu for Org-mode, insert it into the menu."
11802 (if (fboundp 'customize-menu-create)
11805 '("Org") "Customize"
11806 `(["Browse Org group" org-customize t]
11808 ,(customize-menu-create 'org)
11809 ["Set" Custom-set t]
11810 ["Save" Custom-save t]
11811 ["Reset to Current" Custom-reset-current t]
11812 ["Reset to Saved" Custom-reset-saved t]
11813 ["Reset to Standard Settings" Custom-reset-standard t]))
11814 (message "\"Org\"-menu now contains full customization menu"))
11815 (error "Cannot expand menu (outdated version of cus-edit.el)")))
11817 ;;; Miscellaneous stuff
11819 (defun org-move-line-down (arg)
11820 "Move the current line down. With prefix argument, move it past ARG lines."
11822 (let ((col (current-column))
11824 (beginning-of-line 1) (setq beg (point))
11825 (beginning-of-line 2) (setq end (point))
11826 (beginning-of-line (+ 1 arg))
11827 (setq pos (move-marker (make-marker) (point)))
11828 (insert (delete-and-extract-region beg end))
11830 (move-to-column col)))
11832 (defun org-move-line-up (arg)
11833 "Move the current line up. With prefix argument, move it past ARG lines."
11835 (let ((col (current-column))
11837 (beginning-of-line 1) (setq beg (point))
11838 (beginning-of-line 2) (setq end (point))
11839 (beginning-of-line (- arg))
11840 (setq pos (move-marker (make-marker) (point)))
11841 (insert (delete-and-extract-region beg end))
11843 (move-to-column col)))
11845 ;; Paragraph filling stuff.
11846 ;; We want this to be just right, so use the full arsenal.
11847 ;; FIXME: This very likely does not work correctly for XEmacs, because the
11848 ;; filladapt package works slightly differently.
11850 (defun org-set-autofill-regexps ()
11852 ;; In the paragraph separator we include headlines, because filling
11853 ;; text in a line directly attached to a headline would otherwise
11854 ;; fill the headline as well.
11855 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
11856 ;; The paragraph starter includes hand-formatted lists.
11857 (set (make-local-variable 'paragraph-start)
11858 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
11859 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
11860 ;; But only if the user has not turned off tables or fixed-width regions
11861 (set (make-local-variable 'auto-fill-inhibit-regexp)
11863 (if (or org-enable-table-editor org-enable-fixed-width-editor)
11866 (if org-enable-table-editor "|" "")
11867 (if org-enable-fixed-width-editor ":" "")
11869 ;; We use our own fill-paragraph function, to make sure that tables
11870 ;; and fixed-width regions are not wrapped. That function will pass
11871 ;; through to `fill-paragraph' when appropriate.
11872 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
11873 ;; Adaptive filling: To get full control, first make sure that
11874 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
11875 (setq adaptive-fill-regexp "\000")
11876 (setq adaptive-fill-function 'org-adaptive-fill-function))
11878 (defun org-fill-paragraph (&optional justify)
11879 "Re-align a table, pass through to fill-paragraph if no table."
11880 (let ((table-p (org-at-table-p))
11881 (table.el-p (org-at-table.el-p)))
11882 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
11883 (table.el-p t) ; skip table.el tables
11884 (table-p (org-table-align) t) ; align org-mode tables
11885 (t nil)))) ; call paragraph-fill
11887 ;; For reference, this is the default value of adaptive-fill-regexp
11888 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
11890 (defun org-adaptive-fill-function ()
11891 "Return a fill prefix for org-mode files.
11892 In particular, this makes sure hanging paragraphs for hand-formatted lists
11894 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
11895 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11897 ;; Functions needed for Emacs/XEmacs region compatibility
11899 (defun org-region-active-p ()
11900 "Is `transient-mark-mode' on and the region active?
11901 Works on both Emacs and XEmacs."
11902 (if org-ignore-region
11905 (and zmacs-regions (region-active-p))
11906 (and transient-mark-mode mark-active))))
11908 (defun org-add-to-invisibility-spec (arg)
11909 "Add elements to `buffer-invisibility-spec'.
11910 See documentation for `buffer-invisibility-spec' for the kind of elements
11911 that can be added."
11913 ((fboundp 'add-to-invisibility-spec)
11914 (add-to-invisibility-spec arg))
11915 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
11916 (setq buffer-invisibility-spec (list arg)))
11918 (setq buffer-invisibility-spec
11919 (cons arg buffer-invisibility-spec)))))
11921 (defun org-remove-from-invisibility-spec (arg)
11922 "Remove elements from `buffer-invisibility-spec'."
11923 (if (fboundp 'remove-from-invisibility-spec)
11924 (remove-from-invisibility-spec arg)
11925 (if (consp buffer-invisibility-spec)
11926 (setq buffer-invisibility-spec
11927 (delete arg buffer-invisibility-spec)))))
11929 (defun org-in-invisibility-spec-p (arg)
11930 "Is ARG a member of `buffer-invisibility-spec'?."
11931 (if (consp buffer-invisibility-spec)
11932 (member arg buffer-invisibility-spec)
11935 (defun org-image-file-name-regexp ()
11936 "Return regexp matching the file names of images."
11937 (if (fboundp 'image-file-name-regexp)
11938 (image-file-name-regexp)
11939 (let ((image-file-name-extensions
11940 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
11941 "xbm" "xpm" "pbm" "pgm" "ppm")))
11943 (regexp-opt (nconc (mapcar 'upcase
11944 image-file-name-extensions)
11945 image-file-name-extensions)
11949 ;; Functions needed for compatibility with old outline.el
11951 ;; The following functions capture almost the entire compatibility code
11952 ;; between the different versions of outline-mode. The only other place
11953 ;; where this is important are the font-lock-keywords. Search for
11954 ;; `org-noutline-p' to find it.
11956 ;; C-a should go to the beginning of a *visible* line, also in the
11957 ;; new outline.el. I guess this should be patched into Emacs?
11958 (defun org-beginning-of-line ()
11959 "Go to the beginning of the current line. If that is invisible, continue
11960 to a visible line beginning. This makes the function of C-a more intuitive."
11962 (beginning-of-line 1)
11966 (if (org-invisible-p)
11967 (while (and (not (bobp)) (org-invisible-p))
11969 (beginning-of-line 1))
11970 (forward-char 1))))
11971 (when org-noutline-p
11972 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
11974 (defun org-invisible-p ()
11975 "Check if point is at a character currently not visible."
11977 ;; Early versions of noutline don't have `outline-invisible-p'.
11978 (if (fboundp 'outline-invisible-p)
11979 (outline-invisible-p)
11980 (get-char-property (point) 'invisible))
11982 (skip-chars-backward "^\r\n")
11983 (equal (char-before) ?\r))))
11985 (defun org-back-to-heading (&optional invisible-ok)
11986 "Move to previous heading line, or beg of this line if it's a heading.
11987 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
11989 (outline-back-to-heading invisible-ok)
11990 (if (looking-at outline-regexp)
11992 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
11996 (progn (goto-char (match-end 1))
11997 (looking-at outline-regexp)))
11998 (error "Before first heading")))))
12000 (defun org-on-heading-p (&optional invisible-ok)
12001 "Return t if point is on a (visible) heading line.
12002 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12004 (outline-on-heading-p 'invisible-ok)
12006 (skip-chars-backward "^\n\r")
12007 (and (looking-at outline-regexp)
12010 (equal (char-before) ?\n))))))
12012 (defun org-up-heading-all (arg)
12013 "Move to the heading line of which the present line is a subheading.
12014 This function considers both visible and invisible heading lines.
12015 With argument, move up ARG levels."
12017 (if (fboundp 'outline-up-heading-all)
12018 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12019 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12020 (org-back-to-heading t)
12021 (looking-at outline-regexp)
12022 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12023 (error "Cannot move up %d levels" arg)
12024 (re-search-backward
12025 (concat "[\n\r]" (regexp-quote
12026 (make-string (- (match-end 0) (match-beginning 0) arg)
12029 (forward-char 1))))
12031 (defun org-show-hidden-entry ()
12032 "Show an entry where even the heading is hidden."
12034 (if (not org-noutline-p)
12036 (org-back-to-heading t)
12037 (org-flag-heading nil)))
12040 (defun org-check-occur-regexp (regexp)
12041 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12042 Of course, only for the old outline mode."
12045 (if (string-match "^\\^" regexp)
12046 (concat "[\n\r]" (substring regexp 1))
12049 (defun org-flag-heading (flag &optional entry)
12050 "Flag the current heading. FLAG non-nil means make invisible.
12051 When ENTRY is non-nil, show the entire entry."
12053 (org-back-to-heading t)
12054 (if (not org-noutline-p)
12055 ;; Make the current headline visible
12056 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12057 ;; Check if we should show the entire entry
12061 (save-excursion ;; FIXME: Is this the fix for points in the -|
12062 ;; middle of text? |
12063 (and (outline-next-heading) ;; |
12064 (org-flag-heading nil)))) ; show the next heading _|
12065 (outline-flag-region (max 1 (1- (point)))
12066 (save-excursion (outline-end-of-heading) (point))
12069 (if flag ?\r ?\n))))))
12071 (defun org-show-subtree ()
12072 "Show everything after this heading at deeper levels."
12073 (outline-flag-region
12076 (outline-end-of-subtree) (outline-next-heading) (point))
12077 (if org-noutline-p nil ?\n)))
12079 (defun org-show-entry ()
12080 "Show the body directly following this heading.
12081 Show the heading too, if it is currently invisible."
12084 (org-back-to-heading t)
12085 (outline-flag-region
12088 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12089 (or (match-beginning 1) (point-max)))
12090 (if org-noutline-p nil ?\n))))
12093 (defun org-make-options-regexp (kwds)
12094 "Make a regular expression for keyword lines."
12096 (if org-noutline-p "^" "[\n\r]")
12098 (mapconcat 'regexp-quote kwds "\\|")
12100 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12102 ;; Make `bookmark-jump' show the jump location if it was hidden.
12103 (eval-after-load "bookmark"
12104 '(if (boundp 'bookmark-after-jump-hook)
12105 ;; We can use the hook
12106 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12107 ;; Hook not available, use advice
12108 (defadvice bookmark-jump (after org-make-visible activate)
12109 "Make the position visible."
12110 (org-bookmark-jump-unhide))))
12112 (defun org-bookmark-jump-unhide ()
12113 "Unhide the current position, to show the bookmark location."
12114 (and (eq major-mode 'org-mode)
12115 (or (org-invisible-p)
12116 (save-excursion (goto-char (max (point-min) (1- (point))))
12117 (org-invisible-p)))
12118 (org-show-hierarchy-above)))
12124 (run-hooks 'org-load-hook)
12126 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12127 ;;; org.el ends here