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
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-todo-list "org" "Multi-file todo list from Org mode" t)
63 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
64 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
65 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
67 ;; This setup will put all files with extension ".org" into Org-mode. As
68 ;; an alternative, make the first line of a file look like this:
70 ;; MY PROJECTS -*- mode: org; -*-
72 ;; which will select Org-mode for this buffer no matter what the file's
77 ;; The documentation of Org-mode can be found in the TeXInfo file. The
78 ;; distribution also contains a PDF version of it. At the homepage of
79 ;; Org-mode, you can read the same text online as HTML. There is also an
80 ;; excellent reference card made by Philip Rooke. This card can be found
81 ;; in the etc/ directory of Emacs 22.
86 ;; - M-RET makes new items as well as new headings.
87 ;; - Various small bug fixes
90 ;; - CamelCase words link to other locations in the same file.
91 ;; - File links accept search options, to link to specific locations.
92 ;; - Plain list items can be folded with `org-cycle'. See new option
93 ;; `org-cycle-include-plain-lists'.
94 ;; - Sparse trees for specific TODO keywords through numeric prefix
95 ;; argument to `C-c C-v'.
96 ;; - Global TODO list, also for specific keywords.
97 ;; - Matches in sparse trees are highlighted (highlights disappear with
98 ;; next buffer change due to editing).
101 ;; - Improved CSS support for the HTML export. Thanks to Christian Egli.
102 ;; - Editing support for hand-formatted lists
103 ;; - M-S-cursor keys handle plain list items
104 ;; - C-c C-c renumbers ordered plain lists
107 ;; - There is finally an option to make TAB jump over horizontal lines
108 ;; in tables instead of creating a new line before that line.
109 ;; The option is `org-table-tab-jumps-over-hlines', default nil.
110 ;; - New command for sorting tables, on `C-c ^'.
111 ;; - Changes to the HTML exporter
112 ;; - hand-formatted lists are exported correctly, similar to
113 ;; markdown lists. Nested lists are possible. See the docstring
114 ;; of the variable `org-export-plain-list-max-depth'.
115 ;; - cleaned up to produce valid HTML 4.0 (transitional).
116 ;; - support for cascading style sheets.
117 ;; - New command to cycle through all agenda files, on C-,
118 ;; - C-c [ can now also be used to change the sequence of agenda files.
124 ;; - Export of calendar information in the standard iCalendar format.
128 ;; - HTML export specifies character set depending on coding-system.
131 ;; - In tables, directly after the field motion commands like TAB and RET,
132 ;; typing a character will blank the field. Can be turned off with
133 ;; variable `org-table-auto-blank-field'.
134 ;; - Inactive timestamps with `C-c !'. These do not trigger the agenda
135 ;; and are not linked to the calendar.
136 ;; - Additional key bindings to allow Org-mode to function on a tty emacs.
137 ;; - `C-c C-h' prefix key replaced by `C-c C-x', and `C-c C-x C-h' replaced
138 ;; by `C-c C-x b' (b=Browser). This was necessary to recover the
139 ;; standard meaning of C-h after a prefix key (show prefix bindings).
142 ;; - QUOTE keyword at the beginning of an entry causes fixed-width export
143 ;; of unmodified entry text. `C-c :' toggles this keyword.
144 ;; - New face `org-special-keyword' which is used for COMMENT, QUOTE,
145 ;; DEADLINE and SCHEDULED, and priority cookies. Default is only a weak
146 ;; color, to reduce the amount of aggressive color in the buffer.
149 ;; - Formulas for individual fields in table.
150 ;; - Automatic recalculation in calculating tables.
151 ;; - Named fields and columns in tables.
152 ;; - Fixed bug with calling `org-archive' several times in a row.
155 ;; - Efficiency improvements: Fewer table re-alignments needed.
156 ;; - New special lines in tables, for defining names for individual cells.
159 ;; - Tables can store formulas (one per column) and compute fields.
160 ;; Not quite like a full spreadsheet, but very powerful.
161 ;; - table.el keybinding is now `C-c ~'.
162 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
163 ;; - Small changes to keys in agenda buffer. Affected keys:
164 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
168 ;; - Links inserted with C-c C-l are now by default enclosed in angle
169 ;; brackets. See the new variable `org-link-format'.
170 ;; - ">" terminates a link, this is a way to have several links in a line.
171 ;; Both "<" and ">" are no longer allowed as characters in a link.
172 ;; - Archiving of finished tasks.
173 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
174 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
175 ;; - Compatibility problems with viper-mode fixed.
176 ;; - Improved html export of tables.
177 ;; - Various clean-up changes.
180 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
183 ;; - Time-of-day specifications in agenda are extracted and placed
184 ;; into the prefix. Timed entries can be placed into a time grid for
188 ;; - "|" no longer allowed as part of a link, to allow links in tables.
189 ;; - The prefix of items in the agenda buffer can be configured.
193 ;; - Some folding incinsistencies removed.
194 ;; - BBDB links to company-only entries.
195 ;; - Bug fixes and global cleanup.
198 ;; - M-S-RET inserts a new TODO heading.
199 ;; - New startup option `content'.
200 ;; - Better visual response when TODO items in agenda change status.
201 ;; - Window positioning after visibility state changes optimized and made
202 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
205 ;; - Agenda entries from the diary are linked to the diary file, so
206 ;; adding and editing diary entries can be done directly from the agenda.
207 ;; - Many calendar/diary commands available directly from agenda.
208 ;; - Field copying in tables with S-RET does increment.
209 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
210 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
213 ;; - Table editor optimized to need fewer realignments, and to keep
214 ;; table shape when typing in fields.
215 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
216 ;; into arbitrary major modes.
217 ;; - Fixed bug with realignment in XEmacs.
218 ;; - Startup options can be set with special #+STARTUP line.
219 ;; - Heading following a match in org-occur can be suppressed.
222 ;; - Copyright transfer to the FSF.
223 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
224 ;; - Timeline now always contains today, and `.' jumps to it.
226 ;; - cut and paste of rectangular regions in tables
227 ;; - command to convert org-mode table to table.el table and back
228 ;; - command to treat several cells like a paragraph and fill it
229 ;; - command to convert a buffer region to a table
230 ;; - import/export tables as tab-separated files (exchange with Excel)
232 ;; - Sorting mechanism for agenda items rewritten from scratch.
233 ;; - Sorting fully configurable.
234 ;; - Entries specifying a time are sorted together.
235 ;; - Completion also covers option keywords after `#-'.
239 ;; - New reference card, thanks to Philip Rooke for creating it.
240 ;; - Single file agenda renamed to "Timeline". It no longer shows
241 ;; warnings about upcoming deadlines/overdue scheduled items.
242 ;; That functionality is now limited to the (multifile) agenda.
243 ;; - When reading a date, the calendar can be manipulated with keys.
244 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
245 ;; - Minor bug fixes and documentation improvements.
249 (eval-when-compile (require 'cl) (require 'calendar))
254 (defvar calc-embedded-close-formula)
255 (defvar calc-embedded-open-formula)
256 (defvar font-lock-unfontify-region-function)
258 ;;; Customization variables
260 (defvar org-version "3.23"
261 "The version number of the file org.el.")
262 (defun org-version ()
264 (message "Org-mode version %s" org-version))
266 ;; The following two constants are for compatibility with different Emacs
267 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
268 ;; The compatibility code in org.el is based on these two constants.
269 (defconst org-xemacs-p (featurep 'xemacs)
270 "Are we running xemacs?")
271 (defconst org-noutline-p (featurep 'noutline)
272 "Are we using the new outline mode?")
275 "Outline-based notes management and organizer "
281 (defgroup org-startup nil
282 "Options concerning startup of Org-mode."
286 (defcustom org-CUA-compatible nil
287 "Non-nil means use alternative key bindings for S-<cursor movement>.
288 Org-mode used S-<cursor movement> for changing timestamps and priorities.
289 S-<cursor movement> is also used for example by `CUA-mode' to select text.
290 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
291 alternative bindings. Setting this variable to t will replace the following
292 keys both in Org-mode and in the Org-agenda buffer.
300 If you do not like the alternative keys, take a look at the variable
303 This option is only relevant at load-time of Org-mode. Changing it requires
304 a restart of Emacs to become effective."
308 (defvar org-disputed-keys
309 '((S-up [(shift up)] [(meta ?p)])
310 (S-down [(shift down)] [(meta ?n)])
311 (S-left [(shift left)] [(meta ?-)])
312 (S-right [(shift right)] [(meta ?+)])
313 (S-return [(shift return)] [(control shift return)]))
314 "Keys for which Org-mode and other modes compete.
315 This is an alist, cars are symbols for lookup, 1st element is the default key,
316 second element will be used when `org-CUA-compatible' is t.")
319 "Select a key according to `org-CUA-compatible'."
320 (nth (if org-CUA-compatible 2 1)
321 (or (assq key org-disputed-keys)
322 (error "Invalid Key %s in `org-key'" key))))
324 (defcustom org-startup-folded t
325 "Non-nil means, entering Org-mode will switch to OVERVIEW.
326 This can also be configured on a per-file basis by adding one of
327 the following lines anywhere in the buffer:
334 (const :tag "nofold: show all" nil)
335 (const :tag "fold: overview" t)
336 (const :tag "content: all headlines" content)))
338 (defcustom org-startup-truncated t
339 "Non-nil means, entering Org-mode will set `truncate-lines'.
340 This is useful since some lines containing links can be very long and
341 uninteresting. Also tables look terrible when wrapped."
345 (defcustom org-startup-with-deadline-check nil
346 "Non-nil means, entering Org-mode will run the deadline check.
347 This means, if you start editing an org file, you will get an
348 immediate reminder of any due deadlines.
349 This can also be configured on a per-file basis by adding one of
350 the following lines anywhere in the buffer:
353 #+STARTUP: nodlcheck"
357 (defcustom org-insert-mode-line-in-empty-file nil
358 "Non-nil means insert the first line setting Org-mode in empty files.
359 When the function `org-mode' is called interactively in an empty file, this
360 normally means that the file name does not automatically trigger Org-mode.
361 To ensure that the file will always be in Org-mode in the future, a
362 line enforcing Org-mode will be inserted into the buffer, if this option
367 (defgroup org-keywords nil
368 "Options concerning TODO items in Org-mode."
372 (defcustom org-todo-keywords '("TODO" "DONE")
373 "List of TODO entry keywords.
374 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
375 considered to mean that the entry is \"done\". All the other mean that
376 action is required, and will make the entry show up in todo lists, diaries
378 The command \\[org-todo] cycles an entry through these states, and an
379 additional state where no keyword is present. For details about this
380 cycling, see also the variable `org-todo-interpretation'
381 Changes become only effective after restarting Emacs."
383 :type '(repeat (string :tag "Keyword")))
385 (defcustom org-todo-interpretation 'sequence
386 "Controls how TODO keywords are interpreted.
387 \\<org-mode-map>Possible values are `sequence' and `type'.
388 This variable is only relevant if `org-todo-keywords' contains more than two
389 states. There are two ways how these keywords can be used:
391 - As a sequence in the process of working on a TODO item, for example
392 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
393 org-todo-interpretation 'sequence)
395 - As different types of TODO items, for example
396 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
397 org-todo-interpretation 'type)
399 When the states are interpreted as a sequence, \\[org-todo] always cycles
400 to the next state, in order to walk through all different states. So with
401 \\[org-todo], you turn an empty entry into the state TODO. When you started
402 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
403 later to VERIFY and finally to DONE.
405 When the states are interpreted as types, \\[org-todo] still cycles through
406 when it is called several times in direct succession, in order to initially
407 select the type. However, if not called immediately after a previous
408 \\[org-todo], it switches from each type directly to DONE. So with the
409 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
410 RELAXED. If you later return to this entry and press \\[org-todo] again,
411 RELAXED will not be changed REMIND, but directly to DONE.
413 You can create a large number of types. To initially select a
414 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
415 type with completion. Of course, you can also type the keyword
416 directly into the buffer. M-TAB completes TODO keywords at the
417 beginning of a headline."
419 :type '(choice (const sequence)
422 (defcustom org-default-priority ?B
423 "The default priority of TODO items.
424 This is the priority an item get if no explicit priority is given."
428 (defcustom org-lowest-priority ?C
429 "The lowest priority of TODO items. A character like ?A, ?B etc."
433 (defcustom org-deadline-string "DEADLINE:"
434 "String to mark deadline entries.
435 A deadline is this string, followed by a time stamp. Should be a word,
436 terminated by a colon. You can insert a schedule keyword and
437 a timestamp with \\[org-deadline].
438 Changes become only effective after restarting Emacs."
442 (defcustom org-scheduled-string "SCHEDULED:"
443 "String to mark scheduled TODO entries.
444 A schedule is this string, followed by a time stamp. Should be a word,
445 terminated by a colon. You can insert a schedule keyword and
446 a timestamp with \\[org-schedule].
447 Changes become only effective after restarting Emacs."
451 (defcustom org-comment-string "COMMENT"
452 "Entries starting with this keyword will never be exported.
453 An entry can be toggled between COMMENT and normal with
454 \\[org-toggle-comment].
455 Changes become only effective after restarting Emacs."
459 (defcustom org-quote-string "QUOTE"
460 "Entries starting with this keyword will be exported in fixed-width font.
461 Quoting applies only to the text in the entry following the headline, and does
462 not extend beyond the next headline, even if that is lower level.
463 An entry can be toggled between QUOTE and normal with
464 \\[org-toggle-fixed-width-section]"
468 (defcustom org-after-todo-state-change-hook nil
469 "Hook which is run after the state of a TODO item was changed.
470 The new state (a string with a todo keyword, or nil) is available in the
471 Lisp variable `state'."
475 ;; Variables for pre-computed regular expressions, all buffer local
476 (defvar org-todo-kwd-priority-p nil
477 "Do TODO items have priorities?")
478 (make-variable-buffer-local 'org-todo-kwd-priority-p)
479 (defvar org-todo-kwd-max-priority nil
480 "Maximum priority of TODO items.")
481 (make-variable-buffer-local 'org-todo-kwd-max-priority)
482 (defvar org-ds-keyword-length 12
483 "Maximum length of the Deadline and SCHEDULED keywords.")
484 (make-variable-buffer-local 'org-ds-keyword-length)
485 (defvar org-done-string nil
486 "The last string in `org-todo-keywords', indicating an item is DONE.")
487 (make-variable-buffer-local 'org-done-string)
488 (defvar org-todo-regexp nil
489 "Matches any of the TODO state keywords.")
490 (make-variable-buffer-local 'org-todo-regexp)
491 (defvar org-not-done-regexp nil
492 "Matches any of the TODO state keywords except the last one.")
493 (make-variable-buffer-local 'org-not-done-regexp)
494 (defvar org-todo-line-regexp nil
495 "Matches a headline and puts TODO state into group 2 if present.")
496 (make-variable-buffer-local 'org-todo-line-regexp)
497 (defvar org-nl-done-regexp nil
498 "Matches newline followed by a headline with the DONE keyword.")
499 (make-variable-buffer-local 'org-nl-done-regexp)
500 (defvar org-looking-at-done-regexp nil
501 "Matches the DONE keyword a point.")
502 (make-variable-buffer-local 'org-looking-at-done-regexp)
503 (defvar org-deadline-regexp nil
504 "Matches the DEADLINE keyword.")
505 (make-variable-buffer-local 'org-deadline-regexp)
506 (defvar org-deadline-time-regexp nil
507 "Matches the DEADLINE keyword together with a time stamp.")
508 (make-variable-buffer-local 'org-deadline-time-regexp)
509 (defvar org-deadline-line-regexp nil
510 "Matches the DEADLINE keyword and the rest of the line.")
511 (make-variable-buffer-local 'org-deadline-line-regexp)
512 (defvar org-scheduled-regexp nil
513 "Matches the SCHEDULED keyword.")
514 (make-variable-buffer-local 'org-scheduled-regexp)
515 (defvar org-scheduled-time-regexp nil
516 "Matches the SCHEDULED keyword together with a time stamp.")
517 (make-variable-buffer-local 'org-scheduled-time-regexp)
519 (defvar org-category nil
520 "Variable used by org files to set a category for agenda display.
521 Such files should use a file variable to set it, for example
523 -*- mode: org; org-category: \"ELisp\"
525 or contain a special line
529 If the file does not specify a category, then file's base name
532 (defgroup org-time nil
533 "Options concerning time stamps and deadlines in Org-mode."
537 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
538 "Formats for `format-time-string' which are used for time stamps.
539 It is not recommended to change this constant.")
542 (defcustom org-deadline-warning-days 30
543 "No. of days before expiration during which a deadline becomes active.
544 This variable governs the display in the org file."
548 (defcustom org-popup-calendar-for-date-prompt t
549 "Non-nil means, pop up a calendar when prompting for a date.
550 In the calendar, the date can be selected with mouse-1. However, the
551 minibuffer will also be active, and you can simply enter the date as well.
552 When nil, only the minibuffer will be available."
556 (defcustom org-calendar-follow-timestamp-change t
557 "Non-nil means, make the calendar window follow timestamp changes.
558 When a timestamp is modified and the calendar window is visible, it will be
559 moved to the new date."
563 (defgroup org-agenda nil
564 "Options concerning agenda display Org-mode."
568 (defcustom org-agenda-files nil
569 "A list of org files for agenda/diary display.
570 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
571 \\[org-remove-file]. You can also use customize to edit the list."
573 :type '(repeat file))
575 (defcustom org-select-timeline-window t
576 "Non-nil means, after creating a timeline, move cursor into Timeline window.
577 When nil, cursor will remain in the current window."
581 (defcustom org-select-agenda-window t
582 "Non-nil means, after creating an agenda, move cursor into Agenda window.
583 When nil, cursor will remain in the current window."
587 (defcustom org-fit-agenda-window t
588 "Non-nil means, change window size of agenda to fit content."
592 (defcustom org-agenda-show-all-dates t
593 "Non-nil means, `org-agenda' shows every day in the selected range.
594 When nil, only the days which actually have entries are shown."
598 ;; FIXME: First day of month works only for current month because it would
599 ;; require a variable ndays treatment.
600 (defcustom org-agenda-start-on-weekday 1
601 "Non-nil means, start the overview always on the specified weekday.
602 0 Denotes Sunday, 1 denotes Monday etc.
603 When nil, always start on the current day."
605 :type '(choice (const :tag "Today" nil)
606 (const :tag "First day of month" t)
607 (number :tag "Weekday No.")))
609 (defcustom org-agenda-ndays 7
610 "Number of days to include in overview display."
614 (defcustom org-agenda-include-all-todo t
615 "Non-nil means, the agenda will always contain all TODO entries.
616 When nil, date-less entries will only be shown if `org-agenda' is called
617 with a prefix argument.
618 When non-nil, the TODO entries will be listed at the top of the agenda, before
619 the entries for specific days."
623 (defcustom org-agenda-include-diary nil
624 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
628 (defcustom org-calendar-to-agenda-key [?c]
629 "The key to be installed in `calendar-mode-map' for switching to the agenda.
630 The command `org-calendar-goto-agenda' will be bound to this key. The
631 default is the character `c' because then`c' can be used to switch back and
632 force between agenda and calendar."
636 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
637 "Sorting structure for the agenda items of a single day.
638 This is a list of symbols which will be used in sequence to determine
639 if an entry should be listed before another entry. The following
640 symbols are recognized.
642 time-up Put entries with time-of-day indications first, early first
643 time-down Put entries with time-of-day indications first, late first
644 category-keep Keep the default order of categories, corresponding to the
645 sequence in `org-agenda-files'.
646 category-up Sort alphabetically by category, A-Z.
647 category-down Sort alphabetically by category, Z-A.
648 priority-up Sort numerically by priority, high priority last.
649 priority-down Sort numerically by priority, high priority first.
651 The different possibilities will be tried in sequence, and testing stops
652 if one comparison returns a \"not-equal\". For example, the default
653 '(time-up category-keep priority-down)
654 means: Pull out all entries having a specified time of day and sort them,
655 in order to make a time schedule for the current day the first thing in the
656 agenda listing for the day. Of the entries without a time indication, keep
657 the grouped in categories, don't sort the categories, but keep them in
658 the sequence given in `org-agenda-files'. Within each category sort by
661 Leaving out `category-keep' would mean that items will be sorted across
662 categories by priority."
668 (const category-keep)
670 (const category-down)
672 (const priority-down))))
674 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
675 "Format specification for the prefix of items in the agenda buffer.
676 This format works similar to a printf format, with the following meaning:
678 %c the category of the item, \"Diary\" for entries from the diary, or
679 as given by the CATEGORY keyword or derived from the file name.
680 %t the time-of-day specification if one applies to the entry, in the
682 %s Scheduling/Deadline information, a short string
684 All specifiers work basically like the standard `%s' of printf, but may
685 contain two additional characters: A question mark just after the `%' and
686 a whitespace/punctuation character just before the final letter.
688 If the first character after `%' is a question mark, the entire field
689 will only be included if the corresponding value applies to the
690 current entry. This is useful for fields which should have fixed
691 width when present, but zero width when absent. For example,
692 \"%?-12t\" will result in a 12 character time field if a time of the
693 day is specified, but will completely disappear in entries which do
696 If there is punctuation or whitespace character just before the final
697 format letter, this character will be appended to the field value if
698 the value is not empty. For example, the format \"%-12:c\" leads to
699 \"Diary: \" if the category is \"Diary\". If the category were be
700 empty, no additional colon would be interted.
702 The default value of this option is \" %-12:c%?-12t% s\", meaning:
703 - Indent the line with two space characters
704 - Give the category in a 12 chars wide field, padded with whitespace on
705 the right (because of `-'). Append a colon if there is a category
707 - If there is a time-of-day, put it into a 12 chars wide field. If no
708 time, don't put in an empty field, just skip it (because of '?').
709 - Finally, put the scheduling information and append a whitespace.
711 As another example, if you don't want the time-of-day of entries in
712 the prefix, you could use:
714 (setq org-agenda-prefix-format \" %-11:c% s\")
716 See also the variable `org-agenda-remove-times-when-in-prefix'."
720 (defcustom org-timeline-prefix-format " % s"
721 "Like `org-agenda-prefix-format', but for the timeline of a single file."
725 (defvar org-prefix-format-compiled nil
726 "The compiled version of the most recently used prefix format.
727 Depending on which command was used last, this may be the compiled version
728 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
730 (defcustom org-agenda-use-time-grid t
731 "Non-nil means, show a time grid in the agenda schedule.
732 A time grid is a set of lines for specific times (like every two hours between
733 8:00 and 20:00. The items scheduled for a day at specific times are
734 sorted in between these lines.
735 For deails about when the grid will be shown, and what it will look like, see
736 the variable `org-agenda-time-grid'."
740 (defcustom org-agenda-time-grid
741 '((daily today require-timed)
743 (800 1000 1200 1400 1600 1800 2000))
745 "The settings for time grid for agenda display.
746 This is a list of three items. The first item is again a list. It contains
747 symbols specifying conditions when the grid should be displayed:
749 daily if the agenda shows a single day
750 weekly if the agenda shows an entire week
751 today show grid on current date, independent of daily/weekly display
752 require-timed show grid only if at least on item has a time specification
754 The second item is a string which will be places behing the grid time.
756 The third item is a list of integers, indicating the times that should have
761 (set :greedy t :tag "Grid Display Options"
762 (const :tag "Show grid in single day agenda display" daily)
763 (const :tag "Show grid in weekly agenda display" weekly)
764 (const :tag "Always show grid for today" today)
765 (const :tag "Show grid only if any timed entries are present"
767 (const :tag "Skip grid times already present in an entry"
769 (string :tag "Grid String")
770 (repeat :tag "Grid Times" (integer :tag "Time"))))
772 (defcustom org-agenda-remove-times-when-in-prefix t
773 "Non-nil means, remove duplicate time specifications in agenda items.
774 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
775 time-of-day specification in a headline or diary entry is extracted and
776 placed into the prefix. If this option is non-nil, the original specification
777 \(a timestamp or -range, or just a plain time(range) specification like
778 11:30-4pm) will be removed for agenda display. This makes the agenda less
780 The option can be t or nil. It may also be the symbol `beg', indicating
781 that the time should only be removed what it is located at the beginning of
782 the headline/diary entry."
785 (const :tag "Always" t)
786 (const :tag "Never" nil)
787 (const :tag "When at beginning of entry" beg)))
789 (defcustom org-sort-agenda-notime-is-late t
790 "Non-nil means, items without time are considered late.
791 This is only relevant for sorting. When t, items which have no explicit
792 time like 15:30 will be considered as 24:01, i.e. later than any items which
793 do have a time. When nil, the default time is before 0:00. You can use this
794 option to decide if the schedule for today should come before or after timeless
799 (defgroup org-structure nil
800 "Options concerning structure editing in Org-mode."
804 (defcustom org-cycle-include-plain-lists nil
805 "Non-nil means, include plain lists into visibility cycling.
806 This means that during cycling, plain list items will *temporarily* be
807 interpreted as outline headlines with a level given by 1000+i where i is the
808 indentation of the bullet. In all other operations, plain list items are
809 not seen as headlines. For example, you cannot assign a TODO keyword to
811 :group 'org-structure
814 (defcustom org-cycle-emulate-tab t
815 "Where should `org-cycle' emulate TAB.
817 white Only in completely white lines
818 t Everywhere except in headlines"
819 :group 'org-structure
820 :type '(choice (const :tag "Never" nil)
821 (const :tag "Only in completely white lines" white)
822 (const :tag "Everywhere except in headlines" t)
825 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
826 "Hook that is run after `org-cycle' has changed the buffer visibility.
827 The function(s) in this hook must accept a single argument which indicates
828 the new state that was set by the most recent `org-cycle' command. The
829 argument is a symbol. After a global state change, it can have the values
830 `overview', `content', or `all'. After a local state change, it can have
831 the values `folded', `children', or `subtree'."
832 :group 'org-structure
835 (defcustom org-highlight-sparse-tree-matches t
836 "Non-nil means, highlight all matches that define a sparse tree.
837 The highlights will automatically disappear the next time the buffer is
838 changed by an edit command."
839 :group 'org-structure
842 (defcustom org-show-hierarchy-above t
843 "Non-nil means, show full hierarchy when showing a spot in the tree.
844 Turning this off makes sparse trees more compact, but also less clear."
845 :group 'org-structure
848 (defcustom org-show-following-heading t
849 "Non-nil means, show heading following match in `org-occur'.
850 When doing an `org-occur' it is useful to show the headline which
851 follows the match, even if they do not match the regexp. This makes it
852 easier to edit directly inside the sparse tree. However, if you use
853 org-occur mainly as an overview, the following headlines are
854 unnecessary clutter."
855 :group 'org-structure
858 (defcustom org-occur-hook '(org-first-headline-recenter)
859 "Hook that is run after `org-occur' has constructed a sparse tree.
860 This can be used to recenter the window to show as much of the structure
862 :group 'org-structure
865 (defcustom org-level-color-stars-only nil
866 "Non-nil means fontify only the stars in each headline.
867 When nil, the entire headline is fontified.
868 After changin this, requires restart of Emacs to become effective."
869 :group 'org-structure
872 (defcustom org-adapt-indentation t
873 "Non-nil means, adapt indentation when promoting and demoting.
874 When this is set and the *entire* text in an entry is indented, the
875 indentation is increased by one space in a demotion command, and
876 decreased by one in a promotion command. If any line in the entry
877 body starts at column 0, indentation is not changed at all."
878 :group 'org-structure
881 (defcustom org-plain-list-ordered-item-terminator t
882 "The character that makes a line with leading number an ordered list item.
883 Valid values are ?. and ?\). To get both terminators, use t. While
884 ?. may look nicer, it creates the danger that a line with leading
885 number may be incorrectly interpreted as an item. ?\) therefore is
887 :group 'org-structure
888 :type '(choice (const :tag "dot like in \"2.\"" ?.)
889 (const :tag "paren like in \"2)\"" ?\))
890 (const :tab "both" t)))
892 (defcustom org-auto-renumber-ordered-lists t
893 "Non-nil means, automatically renumber ordered plain lists.
894 Renumbering happens when the sequence have been changed with
895 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
896 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
897 :group 'org-structure
900 (defcustom org-enable-fixed-width-editor t
901 "Non-nil means, lines starting with \":\" are treated as fixed-width.
902 This currently only means, they are never auto-wrapped.
903 When nil, such lines will be treated like ordinary lines.
904 See also the QUOTE keyword."
905 :group 'org-structure
908 (defcustom org-archive-location "%s_archive::"
909 "The location where subtrees should be archived.
910 This string consists of two parts, separated by a double-colon.
912 The first part is a file name - when omitted, archiving happens in the same
913 file. %s will be replaced by the current file name (without directory part).
914 Archiving to a different file is useful to keep archived entries from
915 contributing to the Org-mode Agenda.
917 The part after the double colon is a headline. The archived entries will be
918 filed under that headline. When omitted, the subtrees are simply filed away
919 at the end of the file, as top-level entries.
921 Here are a few examples:
923 If the current file is Projects.org, archive in file
924 Projects.org_archive, as top-level trees. This is the default.
926 \"::* Archived Tasks\"
927 Archive in the current file, under the top-level headline
928 \"* Archived Tasks\".
930 \"~/org/archive.org::\"
931 Archive in file ~/org/archive.org (absolute path), as top-level trees.
933 \"basement::** Finished Tasks\"
934 Archive in file ./basement (relative path), as level 3 trees
935 below the level 2 heading \"** Finished Tasks\".
937 You may set this option on a per-file basis by adding to the buffer a
940 #+ARCHIVE: basement::** Finished Tasks"
941 :group 'org-structure
944 (defcustom org-archive-mark-done t
945 "Non-nil means, mark archived entries as DONE."
946 :group 'org-structure
949 (defcustom org-archive-stamp-time t
950 "Non-nil means, add a time stamp to archived entries.
951 The time stamp will be added directly after the TODO state keyword in the
952 first line, so it is probably best to use this in combinations with
953 `org-archive-mark-done'."
954 :group 'org-structure
957 (defgroup org-link nil
958 "Options concerning links in Org-mode."
962 (defcustom org-link-format "<%s>"
963 "Default format for linkes in the buffer.
964 This is a format string for printf, %s will be replaced by the link text.
965 If you want to make sure that your link is always properly terminated,
966 include angle brackets into this format, like \"<%s>\". Some people also
967 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
970 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
971 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
972 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
973 (string :tag "Other" :value "<%s>")))
975 (defcustom org-allow-space-in-links t
976 "Non-nil means, file names in links may contain space characters.
977 When nil, it becomes possible to put several links into a line.
978 Note that in tables, a link never extends accross fields, so in a table
979 it is always possible to put several links into a line.
980 Changing this varable requires a re-launch of Emacs of become effective."
984 (defcustom org-context-in-file-links t
985 "Non-nil means, file links from `org-store-link' contain context.
986 The line number will be added to the file name with :: as separator and
987 used to find the context when the link is activated by the command
989 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
990 negates this setting for the duration of the command."
994 (defcustom org-keep-stored-link-after-insertion nil
995 "Non-nil means, keep link in list for entire session.
997 The command `org-store-link' adds a link pointing to the current
998 location to an internal list. These links accumulate during a session.
999 The command `org-insert-link' can be used to insert links into any
1000 Org-mode file (offering completion for all stored links). When this
1001 option is nil, every link which has been inserted once using \\[org-insert-link]
1002 will be removed from the list, to make completing the unused links
1007 (defcustom org-link-frame-setup
1008 '((vm . vm-visit-folder-other-frame)
1009 (gnus . gnus-other-frame)
1010 (file . find-file-other-window))
1011 "Setup the frame configuration for following links.
1012 When following a link with Emacs, it may often be useful to display
1013 this link in another window or frame. This variable can be used to
1014 set this up for the different types of links.
1017 `vm-visit-folder-other-frame'
1018 For Gnus, use any of
1021 For FILE, use any of
1023 `find-file-other-window'
1024 `find-file-other-frame'
1025 For the calendar, use the variable `calendar-setup'.
1026 For BBDB, it is currently only possible to display the matches in
1032 (const vm-visit-folder)
1033 (const vm-visit-folder-other-window)
1034 (const vm-visit-folder-other-frame)))
1038 (const gnus-other-frame)))
1042 (const find-file-other-window)
1043 (const find-file-other-frame)))))
1045 (defcustom org-usenet-links-prefer-google nil
1046 "Non-nil means, `org-store-link' will create web links to google groups.
1047 When nil, Gnus will be used for such links.
1048 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1049 negates this setting for the duration of the command."
1053 (defcustom org-open-non-existing-files nil
1054 "Non-nil means, `org-open-file' will open non-existing file.
1055 When nil, an error will be generated."
1059 (defcustom org-confirm-shell-links t
1060 "Non-nil means, ask for confirmation before executing shell links.
1061 The default is true, to keep new users from shooting into their own foot."
1065 (defconst org-file-apps-defaults-gnu
1077 ("eps.gz" . "gv %s")
1079 ("mpeg" . "plaympeg %s")
1080 ("mp3" . "plaympeg %s")
1082 ("pdf" . "acroread %s")
1083 ("doc" . "soffice %s")
1084 ("ppt" . "soffice %s")
1085 ("pps" . "soffice %s")
1086 ("html" . "netscape -remote openURL(%s,new-window)")
1087 ("htm" . "netscape -remote openURL(%s,new-window)")
1088 ("xs" . "soffice %s"))
1089 "Default file applications on a UNIX/LINUX system.
1090 See `org-file-apps'.")
1092 (defconst org-file-apps-defaults-macosx
1097 ("eps.gz" . "gv %s")
1099 ("fig" . "xfig %s"))
1100 "Default file applications on a MacOS X system.
1101 The system \"open\" is known as a default, but we use X11 applications
1102 for some files for which the OS does not have a good default.
1103 See `org-file-apps'.")
1105 (defconst org-file-apps-defaults-windowsnt
1106 '((t . (w32-shell-execute "open" file)))
1107 "Default file applications on a Windows NT system.
1108 The system \"open\" is used for most files.
1109 See `org-file-apps'.")
1111 (defcustom org-file-apps
1119 "External applications for opening `file:path' items in a document.
1120 Org-mode uses system defaults for different file types, but
1121 you can use this variable to set the application for a given file
1122 extension. The entries in this list are cons cells with a file extension
1123 and the corresponding command. Possible values for the command are:
1124 `emacs' The file will be visited by the current Emacs process.
1125 `default' Use the default application for this file type.
1126 string A command to be executed by a shell; %s will be replaced
1127 by the path to the file.
1128 sexp A Lisp form which will be evaluated. The file path will
1129 be available in the Lisp variable `file'.
1130 For more examples, see the system specific constants
1131 `org-file-apps-defaults-macosx'
1132 `org-file-apps-defaults-windowsnt'
1133 `org-file-apps-defaults-gnu'."
1136 (cons (string :tag "Extension")
1138 (const :tag "Visit with Emacs" 'emacs)
1139 (const :tag "Use system default" 'default)
1140 (string :tag "Command")
1141 (sexp :tag "Lisp form")))))
1144 (defgroup org-remember nil
1145 "Options concerning interaction with remember.el."
1149 (defcustom org-directory "~/org"
1150 "Directory with org files.
1151 This directory will be used as default to prompt for org files.
1152 Used by the hooks for remember.el."
1153 :group 'org-remember
1156 (defcustom org-default-notes-file "~/.notes"
1157 "Default target for storing notes.
1158 Used by the hooks for remember.el. This can be a string, or nil to mean
1159 the value of `remember-data-file'."
1160 :group 'org-remember
1162 (const :tag "Default from remember-data-file" nil)
1165 (defcustom org-reverse-note-order nil
1166 "Non-nil means, store new notes at the beginning of a file or entry.
1167 When nil, new notes will be filed to the end of a file or entry."
1168 :group 'org-remember
1170 (const :tag "Reverse always" t)
1171 (const :tag "Reverse never" nil)
1172 (repeat :tag "By file name regexp"
1173 (cons regexp boolean))))
1175 (defgroup org-table nil
1176 "Options concerning tables in Org-mode."
1180 (defcustom org-enable-table-editor 'optimized
1181 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1182 When nil, such lines will be treated like ordinary lines.
1184 When equal to the symbol `optimized', the table editor will be optimized to
1186 - Use automatic overwrite mode in front of whitespace in table fields.
1187 This make the structure of the table stay in tact as long as the edited
1188 field does not exceed the column width.
1189 - Minimize the number of realigns. Normally, the table is aligned each time
1190 TAB or RET are pressed to move to another field. With optimization this
1191 happens only if changes to a field might have changed the column width.
1192 Optimization requires replacing the functions `self-insert-command',
1193 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1194 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1195 very good at guessing when a re-align will be necessary, but you can always
1196 force one with \\[org-ctrl-c-ctrl-c].
1198 If you would like to use the optimized version in Org-mode, but the
1199 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1201 This variable can be used to turn on and off the table editor during a session,
1202 but in order to toggle optimization, a restart is required.
1204 See also the variable `org-table-auto-blank-field'."
1207 (const :tag "off" nil)
1209 (const :tag "on, optimized" optimized)))
1211 ;; FIXME: We could have a third option which makes it jump only over the first
1212 ;; hline in a table.
1213 (defcustom org-table-tab-jumps-over-hlines t
1214 "Non-nil means, tab in the last column of a table with jump over a hline.
1215 If a horizontal separator line is following the current line,
1216 `org-table-next-field' can either create a new row before that line, or jump
1217 over the line. When this option is nil, a new line will be created before
1222 (defcustom org-table-auto-blank-field t
1223 "Non-nil means, automatically blank table field when starting to type into it.
1224 This only happens when typing immediately after a field motion
1225 command (TAB, S-TAB or RET).
1226 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1230 (defcustom org-table-default-size "5x2"
1231 "The default size for newly created tables, Columns x Rows."
1235 (defcustom org-table-automatic-realign t
1236 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1237 When nil, aligning is only done with \\[org-table-align], or after column
1242 (defcustom org-table-spaces-around-separators '(1 . 1)
1243 "The number of spaces to be placed before and after separators."
1245 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1247 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1248 "The number of spaces to be placed before and after separators.
1249 This option applies when the column separators have been made invisible."
1251 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1253 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1254 "Regular expression for recognizing numbers in table columns.
1255 If a table column contains mostly numbers, it will be aligned to the
1256 right. If not, it will be aligned to the left.
1258 The default value of this option is a regular expression which allows
1259 anything which looks remotely like a number as used in scientific
1260 context. For example, all of the following will be considered a
1262 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1264 Other options offered by the customize interface are more restrictive."
1267 (const :tag "Positive Integers"
1269 (const :tag "Integers"
1271 (const :tag "Floating Point Numbers"
1272 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1273 (const :tag "Floating Point Number or Integer"
1274 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1275 (const :tag "Exponential, Floating point, Integer"
1276 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1277 (const :tag "Very General Number-Like"
1278 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1279 (string :tag "Regexp:")))
1281 (defcustom org-table-number-fraction 0.5
1282 "Fraction of numbers in a column required to make the column align right.
1283 In a column all non-white fields are considered. If at least this
1284 fraction of fields is matched by `org-table-number-fraction',
1285 alignment to the right border applies."
1289 (defcustom org-export-highlight-first-table-line t
1290 "Non-nil means, highlight the first table line.
1291 In HTML export, this means use <th> instead of <td>.
1292 In tables created with table.el, this applies to the first table line.
1293 In Org-mode tables, all lines before the first horizontal separator
1294 line will be formatted with <th> tags."
1298 (defcustom org-table-tab-recognizes-table.el t
1299 "Non-nil means, TAB will automatically notice a table.el table.
1300 When it sees such a table, it moves point into it and - if necessary -
1301 calls `table-recognize-table'."
1305 (defgroup org-table-calculation nil
1306 "Options concerning tables in Org-mode."
1307 :tag "Org Table Calculation"
1310 (defcustom org-table-copy-increment t
1311 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1312 :group 'org-table-calculation
1315 (defcustom org-calc-default-modes
1316 '(calc-internal-prec 12
1317 calc-float-format (float 5)
1319 calc-prefer-frac nil
1320 calc-symbolic-mode nil
1321 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1322 calc-display-working-message t
1324 "List with Calc mode settings for use in calc-eval for table formulas.
1325 The list must contain alternating symbols (calc modes variables and values.
1326 Don't remove any of the default settings, just change the values. Org-mode
1327 relies on the variables to be present in the list."
1328 :group 'org-table-calculation
1331 (defcustom org-table-formula-evaluate-inline t
1332 "Non-nil means, TAB and RET evaluate a formula in current table field.
1333 If the current field starts with an equal sign, it is assumed to be a formula
1334 which should be evaluated as described in the manual and in the documentation
1335 string of the command `org-table-eval-formula'. This feature requires the
1337 When this variable is nil, formula calculation is only available through
1338 the command \\[org-table-eval-formula]."
1339 :group 'org-table-calculation
1343 (defcustom org-table-formula-use-constants t
1344 "Non-nil means, interpret constants in formulas in tables.
1345 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1346 by the value given in `org-table-formula-constants', or by a value obtained
1347 from the `constants.el' package."
1348 :group 'org-table-calculation
1351 (defcustom org-table-formula-constants nil
1352 "Alist with constant names and values, for use in table formulas.
1353 The car of each element is a name of a constant, without the `$' before it.
1354 The cdr is the value as a string. For example, if you'd like to use the
1355 speed of light in a formula, you would configure
1357 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1359 and then use it in an equation like `$1*$c'."
1360 :group 'org-table-calculation
1362 (cons (string :tag "name")
1363 (string :tag "value"))))
1365 (defcustom org-table-formula-numbers-only nil
1366 "Non-nil means, calculate only with numbers in table formulas.
1367 Then all input fields will be converted to a number, and the result
1368 must also be a number. When nil, calc's full potential is available
1369 in table calculations, including symbolics etc."
1370 :group 'org-table-calculation
1373 (defcustom org-table-allow-automatic-line-recalculation t
1374 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1375 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1376 :group 'org-table-calculation
1379 (defgroup org-export nil
1380 "Options for exporting org-listings."
1384 (defcustom org-export-language-setup
1385 '(("en" "Author" "Date" "Table of Contents")
1386 ("da" "Ophavsmand" "Dato" "Indhold")
1387 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1388 ("es" "Autor" "Fecha" "\xccndice")
1389 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1390 ("it" "Autore" "Data" "Indice")
1391 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1392 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1393 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1394 "Terms used in export text, translated to different languages.
1395 Use the variable `org-export-default-language' to set the language,
1396 or use the +OPTION lines for a per-file setting."
1400 (string :tag "HTML language tag")
1401 (string :tag "Author")
1402 (string :tag "Date")
1403 (string :tag "Table of Contents"))))
1405 (defcustom org-export-default-language "en"
1406 "The default language of HTML export, as a string.
1407 This should have an association in `org-export-language-setup'."
1411 (defcustom org-export-html-style
1412 "<style type=\"text/css\">
1414 font-family: Times, serif;
1417 .title { text-align: center; }
1418 .todo, .deadline { color: red; }
1419 .done { color: green; }
1421 border: 1pt solid #AEBDCC;
1422 background-color: #F3F5F7;
1424 font-family: courier, monospace;
1426 table { border-collapse: collapse; }
1428 vertical-align: top;
1429 border: 1pt solid #ADB9CC;
1432 "The default style specification for exported HTML files.
1433 Since there are different ways of setting style information, this variable
1434 needs to contain the full HTML structure to provide a style, including the
1435 surrounding HTML tags. The style specifications should include definiitons
1436 for new classes todo, done, title, and deadline. For example, legal values
1439 <style type=\"text/css\">
1440 p {font-weight: normal; color: gray; }
1442 .title { text-align: center; }
1443 .todo, .deadline { color: red; }
1444 .done { color: green; }
1447 or, if you want to keep the style in a file,
1449 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1451 As the value of this option simply gets inserted into the HTML <head> header,
1452 you can \"misuse\" it to add arbitrary text to the header."
1456 (defcustom org-export-headline-levels 3
1457 "The last level which is still exported as a headline.
1458 Inferior levels will produce itemize lists when exported.
1459 Note that a numeric prefix argument to an exporter function overrides
1462 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1466 (defcustom org-export-with-section-numbers t
1467 "Non-nil means, add section numbers to headlines when exporting.
1469 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1473 (defcustom org-export-with-toc t
1474 "Non-nil means, create a table of contents in exported files.
1475 The TOC contains headlines with levels up to`org-export-headline-levels'.
1477 Headlines which contain any TODO items will be marked with \"(*)\" in
1478 ASCII export, and with red color in HTML output.
1480 In HTML output, the TOC will be clickable.
1482 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1486 (defcustom org-export-plain-list-max-depth 20
1487 "Maximum depth of hand-formatted lists in HTML export.
1489 Org-mode parses hand-formatted enumeration and bullet lists and
1490 transforms them to HTML open export. Different indentation of the
1491 bullet or number indicates different list nesting levels. To avoid
1492 confusion, only a single level is allowed by default. When this is
1493 larger than 1, deeper indentation leads to deeper list nesting. For
1494 example, the default value of 3 allows the following list to be
1495 formatted correctly in HTML:
1501 2. from South America
1508 (defcustom org-export-preserve-breaks nil
1509 "Non-nil means, preserve all line breaks when exporting.
1510 Normally, in HTML output paragraphs will be reformatted. In ASCII
1511 export, line breaks will always be preserved, regardless of this variable.
1513 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1517 (defcustom org-export-html-inline-images t
1518 "Non-nil means, inline images into exported HTML pages.
1519 The link will still be to the original location of the image file.
1520 So if you are moving the page, lets say to your public HTML site,
1521 you will have to move the image and maybe change the link."
1525 (defcustom org-export-html-expand t
1526 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1527 When nil, these tags will be exported as plain text and therefore
1528 not be interpreted by a browser.
1530 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1534 (defcustom org-export-with-fixed-width t
1535 "Non-nil means, lines starting with \":\" will be in fixed width font.
1536 This can be used to have pre-formatted text, fragments of code etc. For
1538 : ;; Some Lisp examples
1541 will be looking just like this in also HTML. In ASCII export, this option
1544 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1548 (defcustom org-export-with-tables t
1549 "If non-nil, lines starting with \"|\" define a table.
1552 | Name | Address | Birthday |
1553 |-------------+----------+-----------|
1554 | Arthur Dent | England | 29.2.2100 |
1556 In ASCII export, this option has no effect.
1558 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1562 (defcustom org-export-prefer-native-exporter-for-tables nil
1563 "Non-nil means, always export tables created with table.el natively.
1564 Natively means, use the HTML code generator in table.el.
1565 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1566 the table does not use row- or column-spanning). This has the
1567 advantage, that the automatic HTML conversions for math symbols and
1568 sub/superscripts can be applied. Org-mode's HTML generator is also
1573 (defcustom org-export-html-table-tag
1574 "<table border=1 cellspacing=0 cellpadding=6>"
1575 "The HTML tag used to start a table.
1576 This must be a <table> tag, but you may change the options like
1577 borders and spacing."
1581 (defcustom org-export-with-emphasize t
1582 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1583 If the export target supports emphasizing text, the word will be
1584 typeset in bold, italic, or underlined, respectively. Works only for
1585 single words, but you can say: I *really* *mean* *this*.
1586 In ASCII export, this option has no effect.
1588 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1592 (defcustom org-match-sexp-depth 3
1593 "Number of stacked braces for sub/superscript matching.
1594 This has to be set before loading org.el to be effective."
1598 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1599 (defcustom org-export-with-sub-superscripts t
1600 "Non-nil means, interpret \"_\" and \"^\" for export.
1601 When this option is turned on, you can use TeX-like syntax for sub- and
1602 superscripts. Several characters after \"_\" or \"^\" will be
1603 considered as a single item - so grouping with {} is normally not
1604 needed. For example, the following things will be parsed as single
1605 sub- or superscripts.
1607 10^24 or 10^tau several digits will be considered 1 item
1608 10^-12 or 10^-tau a leading sign with digits or a word
1609 x^2-y^3 will be read as x^2 - y^3, because items are
1610 terminated by almost any nonword/nondigit char.
1611 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1613 Still, ambiguity is possible - so when in doubt use {} to enclose the
1615 In ASCII export, this option has no effect.
1617 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1621 (defcustom org-export-with-TeX-macros t
1622 "Non-nil means, interpret simple TeX-like macros when exporting.
1623 For example, HTML export converts \\alpha to α and \\AA to Å.
1624 No only real TeX macros will work here, but the standard HTML entities
1625 for math can be used as macro names as well. For a list of supported
1626 names in HTML export, see the constant `org-html-entities'.
1627 In ASCII export, this option has no effect.
1629 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1633 (defcustom org-export-html-with-timestamp nil
1634 "If non-nil, write `org-export-html-html-helper-timestamp'
1635 into the exported html text. Otherwise, the buffer will just be saved
1640 (defcustom org-export-html-html-helper-timestamp
1641 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1642 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1646 (defcustom org-export-ascii-show-new-buffer t
1647 "Non-nil means, popup buffer containing the exported ASCII text.
1648 Otherwise the buffer will just be saved to a file and stay hidden."
1652 (defcustom org-export-html-show-new-buffer nil
1653 "Non-nil means, popup buffer containing the exported html text.
1654 Otherwise, the buffer will just be saved to a file and stay hidden."
1658 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1659 "The file name for the iCalendar file covering all agenda files.
1660 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1664 (defcustom org-icalendar-include-todo nil
1665 "Non-nil means, export to iCalendar files should also cover TODO items."
1669 (defcustom org-icalendar-combined-name "OrgMode"
1670 "Calendar name for the combined iCalendar representing all agenda files."
1674 (defgroup org-faces nil
1675 "Faces for highlighting in Org-mode."
1679 (defface org-level-1 ;; font-lock-function-name-face
1680 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1681 (((class color) (background light)) (:foreground "Blue"))
1682 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1683 (t (:inverse-video t :bold t)))
1684 "Face used for level 1 headlines."
1687 (defface org-level-2 ;; font-lock-variable-name-face
1688 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1689 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1690 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1691 (t (:bold t :italic t)))
1692 "Face used for level 2 headlines."
1695 (defface org-level-3 ;; font-lock-keyword-face
1696 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1697 (((class color) (background light)) (:foreground "Purple"))
1698 (((class color) (background dark)) (:foreground "Cyan"))
1700 "Face used for level 3 headlines."
1703 (defface org-level-4 ;; font-lock-comment-face
1704 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1705 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1706 (((class color) (background light)) (:foreground "Firebrick"))
1707 (((class color) (background dark)) (:foreground "chocolate1"))
1708 (t (:bold t :italic t)))
1709 "Face used for level 4 headlines."
1712 (defface org-level-5 ;; font-lock-type-face
1713 '((((type tty) (class color)) (:foreground "green"))
1714 (((class color) (background light)) (:foreground "ForestGreen"))
1715 (((class color) (background dark)) (:foreground "PaleGreen"))
1716 (t (:bold t :underline t)))
1717 "Face used for level 5 headlines."
1720 (defface org-level-6 ;; font-lock-constant-face
1721 '((((type tty) (class color)) (:foreground "magenta"))
1722 (((class color) (background light)) (:foreground "CadetBlue"))
1723 (((class color) (background dark)) (:foreground "Aquamarine"))
1724 (t (:bold t :underline t)))
1725 "Face used for level 6 headlines."
1728 (defface org-level-7 ;; font-lock-builtin-face
1729 '((((type tty) (class color)) (:foreground "blue" :weight light))
1730 (((class color) (background light)) (:foreground "Orchid"))
1731 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1733 "Face used for level 7 headlines."
1736 (defface org-level-8 ;; font-lock-string-face
1737 '((((type tty) (class color)) (:foreground "green"))
1738 (((class color) (background light)) (:foreground "RosyBrown"))
1739 (((class color) (background dark)) (:foreground "LightSalmon"))
1741 "Face used for level 8 headlines."
1744 (defface org-special-keyword ;; font-lock-string-face
1745 '((((type tty) (class color)) (:foreground "green"))
1746 (((class color) (background light)) (:foreground "RosyBrown"))
1747 (((class color) (background dark)) (:foreground "LightSalmon"))
1749 "Face used for level 8 headlines."
1752 (defface org-warning ;; font-lock-warning-face
1753 '((((type tty) (class color)) (:foreground "red"))
1754 (((class color) (background light)) (:foreground "Red" :bold t))
1755 (((class color) (background dark)) (:foreground "Red1" :bold t))
1756 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1757 (t (:inverse-video t :bold t)))
1758 "Face for deadlines and TODO keywords."
1761 (defcustom org-fontify-done-headline nil
1762 "Non-nil means, change the face of a headline if it is marked DONE.
1763 Normally, only the TODO/DONE keyword indicates the state of a headline.
1764 When this is non-nil, the headline after the keyword is set to the
1765 `org-headline-done' as an additional indication."
1769 (defface org-headline-done ;; font-lock-string-face
1770 '((((type tty) (class color)) (:foreground "green"))
1771 (((class color) (background light)) (:foreground "RosyBrown"))
1772 (((class color) (background dark)) (:foreground "LightSalmon"))
1774 "Face used to indicate that a headline is DONE. See also the variable
1775 `org-fontify-done-headline'."
1778 ;; Inheritance does not yet work for xemacs. So we just copy...
1780 (defface org-deadline-announce
1781 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1782 (((class color) (background light)) (:foreground "Blue"))
1783 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1784 (t (:inverse-video t :bold t)))
1785 "Face for upcoming deadlines."
1788 (defface org-scheduled-today
1789 '((((type tty) (class color)) (:foreground "green"))
1790 (((class color) (background light)) (:foreground "DarkGreen"))
1791 (((class color) (background dark)) (:foreground "PaleGreen"))
1792 (t (:bold t :underline t)))
1793 "Face for items scheduled for a certain day."
1796 (defface org-scheduled-previously
1797 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1798 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1799 (((class color) (background light)) (:foreground "Firebrick"))
1800 (((class color) (background dark)) (:foreground "chocolate1"))
1801 (t (:bold t :italic t)))
1802 "Face for items scheduled previously, and not yet done."
1805 (defface org-formula
1806 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1807 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1808 (((class color) (background light)) (:foreground "Firebrick"))
1809 (((class color) (background dark)) (:foreground "chocolate1"))
1810 (t (:bold t :italic t)))
1811 "Face for items scheduled previously, and not yet done."
1815 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1816 (((class color) (background light)) (:foreground "Purple"))
1817 (((class color) (background dark)) (:foreground "Cyan"))
1822 (defface org-done ;; font-lock-type-face
1823 '((((type tty) (class color)) (:foreground "green"))
1824 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1825 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1826 (t (:bold t :underline t)))
1827 "Face used for DONE."
1830 (defface org-table ;; font-lock-function-name-face
1831 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1832 (((class color) (background light)) (:foreground "Blue"))
1833 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1834 (t (:inverse-video t :bold t)))
1835 "Face used for tables."
1838 (defface org-time-grid ;; font-lock-variable-name-face
1839 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1840 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1841 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1842 (t (:bold t :italic t)))
1843 "Face used for level 2 headlines."
1846 (defvar org-level-faces
1857 (defvar org-n-levels (length org-level-faces))
1859 (defun org-set-regexps-and-options ()
1860 "Precompute regular expressions for current buffer."
1861 (when (eq major-mode 'org-mode)
1862 (let ((re (org-make-options-regexp
1863 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1864 "STARTUP" "ARCHIVE")))
1866 kwds int key value cat arch)
1870 (goto-char (point-min))
1871 (while (re-search-forward re nil t)
1872 (setq key (match-string 1) value (match-string 2))
1874 ((equal key "CATEGORY")
1875 (if (string-match "[ \t]+$" value)
1876 (setq value (replace-match "" t t value)))
1877 (setq cat (intern value)))
1878 ((equal key "SEQ_TODO")
1880 kwds (append kwds (org-split-string value splitre))))
1881 ((equal key "PRI_TODO")
1883 kwds (append kwds (org-split-string value splitre))))
1884 ((equal key "TYP_TODO")
1886 kwds (append kwds (org-split-string value splitre))))
1887 ((equal key "STARTUP")
1888 (let ((opts (org-split-string value splitre))
1889 (set '(("fold" org-startup-folded t)
1890 ("nofold" org-startup-folded nil)
1891 ("content" org-startup-folded content)
1892 ("dlcheck" org-startup-with-deadline-check t)
1893 ("nodlcheck" org-startup-with-deadline-check nil)))
1895 (while (setq l (assoc (pop opts) set))
1896 (setq var (nth 1 l) val (nth 2 l))
1897 (set (make-local-variable var) val))))
1898 ((equal key "ARCHIVE")
1899 (string-match " *$" value)
1900 (setq arch (replace-match "" t t value))
1901 (remove-text-properties 0 (length arch)
1902 '(face t fontified t) arch)))
1904 (and cat (set (make-local-variable 'org-category) cat))
1905 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1906 (and arch (set (make-local-variable 'org-archive-location) arch))
1907 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1908 ;; Compute the regular expressions and other local variables
1909 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1910 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1911 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1912 (length org-scheduled-string)))
1914 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1916 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1920 (mapconcat 'regexp-quote
1921 (nreverse (cdr (reverse org-todo-keywords)))
1924 org-todo-line-regexp
1925 (concat "^\\(\\*+\\)[ \t]*\\("
1926 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1929 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1930 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1931 org-deadline-regexp (concat "\\<" org-deadline-string)
1932 org-deadline-time-regexp
1933 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1934 org-deadline-line-regexp
1935 (concat "\\<\\(" org-deadline-string "\\).*")
1936 org-scheduled-regexp
1937 (concat "\\<" org-scheduled-string)
1938 org-scheduled-time-regexp
1939 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1940 (org-set-font-lock-defaults)))
1942 ;; Tell the compiler about dynamically scoped variables,
1943 ;; and variables from other packages
1945 (defvar zmacs-regions)
1946 (defvar original-date)
1947 (defvar org-transient-mark-mode)
1948 (defvar org-old-auto-fill-inhibit-regexp)
1949 (defvar orgtbl-mode-menu)
1950 (defvar org-html-entities)
1951 (defvar org-goto-start-pos)
1952 (defvar org-cursor-color)
1953 (defvar org-time-was-given)
1954 (defvar org-ts-what)
1955 (defvar mark-active)
1957 (defvar levels-open)
1968 (defvar starting-day)
1969 (defvar include-all-loc)
1970 (defvar vm-message-pointer)
1971 (defvar vm-folder-directory)
1972 (defvar wl-summary-buffer-elmo-folder)
1973 (defvar wl-summary-buffer-folder-name)
1974 (defvar gnus-group-name)
1975 (defvar gnus-article-current)
1976 (defvar w3m-current-url)
1977 (defvar org-selected-point)
1978 (defvar calendar-mode-map)
1979 (defvar remember-save-after-remembering)
1980 (defvar remember-data-file))
1985 (defvar org-mode-map (copy-keymap outline-mode-map)
1986 "Keymap for Org-mode.")
1988 (defvar org-struct-menu)
1989 (defvar org-org-menu)
1990 (defvar org-tbl-menu)
1992 ;; We use a before-change function to check if a table might need
1994 (defvar org-table-may-need-update t
1995 "Indicates of a table might need an update.
1996 This variable is set by `org-before-change-function'. `org-table-align'
1997 sets it back to nil.")
1998 (defvar org-mode-hook nil)
1999 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2003 (define-derived-mode org-mode outline-mode "Org"
2004 "Outline-based notes management and organizer, alias
2005 \"Carstens outline-mode for keeping track of everything.\"
2007 Org-mode develops organizational tasks around a NOTES file which
2008 contains information about projects as plain text. Org-mode is
2009 implemented on top of outline-mode, which is ideal to keep the content
2010 of large files well structured. It supports ToDo items, deadlines and
2011 time stamps, which magically appear in the diary listing of the Emacs
2012 calendar. Tables are easily created with a built-in table editor.
2013 Plain text URL-like links connect to websites, emails (VM), Usenet
2014 messages (Gnus), BBDB entries, and any files related to the project.
2015 For printing and sharing of notes, an Org-mode file (or a part of it)
2016 can be exported as a structured ASCII or HTML file.
2018 The following commands are available:
2021 (easy-menu-add org-org-menu)
2022 (easy-menu-add org-tbl-menu)
2023 (org-install-agenda-files-menu)
2024 (setq outline-regexp "\\*+")
2025 (setq outline-level 'org-outline-level)
2026 (if org-startup-truncated (setq truncate-lines t))
2027 (org-set-regexps-and-options)
2028 (set (make-local-variable 'font-lock-unfontify-region-function)
2029 'org-unfontify-region)
2030 ;; Activate before-change-function
2031 (set (make-local-variable 'org-table-may-need-update) t)
2032 (make-local-hook 'before-change-functions) ;; needed for XEmacs
2033 (add-hook 'before-change-functions 'org-before-change-function nil
2035 ;; Paragraphs and auto-filling
2036 (org-set-autofill-regexps)
2037 ;; Settings for Calc embedded mode
2038 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2039 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2040 (if (and org-insert-mode-line-in-empty-file
2042 (= (point-min) (point-max)))
2043 (insert " -*- mode: org -*-\n\n"))
2045 ;; Get rid of Outline menus, they are not needed
2046 ;; Need to do this here because define-derived-mode sets up
2047 ;; the keymap so late.
2050 (delete-menu-item '("Headings"))
2051 (delete-menu-item '("Show"))
2052 (delete-menu-item '("Hide"))
2053 (set-menubar-dirty-flag))
2054 (define-key org-mode-map [menu-bar headings] 'undefined)
2055 (define-key org-mode-map [menu-bar hide] 'undefined)
2056 (define-key org-mode-map [menu-bar show] 'undefined))
2058 (unless org-inhibit-startup
2059 (if org-startup-with-deadline-check
2060 (call-interactively 'org-check-deadlines)
2062 ((eq org-startup-folded t)
2064 ((eq org-startup-folded 'content)
2065 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2066 (org-cycle '(4)) (org-cycle '(4))))))))
2068 (defsubst org-current-line (&optional pos)
2069 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2073 (defvar org-mouse-map (make-sparse-keymap))
2074 (define-key org-mouse-map
2075 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2076 (define-key org-mouse-map
2077 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2079 (require 'font-lock)
2081 (defconst org-non-link-chars "\t\n\r|<>\000")
2082 (defconst org-link-regexp
2083 (if org-allow-space-in-links
2085 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2087 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2089 "Regular expression for matching links.")
2090 (defconst org-link-maybe-angles-regexp
2091 (concat "<?\\(" org-link-regexp "\\)>?")
2092 "Matches a link and optionally surrounding angle brackets.")
2093 (defconst org-protected-link-regexp
2094 (concat "\000" org-link-regexp "\000")
2095 "Matches a link and optionally surrounding angle brackets.")
2097 (defconst org-ts-lengths
2098 (cons (length (format-time-string (car org-time-stamp-formats)))
2099 (length (format-time-string (cdr org-time-stamp-formats))))
2100 "This holds the lengths of the two different time formats.")
2101 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
2102 "Regular expression for fast time stamp matching.")
2103 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2104 "Regular expression matching time strings for analysis.")
2105 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2106 "Regular expression matching time stamps, with groups.")
2107 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2108 "Regular expression matching a time stamp range.")
2109 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2110 org-ts-regexp "\\)?")
2111 "Regular expression matching a time stamp or time stamp range.")
2113 (defun org-activate-links (limit)
2114 "Run through the buffer and add overlays to links."
2115 (if (re-search-forward org-link-regexp limit t)
2117 (add-text-properties (match-beginning 0) (match-end 0)
2118 (list 'mouse-face 'highlight
2119 'keymap org-mouse-map))
2122 (defun org-activate-dates (limit)
2123 "Run through the buffer and add overlays to dates."
2124 (if (re-search-forward org-tsr-regexp limit t)
2126 (add-text-properties (match-beginning 0) (match-end 0)
2127 (list 'mouse-face 'highlight
2128 'keymap org-mouse-map))
2131 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>")
2132 (defun org-activate-camels (limit)
2133 "Run through the buffer and add overlays to dates."
2134 (if (re-search-forward org-camel-regexp limit t)
2136 (add-text-properties (match-beginning 0) (match-end 0)
2137 (list 'mouse-face 'highlight
2138 'keymap org-mouse-map))
2141 (defun org-font-lock-level ()
2143 (org-back-to-heading t)
2144 (- (match-end 0) (match-beginning 0))))
2146 (defun org-outline-level ()
2148 (looking-at outline-regexp)
2149 (if (match-beginning 1)
2150 (+ (org-get-string-indentation (match-string 1)) 1000)
2151 (- (match-end 0) (match-beginning 0)))))
2153 (defvar org-font-lock-keywords nil)
2155 (defun org-set-font-lock-defaults ()
2156 (let ((org-font-lock-extra-keywords
2158 '(org-activate-links (0 'org-link))
2159 '(org-activate-dates (0 'org-link))
2160 '(org-activate-camels (0 'org-link))
2161 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2162 '(1 'org-warning t))
2163 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2164 ; (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
2165 ; (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
2166 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2167 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2168 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2170 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2172 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2174 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2175 ; '(1 'org-warning t))
2176 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2177 "\\|" org-quote-string "\\)\\>")
2178 '(1 'org-special-keyword t))
2179 '("^#.*" (0 'font-lock-comment-face t))
2180 (if org-fontify-done-headline
2181 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2182 '(1 'org-done t) '(2 'org-headline-done t))
2183 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2185 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2187 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2188 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2189 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2191 (set (make-local-variable 'org-font-lock-keywords)
2193 (if org-noutline-p ; FIXME: I am not sure if eval will work
2194 ; on XEmacs if noutline is ever ported
2195 `((eval . (list "^\\(\\*+\\).*"
2196 ,(if org-level-color-stars-only 1 0)
2197 '(nth ;; FIXME: 1<->0 ????
2198 (% (- (match-end 1) (match-beginning 1) 1)
2202 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2203 (,(if org-level-color-stars-only 2 0)
2204 (nth (% (- (match-end 2) (match-beginning 2) 1)
2208 org-font-lock-extra-keywords))
2209 (set (make-local-variable 'font-lock-defaults)
2210 '(org-font-lock-keywords t nil nil backward-paragraph))
2211 (kill-local-variable 'font-lock-keywords) nil))
2213 (defun org-unfontify-region (beg end &optional maybe_loudly)
2214 "Remove fontification and activation overlays from links."
2215 (font-lock-default-unfontify-region beg end)
2216 (let* ((buffer-undo-list t)
2217 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2218 (inhibit-modification-hooks t)
2219 deactivate-mark buffer-file-name buffer-file-truename)
2220 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2222 ;;; Visibility cycling
2224 (defvar org-cycle-global-status nil)
2225 (defvar org-cycle-subtree-status nil)
2226 (defun org-cycle (&optional arg)
2227 "Visibility cycling for Org-mode.
2229 - When this function is called with a prefix argument, rotate the entire
2230 buffer through 3 states (global cycling)
2231 1. OVERVIEW: Show only top-level headlines.
2232 2. CONTENTS: Show all headlines of all levels, but no body text.
2233 3. SHOW ALL: Show everything.
2235 - When point is at the beginning of a headline, rotate the subtree started
2236 by this line through 3 different states (local cycling)
2237 1. FOLDED: Only the main headline is shown.
2238 2. CHILDREN: The main headline and the direct children are shown. From
2239 this state, you can move to one of the children and
2241 3. SUBTREE: Show the entire subtree, including body text.
2243 - When there is a numeric prefix, go up to a heading with level ARG, do
2244 a `show-subtree' and return to the previous cursor position. If ARG
2245 is negative, go up that many levels.
2247 - When point is not at the beginning of a headline, execute
2248 `indent-relative', like TAB normally does. See the option
2249 `org-cycle-emulate-tab' for details.
2251 - Special case: if point is the the beginning of the buffer and there is
2252 no headline in line 1, this function will act as if called with prefix arg."
2255 (if (or (and (bobp) (not (looking-at outline-regexp)))
2257 ;; special case: use global cycling
2260 (let ((outline-regexp
2261 (if org-cycle-include-plain-lists
2262 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2267 ((org-at-table-p 'any)
2268 ;; Enter the table or move to the next field in the table
2269 (or (org-table-recognize-table.el)
2271 (org-table-justify-field-maybe)
2272 (org-table-next-field))))
2274 ((eq arg t) ;; Global cycling
2277 ((and (eq last-command this-command)
2278 (eq org-cycle-global-status 'overview))
2279 ;; We just created the overview - now do table of contents
2280 ;; This can be slow in very large buffers, so indicate action
2281 (message "CONTENTS...")
2283 ;; Visit all headings and show their offspring
2284 (goto-char (point-max))
2286 (while (and (progn (condition-case nil
2287 (outline-previous-visible-heading 1)
2288 (error (goto-char (point-min))))
2290 (looking-at outline-regexp))
2292 (if (bobp) (throw 'exit nil))))
2293 (message "CONTENTS...done"))
2294 (setq org-cycle-global-status 'contents)
2295 (run-hook-with-args 'org-cycle-hook 'contents))
2297 ((and (eq last-command this-command)
2298 (eq org-cycle-global-status 'contents))
2299 ;; We just showed the table of contents - now show everything
2301 (message "SHOW ALL")
2302 (setq org-cycle-global-status 'all)
2303 (run-hook-with-args 'org-cycle-hook 'all))
2306 ;; Default action: go to overview
2308 (message "OVERVIEW")
2309 (setq org-cycle-global-status 'overview)
2310 (run-hook-with-args 'org-cycle-hook 'overview))))
2313 ;; Show-subtree, ARG levels up from here.
2315 (org-back-to-heading)
2316 (outline-up-heading (if (< arg 0) (- arg)
2317 (- (outline-level) arg)))
2318 (org-show-subtree)))
2320 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2321 ;; At a heading: rotate between three different views
2322 (org-back-to-heading)
2323 (let ((goal-column 0) eoh eol eos)
2324 ;; First, some boundaries
2326 (org-back-to-heading)
2328 (beginning-of-line 2)
2329 (while (and (not (eobp)) ;; this is like `next-line'
2330 (get-char-property (1- (point)) 'invisible))
2331 (beginning-of-line 2)) (setq eol (point)))
2332 (outline-end-of-heading) (setq eoh (point))
2333 (outline-end-of-subtree) (setq eos (point))
2334 (outline-next-heading))
2335 ;; Find out what to do next and set `this-command'
2338 ;; Nothing is hidden behind this heading
2339 (message "EMPTY ENTRY")
2340 (setq org-cycle-subtree-status nil))
2342 ;; Entire subtree is hidden in one line: open it
2345 (message "CHILDREN")
2346 (setq org-cycle-subtree-status 'children)
2347 (run-hook-with-args 'org-cycle-hook 'children))
2348 ((and (eq last-command this-command)
2349 (eq org-cycle-subtree-status 'children))
2350 ;; We just showed the children, now show everything.
2353 (setq org-cycle-subtree-status 'subtree)
2354 (run-hook-with-args 'org-cycle-hook 'subtree))
2356 ;; Default action: hide the subtree.
2359 (setq org-cycle-subtree-status 'folded)
2360 (run-hook-with-args 'org-cycle-hook 'folded)))))
2363 (buffer-read-only (org-back-to-heading))
2364 ((if (and (eq org-cycle-emulate-tab 'white)
2365 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2367 (eq org-cycle-emulate-tab t))
2368 (if (and (looking-at "[ \n\r\t]")
2369 (string-match "^[ \t]*$" (buffer-substring
2370 (point-at-bol) (point))))
2372 (beginning-of-line 1)
2373 (and (looking-at "[ \t]+") (replace-match ""))))
2377 (org-back-to-heading)
2380 (defun org-optimize-window-after-visibility-change (state)
2381 "Adjust the window after a change in outline visibility.
2382 This function is the default value of the hook `org-cycle-hook'."
2384 ((eq state 'overview) (org-first-headline-recenter 1))
2385 ((eq state 'content) nil)
2386 ((eq state 'all) nil)
2387 ((eq state 'folded) nil)
2388 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2389 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2391 (defun org-subtree-end-visible-p ()
2392 "Is the end of the current subtree visible?"
2393 (pos-visible-in-window-p
2394 (save-excursion (outline-end-of-subtree) (point))))
2396 (defun org-first-headline-recenter (&optional N)
2397 "Move cursor to the first headline and recenter the headline.
2398 Optional argument N means, put the headline into the Nth line of the window."
2399 (goto-char (point-min))
2400 (when (re-search-forward (concat "^" outline-regexp) nil t)
2402 (recenter (prefix-numeric-value N))))
2404 (defvar org-goto-window-configuration nil)
2405 (defvar org-goto-marker nil)
2406 (defvar org-goto-map (make-sparse-keymap))
2407 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2408 (while (setq cmd (pop cmds))
2409 (substitute-key-definition cmd cmd org-goto-map global-map)))
2410 (define-key org-goto-map "\C-m" 'org-goto-ret)
2411 (define-key org-goto-map [(left)] 'org-goto-left)
2412 (define-key org-goto-map [(right)] 'org-goto-right)
2413 (define-key org-goto-map [(?q)] 'org-goto-quit)
2414 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2415 (define-key org-goto-map "\C-i" 'org-cycle)
2416 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2417 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2418 (define-key org-goto-map "n" 'outline-next-visible-heading)
2419 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2420 (define-key org-goto-map "f" 'outline-forward-same-level)
2421 (define-key org-goto-map "b" 'outline-backward-same-level)
2422 (define-key org-goto-map "u" 'outline-up-heading)
2423 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2424 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2425 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2426 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2427 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2428 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2429 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2431 (defconst org-goto-help
2432 "Select a location to jump to, press RET
2433 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2436 "Go to a different location of the document, keeping current visibility.
2438 When you want to go to a different location in a document, the fastest way
2439 is often to fold the entire buffer and then dive into the tree. This
2440 method has the disadvantage, that the previous location will be folded,
2441 which may not be what you want.
2443 This command works around this by showing a copy of the current buffer in
2444 overview mode. You can dive into the tree in that copy, to find the
2445 location you want to reach. When pressing RET, the command returns to the
2446 original buffer in which the visibility is still unchanged. It then jumps
2447 to the new location, making it and the headline hierarchy above it visible."
2449 (let* ((org-goto-start-pos (point))
2451 (org-get-location (current-buffer) org-goto-help)))
2454 (goto-char selected-point)
2455 (if (org-invisible-p) (org-show-hierarchy-above)))
2458 (defun org-get-location (buf help)
2459 "Let the user select a location in the Org-mode buffer BUF.
2460 This function uses a recursive edit. It returns the selected position
2462 (let (org-selected-point)
2464 (save-window-excursion
2465 (delete-other-windows)
2466 (switch-to-buffer (get-buffer-create "*org-goto*"))
2467 (with-output-to-temp-buffer "*Help*"
2469 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2470 (setq buffer-read-only nil)
2472 (insert-buffer-substring buf)
2473 (let ((org-startup-truncated t)
2474 (org-startup-folded t)
2475 (org-startup-with-deadline-check nil))
2477 (setq buffer-read-only t)
2478 (if (boundp 'org-goto-start-pos)
2479 (goto-char org-goto-start-pos)
2480 (goto-char (point-min)))
2481 (org-beginning-of-line)
2482 (message "Select location and press RET")
2483 ;; now we make sure that during selection, ony very few keys work
2484 ;; and that it is impossible to switch to another window.
2485 (let ((gm (current-global-map))
2486 (overriding-local-map org-goto-map))
2489 (use-global-map org-goto-map)
2491 (use-global-map gm)))))
2492 (kill-buffer "*org-goto*")
2493 org-selected-point))
2495 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2496 (defun org-goto-ret (&optional arg)
2497 "Finish org-goto by going to the new location."
2499 (setq org-selected-point (point)
2500 current-prefix-arg arg)
2503 (defun org-goto-left ()
2504 "Finish org-goto by going to the new location."
2506 (if (org-on-heading-p)
2508 (beginning-of-line 1)
2509 (setq org-selected-point (point)
2510 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2512 (error "Not on a heading")))
2514 (defun org-goto-right ()
2515 "Finish org-goto by going to the new location."
2517 (if (org-on-heading-p)
2519 (outline-end-of-subtree)
2520 (or (eobp) (forward-char 1))
2521 (setq org-selected-point (point)
2522 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2524 (error "Not on a heading")))
2526 (defun org-goto-quit ()
2527 "Finish org-goto without cursor motion."
2529 (setq org-selected-point nil)
2532 ;;; Promotion, Demotion, Inserting new headlines
2534 (defvar org-ignore-region nil
2535 "To temporarily disable the active region.")
2537 (defun org-insert-heading (&optional force-heading)
2538 "Insert a new heading or item with same depth at point.
2541 (when (or force-heading (not (org-insert-item)))
2542 (let* ((head (save-excursion
2544 (org-back-to-heading)
2545 (error (outline-next-heading)))
2546 (prog1 (match-string 0)
2547 (funcall outline-level)))))
2548 (unless (bolp) (newline))
2551 (save-excursion (newline-and-indent)))
2552 (unless (equal (char-before) ?\ )
2554 (run-hooks 'org-insert-heading-hook))))
2556 (defun org-insert-item ()
2557 "Insert a new item at the current level.
2558 Return t when tings worked, nil when we are not in an item."
2559 (when (save-excursion
2562 (org-beginning-of-item)
2566 (unless (bolp) (newline))
2567 (insert (match-string 0))
2568 (org-maybe-renumber-ordered-list)
2571 (defun org-insert-todo-heading (arg)
2572 "Insert a new heading with the same level and TODO state as current heading.
2573 If the heading has no TODO state, or if the state is DONE, use the first
2574 state (TODO by default). Also with prefix arg, force first state."
2576 (org-insert-heading)
2578 (org-back-to-heading)
2579 (outline-previous-heading)
2580 (looking-at org-todo-line-regexp))
2582 (not (match-beginning 2))
2583 (equal (match-string 2) org-done-string))
2584 (insert (car org-todo-keywords) " ")
2585 (insert (match-string 2) " ")))
2587 (defun org-promote-subtree ()
2588 "Promote the entire subtree.
2589 See also `org-promote'."
2592 (org-map-tree 'org-promote)))
2594 (defun org-demote-subtree ()
2595 "Demote the entire subtree. See `org-demote'.
2596 See also `org-promote'."
2599 (org-map-tree 'org-demote)))
2601 (defun org-do-promote ()
2602 "Promote the current heading higher up the tree.
2603 If the region is active in `transient-mark-mode', promote all headings
2607 (if (org-region-active-p)
2608 (org-map-region 'org-promote (region-beginning) (region-end))
2610 (org-fix-position-after-promote))
2612 (defun org-do-demote ()
2613 "Demote the current heading lower down the tree.
2614 If the region is active in `transient-mark-mode', demote all headings
2618 (if (org-region-active-p)
2619 (org-map-region 'org-demote (region-beginning) (region-end))
2621 (org-fix-position-after-promote))
2623 (defun org-fix-position-after-promote ()
2624 "Make sure that after pro/demotion cursor position is right."
2625 (and (equal (char-after) ?\ )
2626 (equal (char-before) ?*)
2629 (defun org-promote ()
2630 "Promote the current heading higher up the tree.
2631 If the region is active in `transient-mark-mode', promote all headings
2633 (org-back-to-heading t)
2634 (let* ((level (save-match-data (funcall outline-level)))
2635 (up-head (make-string (1- level) ?*)))
2636 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2637 (replace-match up-head nil t)
2638 (if org-adapt-indentation
2639 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2641 (defun org-demote ()
2642 "Demote the current heading lower down the tree.
2643 If the region is active in `transient-mark-mode', demote all headings
2645 (org-back-to-heading t)
2646 (let* ((level (save-match-data (funcall outline-level)))
2647 (down-head (make-string (1+ level) ?*)))
2648 (replace-match down-head nil t)
2649 (if org-adapt-indentation
2650 (org-fixup-indentation "^ " " " "^\\S-"))))
2652 (defun org-map-tree (fun)
2653 "Call FUN for every heading underneath the current one."
2654 (org-back-to-heading)
2655 (let ((level (outline-level)))
2659 (outline-next-heading)
2660 (> (funcall outline-level) level))
2664 (defun org-map-region (fun beg end)
2665 "Call FUN for every heading between BEG and END."
2666 (let ((org-ignore-region t))
2668 (setq end (copy-marker end))
2670 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2674 (outline-next-heading)
2679 (defun org-fixup-indentation (from to prohibit)
2680 "Change the indentation in the current entry by re-replacing FROM with TO.
2681 However, if the regexp PROHIBIT matches at all, don't do anything.
2682 This is being used to change indentation along with the length of the
2683 heading marker. But if there are any lines which are not indented, nothing
2686 (let ((end (save-excursion (outline-next-heading)
2688 (unless (save-excursion (re-search-forward prohibit end t))
2689 (while (re-search-forward from end t)
2691 (beginning-of-line 2)))
2692 (move-marker end nil))))
2694 ;;; Vertical tree motion, cutting and pasting of subtrees
2696 (defun org-move-subtree-up (&optional arg)
2697 "Move the current subtree up past ARG headlines of the same level."
2699 (org-move-subtree-down (- (prefix-numeric-value arg))))
2701 (defun org-move-subtree-down (&optional arg)
2702 "Move the current subtree down past ARG headlines of the same level."
2704 (setq arg (prefix-numeric-value arg))
2705 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2706 'outline-get-last-sibling))
2707 (ins-point (make-marker))
2711 (org-back-to-heading)
2714 (save-excursion (outline-end-of-heading)
2715 (setq folded (org-invisible-p)))
2716 (outline-end-of-subtree))
2717 (outline-next-heading)
2719 ;; Find insertion point, with error handling
2722 (or (and (funcall movfunc) (looking-at outline-regexp))
2723 (progn (goto-char beg)
2724 (error "Cannot move past superior level or buffer limit")))
2725 (setq cnt (1- cnt)))
2727 ;; Moving forward - still need to move over subtree
2728 (progn (outline-end-of-subtree)
2729 (outline-next-heading)
2730 (if (not (or (looking-at (concat "^" outline-regexp))
2733 (move-marker ins-point (point))
2734 (setq txt (buffer-substring beg end))
2735 (delete-region beg end)
2737 (goto-char ins-point)
2738 (if folded (hide-subtree))
2739 (move-marker ins-point nil)))
2741 (defvar org-subtree-clip ""
2742 "Clipboard for cut and paste of subtrees.
2743 This is actually only a copy of the kill, because we use the normal kill
2744 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2746 (defvar org-subtree-clip-folded nil
2747 "Was the last copied subtree folded?
2748 This is used to fold the tree back after pasting.")
2750 (defun org-cut-subtree ()
2751 "Cut the current subtree into the clipboard.
2752 This is a short-hand for marking the subtree and then cutting it."
2754 (org-copy-subtree 'cut))
2756 (defun org-copy-subtree (&optional cut)
2757 "Cut the current subtree into the clipboard.
2758 This is a short-hand for marking the subtree and then copying it.
2759 If CUT is non nil, actually cut the subtree."
2761 (let (beg end folded)
2762 (org-back-to-heading)
2765 (save-excursion (outline-end-of-heading)
2766 (setq folded (org-invisible-p)))
2767 (outline-end-of-subtree))
2768 (if (equal (char-after) ?\n) (forward-char 1))
2772 (setq org-subtree-clip-folded folded)
2773 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2774 (setq org-subtree-clip (current-kill 0))
2775 (message "%s: Subtree with %d characters"
2776 (if cut "Cut" "Copied")
2777 (length org-subtree-clip)))))
2779 (defun org-paste-subtree (&optional level tree)
2780 "Paste the clipboard as a subtree, with modification of headline level.
2781 The entire subtree is promoted or demoted in order to match a new headline
2782 level. By default, the new level is derived from the visible headings
2783 before and after the insertion point, and taken to be the inferior headline
2784 level of the two. So if the previous visible heading is level 3 and the
2785 next is level 4 (or vice versa), level 4 will be used for insertion.
2786 This makes sure that the subtree remains an independent subtree and does
2787 not swallow low level entries.
2789 You can also force a different level, either by using a numeric prefix
2790 argument, or by inserting the heading marker by hand. For example, if the
2791 cursor is after \"*****\", then the tree will be shifted to level 5.
2793 If you want to insert the tree as is, just use \\[yank].
2795 If optional TREE is given, use this text instead of the kill ring."
2797 (unless (org-kill-is-subtree-p tree)
2799 (substitute-command-keys
2800 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2801 (let* ((txt (or tree (current-kill 0)))
2802 (^re (concat "^\\(" outline-regexp "\\)"))
2803 (re (concat "\\(" outline-regexp "\\)"))
2804 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2806 (old-level (if (string-match ^re txt)
2807 (- (match-end 0) (match-beginning 0))
2809 (force-level (cond (level (prefix-numeric-value level))
2811 ^re_ (buffer-substring (point-at-bol) (point)))
2812 (- (match-end 0) (match-beginning 0)))
2814 (previous-level (save-excursion
2817 (outline-previous-visible-heading 1)
2819 (- (match-end 0) (match-beginning 0))
2822 (next-level (save-excursion
2825 (outline-next-visible-heading 1)
2827 (- (match-end 0) (match-beginning 0))
2830 (new-level (or force-level (max previous-level next-level)))
2831 (shift (if (or (= old-level -1)
2833 (= old-level new-level))
2835 (- new-level old-level)))
2837 (delta (if (> shift 0) -1 1))
2838 (func (if (> shift 0) 'org-demote 'org-promote))
2840 ;; Remove the forces level indicator
2842 (delete-region (point-at-bol) (point)))
2843 ;; Make sure we start at the beginning of an empty line
2844 (if (not (bolp)) (insert "\n"))
2845 (if (not (looking-at "[ \t]*$"))
2846 (progn (insert "\n") (backward-char 1)))
2852 ;; Shift if necessary
2854 (message "Pasted at level %d, without shift" new-level)
2856 (narrow-to-region beg end)
2857 (while (not (= shift 0))
2858 (org-map-region func (point-min) (point-max))
2859 (setq shift (+ delta shift)))
2860 (goto-char (point-min))
2861 (message "Pasted at level %d, with shift by %d levels"
2863 (if (and (eq org-subtree-clip (current-kill 0))
2864 org-subtree-clip-folded)
2865 ;; The tree was folded before it was killed/copied
2868 (defun org-kill-is-subtree-p (&optional txt)
2869 "Check if the current kill is an outline subtree, or a set of trees.
2870 Returns nil if kill does not start with a headline, or if the first
2871 headline level is not the largest headline level in the tree.
2872 So this will actually accept several entries of equal levels as well,
2873 which is OK for `org-paste-subtree'.
2874 If optional TXT is given, check this string instead of the current kill."
2875 (let* ((kill (or txt (current-kill 0) ""))
2876 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2877 (- (match-end 0) (match-beginning 0))))
2878 (re (concat "^" outline-regexp))
2880 (if (not start-level)
2881 nil ;; does not even start with a heading
2883 (while (setq start (string-match re kill (1+ start)))
2884 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2890 (defun org-at-item-p ()
2891 "Is point in a line starting a hand-formatted item?"
2892 (let ((llt org-plain-list-ordered-item-terminator))
2894 (goto-char (point-at-bol))
2897 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2898 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2899 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2900 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
2902 (defun org-get-indentation ()
2903 "Get the indentation of the current line, ionterpreting tabs."
2905 (beginning-of-line 1)
2906 (skip-chars-forward " \t")
2909 (defun org-beginning-of-item ()
2910 "Go to the beginning of the current hand-formatted item.
2911 If the cursor is not in an item, throw an error."
2913 (limit (save-excursion (org-back-to-heading)
2914 (beginning-of-line 2) (point)))
2917 (beginning-of-line 1)
2918 (beginning-of-line 1)
2919 (skip-chars-forward " \t")
2920 (setq ind (current-column))
2923 (beginning-of-line 0)
2924 (if (< (point) limit) (throw 'exit nil))
2925 (unless (looking-at " \t]*$")
2926 (skip-chars-forward " \t")
2927 (setq ind1 (current-column))
2929 (throw 'exit (org-at-item-p))))))
2932 (error "Not in an item")))))
2934 (defun org-end-of-item ()
2935 "Go to the beginning of the current hand-formatted item.
2936 If the cursor is not in an item, throw an error."
2938 (limit (save-excursion (outline-next-heading) (point)))
2939 (ind (save-excursion
2940 (org-beginning-of-item)
2941 (skip-chars-forward " \t")
2946 (beginning-of-line 2)
2947 (if (>= (point) limit) (throw 'exit t))
2948 (unless (looking-at "[ \t]*$")
2949 (skip-chars-forward " \t")
2950 (setq ind1 (current-column))
2951 (if (<= ind1 ind) (throw 'exit t)))))
2952 (beginning-of-line 1)
2954 (error "Not in an item"))))
2956 (defun org-move-item-down (arg)
2957 "Move the plain list item at point down, i.e. swap with following item.
2958 Subitems (items with larger indentation are considered part of the item,
2959 so this really moves item trees."
2961 (let (beg end ind ind1 (pos (point)) txt)
2962 (org-beginning-of-item)
2964 (setq ind (org-get-indentation))
2967 (setq ind1 (org-get-indentation))
2968 (if (and (org-at-item-p) (= ind ind1))
2971 (setq txt (buffer-substring beg end))
2973 (delete-region beg end))
2977 (org-maybe-renumber-ordered-list))
2979 (error "Cannot move this item further down"))))
2981 (defun org-move-item-up (arg)
2982 "Move the plain list item at point up, i.e. swap with previous item.
2983 Subitems (items with larger indentation are considered part of the item,
2984 so this really moves item trees."
2986 (let (beg end ind ind1 (pos (point)) txt)
2987 (org-beginning-of-item)
2989 (setq ind (org-get-indentation))
2995 (beginning-of-line 0)
2996 (if (looking-at "[ \t]*$")
2998 (if (<= (setq ind1 (org-get-indentation)) ind)
3001 (org-beginning-of-item)
3002 (error (goto-char beg)
3003 (error "Cannot move this item further up")))
3004 (setq ind1 (org-get-indentation))
3005 (if (and (org-at-item-p) (= ind ind1))
3007 (setq txt (buffer-substring beg end))
3009 (delete-region beg end))
3013 (org-maybe-renumber-ordered-list))
3015 (error "Cannot move this item further up"))))
3017 (defun org-maybe-renumber-ordered-list ()
3018 "Renumber the ordered list at point if setup allows it.
3019 This tests the user option `org-auto-renumber-ordered-lists' before
3020 doing the renumbering."
3021 (and org-auto-renumber-ordered-lists
3024 (org-renumber-ordered-list 1)))
3026 (defun org-get-string-indentation (s)
3027 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3028 (let ((n -1) (i 0) (w tab-width) c)
3030 (while (< (setq n (1+ n)) (length s))
3032 (cond ((= c ?\ ) (setq i (1+ i)))
3033 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3034 (t (throw 'exit t)))))
3037 (defun org-renumber-ordered-list (arg)
3038 "Renumber an ordered plain list.
3039 Cursor neext to be in the first line of an item, the line that starts
3040 with something like \"1.\" or \"2)\"."
3042 (unless (and (org-at-item-p)
3043 (match-beginning 3))
3044 (error "This is not an ordered list"))
3045 (let ((line (org-current-line))
3046 (col (current-column))
3047 (ind (org-get-string-indentation
3048 (buffer-substring (point-at-bol) (match-beginning 3))))
3049 (term (substring (match-string 3) -1))
3051 ;; find where this list begins
3055 (beginning-of-line 0)
3056 (if (looking-at "[ \t]*$") (throw 'next t))
3057 (skip-chars-forward " \t") (setq ind1 (current-column))
3058 (if (or (< ind1 ind)
3060 (not (org-at-item-p))))
3062 ;; Walk forward and replace these numbers
3066 (beginning-of-line 2)
3067 (if (eobp) (throw 'exit nil))
3068 (if (looking-at "[ \t]*$") (throw 'next nil))
3069 (skip-chars-forward " \t") (setq ind1 (current-column))
3070 (if (> ind1 ind) (throw 'next t))
3071 (if (< ind1 ind) (throw 'exit t))
3072 (if (not (org-at-item-p)) (throw 'exit nil))
3073 (if (not (match-beginning 3))
3074 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3075 (delete-region (match-beginning 3) (1- (match-end 3)))
3076 (goto-char (match-beginning 3))
3077 (insert (format "%d" (setq n (1+ n)))))))
3079 (move-to-column col)))
3081 (defvar org-last-indent-begin-marker (make-marker))
3082 (defvar org-last-indent-end-marker (make-marker))
3085 (defun org-outdent-item (arg)
3086 "Outdent a local list item."
3088 (org-indent-item (- arg)))
3090 (defun org-indent-item (arg)
3091 "Indent a local list item."
3093 (unless (org-at-item-p)
3094 (error "Not on an item"))
3095 (let (beg end ind ind1)
3096 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3097 (setq beg org-last-indent-begin-marker
3098 end org-last-indent-end-marker)
3099 (org-beginning-of-item)
3100 (setq beg (move-marker org-last-indent-begin-marker (point)))
3102 (setq end (move-marker org-last-indent-end-marker (point))))
3104 (skip-chars-forward " \t") (setq ind (current-column))
3105 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3106 (while (< (point) end)
3107 (beginning-of-line 1)
3108 (skip-chars-forward " \t") (setq ind1 (current-column))
3109 (delete-region (point-at-bol) (point))
3110 (indent-to-column (+ ind1 arg))
3111 (beginning-of-line 2))
3117 (defun org-archive-subtree ()
3118 "Move the current subtree to the archive.
3119 The archive can be a certain top-level heading in the current file, or in
3120 a different file. The tree will be moved to that location, the subtree
3121 heading be marked DONE, and the current time will be added."
3123 ;; Save all relevant TODO keyword-relatex variables
3124 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3125 (tr-org-todo-keywords org-todo-keywords)
3126 (tr-org-todo-interpretation org-todo-interpretation)
3127 (tr-org-done-string org-done-string)
3128 (tr-org-todo-regexp org-todo-regexp)
3129 (tr-org-todo-line-regexp org-todo-line-regexp)
3130 (this-buffer (current-buffer))
3131 file heading buffer level newfile-p)
3132 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3134 (setq file (format (match-string 1 org-archive-location)
3135 (file-name-nondirectory (buffer-file-name)))
3136 heading (match-string 2 org-archive-location)))
3137 (error "Invalid `org-archive-location'"))
3138 (if (> (length file) 0)
3139 (setq newfile-p (not (file-exists-p file))
3140 buffer (find-file-noselect file))
3141 (setq buffer (current-buffer)))
3143 (error "Cannot access file \"%s\"" file))
3144 (if (and (> (length heading) 0)
3145 (string-match "^\\*+" heading))
3146 (setq level (match-end 0))
3147 (setq heading nil level 0))
3149 ;; We first only copy, in case something goes wrong
3150 ;; we need to protect this-command, to avoid kill-region sets it,
3151 ;; which would lead to duplication of subtrees
3152 (let (this-command) (org-copy-subtree))
3154 ;; Enforce org-mode for the archive buffer
3155 (if (not (eq major-mode 'org-mode))
3156 ;; Force the mode for future visits.
3157 (let ((org-insert-mode-line-in-empty-file t))
3158 (call-interactively 'org-mode)))
3160 (goto-char (point-max))
3161 (insert (format "\nArchived entries from file %s\n\n"
3162 (buffer-file-name this-buffer))))
3163 ;; Force the TODO keywords of the original buffer
3164 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3165 (org-todo-keywords tr-org-todo-keywords)
3166 (org-todo-interpretation tr-org-todo-interpretation)
3167 (org-done-string tr-org-done-string)
3168 (org-todo-regexp tr-org-todo-regexp)
3169 (org-todo-line-regexp tr-org-todo-line-regexp))
3170 (goto-char (point-min))
3173 (if (re-search-forward
3174 (concat "\\(^\\|\r\\)"
3175 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3177 (goto-char (match-end 0))
3178 ;; Heading not found, just insert it at the end
3179 (goto-char (point-max))
3180 (or (bolp) (insert "\n"))
3181 (insert "\n" heading "\n")
3183 ;; Make the heading visible, and the following as well
3184 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3185 (if (re-search-forward
3186 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3188 (progn (goto-char (match-beginning 0)) (insert "\n")
3189 (beginning-of-line 0))
3190 (goto-char (point-max)) (insert "\n")))
3191 (goto-char (point-max)) (insert "\n"))
3193 (org-paste-subtree (1+ level))
3194 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3195 (if org-archive-mark-done
3196 (org-todo (length org-todo-keywords)))
3197 ;; Move cursor to right after the TODO keyword
3198 (when org-archive-stamp-time
3199 (beginning-of-line 1)
3200 (looking-at org-todo-line-regexp)
3201 (goto-char (or (match-end 2) (match-beginning 3)))
3202 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3205 ;; Save the buffer, if it is not the same buffer.
3206 (if (not (eq this-buffer buffer)) (save-buffer))))
3207 ;; Here we are back in the original buffer. Everything seems to have
3208 ;; worked. So now cut the tree and finish up.
3209 (let (this-command) (org-cut-subtree))
3210 (if (looking-at "[ \t]*$") (kill-line))
3211 (message "Subtree archived %s"
3212 (if (eq this-buffer buffer)
3213 (concat "under heading: " heading)
3214 (concat "in file: " (abbreviate-file-name file))))))
3218 (defun org-complete (&optional arg)
3219 "Perform completion on word at point.
3220 At the beginning of a headline, this completes TODO keywords as given in
3221 `org-todo-keywords'.
3222 If the current word is preceded by a backslash, completes the TeX symbols
3223 that are supported for HTML support.
3224 If the current word is preceded by \"#+\", completes special words for
3225 setting file options.
3226 At all other locations, this simply calls `ispell-complete-word'."
3229 (let* ((end (point))
3230 (beg (save-excursion
3231 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3232 (skip-chars-backward "a-zA-Z0-9_:$")
3234 (camel (equal (char-before beg) ?*))
3235 (texp (equal (char-before beg) ?\\))
3236 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3239 (pattern (buffer-substring-no-properties beg end))
3240 (completion-ignore-case opt)
3247 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3248 (cons (match-string 2 x) (match-string 1 x)))
3249 (org-split-string (org-get-current-options) "\n")))
3253 ((string-match "\\`\\*+[ \t]*\\'"
3254 (buffer-substring (point-at-bol) beg))
3256 (mapcar 'list org-todo-keywords))
3260 (goto-char (point-min))
3261 (while (re-search-forward org-todo-line-regexp nil t)
3262 (push (list (org-make-org-heading-camel (match-string 3)))
3265 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3266 (completion (try-completion pattern table)))
3267 (cond ((eq completion t)
3268 (if (equal type :opt)
3269 (insert (substring (cdr (assoc (upcase pattern) table))
3270 (length pattern)))))
3272 (message "Can't find completion for \"%s\"" pattern)
3274 ((not (string= pattern completion))
3275 (delete-region beg end)
3276 (if (string-match " +$" completion)
3277 (setq completion (replace-match "" t t completion)))
3279 (if (get-buffer-window "*Completions*")
3280 (delete-window (get-buffer-window "*Completions*")))
3281 (if (and (eq type :todo)
3282 (assoc completion table))
3284 (if (and (equal type :opt) (assoc completion table))
3285 (message "%s" (substitute-command-keys
3286 "Press \\[org-complete] again to insert example settings"))))
3288 (message "Making completion list...")
3289 (let ((list (sort (all-completions pattern table) 'string<)))
3290 (with-output-to-temp-buffer "*Completions*"
3291 (display-completion-list list)))
3292 (message "Making completion list...%s" "done"))))))
3294 ;;; Comments, TODO and DEADLINE
3296 (defun org-toggle-comment ()
3297 "Change the COMMENT state of an entry."
3300 (org-back-to-heading)
3301 (if (looking-at (concat outline-regexp
3302 "\\( +\\<" org-comment-string "\\>\\)"))
3303 (replace-match "" t t nil 1)
3304 (if (looking-at outline-regexp)
3306 (goto-char (match-end 0))
3307 (insert " " org-comment-string))))))
3309 (defvar org-last-todo-state-is-todo nil
3310 "This is non-nil when the last TODO state change led to a TODO state.
3311 If the last change removed the TODO tag or switched to DONE, then
3314 (defun org-todo (&optional arg)
3315 "Change the TODO state of an item.
3316 The state of an item is given by a keyword at the start of the heading,
3318 *** TODO Write paper
3321 The different keywords are specified in the variable `org-todo-keywords'. By
3322 default the available states are \"TODO\" and \"DONE\".
3323 So for this example: when the item starts with TODO, it is changed to DONE.
3324 When it starts with DONE, the DONE is removed. And when neither TODO nor
3325 DONE are present, add TODO at the beginning of the heading.
3327 With prefix arg, use completion to determined the new state. With numeric
3328 prefix arg, switch to that state."
3331 (org-back-to-heading)
3332 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3333 (or (looking-at (concat " +" org-todo-regexp " *"))
3335 (let* ((this (match-string 1))
3336 (completion-ignore-case t)
3337 (member (member this org-todo-keywords))
3341 ;; Read a state with completion
3342 (completing-read "State: " (mapcar (lambda(x) (list x))
3347 (if tail (car tail) nil)
3348 (car org-todo-keywords)))
3350 (if (equal member org-todo-keywords)
3353 (nth (- (length org-todo-keywords) (length tail) 2)
3357 ;; user requests a specific state
3358 (nth (1- (prefix-numeric-value arg))
3360 ((null member) (car org-todo-keywords))
3361 ((null tail) nil) ;; -> first entry
3362 ((eq org-todo-interpretation 'sequence)
3364 ((memq org-todo-interpretation '(type priority))
3365 (if (eq this-command last-command)
3367 (if (> (length tail) 0) org-done-string nil)))
3369 (next (if state (concat " " state " ") " ")))
3370 (replace-match next t t)
3371 (setq org-last-todo-state-is-todo
3372 (not (equal state org-done-string)))
3373 (run-hooks 'org-after-todo-state-change-hook)))
3374 ;; Fixup cursor location if close to the keyword
3375 (if (and (outline-on-heading-p)
3377 (save-excursion (beginning-of-line 1)
3378 (looking-at org-todo-line-regexp))
3379 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3381 (goto-char (or (match-end 2) (match-end 1)))
3384 (defun org-show-todo-tree (arg)
3385 "Make a compact tree which shows all headlines marked with TODO.
3386 The tree will show the lines where the regexp matches, and all higher
3387 headlines above the match.
3388 With \\[universal-argument] prefix, also show the DONE entries.
3389 With a numeric prefix N, construct a sparse tree for the Nth element
3390 of `org-todo-keywords'."
3392 (let ((case-fold-search nil)
3394 (cond ((null arg) org-not-done-regexp)
3395 ((equal arg '(4)) org-todo-regexp)
3396 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3397 (regexp-quote (nth (1- (prefix-numeric-value arg))
3398 org-todo-keywords)))
3399 (t (error "Invalid prefix argument: %s" arg)))))
3400 (message "%d TODO entries found"
3401 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3403 (defun org-deadline ()
3404 "Insert the DEADLINE: string to make a deadline.
3405 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3406 to modify it to the correct date."
3409 org-deadline-string " "
3410 (format-time-string (car org-time-stamp-formats)
3411 (org-read-date nil 'to-time)))
3412 (message "%s" (substitute-command-keys
3413 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3415 (defun org-schedule ()
3416 "Insert the SCHEDULED: string to schedule a TODO item.
3417 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3418 to modify it to the correct date."
3421 org-scheduled-string " "
3422 (format-time-string (car org-time-stamp-formats)
3423 (org-read-date nil 'to-time)))
3424 (message "%s" (substitute-command-keys
3425 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3428 (defun org-occur (regexp &optional callback)
3429 "Make a compact tree which shows all matches of REGEXP.
3430 The tree will show the lines where the regexp matches, and all higher
3431 headlines above the match. It will also show the heading after the match,
3432 to make sure editing the matching entry is easy.
3433 if CALLBACK is non-nil, it is a function which is called to confirm
3434 that the match should indeed be shown."
3435 (interactive "sRegexp: ")
3436 (org-remove-occur-highlights nil nil t)
3437 (setq regexp (org-check-occur-regexp regexp))
3440 (goto-char (point-min))
3442 (while (re-search-forward regexp nil t)
3443 (when (or (not callback)
3444 (save-match-data (funcall callback)))
3446 (org-highlight-new-match (match-beginning 0) (match-end 0))
3447 (org-show-hierarchy-above))))
3448 (make-local-hook 'before-change-functions) ; needed for XEmacs
3449 (add-hook 'before-change-functions 'org-remove-occur-highlights
3451 (run-hooks 'org-occur-hook)
3453 (message "%d match(es) for regexp %s" cnt regexp))
3456 (defun org-show-hierarchy-above ()
3457 "Make sure point and the headings hierarchy above is visible."
3458 (if (org-on-heading-p t)
3459 (org-flag-heading nil) ; only show the heading
3460 (and (org-invisible-p) (org-show-hidden-entry))) ; show entire entry
3462 (and org-show-following-heading
3463 (outline-next-heading)
3464 (org-flag-heading nil))) ; show the next heading
3465 (when org-show-hierarchy-above
3466 (save-excursion ; show all higher headings
3467 (while (condition-case nil
3468 (progn (org-up-heading-all 1) t)
3470 (org-flag-heading nil)))))
3472 (defvar org-occur-highlights nil)
3473 (defun org-highlight-new-match (beg end)
3474 "Highlight from BEG to END and mark the highlight is an occur headline."
3475 (let ((ov (make-overlay beg end)))
3476 (overlay-put ov 'face 'secondary-selection)
3477 (push ov org-occur-highlights)))
3479 (defun org-remove-occur-highlights (&optional beg end noremove)
3480 "Remove the occur highlights from the buffer.
3481 BEG and END are ignored. If NOREMOVE is nil, remove this function
3482 from the before-change-functions in the current buffer."
3484 (mapc 'delete-overlay org-occur-highlights)
3485 (setq org-occur-highlights nil)
3487 (remove-hook 'before-change-functions
3488 'org-remove-occur-highlights 'local)))
3492 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3493 "Regular expression matching the priority indicator.")
3495 (defvar org-remove-priority-next-time nil)
3497 (defun org-priority-up ()
3498 "Increase the priority of the current item."
3502 (defun org-priority-down ()
3503 "Decrease the priority of the current item."
3505 (org-priority 'down))
3507 (defun org-priority (&optional action)
3508 "Change the priority of an item by ARG.
3509 ACTION can be set, up, or down."
3511 (setq action (or action 'set))
3512 (let (current new news have remove)
3514 (org-back-to-heading)
3515 (if (looking-at org-priority-regexp)
3516 (setq current (string-to-char (match-string 2))
3518 (setq current org-default-priority))
3521 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3522 (setq new (read-char-exclusive))
3523 (cond ((equal new ?\ ) (setq remove t))
3524 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3525 (error "Priority must be between `%c' and `%c'"
3526 ?A org-lowest-priority))))
3528 (setq new (1- current)))
3530 (setq new (1+ current)))
3531 (t (error "Invalid action")))
3532 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3533 (setq news (format "%c" new))
3536 (replace-match "" t t nil 1)
3537 (replace-match news t t nil 2))
3539 (error "No priority cookie found in line")
3540 (looking-at org-todo-line-regexp)
3543 (goto-char (match-end 2))
3544 (insert " [#" news "]"))
3545 (goto-char (match-beginning 3))
3546 (insert "[#" news "] ")))))
3548 (message "Priority removed")
3549 (message "Priority of current item set to %s" news))))
3552 (defun org-get-priority (s)
3553 "Find priority cookie and return priority."
3555 (if (not (string-match org-priority-regexp s))
3556 (* 1000 (- org-lowest-priority org-default-priority))
3557 (* 1000 (- org-lowest-priority
3558 (string-to-char (match-string 2 s)))))))
3562 (defvar org-last-changed-timestamp nil)
3564 (defun org-time-stamp (arg)
3565 "Prompt for a date/time and insert a time stamp.
3566 If the user specifies a time like HH:MM, or if this command is called
3567 with a prefix argument, the time stamp will contain date and time.
3568 Otherwise, only the date will be included. All parts of a date not
3569 specified by the user will be filled in from the current date/time.
3570 So if you press just return without typing anything, the time stamp
3571 will represent the current date/time. If there is already a timestamp
3572 at the cursor, it will be modified."
3574 (let ((fmt (if arg (cdr org-time-stamp-formats)
3575 (car org-time-stamp-formats)))
3576 (org-time-was-given nil)
3579 ((and (org-at-timestamp-p)
3580 (eq last-command 'org-time-stamp)
3581 (eq this-command 'org-time-stamp))
3583 (setq time (let ((this-command this-command))
3584 (org-read-date arg 'totime)))
3585 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3586 (insert (format-time-string fmt time)))
3587 ((org-at-timestamp-p)
3588 (setq time (let ((this-command this-command))
3589 (org-read-date arg 'totime)))
3590 (and (org-at-timestamp-p) (replace-match
3591 (setq org-last-changed-timestamp
3592 (format-time-string fmt time))
3594 (message "Timestamp updated"))
3596 (setq time (let ((this-command this-command))
3597 (org-read-date arg 'totime)))
3598 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3599 (insert (format-time-string fmt time))))))
3601 (defun org-time-stamp-inactive (&optional arg)
3602 "Insert an inactive time stamp.
3603 An inactive time stamp is enclosed in square brackets instead of angle
3604 brackets. It is inactive in the sense that it does not trigger agenda entries,
3605 does not link to the calendar and cannot be changed with the S-cursor keys."
3607 (let ((fmt (if arg (cdr org-time-stamp-formats)
3608 (car org-time-stamp-formats)))
3609 (org-time-was-given nil)
3611 (setq time (org-read-date arg 'totime))
3612 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3613 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3614 (insert (format-time-string fmt time))))
3616 ;;; FIXME: Make the function take "Fri" as "next friday"
3617 (defun org-read-date (&optional with-time to-time)
3618 "Read a date and make things smooth for the user.
3619 The prompt will suggest to enter an ISO date, but you can also enter anything
3620 which will at least partially be understood by `parse-time-string'.
3621 Unrecognized parts of the date will default to the current day, month ,year,
3622 hour and minute. For example,
3623 3-2-5 --> 2003-02-05
3624 feb 15 --> currentyear-02-15
3625 sep 12 9 --> 2009-09-12
3626 12:45 --> today 12:45
3627 22 sept 0:34 --> currentyear-09-22 0:34
3628 12 --> currentyear-currentmonth-12
3630 The function understands only English month and weekday abbreviations,
3631 but this can be configured with the variables `parse-time-months' and
3632 `parse-time-weekdays'.
3634 While prompting, a calendar is popped up - you can also select the
3635 date with the mouse (button 1). The calendar shows a period of three
3636 month. To scroll it to other months, use the keys `>' and `<'.
3637 If you don't like the calendar, turn it off with
3638 \(setq org-popup-calendar-for-date-prompt nil).
3640 With optional argument TO-TIME, the date will immediately be converted
3641 to an internal time.
3642 With an optional argument WITH-TIME, the prompt will suggest to also
3643 insert a time. Note that when WITH-TIME is not set, you can still
3644 enter a time, and this function will inform the calling routine about
3645 this change. The calling routine may then choose to change the format
3646 used to insert the time stamp into the buffer to include the time."
3647 (let* ((default-time
3648 ;; Default time is either today, or, when entering a range,
3652 (concat org-ts-regexp "--\\=")
3656 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3657 (parse-time-string (match-string 1))))
3659 (calendar-move-hook nil)
3660 (view-diary-entries-initially nil)
3661 (timestr (format-time-string
3662 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3663 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3665 second minute hour day month year tl)
3667 (if org-popup-calendar-for-date-prompt
3668 ;; Also show a calendar for date selection
3669 ;; Copied (with modifications) from planner.el by John Wiegley
3671 (save-window-excursion
3673 (calendar-forward-day (- (time-to-days default-time)
3674 (calendar-absolute-from-gregorian
3675 (calendar-current-date))))
3676 (let* ((old-map (current-local-map))
3677 (map (copy-keymap calendar-mode-map))
3678 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3679 (define-key map (kbd "RET") 'org-calendar-select)
3680 (define-key map (if org-xemacs-p [button1] [mouse-1])
3681 'org-calendar-select)
3682 (define-key minibuffer-local-map [(meta shift left)]
3683 (lambda () (interactive)
3684 (org-eval-in-calendar '(calendar-backward-month 1))))
3685 (define-key minibuffer-local-map [(meta shift right)]
3686 (lambda () (interactive)
3687 (org-eval-in-calendar '(calendar-forward-month 1))))
3688 (define-key minibuffer-local-map [(shift up)]
3689 (lambda () (interactive)
3690 (org-eval-in-calendar '(calendar-backward-week 1))))
3691 (define-key minibuffer-local-map [(shift down)]
3692 (lambda () (interactive)
3693 (org-eval-in-calendar '(calendar-forward-week 1))))
3694 (define-key minibuffer-local-map [(shift left)]
3695 (lambda () (interactive)
3696 (org-eval-in-calendar '(calendar-backward-day 1))))
3697 (define-key minibuffer-local-map [(shift right)]
3698 (lambda () (interactive)
3699 (org-eval-in-calendar '(calendar-forward-day 1))))
3700 (define-key minibuffer-local-map ">"
3701 (lambda () (interactive)
3702 (org-eval-in-calendar '(scroll-calendar-left 1))))
3703 (define-key minibuffer-local-map "<"
3704 (lambda () (interactive)
3705 (org-eval-in-calendar '(scroll-calendar-right 1))))
3709 (setq ans (read-string prompt "" nil nil))
3710 (setq ans (or ans1 ans2 ans)))
3711 (use-local-map old-map)))))
3712 ;; Naked prompt only
3713 (setq ans (read-string prompt "" nil timestr)))
3716 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3718 (setq year (if (match-end 2)
3719 (string-to-number (match-string 2 ans))
3720 (string-to-number (format-time-string "%Y")))
3721 month (string-to-number (match-string 3 ans))
3722 day (string-to-number (match-string 4 ans)))
3723 (if (< year 100) (setq year (+ 2000 year)))
3724 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3726 (setq tl (parse-time-string ans)
3727 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3728 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3729 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3730 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3731 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3732 second (or (nth 0 tl) 0))
3733 (if (and (boundp 'org-time-was-given)
3735 (setq org-time-was-given t))
3736 (if (< year 100) (setq year (+ 2000 year)))
3738 (encode-time second minute hour day month year)
3739 (if (or (nth 1 tl) (nth 2 tl))
3740 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3741 (format "%04d-%02d-%02d" year month day)))))
3743 (defun org-eval-in-calendar (form)
3744 "Eval FORM in the calendar window and return to current window.
3745 Also, store the cursor date in variable ans2."
3746 (let ((sw (selected-window)))
3747 (select-window (get-buffer-window "*Calendar*"))
3749 (when (calendar-cursor-to-date)
3750 (let* ((date (calendar-cursor-to-date))
3751 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3752 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3753 (select-window sw)))
3755 (defun org-calendar-select ()
3756 "Return to `org-read-date' with the date currently selected.
3757 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3759 (when (calendar-cursor-to-date)
3760 (let* ((date (calendar-cursor-to-date))
3761 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3762 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3763 (if (active-minibuffer-window) (exit-minibuffer))))
3765 (defun org-check-deadlines (ndays)
3766 "Check if there are any deadlines due or past due.
3767 A deadline is considered due if it happens within `org-deadline-warning-days'
3768 days from today's date. If the deadline appears in an entry marked DONE,
3769 it is not shown. The prefix arg NDAYS can be used to test that many
3770 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3772 (let* ((org-warn-days
3774 ((equal ndays '(4)) 100000)
3775 (ndays (prefix-numeric-value ndays))
3776 (t org-deadline-warning-days)))
3777 (case-fold-search nil)
3778 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3781 (and (let ((d1 (time-to-days (current-time)))
3783 (org-time-string-to-time (match-string 1)))))
3784 (< (- d2 d1) org-warn-days))
3785 (not (org-entry-is-done-p))))))
3786 (message "%d deadlines past-due or due within %d days"
3787 (org-occur regexp callback)
3790 (defun org-evaluate-time-range (&optional to-buffer)
3791 "Evaluate a time range by computing the difference between start and end.
3792 Normally the result is just printed in the echo area, but with prefix arg
3793 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3794 If the time range is actually in a table, the result is inserted into the
3796 For time difference computation, a year is assumed to be exactly 365
3797 days in order to avoid rounding problems."
3800 (unless (org-at-date-range-p)
3801 (goto-char (point-at-bol))
3802 (re-search-forward org-tr-regexp (point-at-eol) t))
3803 (if (not (org-at-date-range-p))
3804 (error "Not at a time-stamp range, and none found in current line")))
3805 (let* ((ts1 (match-string 1))
3806 (ts2 (match-string 2))
3807 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3808 (match-end (match-end 0))
3809 (time1 (org-time-string-to-time ts1))
3810 (time2 (org-time-string-to-time ts2))
3811 (t1 (time-to-seconds time1))
3812 (t2 (time-to-seconds time2))
3813 (diff (abs (- t2 t1)))
3814 (negative (< (- t2 t1) 0))
3815 ;; (ys (floor (* 365 24 60 60)))
3818 (fy "%dy %dd %02d:%02d")
3820 (fd "%dd %02d:%02d")
3824 ;; FIXME: Should I re-introduce years, make year refer to same date?
3825 ;; This would be the only useful way to have years, actually.
3827 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3829 d (floor (/ diff ds)) diff (mod diff ds)
3830 h (floor (/ diff hs)) diff (mod diff hs)
3831 m (floor (/ diff 60)))
3832 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3834 d (floor (+ (/ diff ds) 0.5))
3837 (message (org-make-tdiff-string y d h m))
3838 (when (org-at-table-p)
3839 (goto-char match-end)
3841 (and (looking-at " *|") (goto-char (match-end 0))))
3843 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3845 (if negative (insert " -"))
3846 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3847 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3848 (insert " " (format fh h m))))
3849 (if align (org-table-align))
3850 (message "Time difference inserted"))))
3852 (defun org-make-tdiff-string (y d h m)
3855 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3857 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3859 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3861 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3863 (apply 'format fmt (nreverse l))))
3865 (defun org-time-string-to-time (s)
3866 (apply 'encode-time (org-parse-time-string s)))
3868 (defun org-parse-time-string (s &optional nodefault)
3869 "Parse the standard Org-mode time string.
3870 This should be a lot faster than the normal `parse-time-string'.
3871 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3872 hour and minute fields will be nil if not given."
3873 (if (string-match org-ts-regexp1 s)
3875 (if (or (match-beginning 8) (not nodefault))
3876 (string-to-number (or (match-string 8 s) "0")))
3877 (if (or (match-beginning 7) (not nodefault))
3878 (string-to-number (or (match-string 7 s) "0")))
3879 (string-to-number (match-string 4 s))
3880 (string-to-number (match-string 3 s))
3881 (string-to-number (match-string 2 s))
3885 (defun org-timestamp-up (&optional arg)
3886 "Increase the date item at the cursor by one.
3887 If the cursor is on the year, change the year. If it is on the month or
3888 the day, change that.
3889 With prefix ARG, change by that many units."
3891 (org-timestamp-change (prefix-numeric-value arg)))
3893 (defun org-timestamp-down (&optional arg)
3894 "Decrease the date item at the cursor by one.
3895 If the cursor is on the year, change the year. If it is on the month or
3896 the day, change that.
3897 With prefix ARG, change by that many units."
3899 (org-timestamp-change (- (prefix-numeric-value arg))))
3901 (defun org-timestamp-up-day (&optional arg)
3902 "Increase the date in the time stamp by one day.
3903 With prefix ARG, change that many days."
3905 (if (and (not (org-at-timestamp-p))
3908 (org-timestamp-change (prefix-numeric-value arg) 'day)))
3910 (defun org-timestamp-down-day (&optional arg)
3911 "Decrease the date in the time stamp by one day.
3912 With prefix ARG, change that many days."
3914 (if (and (not (org-at-timestamp-p))
3917 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
3919 (defsubst org-pos-in-match-range (pos n)
3920 (and (match-beginning n)
3921 (<= (match-beginning n) pos)
3922 (>= (match-end n) pos)))
3924 (defun org-at-timestamp-p ()
3925 "Determine if the cursor is in or at a timestamp."
3927 (let* ((tsr org-ts-regexp2)
3929 (ans (or (looking-at tsr)
3931 (skip-chars-backward "^<\n\r\t")
3932 (if (> (point) 1) (backward-char 1))
3933 (and (looking-at tsr)
3934 (> (- (match-end 0) pos) -1))))))
3935 (and (boundp 'org-ts-what)
3938 ((org-pos-in-match-range pos 2) 'year)
3939 ((org-pos-in-match-range pos 3) 'month)
3940 ((org-pos-in-match-range pos 7) 'hour)
3941 ((org-pos-in-match-range pos 8) 'minute)
3942 ((or (org-pos-in-match-range pos 4)
3943 (org-pos-in-match-range pos 5)) 'day)
3947 (defun org-timestamp-change (n &optional what)
3948 "Change the date in the time stamp at point.
3949 The date will be changed by N times WHAT. WHAT can be `day', `month',
3950 `year', `minute', `second'. If WHAT is not given, the cursor position
3951 in the timestamp determines what will be changed."
3952 (let ((fmt (car org-time-stamp-formats))
3956 (if (not (org-at-timestamp-p))
3957 (error "Not at a timestamp"))
3958 (setq org-ts-what (or what org-ts-what))
3959 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3960 (- (match-end 0) (match-beginning 0))))
3962 (cdr org-time-stamp-formats)
3963 (car org-time-stamp-formats)))
3964 (setq ts (match-string 0))
3966 (setq time0 (org-parse-time-string ts))
3970 (list (or (car time0) 0))
3971 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3972 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3973 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3974 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3975 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3977 (if (eq what 'calendar)
3981 (set-buffer "*Calendar*")
3982 (calendar-cursor-to-date)))))
3983 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3984 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3985 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3986 (setcar time0 (or (car time0) 0))
3987 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3988 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3989 (setq time (apply 'encode-time time0))))
3990 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3992 ;; Try to recenter the calendar window, if any
3993 (if (and org-calendar-follow-timestamp-change
3994 (get-buffer-window "*Calendar*" t)
3995 (memq org-ts-what '(day month year)))
3996 (org-recenter-calendar (time-to-days time)))))
3998 (defun org-recenter-calendar (date)
3999 "If the calendar is visible, recenter it to DATE."
4000 (let* ((win (selected-window))
4001 (cwin (get-buffer-window "*Calendar*" t))
4002 (calendar-move-hook nil))
4004 (select-window cwin)
4005 (calendar-goto-date (if (listp date) date
4006 (calendar-gregorian-from-absolute date)))
4007 (select-window win))))
4009 (defun org-goto-calendar (&optional arg)
4010 "Go to the Emacs calendar at the current date.
4011 If there is a time stamp in the current line, go to that date.
4012 A prefix ARG can be used force the current date."
4014 (let ((tsr org-ts-regexp) diff
4015 (calendar-move-hook nil)
4016 (view-diary-entries-initially nil))
4017 (if (or (org-at-timestamp-p)
4019 (beginning-of-line 1)
4020 (looking-at (concat ".*" tsr))))
4021 (let ((d1 (time-to-days (current-time)))
4023 (org-time-string-to-time (match-string 1)))))
4024 (setq diff (- d2 d1))))
4026 (calendar-goto-today)
4027 (if (and diff (not arg)) (calendar-forward-day diff))))
4029 (defun org-date-from-calendar ()
4030 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4031 If there is already a time stamp at the cursor position, update it."
4033 (org-timestamp-change 0 'calendar))
4035 ;;; Agenda, and Diary Integration
4039 (defvar org-agenda-mode-map (make-sparse-keymap)
4040 "Keymap for `org-agenda-mode'.")
4042 (defvar org-agenda-menu)
4043 (defvar org-agenda-follow-mode nil)
4044 (defvar org-agenda-buffer-name "*Org Agenda*")
4045 (defvar org-agenda-redo-command nil)
4046 (defvar org-agenda-mode-hook nil)
4049 (defun org-agenda-mode ()
4050 "Mode for time-sorted view on action items in Org-mode files.
4052 The following commands are available:
4054 \\{org-agenda-mode-map}"
4056 (kill-all-local-variables)
4057 (setq major-mode 'org-agenda-mode)
4058 (setq mode-name "Org-Agenda")
4059 (use-local-map org-agenda-mode-map)
4060 (easy-menu-add org-agenda-menu)
4061 (if org-startup-truncated (setq truncate-lines t))
4062 (make-local-hook 'post-command-hook) ; Needed for XEmacs
4063 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4064 (make-local-hook 'pre-command-hook) ; Needed for XEmacs
4065 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4066 (setq org-agenda-follow-mode nil)
4068 '("Agenda") "Agenda Files"
4071 ["Edit File List" (customize-variable 'org-agenda-files) t]
4073 (mapcar 'org-file-menu-entry org-agenda-files)))
4074 (org-agenda-set-mode-name)
4076 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4077 (list 'org-agenda-mode-hook)))
4079 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4080 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4081 (define-key org-agenda-mode-map " " 'org-agenda-show)
4082 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4083 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4084 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
4085 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4086 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4087 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4088 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4089 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4090 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4091 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4092 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4094 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4095 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4096 (while l (define-key org-agenda-mode-map
4097 (int-to-string (pop l)) 'digit-argument)))
4099 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4100 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4101 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4102 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4103 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4104 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4105 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4106 (define-key org-agenda-mode-map "n" 'next-line)
4107 (define-key org-agenda-mode-map "p" 'previous-line)
4108 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4109 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4110 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4111 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4112 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4113 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4114 (eval-after-load "calendar"
4115 '(define-key calendar-mode-map org-calendar-to-agenda-key
4116 'org-calendar-goto-agenda))
4117 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4118 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4119 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4120 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4121 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4122 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4123 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4124 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4125 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4126 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4127 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4128 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4129 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4130 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4131 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4132 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4133 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4134 "Local keymap for agenda entries from Org-mode.")
4136 (define-key org-agenda-keymap
4137 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4138 (define-key org-agenda-keymap
4139 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4141 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4145 ["Show" org-agenda-show t]
4146 ["Go To (other window)" org-agenda-goto t]
4147 ["Go To (one window)" org-agenda-switch-to t]
4148 ["Follow Mode" org-agenda-follow-mode
4149 :style toggle :selected org-agenda-follow-mode :active t]
4151 ["Cycle TODO" org-agenda-todo t]
4153 ["Reschedule +1 day" org-agenda-date-later t]
4154 ["Reschedule -1 day" org-agenda-date-earlier t]
4156 ["Reschedule to ..." org-agenda-date-prompt t])
4158 ["Set Priority" org-agenda-priority t]
4159 ["Increase Priority" org-agenda-priority-up t]
4160 ["Decrease Priority" org-agenda-priority-down t]
4161 ["Show Priority" org-agenda-show-priority t])
4163 ["Rebuild buffer" org-agenda-redo t]
4164 ["Goto Today" org-agenda-goto-today t]
4165 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
4166 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
4168 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
4169 :style radio :selected (equal org-agenda-ndays 1)]
4170 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
4171 :style radio :selected (equal org-agenda-ndays 7)]
4173 ["Include Diary" org-agenda-toggle-diary
4174 :style toggle :selected org-agenda-include-diary :active t]
4175 ["Use Time Grid" org-agenda-toggle-time-grid
4176 :style toggle :selected org-agenda-use-time-grid :active t]
4178 ["New Diary Entry" org-agenda-diary-entry t]
4179 ("Calendar Commands"
4180 ["Goto Calendar" org-agenda-goto-calendar t]
4181 ["Phases of the Moon" org-agenda-phases-of-moon t]
4182 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
4183 ["Holidays" org-agenda-holidays t]
4184 ["Convert" org-agenda-convert-date t])
4185 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4187 ["Quit" org-agenda-quit t]
4188 ["Exit and Release Buffers" org-agenda-exit t]
4191 (defvar org-agenda-markers nil
4192 "List of all currently active markers created by `org-agenda'.")
4193 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4194 "Creation time of the last agenda marker.")
4196 (defun org-agenda-new-marker (&optional pos)
4197 "Return a new agenda marker.
4198 Org-mode keeps a list of these markers and resets them when they are
4200 (let ((m (copy-marker (or pos (point)))))
4201 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4202 (push m org-agenda-markers)
4205 (defun org-agenda-maybe-reset-markers (&optional force)
4206 "Reset markers created by `org-agenda'. But only if they are old enough."
4208 (> (- (time-to-seconds (current-time))
4209 org-agenda-last-marker-time)
4211 (while org-agenda-markers
4212 (move-marker (pop org-agenda-markers) nil))))
4214 (defvar org-agenda-new-buffers nil
4215 "Buffers created to visit agenda files.")
4217 (defun org-get-agenda-file-buffer (file)
4218 "Get a buffer visiting FILE. If the buffer needs to be created, add
4219 it to the list of buffers which might be released later."
4220 (let ((buf (find-buffer-visiting file)))
4222 buf ; just return it
4223 ;; Make a new buffer and remember it
4224 (setq buf (find-file-noselect file))
4225 (if buf (push buf org-agenda-new-buffers))
4228 (defun org-release-buffers (blist)
4229 "Release all buffers in list, asking the user for confirmation when needed.
4230 When a buffer is unmodified, it is just killed. When modified, it is saved
4231 \(if the user agrees) and then killed."
4233 (while (setq buf (pop blist))
4234 (setq file (buffer-file-name buf))
4235 (when (and (buffer-modified-p buf)
4237 (y-or-n-p (format "Save file %s? " file)))
4238 (with-current-buffer buf (save-buffer)))
4239 (kill-buffer buf))))
4241 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4243 (defun org-timeline (&optional include-all)
4244 "Show a time-sorted view of the entries in the current org file.
4245 Only entries with a time stamp of today or later will be listed. With
4246 one \\[universal-argument] prefix argument, past entries will also be listed.
4247 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
4248 under the current date.
4249 If the buffer contains an active region, only check the region for
4253 (org-agenda-maybe-reset-markers 'force)
4254 (org-compile-prefix-format org-timeline-prefix-format)
4255 (let* ((dopast include-all)
4256 (dotodo (equal include-all '(16)))
4257 (entry (buffer-file-name))
4258 (org-agenda-files (list (buffer-file-name)))
4259 (date (calendar-current-date))
4260 (win (selected-window))
4262 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4263 (end (if (org-region-active-p) (region-end) (point-max)))
4264 (day-numbers (org-get-all-dates beg end 'no-ranges
4265 t)) ; always include today
4266 (today (time-to-days (current-time)))
4267 (org-respect-restriction t)
4270 (setq org-agenda-redo-command
4272 (list 'switch-to-buffer-other-window (current-buffer))
4273 (list 'org-timeline (list 'quote include-all))))
4275 ;; Remove past dates from the list of dates.
4276 (setq day-numbers (delq nil (mapcar (lambda(x)
4277 (if (>= x today) x nil))
4279 (switch-to-buffer-other-window
4280 (get-buffer-create org-agenda-buffer-name))
4281 (setq buffer-read-only nil)
4283 (org-agenda-mode) (setq buffer-read-only nil)
4284 (while (setq d (pop day-numbers))
4285 (if (and (>= d today)
4290 (insert (make-string 79 ?-) "\n")))
4291 (setq date (calendar-gregorian-from-absolute d))
4294 (setq rtn (org-agenda-get-day-entries
4295 entry date :todo :timestamp))
4296 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
4297 (if (or rtn (equal d today))
4299 (insert (calendar-day-name date) " "
4300 (number-to-string (extract-calendar-day date)) " "
4301 (calendar-month-name (extract-calendar-month date)) " "
4302 (number-to-string (extract-calendar-year date)) "\n")
4303 (put-text-property s (1- (point)) 'face
4306 (put-text-property s (1- (point)) 'org-today t))
4307 (insert (org-finalize-agenda-entries rtn) "\n")
4308 (put-text-property s (1- (point)) 'day d))))
4309 (goto-char (point-min))
4310 (setq buffer-read-only t)
4311 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4313 (when (not org-select-timeline-window)
4318 (defun org-agenda (&optional include-all start-day ndays)
4319 "Produce a weekly view from all files in variable `org-agenda-files'.
4320 The view will be for the current week, but from the overview buffer you
4321 will be able to go to other weeks.
4322 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4323 also be shown, under the current date.
4324 START-DAY defaults to TODAY, or to the most recent match for the weekday
4325 given in `org-agenda-start-on-weekday'.
4326 NDAYS defaults to `org-agenda-ndays'."
4328 (org-agenda-maybe-reset-markers 'force)
4329 (org-compile-prefix-format org-agenda-prefix-format)
4331 (let* ((org-agenda-start-on-weekday
4332 (if (or (equal ndays 1)
4333 (and (null ndays) (equal 1 org-agenda-ndays)))
4334 nil org-agenda-start-on-weekday))
4335 (files (copy-sequence org-agenda-files))
4336 (win (selected-window))
4337 (today (time-to-days (current-time)))
4338 (sd (or start-day today))
4339 (start (if (or (null org-agenda-start-on-weekday)
4340 (< org-agenda-ndays 7))
4342 (let* ((nt (calendar-day-of-week
4343 (calendar-gregorian-from-absolute sd)))
4344 (n1 org-agenda-start-on-weekday)
4346 (- sd (+ (if (< d 0) 7 0) d)))))
4347 (day-numbers (list start))
4348 (inhibit-redisplay t)
4349 s e rtn rtnall file date d start-pos end-pos todayp nd)
4350 (setq org-agenda-redo-command
4351 (list 'org-agenda (list 'quote include-all) start-day ndays))
4352 ;; Make the list of days
4353 (setq ndays (or ndays org-agenda-ndays)
4356 (push (1+ (car day-numbers)) day-numbers)
4357 (setq ndays (1- ndays)))
4358 (setq day-numbers (nreverse day-numbers))
4359 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4361 (delete-other-windows)
4362 (switch-to-buffer-other-window
4363 (get-buffer-create org-agenda-buffer-name))))
4364 (setq buffer-read-only nil)
4366 (org-agenda-mode) (setq buffer-read-only nil)
4367 (set (make-local-variable 'starting-day) (car day-numbers))
4368 (set (make-local-variable 'include-all-loc) include-all)
4369 (when (and (or include-all org-agenda-include-all-todo)
4370 (member today day-numbers))
4371 (setq files org-agenda-files
4373 (while (setq file (pop files))
4375 (org-check-agenda-file file)
4376 (setq date (calendar-gregorian-from-absolute today)
4377 rtn (org-agenda-get-day-entries
4379 (setq rtnall (append rtnall rtn))))
4381 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4382 (add-text-properties (point-min) (1- (point))
4383 (list 'face 'org-link))
4384 (insert (org-finalize-agenda-entries rtnall) "\n")))
4385 (while (setq d (pop day-numbers))
4386 (setq date (calendar-gregorian-from-absolute d)
4388 (if (or (setq todayp (= d today))
4389 (and (not start-pos) (= d sd)))
4390 (setq start-pos (point))
4391 (if (and start-pos (not end-pos))
4392 (setq end-pos (point))))
4393 (setq files org-agenda-files
4395 (while (setq file (pop files))
4397 (org-check-agenda-file file)
4398 (setq rtn (org-agenda-get-day-entries file date))
4399 (setq rtnall (append rtnall rtn))))
4400 (if org-agenda-include-diary
4402 (require 'diary-lib)
4403 (setq rtn (org-get-entries-from-diary date))
4404 (setq rtnall (append rtnall rtn))))
4405 (if (or rtnall org-agenda-show-all-dates)
4407 (insert (format "%-9s %2d %s %4d\n"
4408 (calendar-day-name date)
4409 (extract-calendar-day date)
4410 (calendar-month-name (extract-calendar-month date))
4411 (extract-calendar-year date)))
4412 (put-text-property s (1- (point)) 'face
4415 (org-finalize-agenda-entries
4416 (org-agenda-add-time-grid-maybe
4419 (put-text-property s (1- (point)) 'day d))))
4420 (goto-char (point-min))
4421 (setq buffer-read-only t)
4422 (if org-fit-agenda-window
4423 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4424 (/ (frame-height) 2)))
4425 (unless (and (pos-visible-in-window-p (point-min))
4426 (pos-visible-in-window-p (point-max)))
4427 (goto-char (1- (point-max)))
4429 (if (not (pos-visible-in-window-p (or start-pos 1)))
4431 (goto-char (or start-pos 1))
4433 (goto-char (or start-pos 1))
4434 (if (not org-select-agenda-window) (select-window win))
4437 (defvar org-select-this-todo-keyword nil)
4440 (defun org-todo-list (arg)
4441 "Show all TODO entries from all agenda file in a single list.
4442 The prefix arg can be used to select a specific TODO keyword and limit
4443 the list to these. When using \\[universal-argument], you will be prompted
4444 for a keyword. A numeric prefix directly selects the Nth keyword in
4445 `org-todo-keywords'."
4447 (org-agenda-maybe-reset-markers 'force)
4448 (org-compile-prefix-format org-agenda-prefix-format)
4449 (let* ((today (time-to-days (current-time)))
4450 (date (calendar-gregorian-from-absolute today))
4451 (win (selected-window))
4452 (kwds org-todo-keywords)
4453 (completion-ignore-case t)
4454 (org-select-this-todo-keyword
4455 (and arg (integerp arg) (nth (1- arg) org-todo-keywords)))
4456 rtn rtnall files file pos)
4457 (when (equal arg '(4))
4458 (setq org-select-this-todo-keyword
4459 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4461 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4462 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4464 (delete-other-windows)
4465 (switch-to-buffer-other-window
4466 (get-buffer-create org-agenda-buffer-name))))
4467 (setq buffer-read-only nil)
4469 (org-agenda-mode) (setq buffer-read-only nil)
4470 (set (make-local-variable 'last-arg) arg)
4471 (set (make-local-variable 'org-todo-keywords) kwds)
4472 (set (make-local-variable 'org-agenda-redo-command)
4473 '(org-todo-list (or current-prefix-arg last-arg)))
4474 (setq files org-agenda-files
4476 (while (setq file (pop files))
4478 (org-check-agenda-file file)
4479 (setq rtn (org-agenda-get-day-entries file date :todo))
4480 (setq rtnall (append rtnall rtn))))
4481 (insert "Global list of TODO items of type: ")
4482 (add-text-properties (point-min) (1- (point))
4483 (list 'face 'org-link))
4485 (insert (or org-select-this-todo-keyword "ALL") "\n")
4486 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4488 (insert (org-finalize-agenda-entries rtnall) "\n"))
4489 (goto-char (point-min))
4490 (setq buffer-read-only t)
4491 (if org-fit-agenda-window
4492 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4493 (/ (frame-height) 2)))
4494 (if (not org-select-agenda-window) (select-window win))))
4496 (defun org-check-agenda-file (file)
4497 "Make sure FILE exists. If not, ask user what to do."
4498 ;; FIXME: this does not correctly change the menus
4499 ;; Could probably be fixed by explicitly going to the buffer.
4500 (when (not (file-exists-p file))
4501 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4503 (let ((r (downcase (read-char-exclusive))))
4506 (org-remove-file file)
4507 (throw 'nextfile t))
4508 (t (error "Abort"))))))
4510 (defun org-agenda-quit ()
4511 "Exit agenda by removing the window or the buffer."
4513 (let ((buf (current-buffer)))
4514 (if (not (one-window-p)) (delete-window))
4516 (org-agenda-maybe-reset-markers 'force)))
4518 (defun org-agenda-exit ()
4519 "Exit agenda by removing the window or the buffer.
4520 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4521 Org-mode buffers visited directly by the user will not be touched."
4523 (org-release-buffers org-agenda-new-buffers)
4524 (setq org-agenda-new-buffers nil)
4527 (defun org-agenda-redo ()
4529 When this is the global TODO list, a prefix argument will be interpreted."
4531 (eval org-agenda-redo-command))
4533 (defun org-agenda-goto-today ()
4536 (if (boundp 'starting-day)
4537 (let ((cmd (car org-agenda-redo-command))
4538 (iall (nth 1 org-agenda-redo-command))
4539 (nday (nth 3 org-agenda-redo-command)))
4540 (eval (list cmd iall nil nday)))
4541 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4544 (defun org-agenda-later (arg)
4545 "Go forward in time by `org-agenda-ndays' days.
4546 With prefix ARG, go forward that many times `org-agenda-ndays'."
4548 (unless (boundp 'starting-day)
4549 (error "Not allowed"))
4550 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
4551 (+ starting-day (* arg org-agenda-ndays))))
4553 (defun org-agenda-earlier (arg)
4554 "Go back in time by `org-agenda-ndays' days.
4555 With prefix ARG, go back that many times `org-agenda-ndays'."
4557 (unless (boundp 'starting-day)
4558 (error "Not allowed"))
4559 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
4560 (- starting-day (* arg org-agenda-ndays))))
4562 (defun org-agenda-week-view ()
4563 "Switch to weekly view for agenda."
4565 (unless (boundp 'starting-day)
4566 (error "Not allowed"))
4567 (setq org-agenda-ndays 7)
4568 (org-agenda include-all-loc
4569 (or (get-text-property (point) 'day)
4571 (org-agenda-set-mode-name)
4572 (message "Switched to week view"))
4574 (defun org-agenda-day-view ()
4575 "Switch to weekly view for agenda."
4577 (unless (boundp 'starting-day)
4578 (error "Not allowed"))
4579 (setq org-agenda-ndays 1)
4580 (org-agenda include-all-loc
4581 (or (get-text-property (point) 'day)
4583 (org-agenda-set-mode-name)
4584 (message "Switched to day view"))
4586 (defun org-agenda-next-date-line (&optional arg)
4587 "Jump to the next line indicating a date in agenda buffer."
4589 (beginning-of-line 1)
4590 (if (looking-at "^\\S-") (forward-char 1))
4591 (if (not (re-search-forward "^\\S-" nil t arg))
4594 (error "No next date after this line in this buffer")))
4595 (goto-char (match-beginning 0)))
4597 (defun org-agenda-previous-date-line (&optional arg)
4598 "Jump to the next line indicating a date in agenda buffer."
4600 (beginning-of-line 1)
4601 (if (not (re-search-backward "^\\S-" nil t arg))
4602 (error "No previous date before this line in this buffer")))
4604 ;; Initialize the highlight
4605 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
4606 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
4609 (defun org-highlight (begin end &optional buffer)
4610 "Highlight a region with overlay."
4611 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4612 org-hl begin end (or buffer (current-buffer))))
4614 (defun org-unhighlight ()
4615 "Detach overlay INDEX."
4616 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4619 (defun org-agenda-follow-mode ()
4620 "Toggle follow mode in an agenda buffer."
4622 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4623 (org-agenda-set-mode-name)
4624 (message "Follow mode is %s"
4625 (if org-agenda-follow-mode "on" "off")))
4627 (defun org-agenda-toggle-diary ()
4628 "Toggle follow mode in an agenda buffer."
4630 (setq org-agenda-include-diary (not org-agenda-include-diary))
4632 (org-agenda-set-mode-name)
4633 (message "Diary inclusion turned %s"
4634 (if org-agenda-include-diary "on" "off")))
4636 (defun org-agenda-toggle-time-grid ()
4637 "Toggle follow mode in an agenda buffer."
4639 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4641 (org-agenda-set-mode-name)
4642 (message "Time-grid turned %s"
4643 (if org-agenda-use-time-grid "on" "off")))
4645 (defun org-agenda-set-mode-name ()
4646 "Set the mode name to indicate all the small mode settings."
4648 (concat "Org-Agenda"
4649 (if (equal org-agenda-ndays 1) " Day" "")
4650 (if (equal org-agenda-ndays 7) " Week" "")
4651 (if org-agenda-follow-mode " Follow" "")
4652 (if org-agenda-include-diary " Diary" "")
4653 (if org-agenda-use-time-grid " Grid" "")))
4654 (force-mode-line-update))
4656 (defun org-agenda-post-command-hook ()
4657 (and (eolp) (not (bolp)) (backward-char 1))
4658 (if (and org-agenda-follow-mode
4659 (get-text-property (point) 'org-marker))
4662 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4664 (defun org-get-entries-from-diary (date)
4665 "Get the (Emacs Calendar) diary entries for DATE."
4666 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4667 (diary-display-hook '(fancy-diary-display))
4668 (list-diary-entries-hook
4669 (cons 'org-diary-default-entry list-diary-entries-hook))
4670 (diary-file-name-prefix-function nil) ; turn this feature off
4671 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4673 (org-disable-agenda-to-diary t))
4675 (save-window-excursion
4676 (list-diary-entries date 1)))
4677 (if (not (get-buffer fancy-diary-buffer))
4679 (with-current-buffer fancy-diary-buffer
4680 (setq buffer-read-only nil)
4681 (if (= (point-max) 1)
4684 ;; Omit the date and other unnecessary stuff
4685 (org-agenda-cleanup-fancy-diary)
4686 ;; Add prefix to each line and extend the text properties
4687 (if (= (point-max) 1)
4689 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4690 (set-buffer-modified-p nil)
4691 (kill-buffer fancy-diary-buffer)))
4693 (setq entries (org-split-string entries "\n"))
4697 (setq x (org-format-agenda-item "" x "Diary" 'time))
4698 ;; Extend the text properties to the beginning of the line
4699 (add-text-properties
4701 (text-properties-at (1- (length x)) x)
4706 (defun org-agenda-cleanup-fancy-diary ()
4707 "Remove unwanted stuff in buffer created by fancy-diary-display.
4708 This gets rid of the date, the underline under the date, and
4709 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4710 date. Itt also removes lines that contain only whitespace."
4711 (goto-char (point-min))
4712 (if (looking-at ".*?:[ \t]*")
4715 (re-search-forward "\n=+$" nil t)
4717 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4718 (re-search-forward "\n=+$" nil t)
4719 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4720 (goto-char (point-min))
4721 (while (re-search-forward "^ +\n" nil t)
4723 (goto-char (point-min))
4724 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4725 (replace-match "")))
4727 ;; Make sure entries from the diary have the right text properties.
4728 (eval-after-load "diary-lib"
4729 '(if (boundp 'diary-modify-entry-list-string-function)
4730 ;; We can rely on the hook, nothing to do
4732 ;; Hook not avaiable, must use advice to make this work
4733 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4734 "Make the position visible."
4735 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4738 (setq string (org-modify-diary-entry-string string))))))
4740 (defun org-modify-diary-entry-string (string)
4741 "Add text properties to string, allowing org-mode to act on it."
4742 (add-text-properties
4744 (list 'mouse-face 'highlight
4745 'keymap org-agenda-keymap
4748 "mouse-2 or RET jump to diary file %s"
4749 (abbreviate-file-name (buffer-file-name)))
4750 'org-agenda-diary-link t
4751 'org-marker (org-agenda-new-marker (point-at-bol)))
4755 (defun org-diary-default-entry ()
4756 "Add a dummy entry to the diary.
4757 Needed to avoid empty dates which mess up holiday display."
4758 ;; Catch the error if dealing with the new add-to-diary-alist
4759 (when org-disable-agenda-to-diary
4761 (add-to-diary-list original-date "Org-mode dummy" "")
4763 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
4765 (defun org-cycle-agenda-files ()
4766 "Cycle through the files in `org-agenda-files'.
4767 If the current buffer visits an agenda file, find the next one in the list.
4768 If the current buffer does not, find the first agenda file."
4770 (let ((files (append org-agenda-files (list (car org-agenda-files))))
4771 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
4773 (unless files (error "No agenda files"))
4775 (while (setq file (pop files))
4776 (if (equal (file-truename file) tcf)
4778 (find-file (car files))
4780 (find-file (car org-agenda-files)))))
4782 (defun org-agenda-file-to-end (&optional file)
4783 "Move/add the current file to the end of the agenda fiole list.
4784 I the file is not present in the list, it is appended ot the list. If it is
4785 present, it is moved there."
4787 (org-agenda-file-to-front 'to-end file))
4789 (defun org-agenda-file-to-front (&optional to-end file)
4790 "Move/add the current file to the top of the agenda file list.
4791 If the file is not present in the list, it is added to the front. If it is
4792 present, it is moved there. With optional argument TO-END, add/move to the
4795 (let ((file-alist (mapcar (lambda (x)
4796 (cons (file-truename x) x))
4798 (ctf (file-truename (buffer-file-name)))
4800 (setq x (assoc ctf file-alist) had x)
4802 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
4804 (setq file-alist (append (delq x file-alist) (list x)))
4805 (setq file-alist (cons x (delq x file-alist))))
4806 (setq org-agenda-files (mapcar 'cdr file-alist))
4807 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4808 (customize-save-variable 'org-agenda-files org-agenda-files))
4809 (org-install-agenda-files-menu)
4810 (message "File %s to %s of agenda file list"
4811 (if had "moved" "added") (if to-end "end" "front"))))
4813 (defun org-remove-file (&optional file)
4814 "Remove current file from the list of files in variable `org-agenda-files'.
4815 These are the files which are being checked for agenda entries.
4816 Optional argument FILE means, use this file instead of the current."
4818 (let* ((file (or file (buffer-file-name)))
4819 (true-file (file-truename file))
4820 (afile (abbreviate-file-name file))
4821 (files (delq nil (mapcar
4823 (if (equal true-file
4826 org-agenda-files))))
4827 (if (not (= (length files) (length org-agenda-files)))
4829 (setq org-agenda-files files)
4830 (customize-save-variable 'org-agenda-files org-agenda-files)
4831 (org-install-agenda-files-menu)
4832 (message "Removed file: %s" afile))
4833 (message "File was not in list: %s" afile))))
4835 (defun org-file-menu-entry (file)
4836 (vector file (list 'find-file file) t))
4837 ;; FIXME: Maybe removed a buffer visited through the menu from
4838 ;; org-agenda-new-buffers, so that the buffer will not be removed
4839 ;; when exiting the agenda????
4841 (defun org-get-all-dates (beg end &optional no-ranges force-today)
4842 "Return a list of all relevant day numbers from BEG to END buffer positions.
4843 If NO-RANGES is non-nil, include only the start and end dates of a range,
4844 not every single day in the range. If FORCE-TODAY is non-nil, make
4845 sure that TODAY is included in the list."
4846 (let (dates date day day1 day2 ts1 ts2)
4848 (setq dates (list (time-to-days (current-time)))))
4851 (while (re-search-forward org-ts-regexp end t)
4852 (setq day (time-to-days (org-time-string-to-time
4853 (substring (match-string 1) 0 10))))
4854 (or (memq day dates) (push day dates)))
4857 (while (re-search-forward org-tr-regexp end t)
4858 (setq ts1 (substring (match-string 1) 0 10)
4859 ts2 (substring (match-string 2) 0 10)
4860 day1 (time-to-days (org-time-string-to-time ts1))
4861 day2 (time-to-days (org-time-string-to-time ts2)))
4862 (while (< (setq day1 (1+ day1)) day2)
4863 (or (memq day1 dates) (push day1 dates)))))
4867 (defun org-diary (&rest args)
4868 "Return diary information from org-files.
4869 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4870 It accesses org files and extracts information from those files to be
4871 listed in the diary. The function accepts arguments specifying what
4872 items should be listed. The following arguments are allowed:
4874 :timestamp List the headlines of items containing a date stamp or
4875 date range matching the selected date. Deadlines will
4876 also be listed, on the expiration day.
4878 :deadline List any deadlines past due, or due within
4879 `org-deadline-warning-days'. The listing occurs only
4880 in the diary for *today*, not at any other date. If
4881 an entry is marked DONE, it is no longer listed.
4883 :scheduled List all items which are scheduled for the given date.
4884 The diary for *today* also contains items which were
4885 scheduled earlier and are not yet marked DONE.
4887 :todo List all TODO items from the org-file. This may be a
4888 long list - so this is not turned on by default.
4889 Like deadlines, these entries only show up in the
4890 diary for *today*, not at any other date.
4892 The call in the diary file should look like this:
4894 &%%(org-diary) ~/path/to/some/orgfile.org
4896 Use a separate line for each org file to check. Or, if you omit the file name,
4897 all files listed in `org-agenda-files' will be checked automatically:
4901 If you don't give any arguments (as in the example above), the default
4902 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4905 &%%(org-diary :deadline :timestamp :scheduled)
4907 The function expects the lisp variables `entry' and `date' to be provided
4908 by the caller, because this is how the calendar works. Don't use this
4909 function from a program - use `org-agenda-get-day-entries' instead."
4910 (org-agenda-maybe-reset-markers)
4911 (org-compile-prefix-format org-agenda-prefix-format)
4912 (setq args (or args '(:deadline :scheduled :timestamp)))
4913 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4917 ;; If this is called during org-agenda, don't return any entries to
4918 ;; the calendar. Org Agenda will list these entries itself.
4919 (if org-disable-agenda-to-diary (setq files nil))
4920 (while (setq file (pop files))
4921 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4922 (setq results (append results rtn)))
4924 (concat (org-finalize-agenda-entries results) "\n"))))
4925 (defvar org-category-table nil)
4926 (defun org-get-category-table ()
4927 "Get the table of categories and positions in current buffer."
4930 (goto-char (point-min))
4931 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
4932 (push (cons (point) (org-trim (match-string 2))) tbl)))
4934 (defun org-get-category (&optional pos)
4935 "Get the category applying to position POS."
4936 (if (not org-category-table)
4938 (let ((tbl org-category-table)
4939 (pos (or pos (point))))
4940 (while (and tbl (> (caar tbl) pos))
4942 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
4943 org-category-table))))))
4945 (defun org-agenda-get-day-entries (file date &rest args)
4946 "Does the work for `org-diary' and `org-agenda'.
4947 FILE is the path to a file to be checked for entries. DATE is date like
4948 the one returned by `calendar-current-date'. ARGS are symbols indicating
4949 which kind of entries should be extracted. For details about these, see
4950 the documentation of `org-diary'."
4951 (setq args (or args '(:deadline :scheduled :timestamp)))
4952 (let* ((org-startup-with-deadline-check nil)
4953 (org-startup-folded nil)
4954 (buffer (if (file-exists-p file)
4955 (org-get-agenda-file-buffer file)
4956 (error "No such file %s" file)))
4959 ;; If file does not exist, make sure an error message ends up in diary
4960 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4961 (with-current-buffer buffer
4962 (unless (eq major-mode 'org-mode)
4963 (error "Agenda file %s is not in `org-mode'" file))
4964 (setq org-category-table (org-get-category-table))
4965 (let ((case-fold-search nil))
4968 (if org-respect-restriction
4969 (if (org-region-active-p)
4970 ;; Respect a region to restrict search
4971 (narrow-to-region (region-beginning) (region-end)))
4972 ;; If we work for the calendar or many files,
4973 ;; get rid of any restriction
4975 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4976 (while (setq arg (pop args))
4978 ((and (eq arg :todo)
4979 (equal date (calendar-current-date)))
4980 (setq rtn (org-agenda-get-todos))
4981 (setq results (append results rtn)))
4982 ((eq arg :timestamp)
4983 (setq rtn (org-agenda-get-blocks))
4984 (setq results (append results rtn))
4985 (setq rtn (org-agenda-get-timestamps))
4986 (setq results (append results rtn)))
4987 ((eq arg :scheduled)
4988 (setq rtn (org-agenda-get-scheduled))
4989 (setq results (append results rtn)))
4990 ((and (eq arg :deadline)
4991 (equal date (calendar-current-date)))
4992 (setq rtn (org-agenda-get-deadlines))
4993 (setq results (append results rtn))))))))
4996 (defun org-entry-is-done-p ()
4997 "Is the current entry marked DONE?"
4999 (and (re-search-backward "[\r\n]\\*" nil t)
5000 (looking-at org-nl-done-regexp))))
5002 (defun org-at-date-range-p ()
5003 "Is the cursor inside a date range?"
5007 (let ((pos (point)))
5008 (skip-chars-backward "^<\r\n")
5009 (skip-chars-backward "<")
5010 (and (looking-at org-tr-regexp)
5011 (>= (match-end 0) pos)
5013 (skip-chars-backward "^<\r\n")
5014 (skip-chars-backward "<")
5015 (and (looking-at org-tr-regexp)
5016 (>= (match-end 0) pos)
5020 (defun org-agenda-get-todos ()
5021 "Return the TODO information for agenda display."
5022 (let* ((props (list 'face nil
5023 'done-face 'org-done
5024 'mouse-face 'highlight
5025 'keymap org-agenda-keymap
5027 (format "mouse-2 or RET jump to org file %s"
5028 (abbreviate-file-name (buffer-file-name)))))
5029 (regexp (concat "[\n\r]\\*+ *\\("
5030 (if org-select-this-todo-keyword
5031 (concat "\\<\\(" org-select-this-todo-keyword
5033 org-not-done-regexp)
5035 marker priority category
5037 (goto-char (point-min))
5038 (while (re-search-forward regexp nil t)
5039 (goto-char (match-beginning 1))
5040 (setq marker (org-agenda-new-marker (point-at-bol))
5041 category (org-get-category)
5042 txt (org-format-agenda-item "" (match-string 1) category)
5044 (+ (org-get-priority txt)
5045 (if org-todo-kwd-priority-p
5046 (- org-todo-kwd-max-priority -2
5048 (member (match-string 2) org-todo-keywords)))
5050 (add-text-properties
5051 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5052 'priority priority 'category category)
5056 (goto-char (match-end 1)))
5059 (defconst org-agenda-no-heading-message
5060 "No heading for this item in buffer or region")
5062 (defun org-agenda-get-timestamps ()
5063 "Return the date stamp information for agenda display."
5064 (let* ((props (list 'face nil
5065 'mouse-face 'highlight
5066 'keymap org-agenda-keymap
5068 (format "mouse-2 or RET jump to org file %s"
5069 (abbreviate-file-name (buffer-file-name)))))
5070 (regexp (regexp-quote
5073 (car org-time-stamp-formats)
5074 (apply 'encode-time ; DATE bound by calendar
5075 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5077 marker hdmarker deadlinep scheduledp donep tmp priority category
5079 (goto-char (point-min))
5080 (while (re-search-forward regexp nil t)
5081 (if (not (save-match-data (org-at-date-range-p)))
5083 (setq marker (org-agenda-new-marker (match-beginning 0))
5084 category (org-get-category (match-beginning 0))
5085 tmp (buffer-substring (max (point-min)
5086 (- (match-beginning 0)
5087 org-ds-keyword-length))
5088 (match-beginning 0))
5089 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5090 deadlinep (string-match org-deadline-regexp tmp)
5091 scheduledp (string-match org-scheduled-regexp tmp)
5092 donep (org-entry-is-done-p))
5093 (if (string-match ">" timestr)
5094 ;; substring should only run to end of time stamp
5095 (setq timestr (substring timestr 0 (match-end 0))))
5097 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5099 (goto-char (match-end 1))
5100 (setq hdmarker (org-agenda-new-marker))
5101 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5102 (setq txt (org-format-agenda-item
5104 (if deadlinep "Deadline: " "")
5105 (if scheduledp "Scheduled: " ""))
5106 (match-string 1) category timestr)))
5107 (setq txt org-agenda-no-heading-message))
5108 (setq priority (org-get-priority txt))
5109 (add-text-properties
5110 0 (length txt) (append (list 'org-marker marker
5111 'org-hd-marker hdmarker) props)
5114 (add-text-properties
5117 (if donep 'org-done 'org-warning)
5118 'undone-face 'org-warning
5119 'done-face 'org-done
5120 'priority (+ 100 priority))
5123 (add-text-properties
5125 (list 'face 'org-scheduled-today
5126 'undone-face 'org-scheduled-today
5127 'done-face 'org-done
5128 priority (+ 99 priority))
5130 (add-text-properties
5132 (list 'priority priority 'category category) txt)))
5134 (outline-next-heading))))
5137 (defun org-agenda-get-deadlines ()
5138 "Return the deadline information for agenda display."
5139 (let* ((wdays org-deadline-warning-days)
5140 (props (list 'mouse-face 'highlight
5141 'keymap org-agenda-keymap
5143 (format "mouse-2 or RET jump to org file %s"
5144 (abbreviate-file-name (buffer-file-name)))))
5145 (regexp org-deadline-time-regexp)
5146 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5147 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5148 d2 diff pos pos1 category
5150 (goto-char (point-min))
5151 (while (re-search-forward regexp nil t)
5152 (setq pos (1- (match-beginning 1))
5154 (org-time-string-to-time (match-string 1)))
5156 ;; When to show a deadline in the calendar:
5157 ;; If the expiration is within wdays warning time.
5158 ;; Past-due deadlines are only shown on the current date
5159 (if (and (< diff wdays) todayp (not (= diff 0)))
5161 (setq category (org-get-category))
5162 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5164 (goto-char (match-end 0))
5165 (setq pos1 (match-end 1))
5166 (setq head (buffer-substring-no-properties
5168 (progn (skip-chars-forward "^\r\n")
5170 (if (string-match org-looking-at-done-regexp head)
5172 (setq txt (org-format-agenda-item
5173 (format "In %3d d.: " diff) head category))))
5174 (setq txt org-agenda-no-heading-message))
5176 (add-text-properties
5179 (list 'org-marker (org-agenda-new-marker pos)
5180 'org-hd-marker (org-agenda-new-marker pos1)
5181 'priority (+ (- 10 diff) (org-get-priority txt))
5183 'face (cond ((<= diff 0) 'org-warning)
5184 ((<= diff 5) 'org-scheduled-previously)
5187 ((<= diff 0) 'org-warning)
5188 ((<= diff 5) 'org-scheduled-previously)
5190 'done-face 'org-done)
5196 (defun org-agenda-get-scheduled ()
5197 "Return the scheduled information for agenda display."
5198 (let* ((props (list 'face 'org-scheduled-previously
5199 'undone-face 'org-scheduled-previously
5200 'done-face 'org-done
5201 'mouse-face 'highlight
5202 'keymap org-agenda-keymap
5204 (format "mouse-2 or RET jump to org file %s"
5205 (abbreviate-file-name (buffer-file-name)))))
5206 (regexp org-scheduled-time-regexp)
5207 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5208 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5209 d2 diff pos pos1 category
5211 (goto-char (point-min))
5212 (while (re-search-forward regexp nil t)
5213 (setq pos (1- (match-beginning 1))
5215 (org-time-string-to-time (match-string 1)))
5217 ;; When to show a scheduled item in the calendar:
5218 ;; If it is on or past the date.
5219 (if (and (< diff 0) todayp)
5221 (setq category (org-get-category))
5222 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5224 (goto-char (match-end 0))
5225 (setq pos1 (match-end 1))
5226 (setq head (buffer-substring-no-properties
5228 (progn (skip-chars-forward "^\r\n") (point))))
5229 (if (string-match org-looking-at-done-regexp head)
5231 (setq txt (org-format-agenda-item
5232 (format "Sched.%2dx: " (- 1 diff)) head
5234 (setq txt org-agenda-no-heading-message))
5236 (add-text-properties
5238 (append (list 'org-marker (org-agenda-new-marker pos)
5239 'org-hd-marker (org-agenda-new-marker pos1)
5240 'priority (+ (- 5 diff) (org-get-priority txt))
5246 (defun org-agenda-get-blocks ()
5247 "Return the date-range information for agenda display."
5248 (let* ((props (list 'face nil
5249 'mouse-face 'highlight
5250 'keymap org-agenda-keymap
5252 (format "mouse-2 or RET jump to org file %s"
5253 (abbreviate-file-name (buffer-file-name)))))
5254 (regexp org-tr-regexp)
5255 (d0 (calendar-absolute-from-gregorian date))
5256 marker hdmarker ee txt d1 d2 s1 s2 timestr category)
5257 (goto-char (point-min))
5258 (while (re-search-forward regexp nil t)
5259 (setq timestr (match-string 0)
5262 d1 (time-to-days (org-time-string-to-time s1))
5263 d2 (time-to-days (org-time-string-to-time s2)))
5264 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5265 ;; Only allow days between the limits, because the normal
5266 ;; date stamps will catch the limits.
5268 (setq marker (org-agenda-new-marker (point)))
5269 (setq category (org-get-category))
5270 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5272 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5273 (goto-char (match-end 1))
5274 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5275 (setq txt (org-format-agenda-item
5276 (format (if (= d1 d2) "" "(%d/%d): ")
5277 (1+ (- d0 d1)) (1+ (- d2 d1)))
5278 (match-string 1) category
5279 (if (= d0 d1) timestr))))
5280 (setq txt org-agenda-no-heading-message))
5281 (add-text-properties
5282 0 (length txt) (append (list 'org-marker marker
5283 'org-hd-marker hdmarker
5284 'priority (org-get-priority txt)
5289 (outline-next-heading))
5290 ;; Sort the entries by expiration date.
5293 (defconst org-plain-time-of-day-regexp
5296 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5299 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5301 "Regular expression to match a plain time or time range.
5302 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5303 groups carry important information:
5305 1 the first time, range or not
5306 8 the second time, if it is a range.")
5308 (defconst org-stamp-time-of-day-regexp
5310 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5311 "\\([012][0-9]:[0-5][0-9]\\)>"
5313 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5314 "Regular expression to match a timestamp time or time range.
5315 After a match, the following groups carry important information:
5317 1 date plus weekday, for backreferencing to make sure both times on same day
5318 2 the first time, range or not
5319 4 the second time, if it is a range.")
5321 (defvar org-prefix-has-time nil
5322 "A flag, set by `org-compile-prefix-format'.
5323 The flag is set if the currently compiled format contains a `%t'.")
5325 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
5326 "Format TXT to be inserted into the agenda buffer.
5327 In particular, it adds the prefix and corresponding text properties. EXTRA
5328 must be a string and replaces the `%s' specifier in the prefix format.
5329 CATEGORY (string, symbol or nil) may be used to overule the default
5330 category taken from local variable or file name. It will replace the `%c'
5331 specifier in the format. DOTIME, when non-nil, indicates that a
5332 time-of-day should be extracted from TXT for sorting of this entry, and for
5333 the `%t' specifier in the format. When DOTIME is a string, this string is
5334 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5335 only the correctly processes TXT should be returned - this is used by
5336 `org-agenda-change-all-lines'."
5338 ;; Diary entries sometimes have extra whitespace at the beginning
5339 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5340 (let* ((category (or category
5342 (if (buffer-file-name)
5343 (file-name-sans-extension
5344 (file-name-nondirectory (buffer-file-name)))
5346 time ;; needed for the eval of the prefix format
5347 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5348 (time-of-day (and dotime (org-get-time-of-day ts)))
5349 stamp plain s0 s1 s2 rtn)
5350 (when (and dotime time-of-day org-prefix-has-time)
5351 ;; Extract starting and ending time and move them to prefix
5352 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5353 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5354 (setq s0 (match-string 0 ts)
5355 s1 (match-string (if plain 1 2) ts)
5356 s2 (match-string (if plain 8 4) ts))
5358 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5359 ;; them, we might want to remove them there to avoid duplication.
5360 ;; The user can turn this off with a variable.
5361 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5362 (string-match (concat (regexp-quote s0) " *") txt)
5363 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5364 (= (match-beginning 0) 0)
5366 (setq txt (replace-match "" nil nil txt))))
5367 ;; Normalize the time(s) to 24 hour
5368 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5369 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5371 ;; Create the final string
5374 ;; Prepare the variables needed in the eval of the compiled format
5375 (setq time (cond (s2 (concat s1 "-" s2))
5376 (s1 (concat s1 "......"))
5379 category (if (symbolp category) (symbol-name category) category))
5380 ;; Evaluate the compiled format
5381 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5383 ;; And finally add the text properties
5384 (add-text-properties
5385 0 (length rtn) (list 'category (downcase category)
5386 'prefix-length (- (length rtn) (length txt))
5387 'time-of-day time-of-day
5392 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5394 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5395 ((and todayp (member 'today (car org-agenda-time-grid))))
5396 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5397 ((member 'weekly (car org-agenda-time-grid)))
5398 (t (throw 'exit list)))
5399 (let* ((have (delq nil (mapcar
5400 (lambda (x) (get-text-property 1 'time-of-day x))
5402 (string (nth 1 org-agenda-time-grid))
5403 (gridtimes (nth 2 org-agenda-time-grid))
5404 (req (car org-agenda-time-grid))
5405 (remove (member 'remove-match req))
5407 (if (and (member 'require-timed req) (not have))
5408 ;; don't show empty grid
5410 (while (setq time (pop gridtimes))
5411 (unless (and remove (member time have))
5412 (setq time (int-to-string time))
5413 (push (org-format-agenda-item
5414 nil string "" ;; FIXME: put a category?
5415 (concat (substring time 0 -2) ":" (substring time -2)))
5418 1 (length (car new)) 'face 'org-time-grid (car new))))
5419 (if (member 'time-up org-agenda-sorting-strategy)
5421 (append list new)))))
5423 (defun org-compile-prefix-format (format)
5424 "Compile the prefix format into a Lisp form that can be evaluated.
5425 The resulting form is returned and stored in the variable
5426 `org-prefix-format-compiled'."
5427 (setq org-prefix-has-time nil)
5428 (let ((start 0) varform vars var (s format) c f opt)
5429 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5431 (setq var (cdr (assoc (match-string 4 s)
5432 '(("c" . category) ("t" . time) ("s" . extra))))
5433 c (or (match-string 3 s) "")
5434 opt (match-beginning 1)
5435 start (1+ (match-beginning 0)))
5436 (if (equal var 'time) (setq org-prefix-has-time t))
5437 (setq f (concat "%" (match-string 2 s) "s"))
5440 `(if (equal "" ,var)
5442 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5443 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5444 (setq s (replace-match "%s" t nil s))
5445 (push varform vars))
5446 (setq vars (nreverse vars))
5447 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5449 (defun org-get-time-of-day (s &optional string)
5450 "Check string S for a time of day.
5451 If found, return it as a military time number between 0 and 2400.
5452 If not found, return nil.
5453 The optional STRING argument forces conversion into a 5 character wide string
5459 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5461 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5462 (let* ((t0 (+ (* 100
5463 (+ (string-to-number (match-string 1 s))
5464 (if (and (match-beginning 4)
5465 (equal (downcase (match-string 4 s)) "pm"))
5467 (if (match-beginning 3)
5468 (string-to-number (match-string 3 s))
5470 (t1 (concat " " (int-to-string t0))))
5471 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5473 (defun org-finalize-agenda-entries (list)
5474 "Sort and concatenate the agenda items."
5475 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5477 (defsubst org-cmp-priority (a b)
5478 "Compare the priorities of string a and b."
5479 (let ((pa (or (get-text-property 1 'priority a) 0))
5480 (pb (or (get-text-property 1 'priority b) 0)))
5481 (cond ((> pa pb) +1)
5485 (defsubst org-cmp-category (a b)
5486 "Compare the string values of categories of strings a and b."
5487 (let ((ca (or (get-text-property 1 'category a) ""))
5488 (cb (or (get-text-property 1 'category b) "")))
5489 (cond ((string-lessp ca cb) -1)
5490 ((string-lessp cb ca) +1)
5493 (defsubst org-cmp-time (a b)
5494 "Compare the time-of-day values of strings a and b."
5495 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5496 (ta (or (get-text-property 1 'time-of-day a) def))
5497 (tb (or (get-text-property 1 'time-of-day b) def)))
5498 (cond ((< ta tb) -1)
5502 (defun org-entries-lessp (a b)
5503 "Predicate for sorting agenda entries."
5504 ;; The following variables will be used when the form is evaluated.
5505 (let* ((time-up (org-cmp-time a b))
5506 (time-down (if time-up (- time-up) nil))
5507 (priority-up (org-cmp-priority a b))
5508 (priority-down (if priority-up (- priority-up) nil))
5509 (category-up (org-cmp-category a b))
5510 (category-down (if category-up (- category-up) nil))
5511 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
5513 (eval (cons 'or org-agenda-sorting-strategy))
5514 '((-1 . t) (1 . nil) (nil . nil))))))
5516 (defun org-agenda-show-priority ()
5517 "Show the priority of the current item.
5518 This priority is composed of the main priority given with the [#A] cookies,
5519 and by additional input from the age of a schedules or deadline entry."
5521 (let* ((pri (get-text-property (point-at-bol) 'priority)))
5522 (message "Priority is %d" (if pri pri -1000))))
5524 (defun org-agenda-goto (&optional highlight)
5525 "Go to the Org-mode file which contains the item at point."
5527 (let* ((marker (or (get-text-property (point) 'org-marker)
5528 (org-agenda-error)))
5529 (buffer (marker-buffer marker))
5530 (pos (marker-position marker)))
5531 (switch-to-buffer-other-window buffer)
5534 (when (eq major-mode 'org-mode)
5535 (org-show-hidden-entry)
5537 (and (outline-next-heading)
5538 (org-flag-heading nil)))) ; show the next heading
5539 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
5541 (defun org-agenda-switch-to ()
5542 "Go to the Org-mode file which contains the item at point."
5544 (let* ((marker (or (get-text-property (point) 'org-marker)
5545 (org-agenda-error)))
5546 (buffer (marker-buffer marker))
5547 (pos (marker-position marker)))
5548 (switch-to-buffer buffer)
5549 (delete-other-windows)
5552 (when (eq major-mode 'org-mode)
5553 (org-show-hidden-entry)
5555 (and (outline-next-heading)
5556 (org-flag-heading nil)))))) ; show the next heading
5558 (defun org-agenda-goto-mouse (ev)
5559 "Go to the Org-mode file which contains the item at the mouse click."
5561 (mouse-set-point ev)
5564 (defun org-agenda-show ()
5565 "Display the Org-mode file which contains the item at point."
5567 (let ((win (selected-window)))
5569 (select-window win)))
5571 (defun org-agenda-recenter (arg)
5572 "Display the Org-mode file which contains the item at point and recenter."
5574 (let ((win (selected-window)))
5577 (select-window win)))
5579 (defun org-agenda-show-mouse (ev)
5580 "Display the Org-mode file which contains the item at the mouse click."
5582 (mouse-set-point ev)
5585 (defun org-agenda-check-no-diary ()
5586 "Check if the entry is a diary link and abort if yes."
5587 (if (get-text-property (point) 'org-agenda-diary-link)
5588 (org-agenda-error)))
5590 (defun org-agenda-error ()
5591 (error "Command not allowed in this line"))
5593 (defvar org-last-heading-marker (make-marker)
5594 "Marker pointing to the headline that last changed its TODO state
5595 by a remote command from the agenda.")
5597 (defun org-agenda-todo (&optional arg)
5598 "Cycle TODO state of line at point, also in Org-mode file.
5599 This changes the line at point, all other lines in the agenda referring to
5600 the same tree node, and the headline of the tree node in the Org-mode file."
5602 (org-agenda-check-no-diary)
5603 (let* ((col (current-column))
5604 (marker (or (get-text-property (point) 'org-marker)
5605 (org-agenda-error)))
5606 (buffer (marker-buffer marker))
5607 (pos (marker-position marker))
5608 (hdmarker (get-text-property (point) 'org-hd-marker))
5609 (buffer-read-only nil)
5611 (with-current-buffer buffer
5614 (org-show-hidden-entry)
5616 (and (outline-next-heading)
5617 (org-flag-heading nil))) ; show the next heading
5620 (setq newhead (org-get-heading))
5622 (org-back-to-heading)
5623 (move-marker org-last-heading-marker (point))))
5624 (beginning-of-line 1)
5626 (org-agenda-change-all-lines newhead hdmarker 'fixface))
5627 (move-to-column col)))
5629 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
5630 "Change all lines in the agenda buffer which match hdmarker.
5631 The new content of the line will be NEWHEAD (as modified by
5632 `org-format-agenda-item'). HDMARKER is checked with
5633 `equal' against all `org-hd-marker' text properties in the file.
5634 If FIXFACE is non-nil, the face of each item is modified acording to
5635 the new TODO state."
5636 (let* (props m pl undone-face done-face finish new dotime cat)
5637 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
5639 (goto-char (point-max))
5640 (beginning-of-line 1)
5642 (setq finish (bobp))
5643 (when (and (setq m (get-text-property (point) 'org-hd-marker))
5645 (setq props (text-properties-at (point))
5646 dotime (get-text-property (point) 'dotime)
5647 cat (get-text-property (point) 'category)
5648 new (org-format-agenda-item "x" newhead cat dotime 'noprefix)
5649 pl (get-text-property (point) 'prefix-length)
5650 undone-face (get-text-property (point) 'undone-face)
5651 done-face (get-text-property (point) 'done-face))
5653 (if (looking-at ".*")
5655 (replace-match new t t)
5656 (beginning-of-line 1)
5657 (add-text-properties (point-at-bol) (point-at-eol) props)
5659 (add-text-properties
5660 (point-at-bol) (point-at-eol)
5662 (if org-last-todo-state-is-todo
5663 undone-face done-face))))
5664 (beginning-of-line 1))
5665 (error "Line update did not work")))
5666 (beginning-of-line 0)))))
5668 (defun org-agenda-priority-up ()
5669 "Increase the priority of line at point, also in Org-mode file."
5671 (org-agenda-priority 'up))
5673 (defun org-agenda-priority-down ()
5674 "Decrease the priority of line at point, also in Org-mode file."
5676 (org-agenda-priority 'down))
5678 (defun org-agenda-priority (&optional force-direction)
5679 "Set the priority of line at point, also in Org-mode file.
5680 This changes the line at point, all other lines in the agenda referring to
5681 the same tree node, and the headline of the tree node in the Org-mode file."
5683 (org-agenda-check-no-diary)
5684 (let* ((marker (or (get-text-property (point) 'org-marker)
5685 (org-agenda-error)))
5686 (buffer (marker-buffer marker))
5687 (pos (marker-position marker))
5688 (hdmarker (get-text-property (point) 'org-hd-marker))
5689 (buffer-read-only nil)
5691 (with-current-buffer buffer
5694 (org-show-hidden-entry)
5696 (and (outline-next-heading)
5697 (org-flag-heading nil))) ; show the next heading
5698 (funcall 'org-priority force-direction)
5700 (setq newhead (org-get-heading)))
5701 (org-agenda-change-all-lines newhead hdmarker)
5702 (beginning-of-line 1)))
5704 (defun org-agenda-date-later (arg &optional what)
5705 "Change the date of this item to one day later."
5707 (org-agenda-check-no-diary)
5708 (let* ((marker (or (get-text-property (point) 'org-marker)
5709 (org-agenda-error)))
5710 (buffer (marker-buffer marker))
5711 (pos (marker-position marker)))
5712 (with-current-buffer buffer
5715 (if (not (org-at-timestamp-p))
5716 (error "Cannot find time stamp"))
5717 (org-timestamp-change arg (or what 'day))
5718 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5720 (defun org-agenda-date-earlier (arg &optional what)
5721 "Change the date of this item to one day earlier."
5723 (org-agenda-date-later (- arg) what))
5725 (defun org-agenda-date-prompt (arg)
5726 "Change the date of this item. Date is prompted for, with default today.
5727 The prefix ARG is passed to the `org-time-stamp' command and can therefore
5728 be used to request time specification in the time stamp."
5730 (org-agenda-check-no-diary)
5731 (let* ((marker (or (get-text-property (point) 'org-marker)
5732 (org-agenda-error)))
5733 (buffer (marker-buffer marker))
5734 (pos (marker-position marker)))
5735 (with-current-buffer buffer
5738 (if (not (org-at-timestamp-p))
5739 (error "Cannot find time stamp"))
5740 (org-time-stamp arg)
5741 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5743 (defun org-get-heading ()
5744 "Return the heading of the current entry, without the stars."
5746 (and (bolp) (end-of-line 1))
5747 (if (and (re-search-backward "[\r\n]\\*" nil t)
5748 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5752 (defun org-agenda-diary-entry ()
5753 "Make a diary entry, like the `i' command from the calendar.
5754 All the standard commands work: block, weekly etc"
5756 (require 'diary-lib)
5758 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5759 (read-char-exclusive)))
5760 (cmd (cdr (assoc char
5761 '((?d . insert-diary-entry)
5762 (?w . insert-weekly-diary-entry)
5763 (?m . insert-monthly-diary-entry)
5764 (?y . insert-yearly-diary-entry)
5765 (?a . insert-anniversary-diary-entry)
5766 (?b . insert-block-diary-entry)
5767 (?c . insert-cyclic-diary-entry)))))
5768 (oldf (symbol-function 'calendar-cursor-to-date))
5770 (mark (or (mark t) (point))))
5772 (error "No command associated with <%c>" char))
5773 (unless (and (get-text-property point 'day)
5774 (or (not (equal ?b char))
5775 (get-text-property mark 'day)))
5776 (error "Don't know which date to use for diary entry"))
5777 ;; We implement this by hacking the `calendar-cursor-to-date' function
5778 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5779 (let ((calendar-mark-ring
5780 (list (calendar-gregorian-from-absolute
5781 (or (get-text-property mark 'day)
5782 (get-text-property point 'day))))))
5785 (fset 'calendar-cursor-to-date
5786 (lambda (&optional error)
5787 (calendar-gregorian-from-absolute
5788 (get-text-property point 'day))))
5789 (call-interactively cmd))
5790 (fset 'calendar-cursor-to-date oldf)))))
5793 (defun org-agenda-execute-calendar-command (cmd)
5794 "Execute a calendar command from the agenda, with the date associated to
5795 the cursor position."
5796 (require 'diary-lib)
5797 (unless (get-text-property (point) 'day)
5798 (error "Don't know which date to use for calendar command"))
5799 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5801 (date (calendar-gregorian-from-absolute
5802 (get-text-property point 'day)))
5803 (displayed-day (extract-calendar-day date))
5804 (displayed-month (extract-calendar-month date))
5805 (displayed-year (extract-calendar-year date)))
5808 (fset 'calendar-cursor-to-date
5809 (lambda (&optional error)
5810 (calendar-gregorian-from-absolute
5811 (get-text-property point 'day))))
5812 (call-interactively cmd))
5813 (fset 'calendar-cursor-to-date oldf))))
5815 (defun org-agenda-phases-of-moon ()
5816 "Display the phases of the moon for the 3 months around the cursor date."
5818 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5820 (defun org-agenda-holidays ()
5821 "Display the holidays for the 3 months around the cursor date."
5823 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5825 (defun org-agenda-sunrise-sunset (arg)
5826 "Display sunrise and sunset for the cursor date.
5827 Latitude and longitude can be specified with the variables
5828 `calendar-latitude' and `calendar-longitude'. When called with prefix
5829 argument, latitude and longitude will be prompted for."
5831 (let ((calendar-longitude (if arg nil calendar-longitude))
5832 (calendar-latitude (if arg nil calendar-latitude))
5833 (calendar-location-name
5834 (if arg "the given coordinates" calendar-location-name)))
5835 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5837 (defun org-agenda-goto-calendar ()
5838 "Open the Emacs calendar with the date at the cursor."
5840 (let* ((day (or (get-text-property (point) 'day)
5841 (error "Don't know which date to open in calendar")))
5842 (date (calendar-gregorian-from-absolute day))
5843 (calendar-move-hook nil)
5844 (view-diary-entries-initially nil))
5846 (calendar-goto-date date)))
5848 (defun org-calendar-goto-agenda ()
5849 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5850 This is a command that has to be installed in `calendar-mode-map'."
5852 (org-agenda nil (calendar-absolute-from-gregorian
5853 (calendar-cursor-to-date))))
5855 (defun org-agenda-convert-date ()
5857 (let ((day (get-text-property (point) 'day))
5860 (error "Don't know which date to convert"))
5861 (setq date (calendar-gregorian-from-absolute day))
5863 "Gregorian: " (calendar-date-string date) "\n"
5864 "ISO: " (calendar-iso-date-string date) "\n"
5865 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5866 "Julian: " (calendar-julian-date-string date) "\n"
5867 "Astron. JD: " (calendar-astro-date-string date)
5868 " (Julian date number at noon UTC)\n"
5869 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5870 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5871 "French: " (calendar-french-date-string date) "\n"
5872 "Mayan: " (calendar-mayan-date-string date) "\n"
5873 "Coptic: " (calendar-coptic-date-string date) "\n"
5874 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5875 "Persian: " (calendar-persian-date-string date) "\n"
5876 "Chinese: " (calendar-chinese-date-string date) "\n"))
5877 (with-output-to-temp-buffer "*Dates*"
5879 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5883 (defun org-find-file-at-mouse (ev)
5884 "Open file link or URL at mouse."
5886 (mouse-set-point ev)
5887 (org-open-at-point 'in-emacs))
5889 (defun org-open-at-mouse (ev)
5890 "Open file link or URL at mouse."
5892 (mouse-set-point ev)
5893 (org-open-at-point))
5895 (defun org-open-at-point (&optional in-emacs)
5896 "Open link at or after point.
5897 If there is no link at point, this function will search forward up to
5898 the end of the current subtree.
5899 Normally, files will be opened by an appropriate application. If the
5900 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5902 (org-remove-occur-highlights nil nil t)
5903 (if (org-at-timestamp-p)
5904 (org-agenda nil (time-to-days (org-time-string-to-time
5905 (substring (match-string 1) 0 10)))
5907 (let (type path line search (pos (point)))
5910 (skip-chars-backward
5911 (concat (if org-allow-space-in-links "^" "^ ")
5912 org-non-link-chars))
5913 (when (looking-at org-link-regexp)
5914 (setq type (match-string 1)
5915 path (match-string 2))
5918 (skip-chars-backward "a-zA-Z_")
5919 (when (looking-at org-camel-regexp)
5920 (setq type "camel" path (match-string 0))
5921 (if (equal (char-before) ?*)
5922 (setq path (concat "*" path))))
5925 (when (re-search-forward
5929 (progn (outline-end-of-subtree) (max pos (point)))
5930 (error (end-of-line 1) (point))))
5932 (setq type (match-string 1)
5933 path (match-string 2)))))
5935 (error "No link found"))
5936 ;; Remove any trailing spaces in path
5937 (if (string-match " +\\'" path)
5938 (setq path (replace-match "" t t path)))
5942 ((string= type "camel")
5945 (cond ((equal in-emacs '(4)) 'occur)
5946 ((equal in-emacs '(16)) 'org-occur)
5949 ((string= type "file")
5950 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
5951 (setq line (string-to-number (match-string 1 path))
5952 path (substring path 0 (match-beginning 0)))
5953 (if (string-match "::\\(.+\\)\\'" path)
5954 (setq search (match-string 1 path)
5955 path (substring path 0 (match-beginning 0)))))
5956 (org-open-file path in-emacs line search))
5958 ((string= type "news")
5959 (org-follow-gnus-link path))
5961 ((string= type "bbdb")
5962 (org-follow-bbdb-link path))
5964 ((string= type "gnus")
5965 (let (group article)
5966 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5967 (error "Error in Gnus link"))
5968 (setq group (match-string 1 path)
5969 article (match-string 3 path))
5970 (org-follow-gnus-link group article)))
5972 ((string= type "vm")
5973 (let (folder article)
5974 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5975 (error "Error in VM link"))
5976 (setq folder (match-string 1 path)
5977 article (match-string 3 path))
5978 ;; in-emacs is the prefix arg, will be interpreted as read-only
5979 (org-follow-vm-link folder article in-emacs)))
5981 ((string= type "wl")
5982 (let (folder article)
5983 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5984 (error "Error in Wanderlust link"))
5985 (setq folder (match-string 1 path)
5986 article (match-string 3 path))
5987 (org-follow-wl-link folder article)))
5989 ((string= type "rmail")
5990 (let (folder article)
5991 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5992 (error "Error in RMAIL link"))
5993 (setq folder (match-string 1 path)
5994 article (match-string 3 path))
5995 (org-follow-rmail-link folder article)))
5997 ((string= type "shell")
5999 (while (string-match "@{" cmd)
6000 (setq cmd (replace-match "<" t t cmd)))
6001 (while (string-match "@}" cmd)
6002 (setq cmd (replace-match ">" t t cmd)))
6003 (if (or (not org-confirm-shell-links)
6004 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6009 (browse-url-at-point))))))
6011 (defun org-link-search (s &optional type)
6012 "Search for a link search option.
6013 When S is a CamelCaseWord, search for a target, or for a sentence containing
6014 the words. If S is surrounded by forward slashes, it is interpreted as a
6015 regular expression. In org-mode files, this will create an `org-occur'
6016 sparse tree. In ordinary files, `occur' will be used to list matched.
6017 If the current buffer is in `dired-mode', grep will be used to search
6019 (let ((case-fold-search t)
6023 words re0 re1 re2 re3 re4 re5 reall)
6024 (cond ((string-match "^/\\(.*\\)/$" s)
6025 ;; A regular expression
6027 ((eq major-mode 'org-mode)
6028 (org-occur (match-string 1 s)))
6029 ;;((eq major-mode 'dired-mode)
6030 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6031 (t (org-do-occur (match-string 1 s)))))
6032 ((string-match (concat "^" org-camel-regexp) s)
6034 (if (equal (string-to-char s) ?*)
6035 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6038 (remove-text-properties
6040 '(face nil mouse-face nil keymap nil fontified nil) s)
6041 ;; Make a series of regular expressions to find a match
6042 (setq words (org-camel-to-words s)
6043 re0 (concat "<<" (regexp-quote s0) ">>")
6044 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6045 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6046 re1 (concat pre re2 post)
6047 re3 (concat pre re4 post)
6048 re5 (concat pre ".*" re4)
6049 re2 (concat pre re2)
6050 re4 (concat pre re4)
6051 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6052 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6056 ((eq type 'org-occur) (org-occur reall))
6057 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6058 (t (goto-char (point-min))
6059 (if (or (re-search-forward re0 nil t)
6060 (re-search-forward re1 nil t)
6061 (re-search-forward re2 nil t)
6062 (re-search-forward re3 nil t)
6063 (re-search-forward re4 nil t)
6064 (re-search-forward re5 nil t))
6065 (goto-char (match-beginning 0))
6067 (error "No match")))))
6069 ;; Normal string-search
6070 (goto-char (point-min))
6071 (if (search-forward s nil t)
6072 (goto-char (match-beginning 0))
6073 (error "No match"))))))
6075 (defun org-do-occur (regexp &optional cleanup)
6076 "Call the Emacs command `occur'.
6077 If CLEANUP is non-nil, remove the printout of the regular expression
6078 in the *Occur* buffer. This is useful if the regex is long and not useful
6082 (let ((cwin (selected-window)) win beg end)
6083 (when (setq win (get-buffer-window "*Occur*"))
6084 (select-window win))
6085 (goto-char (point-min))
6086 (when (re-search-forward "match[a-z]+" nil t)
6087 (setq beg (match-end 0))
6088 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6089 (setq end (1- (match-beginning 0)))))
6090 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
6091 (goto-char (point-min))
6092 (select-window cwin))))
6094 (defun org-camel-to-words (s)
6095 "Split \"CamelCaseWords\" to (\"Camel \" \"Case\" \"Words\")."
6096 (let ((case-fold-search nil)
6098 (while (string-match "[a-z][A-Z]" s)
6099 (push (substring s 0 (1+ (match-beginning 0))) words)
6100 (setq s (substring s (1+ (match-beginning 0)))))
6101 (nreverse (cons s words))))
6103 (defun org-follow-bbdb-link (name)
6104 "Follow a BBDB link to NAME."
6106 (let ((inhibit-redisplay t))
6108 ;; Exact match on name
6109 (bbdb-name (concat "\\`" name "\\'") nil)
6110 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6111 ;; Exact match on name
6112 (bbdb-company (concat "\\`" name "\\'") nil)
6113 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6114 ;; Partial match on name
6115 (bbdb-name name nil)
6116 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6117 ;; Partial match on company
6118 (bbdb-company name nil)
6119 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6120 ;; General match including network address and notes
6122 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
6123 (delete-window (get-buffer-window "*BBDB*"))
6124 (error "No matching BBDB record")))))
6126 (defun org-follow-gnus-link (&optional group article)
6127 "Follow a Gnus link to GROUP and ARTICLE."
6129 (funcall (cdr (assq 'gnus org-link-frame-setup)))
6130 (if group (gnus-fetch-group group))
6132 (or (gnus-summary-goto-article article nil 'force)
6133 (if (fboundp 'gnus-summary-insert-cached-articles)
6135 (gnus-summary-insert-cached-articles)
6136 (gnus-summary-goto-article article nil 'force))
6137 (message "Message could not be found.")))))
6139 (defun org-follow-vm-link (&optional folder article readonly)
6140 "Follow a VM link to FOLDER and ARTICLE."
6142 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
6143 ;; ange-ftp or efs or tramp access
6144 (let ((user (or (match-string 1 folder) (user-login-name)))
6145 (host (match-string 2 folder))
6146 (file (match-string 3 folder)))
6149 ;; use tramp to access the file
6151 (setq folder (format "[%s@%s]%s" user host file))
6152 (setq folder (format "/%s@%s:%s" user host file))))
6154 ;; use ange-ftp or efs
6155 (require (if org-xemacs-p 'efs 'ange-ftp))
6156 (setq folder (format "/%s@%s:%s" user host file))))))
6158 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
6161 (vm-select-folder-buffer)
6163 (let ((case-fold-search t))
6164 (goto-char (point-min))
6165 (if (not (re-search-forward
6166 (concat "^" "message-id: *" (regexp-quote article))))
6167 (error "Could not find the specified message in this folder"))
6170 (vm-beginning-of-message)
6173 (defun org-follow-wl-link (folder article)
6174 "Follow a Wanderlust link to FOLDER and ARTICLE."
6175 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
6176 (if article (wl-summary-jump-to-msg-by-message-id article))
6177 (wl-summary-redisplay))
6179 (defun org-follow-rmail-link (folder article)
6180 "Follow an RMAIL link to FOLDER and ARTICLE."
6181 (let (message-number)
6183 (save-window-excursion
6184 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6185 (setq message-number
6188 (goto-char (point-max))
6189 (if (re-search-backward
6190 (concat "^Message-ID:\\s-+" (regexp-quote
6193 (rmail-what-message))))))
6196 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6197 (rmail-show-message message-number)
6199 (error "Message not found"))))
6201 (defun org-open-file (path &optional in-emacs line search)
6202 "Open the file at PATH.
6203 First, this expands any special file name abbreviations. Then the
6204 configuration variable `org-file-apps' is checked if it contains an
6205 entry for this file type, and if yes, the corresponding command is launched.
6206 If no application is found, Emacs simply visits the file.
6207 With optional argument IN-EMACS, Emacs will visit the file.
6208 Optional LINE specifies a line to go to, optional SEARCH a string to
6209 search for. If LINE or SEARCH is given, the file will always be
6211 If the file does not exist, an error is thrown."
6212 (setq in-emacs (or in-emacs line search))
6213 (let* ((file (if (equal path "")
6215 (convert-standard-filename (org-expand-file-name path))))
6216 (dfile (downcase file))
6218 (if (and (not (file-exists-p file))
6219 (not org-open-non-existing-files))
6220 (error "No such file: %s" file))
6221 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
6222 (setq ext (match-string 1 dfile))
6223 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
6224 (setq ext (match-string 1 dfile))))
6225 (setq apps (append org-file-apps (org-default-apps)))
6228 (setq cmd (or (cdr (assoc ext apps))
6229 (cdr (assoc t apps)))))
6231 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
6232 (setq cmd (format cmd (concat "\"" file "\"")))
6233 (save-window-excursion
6234 (shell-command (concat cmd " & &"))))
6237 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
6238 (funcall (cdr (assq 'file org-link-frame-setup)) file))
6239 (if line (goto-line line)
6240 (if search (org-link-search search))))
6243 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
6245 (defun org-default-apps ()
6246 "Return the default applications for this operating system."
6248 ((eq system-type 'darwin)
6249 org-file-apps-defaults-macosx)
6250 ((eq system-type 'windows-nt)
6251 org-file-apps-defaults-windowsnt)
6252 (t org-file-apps-defaults-gnu)))
6254 (defun org-expand-file-name (path)
6255 "Replace special path abbreviations and expand the file name."
6256 (expand-file-name path))
6259 (defvar org-insert-link-history nil
6260 "Minibuffer history for links inserted with `org-insert-link'.")
6262 (defvar org-stored-links nil
6263 "Contains the links stored with `org-store-link'.")
6266 (defun org-store-link (arg)
6267 "\\<org-mode-map>Store an org-link to the current location.
6268 This link can later be inserted into an org-buffer with
6269 \\[org-insert-link].
6270 For some link types, a prefix arg is interpreted:
6271 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6272 For file links, arg negates `org-context-in-file-links'."
6277 ((eq major-mode 'bbdb-mode)
6278 (setq cpltxt (concat
6280 (or (bbdb-record-name (bbdb-current-record))
6281 (bbdb-record-company (bbdb-current-record))))
6282 link (org-make-link cpltxt)))
6284 ((eq major-mode 'calendar-mode)
6285 (let ((cd (calendar-cursor-to-date)))
6288 (car org-time-stamp-formats)
6290 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6293 ((or (eq major-mode 'vm-summary-mode)
6294 (eq major-mode 'vm-presentation-mode))
6295 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
6296 (vm-follow-summary-cursor)
6298 (vm-select-folder-buffer)
6299 (let* ((message (car vm-message-pointer))
6300 (folder (buffer-file-name))
6301 (subject (vm-su-subject message))
6302 (author (vm-su-full-name message))
6303 (message-id (vm-su-message-id message)))
6304 (setq folder (abbreviate-file-name folder))
6305 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
6307 (setq folder (replace-match "" t t folder)))
6308 (setq cpltxt (concat author " on: " subject))
6309 (setq link (concat cpltxt "\n "
6311 "vm:" folder "#" message-id))))))
6313 ((eq major-mode 'wl-summary-mode)
6314 (let* ((msgnum (wl-summary-message-number))
6315 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
6316 msgnum 'message-id))
6317 (wl-message-entity (elmo-msgdb-overview-get-entity
6318 msgnum (wl-summary-buffer-msgdb)))
6319 (author (wl-summary-line-from)) ; FIXME: how to get author name?
6320 (subject "???")) ; FIXME: How to get subject of email?
6321 (setq cpltxt (concat author " on: " subject))
6322 (setq link (concat cpltxt "\n "
6324 "wl:" wl-summary-buffer-folder-name
6327 ((eq major-mode 'rmail-mode)
6330 (rmail-narrow-to-non-pruned-header)
6331 (let ((folder (buffer-file-name))
6332 (message-id (mail-fetch-field "message-id"))
6333 (author (mail-fetch-field "from"))
6334 (subject (mail-fetch-field "subject")))
6335 (setq cpltxt (concat author " on: " subject))
6336 (setq link (concat cpltxt "\n "
6338 "rmail:" folder "#" message-id)))))))
6340 ((eq major-mode 'gnus-group-mode)
6341 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
6342 (gnus-group-group-name)) ; version
6343 ((fboundp 'gnus-group-name)
6346 (setq cpltxt (concat
6347 (if (org-xor arg org-usenet-links-prefer-google)
6348 "http://groups.google.com/groups?group="
6351 link (org-make-link cpltxt))))
6353 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
6354 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
6355 (gnus-summary-beginning-of-article)
6356 (let* ((group (car gnus-article-current))
6357 (article (cdr gnus-article-current))
6358 (header (gnus-summary-article-header article))
6359 (author (mail-header-from header))
6360 (message-id (mail-header-id header))
6361 (date (mail-header-date header))
6362 (subject (gnus-summary-subject-string)))
6363 (setq cpltxt (concat author " on: " subject))
6364 (if (org-xor arg org-usenet-links-prefer-google)
6368 (format "http://groups.google.com/groups?as_umsgid=%s"
6369 (org-fixup-message-id-for-http message-id))))
6370 (setq link (concat cpltxt "\n"
6373 "#" (number-to-string article)))))))
6375 ((eq major-mode 'w3-mode)
6376 (setq cpltxt (url-view-url t)
6377 link (org-make-link cpltxt)))
6378 ((eq major-mode 'w3m-mode)
6379 (setq cpltxt w3m-current-url
6380 link (org-make-link cpltxt)))
6382 ((eq major-mode 'org-mode)
6383 ;; Just link to current headline
6384 (setq cpltxt (concat "file:"
6385 (abbreviate-file-name (buffer-file-name))))
6386 ;; Add a context search string
6387 (when (org-xor org-context-in-file-links arg)
6389 (skip-chars-backward "a-zA-Z<")
6390 (looking-at (concat "<<\\(" org-camel-regexp "\\)>>")))
6391 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6394 (org-make-org-heading-camel
6396 ((org-on-heading-p) nil)
6397 ((org-region-active-p)
6398 (buffer-substring (region-beginning) (region-end)))
6399 (t (buffer-substring (point-at-bol) (point-at-eol))))
6401 (setq link (org-make-link cpltxt)))
6404 ;; Just link to this file here.
6405 (setq cpltxt (concat "file:"
6406 (abbreviate-file-name (buffer-file-name))))
6407 ;; Add a context string
6408 (when (org-xor org-context-in-file-links arg)
6411 (org-make-org-heading-camel
6412 (if (org-region-active-p)
6413 (buffer-substring (region-beginning) (region-end))
6414 (buffer-substring (point-at-bol) (point-at-eol)))))))
6415 (setq link (org-make-link cpltxt)))
6418 (error "Cannot link to a buffer which is not visiting a file"))
6420 (t (setq link nil)))
6422 (if (and (interactive-p) link)
6424 (setq org-stored-links
6425 (cons (cons (or cpltxt link) link) org-stored-links))
6426 (message "Stored: %s" (or cpltxt link)))
6429 (defun org-make-org-heading-camel (&optional string)
6430 "Make a CamelCase string for S or the current headline."
6432 (let ((s (or string (org-get-heading))))
6434 ;; We are using a headline, clean up garbage in there.
6435 (if (string-match org-todo-regexp s)
6436 (setq s (replace-match "" t t s)))
6437 (setq s (org-trim s))
6438 (if (string-match (concat "^\\(" org-quote-string "\\|"
6439 org-comment-string "\\)") s)
6440 (setq s (replace-match "" t t s)))
6441 (while (string-match org-ts-regexp s)
6442 (setq s (replace-match "" t t s))))
6443 (while (string-match "[^a-zA-Z_ \t]+" s)
6444 (setq s (replace-match " " t t s)))
6445 (or string (setq s (concat "*" s))) ; Add * for headlines
6446 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
6448 (defun org-make-link (&rest strings)
6449 "Concatenate STRINGS, format resulting string with `org-link-format'."
6450 (format org-link-format (apply 'concat strings)))
6452 (defun org-xor (a b)
6456 (defun org-get-header (header)
6457 "Find a header field in the current buffer."
6459 (goto-char (point-min))
6460 (let ((case-fold-search t) s)
6463 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6464 (setq s (match-string 1)))
6465 (while (string-match "\"" s)
6466 (setq s (replace-match "" t t s)))
6467 (if (string-match "[<(].*" s)
6468 (setq s (replace-match "" t t s))))
6469 ((eq header 'message-id)
6470 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6471 (setq s (match-string 1))))
6472 ((eq header 'subject)
6473 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6474 (setq s (match-string 1)))))
6475 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6476 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6480 (defun org-fixup-message-id-for-http (s)
6481 "Replace special characters in a message id, so it can be used in an http query."
6482 (while (string-match "<" s)
6483 (setq s (replace-match "%3C" t t s)))
6484 (while (string-match ">" s)
6485 (setq s (replace-match "%3E" t t s)))
6486 (while (string-match "@" s)
6487 (setq s (replace-match "%40" t t s)))
6490 (defun org-insert-link (&optional complete-file)
6491 "Insert a link. At the prompt, enter the link.
6493 Completion can be used to select a link previously stored with
6494 `org-store-link'. When the empty string is entered (i.e. if you just
6495 press RET at the prompt), the link defaults to the most recently
6496 stored link. As SPC triggers completion in the minibuffer, you need to
6497 use M-SPC or C-q SPC to force the insertion of a space character.
6499 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
6500 selected using completion. The path to the file will be relative to
6501 the current directory if the file is in the current directory or a
6502 subdirectory. Otherwise, the link will be the absolute path as
6503 completed in the minibuffer (i.e. normally ~/path/to/file).
6505 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
6506 is in the current directory or below."
6508 (let ((link (if complete-file
6509 (read-file-name "File: ")
6511 "Link: " org-stored-links nil nil nil
6512 org-insert-link-history
6513 (or (car (car org-stored-links))))))
6515 (if (or (not link) (equal link ""))
6516 (error "No links available"))
6518 (let ((pwd (file-name-as-directory (expand-file-name "."))))
6520 ((equal complete-file '(16))
6523 "file:" (abbreviate-file-name (expand-file-name link)))))
6524 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6525 (expand-file-name link))
6528 "file:" (match-string 1 (expand-file-name link)))))
6529 (t (insert (org-make-link "file:" link)))))
6530 (setq linktxt (cdr (assoc link org-stored-links)))
6531 (if (not org-keep-stored-link-after-insertion)
6532 (setq org-stored-links (delq (assoc link org-stored-links)
6534 (if (not linktxt) (setq link (org-make-link link)))
6535 (setq link (or linktxt link))
6536 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
6537 (let* ((path (match-string 1 link))
6538 (case-fold-search nil)
6539 (search (match-string 2 link)))
6540 (when (save-match-data
6541 (equal (file-truename (buffer-file-name))
6542 (file-truename path)))
6543 (if (save-match-data
6544 (string-match (concat "^" org-camel-regexp "$") search))
6545 (setq link (replace-match search t t link)
6547 (setq link (replace-match (concat "<file:::" search ">")
6549 (let ((lines (org-split-string link "\n")))
6550 (insert (car lines))
6551 (setq matched (or matched (string-match org-link-regexp (car lines))))
6552 (setq lines (cdr lines))
6556 (beginning-of-line 0)
6557 (looking-at "[ \t]+\\S-"))
6559 (setq matched (or matched
6560 (string-match org-link-regexp (car lines))))
6561 (insert (car lines))
6562 (setq lines (cdr lines))))
6564 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
6566 ;;; Hooks for remember.el
6568 (defun org-remember-annotation ()
6569 "Return a link to the current location as an annotation for remember.el.
6570 If you are using Org-mode files as target for data storage with
6571 remember.el, then the annotations should include a link compatible with the
6572 conventions in Org-mode. This function returns such a link."
6573 (org-store-link nil))
6575 (defconst org-remember-help
6576 "Select a destination location for the note.
6577 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
6578 RET at beg-of-buf -> Append to file as level 2 headline
6579 RET on headline -> Store as sublevel entry to current headline
6580 <left>/<right> -> before/after current headline, same headings level")
6583 (defun org-remember-handler ()
6584 "Store stuff from remember.el into an org file.
6585 First prompts for an org file. If the user just presses return, the value
6586 of `org-default-notes-file' is used.
6587 Then the command offers the headings tree of the selected file in order to
6588 file the text at a specific location.
6589 You can either immediately press RET to get the note appended to the
6590 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
6591 find a better place. Then press RET or <left> or <right> in insert the note.
6593 Key Cursor position Note gets inserted
6594 -----------------------------------------------------------------------------
6595 RET buffer-start as level 2 heading at end of file
6596 RET on headline as sublevel of the heading at cursor
6597 RET no heading at cursor position, level taken from context.
6598 Or use prefix arg to specify level manually.
6599 <left> on headline as same level, before current heading
6600 <right> on headline as same level, after current heading
6602 So the fastest way to store the note is to press RET RET to append it to
6603 the default file. This way your current train of thought is not
6604 interrupted, in accordance with the principles of remember.el. But with
6605 little extra effort, you can push it directly to the correct location.
6607 Before being stored away, the function ensures that the text has a
6608 headline, i.e. a first line that starts with a \"*\". If not, a headline
6609 is constructed from the current date and some additional data.
6611 If the variable `org-adapt-indentation' is non-nil, the entire text is
6612 also indented so that it starts in the same column as the headline
6613 \(i.e. after the stars).
6615 See also the variable `org-reverse-note-order'."
6617 (let* ((txt (buffer-substring (point-min) (point-max)))
6618 (fastp current-prefix-arg)
6619 (file (if fastp org-default-notes-file (org-get-org-file)))
6620 (visiting (find-buffer-visiting file))
6621 (org-startup-with-deadline-check nil)
6622 (org-startup-folded nil)
6623 spos level indent reversed)
6624 ;; Modify text so that it becomes a nice subtree which can be inserted
6625 ;; into an org tree.
6626 (let* ((lines (split-string txt "\n"))
6628 (lines (cdr lines)))
6629 (if (string-match "^\\*+" first)
6630 ;; Is already a headline
6631 (setq indent (make-string (- (match-end 0) (match-beginning 0)
6633 ;; We need to add a headline: Use time and first buffer line
6634 (setq lines (cons first lines)
6635 first (concat "* " (current-time-string)
6636 " (" (remember-buffer-desc) ")")
6638 (if org-adapt-indentation
6639 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
6640 (setq txt (concat first "\n"
6641 (mapconcat 'identity lines "\n"))))
6644 (find-file-noselect file))
6645 (with-current-buffer (get-file-buffer file)
6646 (setq reversed (org-notes-order-reversed-p))
6650 ;; Ask the User for a location
6651 (setq spos (if fastp 1 (org-get-location
6653 org-remember-help)))
6654 (if (not spos) (throw 'quit nil)) ; return nil to show we did
6655 ; not handle this note
6658 ;; Put it at the start or end, as level 2
6661 (goto-char (if reversed (point-min) (point-max)))
6662 (if (not (bolp)) (newline))
6663 (org-paste-subtree (or current-prefix-arg 2) txt)))
6664 ((and (org-on-heading-p nil) (not current-prefix-arg))
6665 ;; Put it below this entry, at the beg/end of the subtree
6666 (org-back-to-heading)
6667 (setq level (outline-level))
6669 (outline-end-of-heading)
6670 (outline-end-of-subtree))
6671 (if (not (bolp)) (newline))
6672 (beginning-of-line 1)
6673 (org-paste-subtree (1+ level) txt))
6675 ;; Put it right there, with automatic level determined by
6676 ;; org-paste-subtree or from prefix arg
6677 (org-paste-subtree current-prefix-arg txt)))
6678 (when remember-save-after-remembering
6680 (if (not visiting) (kill-buffer (current-buffer)))))))))
6681 t) ;; return t to indicate that we took care of this note.
6683 (defun org-get-org-file ()
6684 "Read a filename, with default directory `org-directory'."
6685 (let ((default (or org-default-notes-file remember-data-file)))
6686 (read-file-name (format "File name [%s]: " default)
6687 (file-name-as-directory org-directory)
6690 (defun org-notes-order-reversed-p ()
6691 "Check if the current file should receive notes in reversed order."
6693 ((not org-reverse-note-order) nil)
6694 ((eq t org-reverse-note-order) t)
6695 ((not (listp org-reverse-note-order)) nil)
6697 (let ((all org-reverse-note-order)
6699 (while (setq entry (pop all))
6700 (if (string-match (car entry) (buffer-file-name))
6701 (throw 'exit (cdr entry))))
6706 ;; Watch out: Here we are talking about two different kind of tables.
6707 ;; Most of the code is for the tables created with the Org-mode table editor.
6708 ;; Sometimes, we talk about tables created and edited with the table.el
6709 ;; Emacs package. We call the former org-type tables, and the latter
6710 ;; table.el-type tables.
6713 (defun org-before-change-function (beg end)
6714 "Every change indicates that a table might need an update."
6715 (setq org-table-may-need-update t))
6717 (defconst org-table-line-regexp "^[ \t]*|"
6718 "Detects an org-type table line.")
6719 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
6720 "Detects an org-type table line.")
6721 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
6722 "Detects a table line marked for automatic recalculation.")
6723 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
6724 "Detects a table line marked for automatic recalculation.")
6725 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
6726 "Detects a table line marked for automatic recalculation.")
6727 (defconst org-table-hline-regexp "^[ \t]*|-"
6728 "Detects an org-type table hline.")
6729 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
6730 "Detects a table-type table hline.")
6731 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
6732 "Detects an org-type or table-type table.")
6733 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
6734 "Searching from within a table (any type) this finds the first line
6735 outside the table.")
6736 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
6737 "Searching from within a table (any type) this finds the first line
6738 outside the table.")
6740 (defun org-table-create-with-table.el ()
6741 "Use the table.el package to insert a new table.
6742 If there is already a table at point, convert between Org-mode tables
6743 and table.el tables."
6747 ((org-at-table.el-p)
6748 (if (y-or-n-p "Convert table to Org-mode table? ")
6749 (org-table-convert)))
6751 (if (y-or-n-p "Convert table to table.el table? ")
6752 (org-table-convert)))
6753 (t (call-interactively 'table-insert))))
6755 (defun org-table-create (&optional size)
6756 "Query for a size and insert a table skeleton.
6757 SIZE is a string Columns x Rows like for example \"3x2\"."
6760 (setq size (read-string
6761 (concat "Table size Columns x Rows [e.g. "
6762 org-table-default-size "]: ")
6763 "" nil org-table-default-size)))
6765 (let* ((pos (point))
6766 (indent (make-string (current-column) ?\ ))
6767 (split (org-split-string size " *x *"))
6768 (rows (string-to-number (nth 1 split)))
6769 (columns (string-to-number (car split)))
6770 (line (concat (apply 'concat indent "|" (make-list columns " |"))
6772 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
6773 (point-at-bol) (point)))
6774 (beginning-of-line 1)
6776 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
6777 (dotimes (i rows) (insert line))
6780 ;; Insert a hline after the first row.
6787 (defun org-table-convert-region (beg0 end0 nspace)
6788 "Convert region to a table.
6789 The region goes from BEG0 to END0, but these borders will be moved
6790 slightly, to make sure a beginning of line in the first line is included.
6791 When NSPACE is non-nil, it indicates the minimum number of spaces that
6792 separate columns (default: just one space)"
6793 (let* ((beg (min beg0 end0))
6794 (end (max beg0 end0))
6798 (beginning-of-line 1)
6799 (setq beg (move-marker (make-marker) (point)))
6801 (if (bolp) (backward-char 1) (end-of-line 1))
6802 (setq end (move-marker (make-marker) (point)))
6803 ;; Lets see if this is tab-separated material. If every nonempty line
6804 ;; contains a tab, we will assume that it is tab-separated material
6808 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
6809 (if nspace (setq tabsep nil))
6812 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
6813 (max 1 (prefix-numeric-value nspace)))))
6815 (while (re-search-forward re end t)
6816 (replace-match "|" t t))
6821 (defun org-table-import (file arg)
6822 "Import FILE as a table.
6823 The file is assumed to be tab-separated. Such files can be produced by most
6824 spreadsheet and database applications. If no tabs (at least one per line)
6825 are found, lines will be split on whitespace into fields."
6826 (interactive "f\nP")
6827 (or (bolp) (newline))
6830 (insert-file-contents file)
6831 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
6833 (defun org-table-export ()
6834 "Export table as a tab-separated file.
6835 Such a file can be imported into a spreadsheet program like Excel."
6837 (let* ((beg (org-table-begin))
6838 (end (org-table-end))
6839 (table (buffer-substring beg end))
6840 (file (read-file-name "Export table to: "))
6842 (unless (or (not (file-exists-p file))
6843 (y-or-n-p (format "Overwrite file %s? " file)))
6845 (with-current-buffer (find-file-noselect file)
6846 (setq buf (current-buffer))
6850 (goto-char (point-min))
6851 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
6852 (replace-match "" t t)
6854 (goto-char (point-min))
6855 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
6856 (replace-match "" t t)
6857 (goto-char (min (1+ (point)) (point-max))))
6858 (goto-char (point-min))
6859 (while (re-search-forward "^-[-+]*$" nil t)
6861 (if (looking-at "\n")
6863 (goto-char (point-min))
6864 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
6865 (replace-match "\t" t t))
6869 (defvar org-table-aligned-begin-marker (make-marker)
6870 "Marker at the beginning of the table last aligned.
6871 Used to check if cursor still is in that table, to minimize realignment.")
6872 (defvar org-table-aligned-end-marker (make-marker)
6873 "Marker at the end of the table last aligned.
6874 Used to check if cursor still is in that table, to minimize realignment.")
6875 (defvar org-table-last-alignment nil
6876 "List of flags for flushright alignment, from the last re-alignment.
6877 This is being used to correctly align a single field after TAB or RET.")
6878 ;; FIXME: The following is currently not used.
6879 (defvar org-table-last-column-widths nil
6880 "List of max width of fields in each column.
6881 This is being used to correctly align a single field after TAB or RET.")
6883 (defvar org-last-recalc-line nil)
6885 (defun org-table-align ()
6886 "Align the table at point by aligning all vertical bars."
6888 ;; (message "align") (sit-for 2)
6891 (beg (org-table-begin))
6892 (end (org-table-end))
6893 ;; Current cursor position
6894 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6895 (colpos (org-table-current-column))
6896 (winstart (window-start))
6897 text lines (new "") lengths l typenums ty fields maxfields i
6899 (indent "") cnt frac
6901 (spaces (if (org-in-invisibility-spec-p '(org-table))
6902 org-table-spaces-around-invisible-separators
6903 org-table-spaces-around-separators))
6907 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6909 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6912 ;; (message "Aligning table...")
6914 (setq lines (org-split-string
6915 (buffer-substring-no-properties beg end) "\n"))
6916 ;; Store the indentation of the first line
6917 (if (string-match "^ *" (car lines))
6918 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6920 (setq lines (mapcar (lambda (l)
6921 (if (string-match "^ *|-" l)
6923 (if (string-match "[ \t]+$" l)
6924 (substring l 0 (match-beginning 0))
6927 ;; Get the data fields
6928 (setq fields (mapcar
6930 (org-split-string l " *| *"))
6931 (delq nil (copy-sequence lines))))
6932 ;; How many fields in the longest line?
6934 (setq maxfields (apply 'max (mapcar 'length fields)))
6936 (kill-region beg end)
6937 (org-table-create org-table-default-size)
6938 (error "Empty table - created default table")))
6939 ;; A list of empty string to fill any short rows on output
6940 (setq emptystrings (make-list maxfields ""))
6941 ;; Get the maximum length of a field and the most common datatype
6944 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6945 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6947 (push (apply 'max 1 (mapcar 'length column)) lengths)
6948 ;; compute the fraction stepwise, ignoring empty fields
6949 (setq cnt 0 frac 0.0)
6954 (setq frac ( / (+ (* frac cnt)
6955 (if (string-match org-table-number-regexp x) 1 0))
6956 (setq cnt (1+ cnt))))))
6958 (push (>= frac org-table-number-fraction) typenums))
6959 (setq lengths (nreverse lengths)
6960 typenums (nreverse typenums))
6961 (setq org-table-last-alignment typenums
6962 org-table-last-column-widths lengths)
6963 ;; Compute the formats needed for output of the table
6964 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6965 (while (setq l (pop lengths))
6966 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6967 (setq rfmt (concat rfmt (format rfmt1 ty l))
6968 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6969 (setq rfmt (concat rfmt "\n")
6970 hfmt (concat (substring hfmt 0 -1) "|\n"))
6971 ;; Produce the new table
6973 ;; (setq l (pop lines))
6975 ;; (setq new (concat new (apply 'format rfmt
6976 ;; (append (pop fields) emptystrings))))
6977 ;; (setq new (concat new hfmt))))
6978 (setq new (mapconcat
6980 (if l (apply 'format rfmt
6981 (append (pop fields) emptystrings))
6984 ;; Replace the old one
6985 (delete-region beg end)
6986 (move-marker end nil)
6987 (move-marker org-table-aligned-begin-marker (point))
6989 (move-marker org-table-aligned-end-marker (point))
6990 ;; Try to move to the old location (approximately)
6992 (set-window-start (selected-window) winstart 'noforce)
6993 (org-table-goto-column colpos)
6994 (setq org-table-may-need-update nil)
6995 (if (org-in-invisibility-spec-p '(org-table))
6996 (org-table-add-invisible-to-vertical-lines))
6999 (defun org-table-begin (&optional table-type)
7000 "Find the beginning of the table and return its position.
7001 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7003 (if (not (re-search-backward
7004 (if table-type org-table-any-border-regexp
7005 org-table-border-regexp)
7007 (error "Can't find beginning of table")
7008 (goto-char (match-beginning 0))
7009 (beginning-of-line 2)
7012 (defun org-table-end (&optional table-type)
7013 "Find the end of the table and return its position.
7014 With argument TABLE-TYPE, go to the end of a table.el-type table."
7016 (if (not (re-search-forward
7017 (if table-type org-table-any-border-regexp
7018 org-table-border-regexp)
7020 (goto-char (point-max))
7021 (goto-char (match-beginning 0)))
7024 (defun org-table-justify-field-maybe (&optional new)
7025 "Justify the current field, text to left, number to right.
7026 Optional argument NEW may specify text to replace the current field content."
7028 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7029 ((org-at-table-hline-p)
7030 ;; FIXME: I used to enforce realign here, but I think this is not needed.
7031 ;; (setq org-table-may-need-update t)
7034 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7036 (< (point) org-table-aligned-begin-marker)
7037 (>= (point) org-table-aligned-end-marker)))
7038 ;; This is not the same table, force a full re-align
7039 (setq org-table-may-need-update t))
7040 (t ;; realign the current field, based on previous full realign
7041 (let* ((pos (point)) s
7042 (col (org-table-current-column))
7043 (num (nth (1- col) org-table-last-alignment))
7046 (skip-chars-backward "^|\n")
7047 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7049 (setq s (match-string 1)
7051 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7052 e (not (= (match-beginning 2) (match-end 2))))
7053 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7054 l (if e "|" (setq org-table-may-need-update t) ""))
7057 (if (<= (length new) l)
7058 (setq n (format f new t t)) ;; FIXME: why t t?????
7059 (setq n (concat new "|") org-table-may-need-update t)))
7061 (let (org-table-may-need-update)
7062 (replace-match n))))
7063 (setq org-table-may-need-update t))
7064 (goto-char pos))))))
7066 (defun org-table-next-field ()
7067 "Go to the next field in the current table, creating new lines as needed.
7068 Before doing so, re-align the table if necessary."
7070 (org-table-maybe-eval-formula)
7071 (org-table-maybe-recalculate-line)
7072 (if (and org-table-automatic-realign
7073 org-table-may-need-update)
7075 (let ((end (org-table-end)))
7076 (if (org-at-table-hline-p)
7080 (re-search-forward "|" end)
7081 (if (looking-at "[ \t]*$")
7082 (re-search-forward "|" end))
7083 (if (and (looking-at "-")
7084 org-table-tab-jumps-over-hlines
7085 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7086 (goto-char (match-beginning 1)))
7087 (if (looking-at "-")
7089 (beginning-of-line 0)
7090 (org-table-insert-row 'below))
7091 (if (looking-at " ") (forward-char 1))))
7093 (org-table-insert-row 'below)))))
7095 (defun org-table-previous-field ()
7096 "Go to the previous field in the table.
7097 Before doing so, re-align the table if necessary."
7099 (org-table-justify-field-maybe)
7100 (org-table-maybe-recalculate-line)
7101 (if (and org-table-automatic-realign
7102 org-table-may-need-update)
7104 (if (org-at-table-hline-p)
7106 (re-search-backward "|" (org-table-begin))
7107 (re-search-backward "|" (org-table-begin))
7108 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7109 (re-search-backward "|" (org-table-begin)))
7110 (if (looking-at "| ?")
7111 (goto-char (match-end 0))))
7113 (defun org-table-next-row ()
7114 "Go to the next row (same column) in the current table.
7115 Before doing so, re-align the table if necessary."
7117 (org-table-maybe-eval-formula)
7118 (org-table-maybe-recalculate-line)
7119 (if (or (looking-at "[ \t]*$")
7120 (save-excursion (skip-chars-backward " \t") (bolp)))
7122 (if (and org-table-automatic-realign
7123 org-table-may-need-update)
7125 (let ((col (org-table-current-column)))
7126 (beginning-of-line 2)
7127 (if (or (not (org-at-table-p))
7128 (org-at-table-hline-p))
7130 (beginning-of-line 0)
7131 (org-table-insert-row 'below)))
7132 (org-table-goto-column col)
7133 (skip-chars-backward "^|\n\r")
7134 (if (looking-at " ") (forward-char 1)))))
7136 (defun org-table-copy-down (n)
7137 "Copy a field down in the current column.
7138 If the field at the cursor is empty, copy into it the content of the nearest
7139 non-empty field above. With argument N, use the Nth non-empty field.
7140 If the current field is not empty, it is copied down to the next row, and
7141 the cursor is moved with it. Therefore, repeating this command causes the
7142 column to be filled row-by-row.
7143 If the variable `org-table-copy-increment' is non-nil and the field is an
7144 integer, it will be incremented while copying."
7146 (let* ((colpos (org-table-current-column))
7147 (field (org-table-get-field))
7148 (non-empty (string-match "[^ \t]" field))
7149 (beg (org-table-begin))
7151 (org-table-check-inside-data-field)
7154 (setq txt (org-trim field))
7155 (org-table-next-row)
7156 (org-table-blank-field))
7160 (while (progn (beginning-of-line 1)
7161 (re-search-backward org-table-dataline-regexp
7163 (org-table-goto-column colpos t)
7164 (if (and (looking-at
7165 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7166 (= (setq n (1- n)) 0))
7167 (throw 'exit (match-string 1))))))))
7170 (if (and org-table-copy-increment
7171 (string-match "^[0-9]+$" txt))
7172 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7174 (org-table-maybe-recalculate-line)
7176 (error "No non-empty field found"))))
7178 (defun org-table-check-inside-data-field ()
7179 "Is point inside a table data field?
7180 I.e. not on a hline or before the first or after the last column?
7181 This actually throws an error, so it aborts the current command."
7182 (if (or (not (org-at-table-p))
7183 (= (org-table-current-column) 0)
7184 (org-at-table-hline-p)
7185 (looking-at "[ \t]*$"))
7186 (error "Not in table data field")))
7188 (defvar org-table-clip nil
7189 "Clipboard for table regions.")
7191 (defun org-table-blank-field ()
7192 "Blank the current table field or active region."
7194 (org-table-check-inside-data-field)
7195 (if (and (interactive-p) (org-region-active-p))
7196 (let (org-table-clip)
7197 (org-table-cut-region (region-beginning) (region-end)))
7198 (skip-chars-backward "^|")
7200 (if (looking-at "|[^|\n]+")
7201 (let* ((pos (match-beginning 0))
7202 (match (match-string 0))
7203 (len (length match)))
7204 (replace-match (concat "|" (make-string (1- len) ?\ )))
7205 (goto-char (+ 2 pos))
7206 (substring match 1)))))
7208 (defun org-table-get-field (&optional n replace)
7209 "Return the value of the field in column N of current row.
7210 N defaults to current field.
7211 If REPLACE is a string, replace field with this value. The return value
7212 is always the old value."
7213 (and n (org-table-goto-column n))
7214 (skip-chars-backward "^|\n")
7216 (if (looking-at "|[^|\r\n]*")
7217 (let* ((pos (match-beginning 0))
7218 (val (buffer-substring (1+ pos) (match-end 0))))
7220 (replace-match (concat "|" replace)))
7221 (goto-char (min (point-at-eol) (+ 2 pos)))
7223 (forward-char 1) ""))
7225 (defun org-table-current-column ()
7226 "Find out which column we are in.
7227 When called interactively, column is also displayed in echo area."
7229 (if (interactive-p) (org-table-check-inside-data-field))
7231 (let ((cnt 0) (pos (point)))
7232 (beginning-of-line 1)
7233 (while (search-forward "|" pos t)
7234 (setq cnt (1+ cnt)))
7235 (if (interactive-p) (message "This is table column %d" cnt))
7238 (defun org-table-goto-column (n &optional on-delim force)
7239 "Move the cursor to the Nth column in the current table line.
7240 With optional argument ON-DELIM, stop with point before the left delimiter
7242 If there are less than N fields, just go to after the last delimiter.
7243 However, when FORCE is non-nil, create new columns if necessary."
7245 (let ((pos (point-at-eol)))
7246 (beginning-of-line 1)
7248 (while (and (> (setq n (1- n)) -1)
7249 (or (search-forward "|" pos t)
7251 (progn (end-of-line 1)
7252 (skip-chars-backward "^|")
7254 ; (backward-char 2) t)))))
7255 (when (and force (not (looking-at ".*|")))
7256 (save-excursion (end-of-line 1) (insert " | ")))
7259 (if (looking-at " ") (forward-char 1))))))
7261 (defun org-at-table-p (&optional table-type)
7262 "Return t if the cursor is inside an org-type table.
7263 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7264 (if org-enable-table-editor
7266 (beginning-of-line 1)
7267 (looking-at (if table-type org-table-any-line-regexp
7268 org-table-line-regexp)))
7271 (defun org-at-table.el-p ()
7272 "Return t if and only if we are at a table.el table."
7273 (and (org-at-table-p 'any)
7275 (goto-char (org-table-begin 'any))
7276 (looking-at org-table1-hline-regexp))))
7278 (defun org-table-recognize-table.el ()
7279 "If there is a table.el table nearby, recognize it and move into it."
7280 (if org-table-tab-recognizes-table.el
7281 (if (org-at-table.el-p)
7283 (beginning-of-line 1)
7284 (if (looking-at org-table-dataline-regexp)
7286 (if (looking-at org-table1-hline-regexp)
7288 (beginning-of-line 2)
7289 (if (looking-at org-table-any-border-regexp)
7290 (beginning-of-line -1)))))
7291 (if (re-search-forward "|" (org-table-end t) t)
7294 (if (table--at-cell-p (point))
7296 (message "recognizing table.el table...")
7297 (table-recognize-table)
7298 (message "recognizing table.el table...done")))
7299 (error "This should not happen..."))
7304 (defun org-at-table-hline-p ()
7305 "Return t if the cursor is inside a hline in a table."
7306 (if org-enable-table-editor
7308 (beginning-of-line 1)
7309 (looking-at org-table-hline-regexp))
7312 (defun org-table-insert-column ()
7313 "Insert a new column into the table."
7315 (if (not (org-at-table-p))
7316 (error "Not at a table"))
7317 (org-table-find-dataline)
7318 (let* ((col (max 1 (org-table-current-column)))
7319 (beg (org-table-begin))
7320 (end (org-table-end))
7321 ;; Current cursor position
7322 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7325 (while (< (point) end)
7326 (if (org-at-table-hline-p)
7328 (org-table-goto-column col t)
7330 (beginning-of-line 2))
7331 (move-marker end nil)
7333 (org-table-goto-column colpos)
7335 (org-table-modify-formulas 'insert col)))
7337 (defun org-table-find-dataline ()
7338 "Find a dataline in the current table, which is needed for column commands."
7339 (if (and (org-at-table-p)
7340 (not (org-at-table-hline-p)))
7342 (let ((col (current-column))
7343 (end (org-table-end)))
7344 (move-to-column col)
7345 (while (and (< (point) end)
7346 (or (not (= (current-column) col))
7347 (org-at-table-hline-p)))
7348 (beginning-of-line 2)
7349 (move-to-column col))
7350 (if (and (org-at-table-p)
7351 (not (org-at-table-hline-p)))
7354 "Please position cursor in a data line for column operations")))))
7356 (defun org-table-delete-column ()
7357 "Delete a column into the table."
7359 (if (not (org-at-table-p))
7360 (error "Not at a table"))
7361 (org-table-find-dataline)
7362 (org-table-check-inside-data-field)
7363 (let* ((col (org-table-current-column))
7364 (beg (org-table-begin))
7365 (end (org-table-end))
7366 ;; Current cursor position
7367 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7370 (while (< (point) end)
7371 (if (org-at-table-hline-p)
7373 (org-table-goto-column col t)
7374 (and (looking-at "|[^|\n]+|")
7375 (replace-match "|")))
7376 (beginning-of-line 2))
7377 (move-marker end nil)
7379 (org-table-goto-column colpos)
7381 (org-table-modify-formulas 'remove col)))
7383 (defun org-table-move-column-right ()
7384 "Move column to the right."
7386 (org-table-move-column nil))
7387 (defun org-table-move-column-left ()
7388 "Move column to the left."
7390 (org-table-move-column 'left))
7392 (defun org-table-move-column (&optional left)
7393 "Move the current column to the right. With arg LEFT, move to the left."
7395 (if (not (org-at-table-p))
7396 (error "Not at a table"))
7397 (org-table-find-dataline)
7398 (org-table-check-inside-data-field)
7399 (let* ((col (org-table-current-column))
7400 (col1 (if left (1- col) col))
7401 (beg (org-table-begin))
7402 (end (org-table-end))
7403 ;; Current cursor position
7404 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7405 (colpos (if left (1- col) (1+ col))))
7406 (if (and left (= col 1))
7407 (error "Cannot move column further left"))
7408 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
7409 (error "Cannot move column further right"))
7411 (while (< (point) end)
7412 (if (org-at-table-hline-p)
7414 (org-table-goto-column col1 t)
7415 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
7416 (replace-match "|\\2|\\1|")))
7417 (beginning-of-line 2))
7418 (move-marker end nil)
7420 (org-table-goto-column colpos)
7422 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
7424 (defun org-table-move-row-down ()
7425 "move table row down."
7427 (org-table-move-row nil))
7428 (defun org-table-move-row-up ()
7429 "move table row up."
7431 (org-table-move-row 'up))
7433 (defun org-table-move-row (&optional up)
7434 "Move the current table line down. With arg UP, move it up."
7436 (let ((col (current-column))
7440 (beginning-of-line tonew)
7441 (if (not (org-at-table-p))
7444 (error "Cannot move row further")))
7446 (beginning-of-line 1)
7448 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
7449 (delete-region (point) (1+ (point-at-eol)))
7450 (beginning-of-line tonew)
7452 (beginning-of-line 0)
7453 (move-to-column col)))
7455 (defun org-table-insert-row (&optional arg)
7456 "Insert a new row above the current line into the table.
7457 With prefix ARG, insert below the current line."
7459 (if (not (org-at-table-p))
7460 (error "Not at a table"))
7461 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
7463 (if (string-match "^[ \t]*|-" line)
7464 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
7465 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
7466 ;; Fix the first field if necessary
7467 (setq new (concat new))
7468 (if (string-match "^[ \t]*| *[#$] *|" line)
7469 (setq new (replace-match (match-string 0 line) t t new)))
7470 (beginning-of-line (if arg 2 1))
7471 (let (org-table-may-need-update)
7472 (insert-before-markers new)
7473 (insert-before-markers "\n"))
7474 (beginning-of-line 0)
7475 (re-search-forward "| ?" (point-at-eol) t)
7476 (and org-table-may-need-update (org-table-align))))
7478 (defun org-table-insert-hline (&optional arg)
7479 "Insert a horizontal-line below the current line into the table.
7480 With prefix ARG, insert above the current line."
7482 (if (not (org-at-table-p))
7483 (error "Not at a table"))
7484 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
7485 (col (current-column))
7487 (if (string-match "^[ \t]*|-" line)
7489 (mapcar (lambda (x) (if (member x '(?| ?+))
7490 (prog1 (if start ?+ ?|) (setq start t))
7494 (mapcar (lambda (x) (if (equal x ?|)
7495 (prog1 (if start ?+ ?|) (setq start t))
7498 (beginning-of-line (if arg 1 2))
7499 (apply 'insert line)
7500 (if (equal (char-before (point)) ?+)
7501 (progn (backward-delete-char 1) (insert "|")))
7503 (beginning-of-line 0)
7504 (move-to-column col)))
7506 (defun org-table-kill-row ()
7507 "Delete the current row or horizontal line from the table."
7509 (if (not (org-at-table-p))
7510 (error "Not at a table"))
7511 (let ((col (current-column)))
7512 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
7513 (if (not (org-at-table-p)) (beginning-of-line 0))
7514 (move-to-column col)))
7516 (defun org-table-sort-lines (beg end numericp)
7517 "Sort table lines in region.
7518 Point and mark define the first and last line to include. Both point and
7519 mark should be in the column that is used for sorting. For example, to
7520 sort according to column 3, put the mark in the first line to sort, in
7521 table column 3. Put point into the last line to be included in the sorting,
7522 also in table column 3. The command will prompt for the sorting method (n for
7523 numerical, a for alphanumeric)."
7524 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
7525 (setq numericp (string-match "[nN]" numericp))
7526 (org-table-align) ;; Just to be safe
7527 (let* (bcol ecol cmp column lns)
7529 (org-table-check-inside-data-field)
7530 (setq column (org-table-current-column)
7531 beg (move-marker (make-marker) (point-at-bol)))
7533 (org-table-check-inside-data-field)
7534 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
7537 (org-table-goto-column column)
7538 (skip-chars-backward "^|")
7539 (setq bcol (current-column))
7540 (org-table-goto-column (1+ column))
7541 (skip-chars-backward "^|")
7542 (setq ecol (1- (current-column)))
7543 (setq cmp (if numericp
7544 (lambda (a b) (< (car a) (car b)))
7545 (lambda (a b) (string< (car a) (car b)))))
7546 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
7547 (split-string (buffer-substring beg end) "\n")))
7549 (setq lns (mapcar (lambda(x)
7550 (cons (string-to-number (car x)) (cdr x)))
7552 (delete-region beg end)
7553 (move-marker beg nil)
7554 (move-marker end nil)
7555 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
7556 (message "%d lines sorted %s based on column %d"
7558 (if numericp "numerically" "alphabetically") column)))
7560 (defun org-table-cut-region (beg end)
7561 "Copy region in table to the clipboard and blank all relevant fields."
7563 (org-table-copy-region beg end 'cut))
7565 (defun org-table-copy-region (beg end &optional cut)
7566 "Copy rectangular region in table to clipboard.
7567 A special clipboard is used which can only be accessed
7568 with `org-table-paste-rectangle'"
7570 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
7572 (rpl (if cut " " nil)))
7574 (org-table-check-inside-data-field)
7575 (setq l01 (count-lines (point-min) (point))
7576 c01 (org-table-current-column))
7578 (org-table-check-inside-data-field)
7579 (setq l02 (count-lines (point-min) (point))
7580 c02 (org-table-current-column))
7581 (setq l1 (min l01 l02) l2 (max l01 l02)
7582 c1 (min c01 c02) c2 (max c01 c02))
7586 (if (> l1 l2) (throw 'exit t))
7588 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
7589 (setq cols nil ic1 c1 ic2 c2)
7590 (while (< ic1 (1+ ic2))
7591 (push (org-table-get-field ic1 rpl) cols)
7592 (setq ic1 (1+ ic1)))
7593 (push (nreverse cols) region)
7594 (setq l1 (1+ l1)))))
7595 (setq org-table-clip (nreverse region))
7596 (if cut (org-table-align))
7599 (defun org-table-paste-rectangle ()
7600 "Paste a rectangular region into a table.
7601 The upper right corner ends up in the current field. All involved fields
7602 will be overwritten. If the rectangle does not fit into the present table,
7603 the table is enlarged as needed. The process ignores horizontal separator
7606 (unless (and org-table-clip (listp org-table-clip))
7607 (error "First cut/copy a region to paste!"))
7608 (org-table-check-inside-data-field)
7609 (let* ((clip org-table-clip)
7610 (line (count-lines (point-min) (point)))
7611 (col (org-table-current-column))
7612 (org-enable-table-editor t)
7613 (org-table-automatic-realign nil)
7615 (while (setq cols (pop clip))
7616 (while (org-at-table-hline-p) (beginning-of-line 2))
7617 (if (not (org-at-table-p))
7618 (progn (end-of-line 0) (org-table-next-field)))
7620 (while (setq field (pop cols))
7621 (org-table-goto-column c nil 'force)
7622 (org-table-get-field nil field)
7624 (beginning-of-line 2))
7626 (org-table-goto-column col)
7629 (defun org-table-convert ()
7630 "Convert from `org-mode' table to table.el and back.
7631 Obviously, this only works within limits. When an Org-mode table is
7632 converted to table.el, all horizontal separator lines get lost, because
7633 table.el uses these as cell boundaries and has no notion of horizontal lines.
7634 A table.el table can be converted to an Org-mode table only if it does not
7635 do row or column spanning. Multiline cells will become multiple cells.
7636 Beware, Org-mode does not test if the table can be successfully converted - it
7637 blindly applies a recipe that works for simple tables."
7640 (if (org-at-table.el-p)
7641 ;; convert to Org-mode table
7642 (let ((beg (move-marker (make-marker) (org-table-begin t)))
7643 (end (move-marker (make-marker) (org-table-end t))))
7644 (table-unrecognize-region beg end)
7646 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
7649 (if (org-at-table-p)
7650 ;; convert to table.el table
7651 (let ((beg (move-marker (make-marker) (org-table-begin)))
7652 (end (move-marker (make-marker) (org-table-end))))
7653 ;; first, get rid of all horizontal lines
7655 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
7657 ;; insert a hline before first
7659 (org-table-insert-hline 'above)
7660 ;; insert a hline after each line
7661 (while (progn (beginning-of-line 2) (< (point) end))
7662 (org-table-insert-hline))
7664 (setq end (move-marker end (org-table-end)))
7665 ;; replace "+" at beginning and ending of hlines
7666 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
7667 (replace-match "\\1+-"))
7669 (while (re-search-forward "-|[ \t]*$" end t)
7670 (replace-match "-+"))
7673 (defun org-table-wrap-region (arg)
7674 "Wrap several fields in a column like a paragraph.
7675 This is useful if you'd like to spread the contents of a field over several
7676 lines, in order to keep the table compact.
7678 If there is an active region, and both point and mark are in the same column,
7679 the text in the column is wrapped to minimum width for the given number of
7680 lines. Generally, this makes the table more compact. A prefix ARG may be
7681 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
7682 formats the selected text to two lines. If the region was longer than 2
7683 lines, the remaining lines remain empty. A negative prefix argument reduces
7684 the current number of lines by that amount. The wrapped text is pasted back
7685 into the table. If you formatted it to more lines than it was before, fields
7686 further down in the table get overwritten - so you might need to make space in
7689 If there is no region, the current field is split at the cursor position and
7690 the text fragment to the right of the cursor is prepended to the field one
7693 If there is no region, but you specify a prefix ARG, the current field gets
7694 blank, and the content is appended to the field above."
7696 (org-table-check-inside-data-field)
7697 (if (org-region-active-p)
7698 ;; There is a region: fill as a paragraph
7699 (let ((beg (region-beginning))
7701 (org-table-cut-region (region-beginning) (region-end))
7702 (if (> (length (car org-table-clip)) 1)
7703 (error "Region must be limited to single column"))
7704 (setq nlines (if arg
7706 (+ (length org-table-clip) arg)
7708 (length org-table-clip)))
7709 (setq org-table-clip
7710 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
7713 (org-table-paste-rectangle))
7714 ;; No region, split the current field at point
7716 ;; combine with field above
7717 (let ((s (org-table-blank-field))
7718 (col (org-table-current-column)))
7719 (beginning-of-line 0)
7720 (while (org-at-table-hline-p) (beginning-of-line 0))
7721 (org-table-goto-column col)
7722 (skip-chars-forward "^|")
7723 (skip-chars-backward " ")
7724 (insert " " (org-trim s))
7727 (when (looking-at "\\([^|]+\\)+|")
7728 (let ((s (match-string 1)))
7729 (replace-match " |")
7730 (goto-char (match-beginning 0))
7731 (org-table-next-row)
7732 (insert (org-trim s) " ")
7733 (org-table-align))))))
7736 "Remove whitespace at beginning and end of string."
7737 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
7738 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
7741 (defun org-wrap (string &optional width lines)
7742 "Wrap string to either a number of lines, or a width in characters.
7743 If WIDTH is non-nil, the string is wrapped to that width, however many lines
7744 that costs. If there is a word longer than WIDTH, the text is actually
7745 wrapped to the length of that word.
7746 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
7747 many lines, whatever width that takes.
7748 The return value is a list of lines, without newlines at the end."
7749 (let* ((words (org-split-string string "[ \t\n]+"))
7750 (maxword (apply 'max (mapcar 'length words)))
7753 (org-do-wrap words (max maxword width)))
7756 (setq ll (org-do-wrap words maxword))
7757 (if (<= (length ll) lines)
7760 (while (> (length ll) lines)
7762 (setq ll (org-do-wrap words w)))
7764 (t (error "Cannot wrap this")))))
7767 (defun org-do-wrap (words width)
7768 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
7771 (setq line (pop words))
7772 (while (and words (< (+ (length line) (length (car words))) width))
7773 (setq line (concat line " " (pop words))))
7774 (setq lines (push line lines)))
7777 ;; FIXME: I think I can make this more efficient
7778 (defun org-split-string (string &optional separators)
7779 "Splits STRING into substrings at SEPARATORS.
7780 No empty strings are returned if there are matches at the beginning
7782 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
7786 (while (and (string-match rexp string
7788 (= start (match-beginning 0))
7789 (< start (length string)))
7791 (< (match-beginning 0) (length string)))
7793 (or (eq (match-beginning 0) 0)
7794 (and (eq (match-beginning 0) (match-end 0))
7795 (eq (match-beginning 0) start))
7797 (cons (substring string start (match-beginning 0))
7799 (setq start (match-end 0)))
7800 (or (eq start (length string))
7802 (cons (substring string start)
7806 (defun org-table-add-invisible-to-vertical-lines ()
7807 "Add an `invisible' property to vertical lines of current table."
7809 (let* ((beg (org-table-begin))
7810 (end (org-table-end))
7814 (while (< (point) end)
7815 (setq end1 (point-at-eol))
7816 (if (looking-at org-table-dataline-regexp)
7817 (while (re-search-forward "|" end1 t)
7818 (add-text-properties (1- (point)) (point)
7819 '(invisible org-table)))
7820 (while (re-search-forward "[+|]" end1 t)
7821 (add-text-properties (1- (point)) (point)
7822 '(invisible org-table))))
7823 (beginning-of-line 2)))))
7825 (defun org-table-toggle-vline-visibility (&optional arg)
7826 "Toggle the visibility of table vertical lines.
7827 The effect is immediate and on all tables in the file.
7828 With prefix ARG, make lines invisible when ARG is positive, make lines
7829 visible when ARG is not positive"
7832 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
7833 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
7834 (t (if (org-in-invisibility-spec-p '(org-table))
7837 (if (eq action 'off)
7839 (org-remove-from-invisibility-spec '(org-table))
7840 (org-table-map-tables 'org-table-align)
7841 (message "Vertical table lines visible")
7842 (if (org-at-table-p)
7844 (org-add-to-invisibility-spec '(org-table))
7845 (org-table-map-tables 'org-table-align)
7846 (message "Vertical table lines invisible"))
7847 (redraw-frame (selected-frame))))
7849 (defun org-table-map-tables (function)
7850 "Apply FUNCTION to the start of all tables in the buffer."
7854 (goto-char (point-min))
7855 (while (re-search-forward org-table-any-line-regexp nil t)
7856 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7857 (beginning-of-line 1)
7858 (if (looking-at org-table-line-regexp)
7859 (save-excursion (funcall function)))
7860 (re-search-forward org-table-any-border-regexp nil 1)))))
7862 (defun org-table-sum (&optional beg end nlast)
7863 "Sum numbers in region of current table column.
7864 The result will be displayed in the echo area, and will be available
7865 as kill to be inserted with \\[yank].
7867 If there is an active region, it is interpreted as a rectangle and all
7868 numbers in that rectangle will be summed. If there is no active
7869 region and point is located in a table column, sum all numbers in that
7872 If at least one number looks like a time HH:MM or HH:MM:SS, all other
7873 numbers are assumed to be times as well (in decimal hours) and the
7874 numbers are added as such.
7876 If NLAST is a number, only the NLAST fields will actually be summed."
7879 (let (col (timecnt 0) diff h m s org-table-clip)
7881 ((and beg end)) ; beg and end given explicitly
7882 ((org-region-active-p)
7883 (setq beg (region-beginning) end (region-end)))
7885 (setq col (org-table-current-column))
7886 (goto-char (org-table-begin))
7887 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7888 (error "No table data"))
7889 (org-table-goto-column col)
7890 ;not needed? (skip-chars-backward "^|")
7892 (goto-char (org-table-end))
7893 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7894 (error "No table data"))
7895 (org-table-goto-column col)
7896 ;not needed? (skip-chars-forward "^|")
7897 (setq end (point))))
7898 (let* ((items (apply 'append (org-table-copy-region beg end)))
7899 (items1 (cond ((not nlast) items)
7900 ((>= nlast (length items)) items)
7901 (t (setq items (reverse items))
7902 (setcdr (nthcdr (1- nlast) items) nil)
7904 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7906 (res (apply '+ numbers))
7907 (sres (if (= timecnt 0)
7909 (setq diff (* 3600 res)
7910 h (floor (/ diff 3600)) diff (mod diff 3600)
7911 m (floor (/ diff 60)) diff (mod diff 60)
7913 (format "%d:%02d:%02d" h m s))))
7917 (substitute-command-keys
7918 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7919 (length numbers) sres))))
7922 (defun org-table-get-number-for-summing (s)
7924 (if (string-match "^ *|? *" s)
7925 (setq s (replace-match "" nil nil s)))
7926 (if (string-match " *|? *$" s)
7927 (setq s (replace-match "" nil nil s)))
7928 (setq n (string-to-number s))
7930 ((and (string-match "0" s)
7931 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7932 ((string-match "\\`[ \t]+\\'" s) nil)
7933 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7934 (let ((h (string-to-number (or (match-string 1 s) "0")))
7935 (m (string-to-number (or (match-string 2 s) "0")))
7936 (s (string-to-number (or (match-string 4 s) "0"))))
7937 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
7938 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7942 (defun org-table-get-vertical-vector (desc &optional tbeg col)
7943 "Get a calc vector from a column, accorting to desctiptor DESC.
7944 Optional arguments TBEG and COL can give the beginning of the table and
7945 the current column, to avoid unnecessary parsing."
7947 (or tbeg (setq tbeg (org-table-begin)))
7948 (or col (setq col (org-table-current-column)))
7949 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
7951 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
7952 (setq n1 (- (match-end 1) (match-beginning 1)))
7953 (if (match-beginning 3)
7954 (setq n2 (- (match-end 2) (match-beginning 3))))
7955 (setq n (if n2 (max n1 n2) n1))
7956 (setq n1 (if n2 (min n1 n2)))
7958 (while (and (> nn 0)
7959 (re-search-backward org-table-hline-regexp tbeg t))
7960 (push (org-current-line) hline-list)
7962 (setq hline-list (nreverse hline-list))
7963 (goto-line (nth (1- n) hline-list))
7964 (when (re-search-forward org-table-dataline-regexp)
7965 (org-table-goto-column col)
7967 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
7968 (when (re-search-backward org-table-dataline-regexp)
7969 (org-table-goto-column col)
7971 (setq l (apply 'append (org-table-copy-region beg end)))
7972 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
7973 (if (equal x "") "0" x))
7975 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
7976 (setq n1 (string-to-number (match-string 1 desc))
7977 n2 (string-to-number (match-string 2 desc)))
7978 (beginning-of-line 1)
7980 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
7981 (org-table-goto-column col)
7982 (setq beg (point))))
7983 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
7984 (org-table-goto-column col)
7986 (setq l (apply 'append (org-table-copy-region beg end)))
7987 (concat "[" (mapconcat
7988 (lambda (x) (setq x (org-trim x))
7989 (if (equal x "") "0" x))
7991 ((string-match "\\([0-9]+\\)" desc)
7992 (beginning-of-line 1)
7993 (when (re-search-backward org-table-dataline-regexp tbeg t
7994 (string-to-number (match-string 0 desc)))
7995 (org-table-goto-column col)
7996 (org-trim (org-table-get-field))))))))
7998 (defvar org-table-formula-history nil)
8000 (defvar org-table-column-names nil
8001 "Alist with column names, derived from the `!' line.")
8002 (defvar org-table-column-name-regexp nil
8003 "Regular expression matching the current column names.")
8004 (defvar org-table-local-parameters nil
8005 "Alist with parameter names, derived from the `$' line.")
8006 (defvar org-table-named-field-locations nil
8007 "Alist with locations of named fields.")
8009 (defun org-table-get-formula (&optional equation named)
8010 "Read a formula from the minibuffer, offer stored formula as default."
8011 (let* ((name (car (rassoc (list (org-current-line)
8012 (org-table-current-column))
8013 org-table-named-field-locations)))
8016 (error "Not in a named field"))
8017 (int-to-string (org-table-current-column))))
8018 (dummy (and name (not named)
8019 (not (y-or-n-p "Replace named-field formula with column equation? " ))
8021 (org-table-may-need-update nil)
8022 (stored-list (org-table-get-stored-formulas))
8023 (stored (cdr (assoc scol stored-list)))
8025 ((and stored equation (string-match "^ *=? *$" equation))
8030 (format "%s formula $%s=" (if named "Field" "Column") scol)
8031 (or stored "") 'org-table-formula-history
8035 (when (not (string-match "\\S-" eq))
8037 (setq stored-list (delq (assoc scol stored-list) stored-list))
8038 (org-table-store-formulas stored-list)
8039 (error "Formula removed"))
8040 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8041 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8042 (if (and name (not named))
8043 ;; We set the column equation, delete the named one.
8044 (setq stored-list (delq (assoc name stored-list) stored-list)
8047 (setcdr (assoc scol stored-list) eq)
8048 (setq stored-list (cons (cons scol eq) stored-list)))
8049 (if (or mustsave (not (equal stored eq)))
8050 (org-table-store-formulas stored-list))
8053 (defun org-table-store-formulas (alist)
8054 "Store the list of formulas below the current table."
8055 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
8057 (goto-char (org-table-end))
8058 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
8059 (delete-region (point) (match-end 0)))
8061 (mapconcat (lambda (x)
8062 (concat "$" (car x) "=" (cdr x)))
8066 (defun org-table-get-stored-formulas ()
8067 "Return an alist with the t=stored formulas directly after current table."
8069 (let (scol eq eq-alist strings string seen)
8071 (goto-char (org-table-end))
8072 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8073 (setq strings (org-split-string (match-string 2) " *:: *"))
8074 (while (setq string (pop strings))
8075 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
8076 (setq scol (match-string 1 string)
8077 eq (match-string 2 string)
8078 eq-alist (cons (cons scol eq) eq-alist))
8079 (if (member scol seen)
8080 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8081 (push scol seen))))))
8082 (nreverse eq-alist)))
8084 (defun org-table-modify-formulas (action &rest columns)
8085 "Modify the formulas stored below the current table.
8086 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
8087 expected, for the other action only a single column number is needed."
8088 (let ((list (org-table-get-stored-formulas))
8089 (nmax (length (org-split-string
8090 (buffer-substring (point-at-bol) (point-at-eol))
8092 col col1 col2 scol si sc1 sc2)
8094 ((null list)) ; No action needed if there are no stored formulas
8095 ((eq action 'remove)
8096 (setq col (car columns)
8097 scol (int-to-string col))
8098 (org-table-replace-in-formulas list scol "INVALID")
8099 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
8100 (loop for i from (1+ col) upto nmax by 1 do
8101 (setq si (int-to-string i))
8102 (org-table-replace-in-formulas list si (int-to-string (1- i)))
8103 (if (assoc si list) (setcar (assoc si list)
8104 (int-to-string (1- i))))))
8105 ((eq action 'insert)
8106 (setq col (car columns))
8107 (loop for i from nmax downto col by 1 do
8108 (setq si (int-to-string i))
8109 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
8110 (if (assoc si list) (setcar (assoc si list)
8111 (int-to-string (1+ i))))))
8113 (setq col1 (car columns) col2 (nth 1 columns)
8114 sc1 (int-to-string col1) sc2 (int-to-string col2))
8115 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
8116 (org-table-replace-in-formulas list sc1 "ZqZ")
8117 (org-table-replace-in-formulas list sc2 sc1)
8118 (org-table-replace-in-formulas list "ZqZ" sc2)
8119 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
8120 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
8121 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
8122 (t (error "Invalid action in `org-table-modify-formulas'")))
8123 (if list (org-table-store-formulas list))))
8125 (defun org-table-replace-in-formulas (list s1 s2)
8127 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
8128 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
8129 re (concat (regexp-quote s1) "\\>"))
8130 (while (setq elt (pop list))
8132 (while (string-match re s)
8133 (setq s (replace-match s2 t t s)))
8136 (defun org-table-get-specials ()
8137 "Get the column nmaes and local parameters for this table."
8139 (let ((beg (org-table-begin)) (end (org-table-end))
8140 names name fields fields1 field cnt c v line col)
8141 (setq org-table-column-names nil
8142 org-table-local-parameters nil
8143 org-table-named-field-locations nil)
8145 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8146 (setq names (org-split-string (match-string 1) " *| *")
8148 (while (setq name (pop names))
8150 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8151 (push (cons name (int-to-string cnt)) org-table-column-names))))
8152 (setq org-table-column-names (nreverse org-table-column-names))
8153 (setq org-table-column-name-regexp
8154 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8156 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8157 (setq fields (org-split-string (match-string 1) " *| *"))
8158 (while (setq field (pop fields))
8159 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8160 (push (cons (match-string 1 field) (match-string 2 field))
8161 org-table-local-parameters))))
8163 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8164 (setq c (match-string 1)
8165 fields (org-split-string (match-string 2) " *| *"))
8167 (beginning-of-line (if (equal c "_") 2 0))
8168 (setq line (org-current-line) col 1)
8169 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8170 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8171 (while (and fields1 (setq field (pop fields)))
8172 (setq v (pop fields1) col (1+ col))
8173 (when (and (stringp field) (stringp v)
8174 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8175 (push (cons field v) org-table-local-parameters)
8176 (push (list field line col) org-table-named-field-locations)))))))
8178 (defun org-this-word ()
8179 ;; Get the current word
8181 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
8182 (end (progn (skip-chars-forward "^ \t\n") (point))))
8183 (buffer-substring-no-properties beg end))))
8185 (defun org-table-maybe-eval-formula ()
8186 "Check if the current field starts with \"=\" or \":=\".
8187 If yes, store the formula and apply it."
8188 ;; We already know we are in a table. Get field will only return a formula
8189 ;; when appropriate. It might return a separator line, but no problem.
8190 (when org-table-formula-evaluate-inline
8191 (let* ((field (org-trim (or (org-table-get-field) "")))
8193 (when (string-match "^:?=\\(.*\\)" field)
8194 (setq named (equal (string-to-char field) ?:)
8195 eq (match-string 1 field))
8196 (if (fboundp 'calc-eval)
8197 (org-table-eval-formula (if named '(4) nil) eq))))))
8199 (defvar org-recalc-commands nil
8200 "List of commands triggering the reccalculation of a line.
8201 Will be filled automatically during use.")
8203 (defvar org-recalc-marks
8204 '((" " . "Unmarked: no special line, no automatic recalculation")
8205 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8206 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8207 ("!" . "Column name definition line. Reference in formula as $name.")
8208 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8209 ("_" . "Names for values in row below this one.")
8210 ("^" . "Names for values in row above this one.")))
8212 (defun org-table-rotate-recalc-marks (&optional newchar)
8213 "Rotate the recalculation mark in the first column.
8214 If in any row, the first field is not consistent with a mark,
8215 insert a new column for the makers.
8216 When there is an active region, change all the lines in the region,
8217 after prompting for the marking character.
8218 After each change, a message will be displayed indication the meaning
8221 (unless (org-at-table-p) (error "Not at a table"))
8222 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8223 (beg (org-table-begin))
8224 (end (org-table-end))
8225 (l (org-current-line))
8226 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8227 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8231 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8232 (col (org-table-current-column))
8233 (forcenew (car (assoc newchar org-recalc-marks)))
8236 (message "Change region to what mark? Type # * ! $ or SPC: ")
8237 (setq newchar (char-to-string (read-char-exclusive))
8238 forcenew (car (assoc newchar org-recalc-marks))))
8239 (if (and newchar (not forcenew))
8240 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8242 (if l1 (goto-line l1))
8244 (beginning-of-line 1)
8245 (unless (looking-at org-table-dataline-regexp)
8246 (error "Not at a table data line")))
8248 (org-table-goto-column 1)
8249 (org-table-insert-column)
8250 (org-table-goto-column (1+ col)))
8251 (setq epos (point-at-eol))
8253 (beginning-of-line 1)
8254 (org-table-get-field
8255 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8257 (setq new (or forcenew
8258 (cadr (member (match-string 1) marks))))
8264 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8265 (and (looking-at org-table-dataline-regexp)
8266 (org-table-get-field 1 (concat " " new " "))))
8268 (if (not (= epos (point-at-eol))) (org-table-align))
8270 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8272 (defun org-table-maybe-recalculate-line ()
8273 "Recompute the current line if marked for it, and if we haven't just done it."
8275 (and org-table-allow-automatic-line-recalculation
8276 (not (and (memq last-command org-recalc-commands)
8277 (equal org-last-recalc-line (org-current-line))))
8278 (save-excursion (beginning-of-line 1)
8279 (looking-at org-table-auto-recalculate-regexp))
8280 (fboundp 'calc-eval)
8281 (org-table-recalculate) t))
8283 (defvar org-table-formula-debug nil
8284 "Non-nil means, debug table formulas.
8285 When nil, simply write \"#ERROR\" in corrupted fields.")
8288 (defsubst org-set-calc-mode (var &optional value)
8290 (setq var (assoc var '(("D" calc-angle-mode deg)
8291 ("R" calc-angle-mode rad)
8292 ("F" calc-prefer-frac t)
8293 ("S" calc-symbolic-mode t)))
8294 value (nth 2 var) var (nth 1 var)))
8295 (if (memq var modes)
8296 (setcar (cdr (memq var modes)) value)
8297 (cons var (cons value modes)))
8300 (defun org-table-eval-formula (&optional arg equation
8301 suppress-align suppress-const
8303 "Replace the table field value at the cursor by the result of a calculation.
8305 This function makes use of Dave Gillespie's calc package, in my view the
8306 most exciting program ever written for GNU Emacs. So you need to have calc
8307 installed in order to use this function.
8309 In a table, this command replaces the value in the current field with the
8310 result of a formula. It also installes the formula as the \"current\" column
8311 formula, by storing it in a special line below the table. When called
8312 with a `C-u' prefix, the current field must ba a named field, and the
8313 formula is installed as valid in only this specific field.
8315 When called, the command first prompts for a formula, which is read in
8316 the minibuffer. Previously entered formulas are available through the
8317 history list, and the last used formula is offered as a default.
8318 These stored formulas are adapted correctly when moving, inserting, or
8319 deleting columns with the corresponding commands.
8321 The formula can be any algebraic expression understood by the calc package.
8322 For details, see the Org-mode manual.
8324 This function can also be called from Lisp programs and offers
8325 additional Arguments: EQUATION can be the formula to apply. If this
8326 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
8327 used to speed-up recursive calls by by-passing unnecessary aligns.
8328 SUPPRESS-CONST suppresses the interpretation of constants in the
8329 formula, assuming that this has been done already outside the fuction.
8330 SUPPRESS-STORE means the formula should not be stored, either because
8331 it is already stored, or because it is a modified equation that should
8332 not overwrite the stored one."
8335 (org-table-check-inside-data-field)
8336 (org-table-get-specials)
8338 (ndown (if (integerp arg) arg 1))
8339 (org-table-automatic-realign nil)
8340 (case-fold-search nil)
8342 (formula (if (and equation suppress-store)
8344 (org-table-get-formula equation (equal arg '(4)))))
8345 (n0 (org-table-current-column))
8346 (modes (copy-sequence org-calc-default-modes))
8347 n form fmt x ev orig c)
8348 ;; Parse the format string. Since we have a lot of modes, this is
8349 ;; a lot of work. However, I think calc still uses most of the time.
8350 (if (string-match ";" formula)
8351 (let ((tmp (org-split-string formula ";")))
8352 (setq formula (car tmp)
8353 fmt (concat (cdr (assoc "%" org-table-local-parameters))
8355 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
8356 (setq c (string-to-char (match-string 1 fmt))
8357 n (string-to-number (or (match-string 1 fmt) "")))
8358 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
8359 (setq modes (org-set-calc-mode
8361 (list (cdr (assoc c '((?n. float) (?f. fix)
8362 (?s. sci) (?e. eng))))
8364 (setq fmt (replace-match "" t t fmt)))
8365 (while (string-match "[DRFS]" fmt)
8366 (setq modes (org-set-calc-mode (match-string 0 fmt)))
8367 (setq fmt (replace-match "" t t fmt)))
8368 (unless (string-match "\\S-" fmt)
8370 (if (and (not suppress-const) org-table-formula-use-constants)
8371 (setq formula (org-table-formula-substitute-names formula)))
8372 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
8374 (setq fields (org-split-string
8376 (point-at-bol) (point-at-eol)) " *| *"))
8377 (if org-table-formula-numbers-only
8378 (setq fields (mapcar
8379 (lambda (x) (number-to-string (string-to-number x)))
8381 (setq ndown (1- ndown))
8382 (setq form (copy-sequence formula))
8383 ;; Insert the references to fields in same row
8384 (while (string-match "\\$\\([0-9]+\\)?" form)
8385 (setq n (if (match-beginning 1)
8386 (string-to-number (match-string 1 form))
8388 x (nth (1- n) fields))
8389 (unless x (error "Invalid field specifier \"%s\""
8390 (match-string 0 form)))
8391 (if (equal x "") (setq x "0"))
8392 (setq form (replace-match (concat "(" x ")") t t form)))
8393 ;; Insert ranges in current column
8394 (while (string-match "\\&[-I0-9]+" form)
8395 (setq form (replace-match
8397 (org-table-get-vertical-vector (match-string 0 form)
8400 (setq ev (calc-eval (cons form modes)
8401 (if org-table-formula-numbers-only 'num)))
8403 (when org-table-formula-debug
8404 (with-output-to-temp-buffer "*Help*"
8405 (princ (format "Substitution history of formula
8408 $1-> %s\n" orig formula form))
8410 (princ (format " %s^\nError: %s"
8411 (make-string (car ev) ?\-) (nth 1 ev)))
8412 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
8414 (if fmt (format fmt (string-to-number ev)) ev)))))
8415 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
8416 (unless (and (interactive-p) (not ndown))
8417 (unless (let (inhibit-redisplay)
8418 (y-or-n-p "Debugging Formula. Continue to next? "))
8421 (delete-window (get-buffer-window "*Help*"))
8423 (if (listp ev) (setq fmt nil ev "#ERROR"))
8424 (org-table-justify-field-maybe
8425 (if fmt (format fmt (string-to-number ev)) ev))
8426 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
8427 (call-interactively 'org-return)
8429 (and down (org-table-maybe-recalculate-line))
8430 (or suppress-align (and org-table-may-need-update
8431 (org-table-align)))))
8433 (defun org-table-recalculate (&optional all noalign)
8434 "Recalculate the current table line by applying all stored formulas."
8436 (or (memq this-command org-recalc-commands)
8437 (setq org-recalc-commands (cons this-command org-recalc-commands)))
8438 (unless (org-at-table-p) (error "Not at a table"))
8439 (org-table-get-specials)
8440 (let* ((eqlist (sort (org-table-get-stored-formulas)
8441 (lambda (a b) (string< (car a) (car b)))))
8442 (inhibit-redisplay t)
8443 (line-re org-table-dataline-regexp)
8444 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8445 (thiscol (org-table-current-column))
8446 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
8447 ;; Insert constants in all formulas
8450 (setcdr x (org-table-formula-substitute-names (cdr x)))
8453 ;; Split the equation list
8454 (while (setq eq (pop eqlist))
8455 (if (<= (string-to-char (car eq)) ?9)
8458 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
8461 (setq end (move-marker (make-marker) (1+ (org-table-end))))
8462 (goto-char (setq beg (org-table-begin)))
8463 (if (re-search-forward org-table-calculate-mark-regexp end t)
8464 ;; This is a table with marked lines, only compute selected lines
8465 (setq line-re org-table-recalculate-regexp)
8466 ;; Move forward to the first non-header line
8467 (if (and (re-search-forward org-table-dataline-regexp end t)
8468 (re-search-forward org-table-hline-regexp end t)
8469 (re-search-forward org-table-dataline-regexp end t))
8470 (setq beg (match-beginning 0))
8471 nil))) ;; just leave beg where it is
8472 (setq beg (point-at-bol)
8473 end (move-marker (make-marker) (1+ (point-at-eol)))))
8475 (and all (message "Re-applying formulas to full table..."))
8476 (while (re-search-forward line-re end t)
8477 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
8478 ;; Unprotected line, recalculate
8479 (and all (message "Re-applying formulas to full table...(line %d)"
8480 (setq cnt (1+ cnt))))
8481 (setq org-last-recalc-line (org-current-line))
8483 (while (setq entry (pop eql))
8484 (goto-line org-last-recalc-line)
8485 (org-table-goto-column (string-to-number (car entry)) nil 'force)
8486 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
8487 (goto-line thisline)
8488 (org-table-goto-column thiscol)
8489 (or noalign (and org-table-may-need-update (org-table-align))
8490 (and all (message "Re-applying formulas to %d lines...done" cnt)))
8491 ;; Now do the names fields
8492 (while (setq eq (pop eqlname))
8494 a (assoc name org-table-named-field-locations))
8496 (message "Re-applying formula to named field: %s" name)
8497 (goto-line (nth 1 a))
8498 (org-table-goto-column (nth 2 a))
8499 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
8500 ;; back to initial position
8501 (goto-line thisline)
8502 (org-table-goto-column thiscol)
8503 (or noalign (and org-table-may-need-update (org-table-align))
8504 (and all (message "Re-applying formulas...done")))))
8506 (defun org-table-formula-substitute-names (f)
8507 "Replace $const with values in string F."
8508 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
8509 ;; First, check for column names
8510 (while (setq start (string-match org-table-column-name-regexp f start))
8511 (setq start (1+ start))
8512 (setq a (assoc (match-string 1 f) org-table-column-names))
8513 (setq f (replace-match (concat "$" (cdr a)) t t f)))
8514 ;; Expand ranges to vectors
8515 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
8516 (setq n1 (string-to-number (match-string 1 f))
8517 n2 (string-to-number (match-string 2 f))
8518 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
8519 s (concat "[($" (number-to-string (1- nn1)) ")"))
8520 (loop for i from nn1 upto nn2 do
8521 (setq s (concat s ",($" (int-to-string i) ")")))
8522 (setq s (concat s "]"))
8523 (if (< n2 n1) (setq s (concat "rev(" s ")")))
8524 (setq f (replace-match s t t f)))
8525 ;; Parameters and constants
8527 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
8528 (setq start (1+ start))
8529 (if (setq a (save-match-data
8530 (org-table-get-constant (match-string 1 f))))
8531 (setq f (replace-match (concat "(" a ")") t t f))))
8532 (if org-table-formula-debug
8533 (put-text-property 0 (length f) :orig-formula f1 f))
8536 (defun org-table-get-constant (const)
8537 "Find the value for a parameter or constant in a formula.
8538 Parameters get priority."
8539 (or (cdr (assoc const org-table-local-parameters))
8540 (cdr (assoc const org-table-formula-constants))
8541 (and (fboundp 'constants-get) (constants-get const))
8544 (defvar org-edit-formulas-map (make-sparse-keymap))
8545 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
8546 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
8547 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
8550 (defvar org-window-configuration)
8552 (defun org-table-edit-formulas ()
8553 "Edit the formulas of the current table in a separate buffer."
8555 (unless (org-at-table-p)
8556 (error "Not at a table"))
8557 (org-table-get-specials)
8558 (let ((eql (org-table-get-stored-formulas))
8559 (pos (move-marker (make-marker) (point)))
8560 (wc (current-window-configuration))
8562 (switch-to-buffer-other-window "*Edit Formulas*")
8565 (set (make-local-variable 'org-pos) pos)
8566 (set (make-local-variable 'org-window-configuration) wc)
8567 (use-local-map org-edit-formulas-map)
8568 (setq s "# Edit formulas and finish with `C-c C-c'.
8569 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
8570 # Use `C-c ?' to get information about $name at point.
8571 # To cancel editing, press `C-c C-q'.\n")
8572 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
8574 (while (setq entry (pop eql))
8575 (when (setq loc (assoc (car entry) org-table-named-field-locations))
8576 (setq s (format "# Named formula, referring to column %d in line %d\n"
8577 (nth 2 loc) (nth 1 loc)))
8578 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
8580 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
8581 (remove-text-properties 0 (length s) '(face nil) s)
8583 (goto-char (point-min))
8584 (message "Edit formulas and finish with `C-c C-c'.")))
8586 (defun org-show-variable ()
8587 "Show the location/value of the $ expression at point."
8589 (let (var (pos org-pos) (win (selected-window)) e)
8591 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
8592 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
8593 (setq var (match-string 1))
8594 (error "No variable at point")))
8596 ((setq e (assoc var org-table-named-field-locations))
8597 (switch-to-buffer-other-window (marker-buffer pos))
8598 (goto-line (nth 1 e))
8599 (org-table-goto-column (nth 2 e))
8601 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
8602 ((setq e (assoc var org-table-column-names))
8603 (switch-to-buffer-other-window (marker-buffer pos))
8605 (goto-char (org-table-begin))
8606 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
8609 (goto-char (match-beginning 1))
8610 (message "Named column (column %s)" (cdr e)))
8611 (error "Column name not found"))
8612 (select-window win))
8613 ((string-match "^[0-9]$" var)
8615 (switch-to-buffer-other-window (marker-buffer pos))
8617 (goto-char (org-table-begin))
8619 (if (re-search-forward org-table-dataline-regexp
8622 (goto-char (match-beginning 0))
8623 (org-table-goto-column (string-to-number var))
8624 (message "Column %s" var))
8625 (error "Column name not found"))
8626 (select-window win))
8627 ((setq e (assoc var org-table-local-parameters))
8628 (switch-to-buffer-other-window (marker-buffer pos))
8630 (goto-char (org-table-begin))
8631 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
8633 (goto-char (match-beginning 1))
8634 (message "Local parameter."))
8635 (error "Parameter not found"))
8636 (select-window win))
8639 ((setq e (assoc var org-table-formula-constants))
8640 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
8641 ((setq e (and (fboundp 'constants-get) (constants-get var)))
8642 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
8643 (t (error "Undefined name $%s" var)))))))
8645 (defun org-finish-edit-formulas (&optional arg)
8646 "Parse the buffer for formula definitions and install them.
8647 With prefix ARG, apply the new formulas to the table."
8649 (let ((pos org-pos) eql)
8650 (goto-char (point-min))
8651 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
8652 (push (cons (match-string 1) (match-string 2)) eql))
8653 (set-window-configuration org-window-configuration)
8654 (select-window (get-buffer-window (marker-buffer pos)))
8656 (unless (org-at-table-p)
8657 (error "Lost table position - cannot install formulae"))
8658 (org-table-store-formulas eql)
8659 (move-marker pos nil)
8660 (kill-buffer "*Edit Formulas*")
8662 (org-table-recalculate 'all)
8663 (message "New formulas installed - press C-u C-c C-c to apply."))))
8665 (defun org-abort-edit-formulas ()
8666 "Abort editing formulas, without installing the changes."
8668 (let ((pos org-pos))
8669 (set-window-configuration org-window-configuration)
8670 (select-window (get-buffer-window (marker-buffer pos)))
8672 (message "Formula editing aborted without installing changes")))
8674 ;;; The orgtbl minor mode
8676 ;; Define a minor mode which can be used in other modes in order to
8677 ;; integrate the org-mode table editor.
8679 ;; This is really a hack, because the org-mode table editor uses several
8680 ;; keys which normally belong to the major mode, for example the TAB and
8681 ;; RET keys. Here is how it works: The minor mode defines all the keys
8682 ;; necessary to operate the table editor, but wraps the commands into a
8683 ;; function which tests if the cursor is currently inside a table. If that
8684 ;; is the case, the table editor command is executed. However, when any of
8685 ;; those keys is used outside a table, the function uses `key-binding' to
8686 ;; look up if the key has an associated command in another currently active
8687 ;; keymap (minor modes, major mode, global), and executes that command.
8688 ;; There might be problems if any of the keys used by the table editor is
8689 ;; otherwise used as a prefix key.
8691 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8692 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8693 ;; addresses this by checking explicitly for both bindings.
8695 ;; The optimized version (see variable `orgtbl-optimized') takes over
8696 ;; all keys which are bound to `self-insert-command' in the *global map*.
8697 ;; Some modes bind other commands to simple characters, for example
8698 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
8699 ;; active, this binding is ignored inside tables and replaced with a
8700 ;; modified self-insert.
8702 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
8703 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
8704 In the optimized version, the table editor takes over all simple keys that
8705 normally just insert a character. In tables, the characters are inserted
8706 in a way to minimize disturbing the table structure (i.e. in overwrite mode
8707 for empty fields). Outside tables, the correct binding of the keys is
8710 The default for this option is t if the optimized version is also used in
8711 Org-mode. See the variable `org-enable-table-editor' for details. Changing
8712 this variable requires a restart of Emacs to become effective."
8716 (defvar orgtbl-mode nil
8717 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
8718 table editor in arbitrary modes.")
8719 (make-variable-buffer-local 'orgtbl-mode)
8721 (defvar orgtbl-mode-map (make-keymap)
8722 "Keymap for `orgtbl-mode'.")
8725 (defun turn-on-orgtbl ()
8726 "Unconditionally turn on `orgtbl-mode'."
8730 (defun orgtbl-mode (&optional arg)
8731 "The `org-mode' table editor as a minor mode for use in other modes."
8733 (if (eq major-mode 'org-mode)
8734 ;; Exit without error, in case some hook functions calls this
8735 ;; by accident in org-mode.
8736 (message "Orgtbl-mode is not useful in org-mode, command ignored")
8738 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
8741 (and (orgtbl-setup) (defun orgtbl-setup () nil))
8742 ;; Make sure we are first in minor-mode-map-alist
8743 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
8744 (and c (setq minor-mode-map-alist
8745 (cons c (delq c minor-mode-map-alist)))))
8746 (set (make-local-variable (quote org-table-may-need-update)) t)
8747 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
8748 (add-hook 'before-change-functions 'org-before-change-function
8750 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
8751 auto-fill-inhibit-regexp)
8752 (set (make-local-variable 'auto-fill-inhibit-regexp)
8753 (if auto-fill-inhibit-regexp
8754 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
8756 (easy-menu-add orgtbl-mode-menu)
8757 (run-hooks 'orgtbl-mode-hook))
8758 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
8759 (remove-hook 'before-change-functions 'org-before-change-function t)
8760 (easy-menu-remove orgtbl-mode-menu)
8761 (force-mode-line-update 'all))))
8763 ;; Install it as a minor mode.
8764 (put 'orgtbl-mode :included t)
8765 (put 'orgtbl-mode :menu-tag "Org Table Mode")
8766 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
8768 (defun orgtbl-make-binding (fun n &rest keys)
8769 "Create a function for binding in the table minor mode.
8770 FUN is the command to call inside a table. N is used to create a unique
8771 command name. KEYS are keys that should be checked in for a command
8772 to execute outside of tables."
8775 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
8777 (concat "In tables, run `" (symbol-name fun) "'.\n"
8778 "Outside of tables, run the binding of `"
8779 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8784 (list 'call-interactively (list 'quote fun))
8785 (list 'let '(orgtbl-mode)
8786 (list 'call-interactively
8789 (list 'key-binding k))
8791 '('orgtbl-error))))))))
8793 (defun orgtbl-error ()
8794 "Error when there is no default binding for a table key."
8796 (error "This key is has no function outside tables"))
8798 (defun orgtbl-setup ()
8799 "Setup orgtbl keymaps."
8803 '([(meta shift left)] org-table-delete-column)
8804 '([(meta left)] org-table-move-column-left)
8805 '([(meta right)] org-table-move-column-right)
8806 '([(meta shift right)] org-table-insert-column)
8807 '([(meta shift up)] org-table-kill-row)
8808 '([(meta shift down)] org-table-insert-row)
8809 '([(meta up)] org-table-move-row-up)
8810 '([(meta down)] org-table-move-row-down)
8811 '("\C-c\C-w" org-table-cut-region)
8812 '("\C-c\M-w" org-table-copy-region)
8813 '("\C-c\C-y" org-table-paste-rectangle)
8814 '("\C-c-" org-table-insert-hline)
8815 ; '([(shift tab)] org-table-previous-field)
8816 '("\C-m" org-table-next-row)
8817 (list (org-key 'S-return) 'org-table-copy-down)
8818 '([(meta return)] org-table-wrap-region)
8819 '("\C-c\C-q" org-table-wrap-region)
8820 '("\C-c?" org-table-current-column)
8821 '("\C-c " org-table-blank-field)
8822 '("\C-c+" org-table-sum)
8823 '("\C-c|" org-table-toggle-vline-visibility)
8824 '("\C-c=" org-table-eval-formula)
8825 '("\C-c'" org-table-edit-formulas)
8826 '("\C-c*" org-table-recalculate)
8827 '("\C-c^" org-table-sort-lines)
8828 '([(control ?#)] org-table-rotate-recalc-marks)))
8830 (while (setq elt (pop bindings))
8831 (setq nfunc (1+ nfunc))
8834 cmd (orgtbl-make-binding fun nfunc key))
8835 (define-key orgtbl-mode-map key cmd))
8836 ;; Special treatment needed for TAB and RET
8837 (define-key orgtbl-mode-map [(return)]
8838 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
8839 (define-key orgtbl-mode-map "\C-m"
8840 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
8841 (define-key orgtbl-mode-map [(tab)]
8842 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
8843 (define-key orgtbl-mode-map "\C-i"
8844 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
8845 (define-key orgtbl-mode-map "\C-i"
8846 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
8847 (define-key orgtbl-mode-map "\C-c\C-c"
8848 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
8849 (when orgtbl-optimized
8850 ;; If the user wants maximum table support, we need to hijack
8851 ;; some standard editing functions
8852 (org-remap orgtbl-mode-map
8853 'self-insert-command 'orgtbl-self-insert-command
8854 'delete-char 'orgtbl-delete-char
8855 'delete-backward-char 'orgtbl-delete-backward-char)
8856 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
8857 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
8859 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
8860 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
8861 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
8862 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
8864 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
8865 ["Copy Field from Above"
8866 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
8869 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
8870 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
8871 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
8872 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
8874 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
8875 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
8876 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
8877 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
8878 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
8880 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
8882 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
8883 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
8884 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
8885 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
8887 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
8888 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
8889 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
8890 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
8891 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
8892 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
8893 ["Sum Column/Rectangle" org-table-sum
8894 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
8895 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
8897 (setq org-table-formula-debug (not org-table-formula-debug))
8898 :style toggle :selected org-table-formula-debug]
8902 (defun orgtbl-tab ()
8903 "Justification and field motion for `orgtbl-mode'."
8905 (org-table-justify-field-maybe)
8906 (org-table-next-field))
8908 (defun orgtbl-ret ()
8909 "Justification and field motion for `orgtbl-mode'."
8911 (org-table-justify-field-maybe)
8912 (org-table-next-row))
8914 (defun orgtbl-self-insert-command (N)
8915 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8916 If the cursor is in a table looking at whitespace, the whitespace is
8917 overwritten, and the table is not marked as requiring realignment."
8919 (if (and (org-at-table-p)
8921 (and org-table-auto-blank-field
8922 (member last-command
8923 '(orgtbl-hijacker-command-100
8924 orgtbl-hijacker-command-101
8925 orgtbl-hijacker-command-102
8926 orgtbl-hijacker-command-103
8927 orgtbl-hijacker-command-104
8928 orgtbl-hijacker-command-105))
8929 (org-table-blank-field))
8932 (looking-at "[^|\n]* +|"))
8933 (let (org-table-may-need-update)
8934 (goto-char (1- (match-end 0)))
8935 (delete-backward-char 1)
8936 (goto-char (match-beginning 0))
8937 (self-insert-command N))
8938 (setq org-table-may-need-update t)
8940 (call-interactively (key-binding (vector last-input-event))))))
8942 (defun org-force-self-insert (N)
8943 "Needed to enforce self-insert under remapping."
8945 (self-insert-command N))
8947 (defun orgtbl-delete-backward-char (N)
8948 "Like `delete-backward-char', insert whitespace at field end in tables.
8949 When deleting backwards, in tables this function will insert whitespace in
8950 front of the next \"|\" separator, to keep the table aligned. The table will
8951 still be marked for re-alignment, because a narrow field may lead to a
8952 reduced column width."
8954 (if (and (org-at-table-p)
8956 (string-match "|" (buffer-substring (point-at-bol) (point)))
8957 (looking-at ".*?|"))
8958 (let ((pos (point)))
8959 (backward-delete-char N)
8960 (skip-chars-forward "^|")
8962 (goto-char (1- pos)))
8963 (delete-backward-char N)))
8965 (defun orgtbl-delete-char (N)
8966 "Like `delete-char', but insert whitespace at field end in tables.
8967 When deleting characters, in tables this function will insert whitespace in
8968 front of the next \"|\" separator, to keep the table aligned. The table
8969 will still be marked for re-alignment, because a narrow field may lead to
8970 a reduced column width."
8972 (if (and (org-at-table-p)
8974 (not (= (char-after) ?|))
8976 (if (looking-at ".*?|")
8977 (let ((pos (point)))
8978 (replace-match (concat
8979 (substring (match-string 0) 1 -1)
8986 (defconst org-level-max 20)
8988 (defun org-export-find-first-heading-line (list)
8989 "Remove all lines from LIST which are before the first headline."
8990 (let ((orig-list list)
8991 (re (concat "^" outline-regexp)))
8993 (not (string-match re (car list))))
8995 (or list orig-list)))
8997 (defun org-skip-comments (lines)
8998 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
8999 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
9000 (re2 "^\\(\\*+\\)[ \t\n\r]")
9002 (while (setq line (pop lines))
9004 ((and (string-match re1 line)
9005 (setq level (- (match-end 1) (match-beginning 1))))
9006 ;; Beginning of a COMMENT subtree. Skip it.
9007 (while (and (setq line (pop lines))
9008 (or (not (string-match re2 line))
9009 (> (- (match-end 1) (match-beginning 1)) level))))
9010 (setq lines (cons line lines)))
9011 ((string-match "^#" line)
9012 ;; an ordinary comment line
9014 (t (setq rtn (cons line rtn)))))
9019 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
9020 "Characters for underlining headings in ASCII export.")
9022 (defconst org-html-entities
9062 ("Aring") ("AA"."Å")
9151 ("varepsilon"."ε")
9164 ("sigmaf") ("varsigma"."ς")
9172 ("thetasym") ("vartheta"."ϑ")
9175 ("bull") ("bullet"."•")
9176 ("hellip") ("dots"."…")
9186 ("larr") ("leftarrow"."←") ("gets"."←")
9187 ("uarr") ("uparrow"."↑")
9188 ("rarr") ("to"."→") ("rightarrow"."→")
9189 ("darr")("downarrow"."↓")
9190 ("harr") ("leftrightarrow"."↔")
9191 ("crarr") ("hookleftarrow"."↵") ; has round hook, not quite CR
9192 ("lArr") ("Leftarrow"."⇐")
9193 ("uArr") ("Uparrow"."⇑")
9194 ("rArr") ("Rightarrow"."⇒")
9195 ("dArr") ("Downarrow"."⇓")
9196 ("hArr") ("Leftrightarrow"."⇔")
9198 ("part") ("partial"."∂")
9199 ("exist") ("exists"."∃")
9200 ("empty") ("emptyset"."∅")
9202 ("isin") ("in"."∈")
9208 ("lowast") ("ast"."∗")
9210 ("prop") ("proptp"."∝")
9211 ("infin") ("infty"."∞")
9212 ("ang") ("angle"."∠")
9213 ("and") ("vee"."∧")
9214 ("or") ("wedge"."∨")
9220 ("cong") ("simeq"."≅")
9221 ("asymp")("approx"."≈")
9222 ("ne") ("neq"."≠")
9226 ("sub") ("subset"."⊂")
9227 ("sup") ("supset"."⊃")
9234 ("sdot") ("cdot"."⋅")
9241 ("loz") ("Diamond"."◊")
9242 ("spades") ("spadesuit"."♠")
9243 ("clubs") ("clubsuit"."♣")
9244 ("hearts") ("diamondsuit"."♥")
9245 ("diams") ("diamondsuit"."♦")
9312 "Entities for TeX->HTML translation.
9313 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
9314 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
9315 In that case, \"\\ent\" will be translated to \"&other;\".
9316 The list contains HTML entities for Latin-1, Greek and other symbols.
9317 It is supplemented by a number of commonly used TeX macros with appropriate
9318 translations. There is currently no way for users to extend this.")
9320 (defvar org-last-level nil) ; dynamically scoped variable
9322 (defun org-export-as-ascii (arg)
9323 "Export the outline as a pretty ASCII file.
9324 If there is an active region, export only the region.
9325 The prefix ARG specifies how many levels of the outline should become
9326 underlined headlines. The default is 3."
9328 (setq-default org-todo-line-regexp org-todo-line-regexp)
9331 (if (org-region-active-p) (region-beginning) (point-min))
9332 (if (org-region-active-p) (region-end) (point-max))))
9333 (lines (org-export-find-first-heading-line
9334 (org-skip-comments (org-split-string region "[\r\n]"))))
9335 (org-startup-with-deadline-check nil)
9338 (case-fold-search nil)
9339 (filename (concat (file-name-sans-extension (buffer-file-name))
9341 (buffer (find-file-noselect filename))
9342 (levels-open (make-vector org-level-max nil))
9343 (date (format-time-string "%Y/%m/%d" (current-time)))
9344 (time (format-time-string "%X" (current-time)))
9345 (author user-full-name)
9346 (title (buffer-name))
9348 (email user-mail-address)
9349 (language org-export-default-language)
9354 (setq org-last-level 1)
9355 (org-init-section-numbers)
9357 (find-file-noselect filename)
9359 ;; Search for the export key lines
9360 (org-parse-key-lines)
9362 (setq lang-words (or (assoc language org-export-language-setup)
9363 (assoc "en" org-export-language-setup)))
9364 (if org-export-ascii-show-new-buffer
9365 (switch-to-buffer-other-window buffer)
9366 (set-buffer buffer))
9369 (if options (org-parse-export-options options))
9370 (setq umax (if arg (prefix-numeric-value arg)
9371 org-export-headline-levels))
9374 (if title (org-insert-centered title ?=))
9376 (if (or author email)
9377 (insert (concat (nth 1 lang-words) ": " (or author "")
9378 (if email (concat " <" email ">") "")
9381 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
9382 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
9386 (if org-export-with-toc
9388 (insert (nth 3 lang-words) "\n"
9389 (make-string (length (nth 3 lang-words)) ?=) "\n")
9390 (mapcar '(lambda (line)
9391 (if (string-match org-todo-line-regexp
9393 ;; This is a headline
9395 (setq level (- (match-end 1) (match-beginning 1))
9396 txt (match-string 3 line)
9398 (or (and (match-beginning 2)
9399 (not (equal (match-string 2 line)
9403 (org-search-todo-below
9404 line lines level))))
9405 (setq txt (org-html-expand-for-ascii txt))
9407 (if org-export-with-section-numbers
9408 (setq txt (concat (org-section-number level)
9413 (make-string (* (1- level) 4) ?\ )
9414 (format (if todo "%s (*)\n" "%s\n") txt))
9415 (setq org-last-level level))
9419 (org-init-section-numbers)
9420 (while (setq line (pop lines))
9421 ;; Remove the quoted HTML tags.
9422 (setq line (org-html-expand-for-ascii line))
9424 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
9426 (setq level (- (match-end 1) (match-beginning 1))
9427 txt (match-string 2 line))
9428 (org-ascii-level-start level txt umax))
9429 (t (insert line "\n"))))
9432 (goto-char (point-min))))
9434 (defun org-search-todo-below (line lines level)
9435 "Search the subtree below LINE for any TODO entries."
9436 (let ((rest (cdr (memq line lines)))
9437 (re org-todo-line-regexp)
9440 (while (setq line (pop rest))
9441 (if (string-match re line)
9443 (setq lv (- (match-end 1) (match-beginning 1))
9444 todo (and (match-beginning 2)
9445 (not (equal (match-string 2 line)
9448 (if (<= lv level) (throw 'exit nil))
9449 (if todo (throw 'exit t))))))))
9451 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
9452 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
9453 (defun org-html-expand-for-ascii (line)
9454 "Handle quoted HTML for ASCII export."
9455 (if org-export-html-expand
9456 (while (string-match "@<[^<>\n]*>" line)
9457 ;; We just remove the tags for now.
9458 (setq line (replace-match "" nil nil line))))
9461 (defun org-insert-centered (s &optional underline)
9462 "Insert the string S centered and underline it with character UNDERLINE."
9463 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
9464 (insert (make-string ind ?\ ) s "\n")
9466 (insert (make-string ind ?\ )
9467 (make-string (length s) underline)
9470 (defun org-ascii-level-start (level title umax)
9471 "Insert a new level in ASCII export."
9474 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
9475 (if (or (not (equal (char-before) ?\n))
9476 (not (equal (char-before (1- (point))) ?\n)))
9478 (setq char (nth (- umax level) (reverse org-ascii-underline)))
9479 (if org-export-with-section-numbers
9480 (setq title (concat (org-section-number level) " " title)))
9481 (insert title "\n" (make-string (string-width title) char) "\n"))))
9483 (defun org-export-copy-visible ()
9484 "Copy the visible part of the buffer to another buffer, for printing.
9485 Also removes the first line of the buffer if it specifies a mode,
9486 and all options lines."
9488 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
9490 (buffer (find-file-noselect filename))
9492 (org-make-options-regexp
9493 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
9495 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
9496 (if org-noutline-p "\\(\n\\|$\\)" "")))
9498 (with-current-buffer buffer
9502 (setq s (goto-char (point-min)))
9503 (while (not (= (point) (point-max)))
9504 (goto-char (org-find-invisible))
9505 (append-to-buffer buffer s (point))
9506 (setq s (goto-char (org-find-visible)))))
9507 (switch-to-buffer-other-window buffer)
9509 (goto-char (point-min))
9510 (if (looking-at ".*-\\*- mode:.*\n")
9512 (while (re-search-forward ore nil t)
9514 (goto-char (point-min))))
9516 (defun org-find-visible ()
9517 (if (featurep 'noutline)
9519 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
9520 (get-char-property s 'invisible)))
9522 (skip-chars-forward "^\n")
9524 (defun org-find-invisible ()
9525 (if (featurep 'noutline)
9527 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
9528 (not (get-char-property s 'invisible))))
9530 (skip-chars-forward "^\r")
9535 (defun org-get-current-options ()
9536 "Return a string with current options as keyword options.
9537 Does include HTML export options as well as TODO and CATEGORY stuff."
9543 #+TEXT: Some descriptive text to be emitted. Several lines OK.
9544 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
9551 (buffer-name) (user-full-name) user-mail-address org-export-default-language
9552 org-export-headline-levels
9553 org-export-with-section-numbers
9555 org-export-preserve-breaks
9556 org-export-html-expand
9557 org-export-with-fixed-width
9558 org-export-with-tables
9559 org-export-with-sub-superscripts
9560 org-export-with-emphasize
9561 org-export-with-TeX-macros
9562 (file-name-nondirectory (buffer-file-name))
9563 (if (equal org-todo-interpretation 'sequence)
9564 (mapconcat 'identity org-todo-keywords " ")
9565 "TODO FEEDBACK VERIFY DONE")
9566 (if (equal org-todo-interpretation 'type)
9567 (mapconcat 'identity org-todo-keywords " ")
9568 "Me Jason Marie DONE")
9569 (cdr (assoc org-startup-folded
9570 '((nil . "nofold")(t . "fold")(content . "content"))))
9571 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
9572 org-archive-location
9575 (defun org-insert-export-options-template ()
9576 "Insert into the buffer a template with information for exporting."
9578 (if (not (bolp)) (newline))
9579 (let ((s (org-get-current-options)))
9580 (and (string-match "#\\+CATEGORY" s)
9581 (setq s (substring s 0 (match-beginning 0))))
9584 (defun org-toggle-fixed-width-section (arg)
9585 "Toggle the fixed-width export.
9586 If there is no active region, the QUOTE keyword at the current headline is
9587 inserted or removed. When present, it causes the text between this headline
9588 and the next to be exported as fixed-width text, and unmodified.
9589 If there is an active region, this command adds or removes a colon as the
9590 first character of this line. If the first character of a line is a colon,
9591 this line is also exported in fixed-width font."
9594 (regionp (org-region-active-p))
9595 (beg (if regionp (region-beginning) (point)))
9596 (end (if regionp (region-end)))
9597 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
9598 (re "[ \t]*\\(:\\)")
9603 (setq cc (current-column))
9604 (beginning-of-line 1)
9605 (setq off (looking-at re))
9607 (setq nlines (1- nlines))
9608 (beginning-of-line 1)
9611 (move-to-column cc t)
9614 ((and off (looking-at re))
9615 (replace-match "" t t nil 1))
9616 ((not off) (move-to-column cc t) (insert ":")))
9619 (org-back-to-heading)
9620 (if (looking-at (concat outline-regexp
9621 "\\( +\\<" org-quote-string "\\>\\)"))
9622 (replace-match "" t t nil 1)
9623 (if (looking-at outline-regexp)
9625 (goto-char (match-end 0))
9626 (insert " " org-quote-string))))))))
9628 (defun org-export-as-html-and-open (arg)
9629 "Export the outline as HTML and immediately open it with a browser.
9630 If there is an active region, export only the region.
9631 The prefix ARG specifies how many levels of the outline should become
9632 headlines. The default is 3. Lower levels will become bulleted lists."
9634 (org-export-as-html arg 'hidden)
9635 (org-open-file (buffer-file-name)))
9637 (defun org-export-as-html-batch ()
9638 "Call `org-export-as-html', may be used in batch processing as
9640 --load=$HOME/lib/emacs/org.el
9641 --eval \"(setq org-export-headline-levels 2)\"
9642 --visit=MyFile --funcall org-export-as-html-batch"
9643 (org-export-as-html org-export-headline-levels 'hidden))
9645 (defun org-export-as-html (arg &optional hidden)
9646 "Export the outline as a pretty HTML file.
9647 If there is an active region, export only the region.
9648 The prefix ARG specifies how many levels of the outline should become
9649 headlines. The default is 3. Lower levels will become bulleted lists."
9651 (setq-default org-todo-line-regexp org-todo-line-regexp)
9652 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
9653 (setq-default org-done-string org-done-string)
9654 (let* ((style org-export-html-style)
9655 (region-p (org-region-active-p))
9658 (if region-p (region-beginning) (point-min))
9659 (if region-p (region-end) (point-max))))
9661 (org-skip-comments (org-split-string region "[\r\n]")))
9662 (lines (org-export-find-first-heading-line all_lines))
9663 (level 0) (line "") (origline "") txt todo
9665 (filename (concat (file-name-sans-extension (buffer-file-name))
9667 (buffer (find-file-noselect filename))
9668 (levels-open (make-vector org-level-max nil))
9669 (date (format-time-string "%Y/%m/%d" (current-time)))
9670 (time (format-time-string "%X" (current-time)))
9671 (author user-full-name)
9672 (title (buffer-name))
9674 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
9678 (local-list-num nil)
9679 (local-list-indent nil)
9680 (llt org-plain-list-ordered-item-terminator)
9681 (email user-mail-address)
9682 (language org-export-default-language)
9687 ;; FIXME: The following returns always nil under XEmacs
9688 (coding-system (and (fboundp 'coding-system-get)
9689 (boundp 'buffer-file-coding-system)
9690 buffer-file-coding-system))
9691 (coding-system-for-write (or coding-system coding-system-for-write))
9692 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
9693 (charset (and coding-system
9694 (coding-system-get coding-system 'mime-charset)))
9696 table-buffer table-orig-buffer
9697 ind start-is-num starter
9699 (message "Exporting...")
9701 (setq org-last-level 1)
9702 (org-init-section-numbers)
9704 ;; Search for the export key lines
9705 (org-parse-key-lines)
9706 (setq lang-words (or (assoc language org-export-language-setup)
9707 (assoc "en" org-export-language-setup)))
9709 ;; Switch to the output buffer
9710 (if (or hidden (not org-export-html-show-new-buffer))
9712 (switch-to-buffer-other-window buffer))
9715 (let ((case-fold-search nil))
9716 (if options (org-parse-export-options options))
9717 (setq umax (if arg (prefix-numeric-value arg)
9718 org-export-headline-levels))
9722 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
9723 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
9724 <html lang=\"%s\"><head>
9726 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
9727 <meta name=generator content=\"Org-mode\">
9728 <meta name=generated content=\"%s %s\">
9729 <meta name=author content=\"%s\">
9733 language (org-html-expand title) (or charset "iso-8859-1")
9734 date time author style))
9735 (if title (insert (concat "<H1 class=\"title\">"
9736 (org-html-expand title) "</H1>\n")))
9737 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
9738 (if email (insert (concat "<a href=\"mailto:" email "\"><"
9739 email "></a>\n")))
9740 (if (or author email) (insert "<br>\n"))
9741 (if (and date time) (insert (concat (nth 2 lang-words) ": "
9742 date " " time "<br>\n")))
9743 (if text (insert (concat "<p>\n" (org-html-expand text))))
9744 (if org-export-with-toc
9746 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
9748 (mapcar '(lambda (line)
9749 (if (string-match org-todo-line-regexp line)
9750 ;; This is a headline
9752 (setq level (- (match-end 1) (match-beginning 1))
9753 txt (save-match-data
9755 (match-string 3 line)))
9757 (or (and (match-beginning 2)
9758 (not (equal (match-string 2 line)
9762 (org-search-todo-below
9763 line lines level))))
9764 (if org-export-with-section-numbers
9765 (setq txt (concat (org-section-number level)
9769 (setq head-count (+ head-count 1))
9770 (if (> level org-last-level)
9772 (setq cnt (- level org-last-level))
9773 (while (>= (setq cnt (1- cnt)) 0)
9776 (if (< level org-last-level)
9778 (setq cnt (- org-last-level level))
9779 (while (>= (setq cnt (1- cnt)) 0)
9785 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
9786 "<li><a href=\"#sec-%d\">%s</a>\n")
9788 (setq org-last-level level))
9791 (while (> org-last-level 0)
9792 (setq org-last-level (1- org-last-level))
9796 (org-init-section-numbers)
9798 (while (setq line (pop lines) origline line)
9801 ;; end of quote section?
9802 (when (and inquote (string-match "^\\*+" line))
9805 ;; inside a quote section?
9807 (insert (org-html-protect line) "\n")
9808 (throw 'nextline nil))
9811 (when (and org-export-with-fixed-width
9812 (string-match "^[ \t]*:\\(.*\\)" line))
9816 (insert (org-html-protect (match-string 1 line)) "\n")
9818 (not (string-match "^[ \t]*\\(:.*\\)"
9821 (insert "</pre>\n"))
9822 (throw 'nextline nil))
9824 ;; Protect the links
9826 (while (string-match org-link-maybe-angles-regexp line start)
9827 (setq start (match-end 0))
9828 (setq line (replace-match
9829 (concat "\000" (match-string 1 line) "\000")
9832 ;; replace "&" by "&", "<" and ">" by "<" and ">"
9833 ;; handle @<..> HTML tags (replace "@>..<" by "<..>")
9834 (setq line (org-html-expand line))
9838 (while (string-match org-protected-link-regexp line start)
9839 (setq start (- (match-end 0) 2))
9840 (setq type (match-string 1 line))
9842 ((member type '("http" "https" "ftp" "mailto" "news"))
9844 (setq line (replace-match
9845 ; "<a href=\"\\1:\\2\"><\\1:\\2></a>"
9846 "<a href=\"\\1:\\2\">\\1:\\2</a>"
9848 ((string= type "file")
9850 (let* ((filename (match-string 2 line))
9851 (abs-p (file-name-absolute-p filename))
9852 (thefile (if abs-p (expand-file-name filename) filename))
9853 (thefile (save-match-data
9854 (if (string-match ":[0-9]+$" thefile)
9855 (replace-match "" t t thefile)
9859 (string-match (org-image-file-name-regexp) thefile))))
9860 (setq line (replace-match
9861 (if (and org-export-html-inline-images
9863 (concat "<img src=\"" thefile "\"/>")
9864 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
9867 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
9868 (setq line (replace-match
9869 "<i><\\1:\\2></i>" nil nil line)))))
9872 (if (and (string-match org-todo-line-regexp line)
9873 (match-beginning 2))
9874 (if (equal (match-string 2 line) org-done-string)
9875 (setq line (replace-match
9876 "<span class=\"done\">\\2</span>"
9878 (setq line (replace-match "<span class=\"todo\">\\2</span>"
9882 (if (string-match org-deadline-line-regexp line)
9884 (if (save-match-data
9885 (string-match "<a href"
9886 (substring line 0 (match-beginning 0))))
9887 nil ; Don't do the replacement - it is inside a link
9888 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
9891 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
9892 ;; This is a headline
9893 (setq level (- (match-end 1) (match-beginning 1))
9894 txt (match-string 2 line))
9895 (if (<= level umax) (setq head-count (+ head-count 1)))
9897 ;; Close any local lists before inserting a new header line
9898 (while local-list-num
9899 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
9900 (pop local-list-num))
9901 (setq local-list-indent nil
9903 (org-html-level-start level txt umax
9904 (and org-export-with-toc (<= level umax))
9907 (when (string-match quote-re line)
9911 ((and org-export-with-tables
9912 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
9913 (if (not table-open)
9915 (setq table-open t table-buffer nil table-orig-buffer nil))
9917 (setq table-buffer (cons line table-buffer)
9918 table-orig-buffer (cons origline table-orig-buffer))
9919 (when (or (not lines)
9920 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
9922 (setq table-open nil
9923 table-buffer (nreverse table-buffer)
9924 table-orig-buffer (nreverse table-orig-buffer))
9925 (insert (org-format-table-html table-buffer table-orig-buffer))))
9928 (when (and (> org-export-plain-list-max-depth 0)
9931 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
9932 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
9933 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
9934 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
9936 (setq ind (org-get-string-indentation line)
9937 start-is-num (match-beginning 4)
9938 starter (if (match-beginning 2) (match-string 2 line))
9939 line (substring line (match-beginning 5)))
9940 (unless (string-match "[^ \t]" line)
9941 ;; empty line. Pretend indentation is large.
9942 (setq ind (1+ (or (car local-list-indent) 1))))
9943 (while (and in-local-list
9944 (or (and (= ind (car local-list-indent))
9946 (< ind (car local-list-indent))))
9947 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
9948 (pop local-list-num) (pop local-list-indent)
9949 (setq in-local-list local-list-indent))
9952 (or (not in-local-list)
9953 (> ind (car local-list-indent)))
9954 (< (length local-list-indent)
9955 org-export-plain-list-max-depth))
9956 ;; Start new (level of ) list
9957 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
9958 (push start-is-num local-list-num)
9959 (push ind local-list-indent)
9960 (setq in-local-list t))
9962 ;; continue current list
9963 (insert "<li>\n"))))
9964 ;; Empty lines start a new paragraph. If hand-formatted lists
9965 ;; are not fully interpreted, lines starting with "-", "+", "*"
9966 ;; also start a new paragraph.
9967 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
9968 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
9970 (if org-export-html-with-timestamp
9971 (insert org-export-html-html-helper-timestamp))
9972 (insert "</body>\n</html>\n")
9975 (goto-char (point-min)))))
9977 (defun org-format-table-html (lines olines)
9978 "Find out which HTML converter to use and return the HTML code."
9979 (if (string-match "^[ \t]*|" (car lines))
9980 ;; A normal org table
9981 (org-format-org-table-html lines)
9982 ;; Table made by table.el - test for spanning
9983 (let* ((hlines (delq nil (mapcar
9985 (if (string-match "^[ \t]*\\+-" x) x
9988 (first (car hlines))
9989 (ll (and (string-match "\\S-+" first)
9990 (match-string 0 first)))
9991 (re (concat "^[ \t]*" (regexp-quote ll)))
9992 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
9994 (if (and (not spanning)
9995 (not org-export-prefer-native-exporter-for-tables))
9996 ;; We can use my own converter with HTML conversions
9997 (org-format-table-table-html lines)
9998 ;; Need to use the code generator in table.el, with the original text.
9999 (org-format-table-table-html-using-table-generate-source olines)))))
10001 (defun org-format-org-table-html (lines)
10002 "Format a table into html."
10003 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10004 (setq lines (nreverse lines))
10005 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10006 (setq lines (nreverse lines))
10007 (let ((head (and org-export-highlight-first-table-line
10009 (lambda (x) (string-match "^[ \t]*|-" x))
10012 (setq html (concat org-export-html-table-tag "\n"))
10013 (while (setq line (pop lines))
10015 (if (string-match "^[ \t]*|-" line)
10017 (setq head nil) ;; head ends here, first time around
10018 ;; ignore this line
10019 (throw 'next-line t)))
10020 ;; Break the line into fields
10021 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10025 (mapconcat (lambda (x)
10027 (concat "<th>" x "</th>")
10028 (concat "<td>" x "</td>")))
10031 (setq html (concat html "</table>\n"))
10034 (defun org-fake-empty-table-line (line)
10035 "Replace everything except \"|\" with spaces."
10036 (let ((i (length line))
10037 (newstr (copy-sequence line)))
10040 (if (not (eq (aref newstr i) ?|))
10041 (aset newstr i ?\ )))
10044 (defun org-format-table-table-html (lines)
10045 "Format a table generated by table.el into html.
10046 This conversion does *not* use `table-generate-source' from table.el.
10047 This has the advantage that Org-mode's HTML conversions can be used.
10048 But it has the disadvantage, that no cell- or row-spanning is allowed."
10049 (let (line field-buffer
10050 (head org-export-highlight-first-table-line)
10052 (setq html (concat org-export-html-table-tag "\n"))
10053 (while (setq line (pop lines))
10054 (setq empty " ")
10056 (if (string-match "^[ \t]*\\+-" line)
10065 (if (equal x "") (setq x empty))
10067 (concat "<th>" x "</th>\n")
10068 (concat "<td>" x "</td>\n")))
10072 (setq field-buffer nil)))
10073 ;; Ignore this line
10074 (throw 'next-line t)))
10075 ;; Break the line into fields and store the fields
10076 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10078 (setq field-buffer (mapcar
10080 (concat x "<br>" (pop fields)))
10082 (setq field-buffer fields))))
10083 (setq html (concat html "</table>\n"))
10086 (defun org-format-table-table-html-using-table-generate-source (lines)
10087 "Format a table into html, using `table-generate-source' from table.el.
10088 This has the advantage that cell- or row-spanning is allowed.
10089 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
10091 (with-current-buffer (get-buffer-create " org-tmp1 ")
10093 (insert (mapconcat 'identity lines "\n"))
10094 (goto-char (point-min))
10095 (if (not (re-search-forward "|[^+]" nil t))
10096 (error "Error processing table"))
10097 (table-recognize-table)
10098 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
10099 (table-generate-source 'html " org-tmp2 ")
10100 (set-buffer " org-tmp2 ")
10101 (buffer-substring (point-min) (point-max))))
10103 (defun org-html-protect (s)
10104 ;; convert & to &, < to < and > to >
10106 (while (string-match "&" s start)
10107 (setq s (replace-match "&" t t s)
10108 start (1+ (match-beginning 0))))
10109 (while (string-match "<" s)
10110 (setq s (replace-match "<" t t s)))
10111 (while (string-match ">" s)
10112 (setq s (replace-match ">" t t s))))
10115 (defun org-html-expand (string)
10116 "Prepare STRING for HTML export. Applies all active conversions."
10117 ;; First check if there is a link in the line - if yes, apply conversions
10118 ;; only before the start of the link.
10119 ;; FIXME: This is no longer correct, because links now have an end.
10120 (let* ((m (string-match org-link-regexp string))
10121 (s (if m (substring string 0 m) string))
10122 (r (if m (substring string m) "")))
10123 ;; convert & to &, < to < and > to >
10124 (setq s (org-html-protect s))
10125 (if org-export-html-expand
10126 (while (string-match "@<\\([^&]*\\)>" s)
10127 (setq s (replace-match "<\\1>" nil nil s))))
10128 (if org-export-with-emphasize
10129 (setq s (org-export-html-convert-emphasize s)))
10130 (if org-export-with-sub-superscripts
10131 (setq s (org-export-html-convert-sub-super s)))
10132 (if org-export-with-TeX-macros
10133 (let ((start 0) wd ass)
10134 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
10135 (setq wd (match-string 1 s))
10136 (if (setq ass (assoc wd org-html-entities))
10137 (setq s (replace-match (or (cdr ass)
10138 (concat "&" (car ass) ";"))
10140 (setq start (+ start (length wd)))))))
10143 (defun org-create-multibrace-regexp (left right n)
10144 "Create a regular expression which will match a balanced sexp.
10145 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
10146 as single character strings.
10147 The regexp returned will match the entire expression including the
10148 delimiters. It will also define a single group which contains the
10149 match except for the outermost delimiters. The maximum depth of
10150 stacked delimiters is N. Escaping delimiters is not possible."
10151 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
10154 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
10157 re (concat re or next)
10158 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
10159 (concat left "\\(" re "\\)" right)))
10161 (defvar org-match-substring-regexp
10163 "\\([^\\]\\)\\([_^]\\)\\("
10164 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
10166 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
10168 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
10169 "The regular expression matching a sub- or superscript.")
10171 (defun org-export-html-convert-sub-super (string)
10172 "Convert sub- and superscripts in STRING to HTML."
10174 (while (string-match org-match-substring-regexp string)
10175 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
10176 (setq c (or (match-string 8 string)
10177 (match-string 6 string)
10178 (match-string 5 string)))
10179 (setq string (replace-match
10180 (concat (match-string 1 string)
10181 "<" key ">" c "</" key ">")
10183 (while (string-match "\\\\\\([_^]\\)" string)
10184 (setq string (replace-match (match-string 1 string) t t string))))
10187 (defun org-export-html-convert-emphasize (string)
10188 (while (string-match
10189 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
10191 (setq string (replace-match
10192 (concat "<b>" (match-string 3 string) "</b>")
10194 (while (string-match
10195 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
10197 (setq string (replace-match
10198 (concat "<i>" (match-string 3 string) "</i>")
10200 (while (string-match
10201 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
10203 (setq string (replace-match
10204 (concat "<u>" (match-string 3 string) "</u>")
10208 (defun org-parse-key-lines ()
10209 "Find the special key lines with the information for exporters."
10212 (let ((re (org-make-options-regexp
10213 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
10215 (while (re-search-forward re nil t)
10216 (setq key (match-string 1))
10217 (cond ((string-equal key "TITLE")
10218 (setq title (match-string 2)))
10219 ((string-equal key "AUTHOR")
10220 (setq author (match-string 2)))
10221 ((string-equal key "EMAIL")
10222 (setq email (match-string 2)))
10223 ((string-equal key "LANGUAGE")
10224 (setq language (match-string 2)))
10225 ((string-equal key "TEXT")
10226 (setq text (concat text "\n" (match-string 2))))
10227 ((string-equal key "OPTIONS")
10228 (setq options (match-string 2))))))))
10230 (defun org-parse-export-options (s)
10231 "Parse the export options line."
10232 (let ((op '(("H" . org-export-headline-levels)
10233 ("num" . org-export-with-section-numbers)
10234 ("toc" . org-export-with-toc)
10235 ("\\n" . org-export-preserve-breaks)
10236 ("@" . org-export-html-expand)
10237 (":" . org-export-with-fixed-width)
10238 ("|" . org-export-with-tables)
10239 ("^" . org-export-with-sub-superscripts)
10240 ("*" . org-export-with-emphasize)
10241 ("TeX" . org-export-with-TeX-macros)))
10243 (while (setq o (pop op))
10244 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
10246 (set (make-local-variable (cdr o))
10247 (car (read-from-string (match-string 1 s))))))))
10249 (defun org-html-level-start (level title umax with-toc head-count)
10250 "Insert a new level in HTML export."
10251 (let ((l (1+ (max level umax))))
10252 (while (<= l org-level-max)
10253 (if (aref levels-open (1- l))
10255 (org-html-level-close l)
10256 (aset levels-open (1- l) nil)))
10260 (if (aref levels-open (1- level))
10261 (insert "<li>" title "<p>\n")
10262 (aset levels-open (1- level) t)
10263 (insert "<ul><li>" title "<p>\n")))
10264 (if org-export-with-section-numbers
10265 (setq title (concat (org-section-number level) " " title)))
10266 (setq level (+ level 1))
10268 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
10269 level head-count title level))
10270 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
10272 (defun org-html-level-close (&rest args)
10273 "Terminate one level in HTML export."
10276 ;; Variable holding the vector with section numbers
10277 (defvar org-section-numbers (make-vector org-level-max 0))
10279 (defun org-init-section-numbers ()
10280 "Initialize the vector for the section numbers."
10282 (numbers (nreverse (org-split-string "" "\\.")))
10283 (depth (1- (length org-section-numbers)))
10284 (i depth) number-string)
10287 (aset org-section-numbers i 0)
10288 (setq number-string (or (car numbers) "0"))
10289 (if (string-match "\\`[A-Z]\\'" number-string)
10290 (aset org-section-numbers i
10291 (- (string-to-char number-string) ?A -1))
10292 (aset org-section-numbers i (string-to-number number-string)))
10296 (defun org-section-number (&optional level)
10297 "Return a string with the current section number.
10298 When LEVEL is non-nil, increase section numbers on that level."
10299 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
10302 (aset org-section-numbers
10303 level (1+ (aref org-section-numbers level))))
10304 (setq idx (1+ level))
10305 (while (<= idx depth)
10306 (if (not (= idx 1))
10307 (aset org-section-numbers idx 0))
10308 (setq idx (1+ idx))))
10310 (while (<= idx depth)
10311 (setq n (aref org-section-numbers idx))
10312 (setq string (concat string (if (not (string= string "")) "." "")
10313 (int-to-string n)))
10314 (setq idx (1+ idx)))
10316 (if (string-match "\\`\\([@0]\\.\\)+" string)
10317 (setq string (replace-match "" nil nil string)))
10318 (if (string-match "\\(\\.0\\)+\\'" string)
10319 (setq string (replace-match "" nil nil string))))
10323 (defun org-export-icalendar-this-file ()
10324 "Export current file as an iCalendar file.
10325 The iCalendar file will be located in the same directory as the Org-mode
10326 file, but with extension `.ics'."
10328 (org-export-icalendar nil (buffer-file-name)))
10331 (defun org-export-icalendar-all-agenda-files ()
10332 "Export all files in `org-agenda-files' to iCalendar .ics files.
10333 Each iCalendar file will be located in the same directory as the Org-mode
10334 file, but with extension `.ics'."
10336 (apply 'org-export-icalendar nil org-agenda-files))
10339 (defun org-export-icalendar-combine-agenda-files ()
10340 "Export all files in `org-agenda-files' to a single combined iCalendar file.
10341 The file is stored under the name `org-combined-agenda-icalendar-file'."
10343 (apply 'org-export-icalendar t org-agenda-files))
10345 (defun org-export-icalendar (combine &rest files)
10346 "Create iCalendar files for all elements of FILES.
10347 If COMBINE is non-nil, combine all calendar entries into a single large
10348 file and store it under the name `org-combined-agenda-icalendar-file'."
10350 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
10352 (setq ical-file org-combined-agenda-icalendar-file
10353 ical-buffer (org-get-agenda-file-buffer ical-file))
10354 (set-buffer ical-buffer) (erase-buffer))
10355 (while (setq file (pop files))
10357 (org-check-agenda-file file)
10359 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
10360 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
10361 (set-buffer ical-buffer) (erase-buffer))
10362 (set-buffer (org-get-agenda-file-buffer file))
10363 (setq category (or org-category
10364 (file-name-sans-extension
10365 (file-name-nondirectory (buffer-file-name)))))
10366 (if (symbolp category) (setq category (symbol-name category)))
10367 (let ((standard-output ical-buffer))
10369 (and (not started) (setq started t)
10370 (org-start-icalendar-file org-icalendar-combined-name))
10371 (org-start-icalendar-file category))
10372 (org-print-icalendar-entries combine category)
10373 (when (or (and combine (not files)) (not combine))
10374 (org-finish-icalendar-file)
10375 (set-buffer ical-buffer)
10377 (run-hooks 'org-after-save-iCalendar-file-hook)))))
10378 (org-release-buffers org-agenda-new-buffers))))
10380 (defvar org-after-save-iCalendar-file-hook nil
10381 "Hook run after an iCalendar file has been saved.
10382 The iCalendar buffer is still current when this hook is run.
10383 A good way to use this is to tell a desktop calenndar application to re-read
10384 the iCalendar file.")
10386 (defun org-print-icalendar-entries (&optional combine category)
10387 "Print iCalendar entries for the current Org-mode file to `standard-output'.
10388 When COMBINE is non nil, add the category to each line."
10389 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
10390 (dts (org-ical-ts-to-string
10391 (format-time-string (cdr org-time-stamp-formats) (current-time))
10393 hd ts ts2 state (inc t) pos scheduledp deadlinep donep tmp pri)
10395 (goto-char (point-min))
10396 (while (re-search-forward org-ts-regexp nil t)
10397 (setq pos (match-beginning 0)
10398 ts (match-string 0)
10400 hd (org-get-heading))
10401 (if (looking-at re2)
10403 (goto-char (match-end 0))
10404 (setq ts2 (match-string 1) inc nil))
10406 tmp (buffer-substring (max (point-min)
10407 (- pos org-ds-keyword-length))
10409 deadlinep (string-match org-deadline-regexp tmp)
10410 scheduledp (string-match org-scheduled-regexp tmp)
10411 donep (org-entry-is-done-p)))
10412 (if (or (string-match org-tr-regexp hd)
10413 (string-match org-ts-regexp hd))
10414 (setq hd (replace-match "" t t hd)))
10416 (setq hd (concat hd " (category " category ")")))
10417 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
10418 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
10419 (princ (format "BEGIN:VEVENT
10424 (org-ical-ts-to-string ts "DTSTART")
10425 (org-ical-ts-to-string ts2 "DTEND" inc)
10427 (when org-icalendar-include-todo
10428 (goto-char (point-min))
10429 (while (re-search-forward org-todo-line-regexp nil t)
10430 (setq state (match-string 1))
10431 (unless (equal state org-done-string)
10432 (setq hd (match-string 3))
10433 (if (string-match org-priority-regexp hd)
10434 (setq pri (string-to-char (match-string 2 hd))
10435 hd (concat (substring hd 0 (match-beginning 1))
10436 (substring hd (- (match-end 1)))))
10437 (setq pri org-default-priority))
10438 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
10439 (- org-lowest-priority ?A))))))
10441 (princ (format "BEGIN:VTODO
10449 (defun org-start-icalendar-file (name)
10450 "Start an iCalendar file by inserting the header."
10451 (let ((user user-full-name)
10452 (calname "something")
10453 (name (or name "unknown"))
10454 (timezone "Europe/Amsterdam")) ;; FIXME: How can I get the real timezone?
10456 (format "BEGIN:VCALENDAR
10459 PRODID:-//%s//Emacs with Org-mode//EN
10461 CALSCALE:GREGORIAN\n" name user timezone))))
10463 (defun org-finish-icalendar-file ()
10464 "Finish an iCalendar file by inserting the END statement."
10465 (princ "END:VCALENDAR\n"))
10467 (defun org-ical-ts-to-string (s keyword &optional inc)
10468 "Take a time string S and convert it to iCalendar format.
10469 KEYWORD is added in front, to make a complete line like DTSTART....
10470 When INC is non-nil, increase the hour by two (if time string contains
10471 a time), or the day by one (if it does not contain a time)."
10472 (let ((t1 (org-parse-time-string s 'nodefault))
10473 t2 fmt have-time time)
10474 (if (and (car t1) (nth 1 t1) (nth 2 t1))
10475 (setq t2 t1 have-time t)
10476 (setq t2 (org-parse-time-string s)))
10477 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
10478 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
10480 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
10481 (setq time (encode-time s mi h d m y)))
10482 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
10483 (concat keyword (format-time-string fmt time))))
10488 ;; - Bindings in Org-mode map are currently
10489 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
10490 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
10491 ;; e (?) useful from outline-mode
10492 ;; i k @ expendable from outline-mode
10493 ;; 0123456789 ! %^& ()_{} " `' free
10495 ;; Make `C-c C-x' a prefix key
10496 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
10498 ;; TAB key with modifiers
10499 (define-key org-mode-map "\C-i" 'org-cycle)
10500 (define-key org-mode-map [(meta tab)] 'org-complete)
10501 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
10502 ;; The following line is necessary under Suse GNU/Linux
10503 (unless org-xemacs-p
10504 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
10505 (define-key org-mode-map [(shift tab)] 'org-shifttab)
10507 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
10508 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
10509 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
10510 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
10511 (define-key org-mode-map [(meta return)] 'org-meta-return)
10512 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
10513 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
10515 ;; Cursor keys with modifiers
10516 (define-key org-mode-map [(meta left)] 'org-metaleft)
10517 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
10518 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
10519 (define-key org-mode-map [(meta right)] 'org-metaright)
10520 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
10521 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
10522 (define-key org-mode-map [(meta up)] 'org-metaup)
10523 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
10524 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
10525 (define-key org-mode-map [(meta down)] 'org-metadown)
10526 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
10527 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
10529 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
10530 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
10531 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
10532 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
10533 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
10534 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
10535 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
10536 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
10537 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
10538 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
10539 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
10540 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
10541 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
10542 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
10543 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
10544 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
10546 ;; All the other keys
10547 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
10548 (define-key org-mode-map "\C-c\C-j" 'org-goto)
10549 (define-key org-mode-map "\C-c\C-t" 'org-todo)
10550 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
10551 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
10552 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
10553 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
10554 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
10555 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
10556 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
10557 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
10558 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
10559 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
10560 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
10561 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
10562 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
10563 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
10564 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
10565 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
10566 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
10567 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
10568 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
10569 (define-key org-mode-map "\C-c]" 'org-remove-file)
10570 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
10571 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
10572 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
10573 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
10574 (define-key org-mode-map "\C-m" 'org-return)
10575 (define-key org-mode-map "\C-c?" 'org-table-current-column)
10576 (define-key org-mode-map "\C-c " 'org-table-blank-field)
10577 (define-key org-mode-map "\C-c+" 'org-table-sum)
10578 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
10579 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
10580 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
10581 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
10582 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
10583 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
10584 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
10585 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
10586 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
10587 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
10588 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
10589 ;; OPML support is only an option for the future
10590 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
10591 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
10592 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
10593 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
10594 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
10595 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
10596 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
10597 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
10598 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
10599 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
10600 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
10602 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
10603 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
10604 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
10606 (defsubst org-table-p () (org-at-table-p))
10608 (defun org-self-insert-command (N)
10609 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10610 If the cursor is in a table looking at whitespace, the whitespace is
10611 overwritten, and the table is not marked as requiring realignment."
10613 (if (and (org-table-p)
10615 (and org-table-auto-blank-field
10616 (member last-command
10617 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
10618 (org-table-blank-field))
10621 (looking-at "[^|\n]* +|"))
10622 (let (org-table-may-need-update)
10623 (goto-char (1- (match-end 0)))
10624 (delete-backward-char 1)
10625 (goto-char (match-beginning 0))
10626 (self-insert-command N))
10627 (setq org-table-may-need-update t)
10628 (self-insert-command N)))
10631 ;; The following two functions might still be optimized to trigger
10632 ;; re-alignment less frequently.
10634 (defun org-delete-backward-char (N)
10635 "Like `delete-backward-char', insert whitespace at field end in tables.
10636 When deleting backwards, in tables this function will insert whitespace in
10637 front of the next \"|\" separator, to keep the table aligned. The table will
10638 still be marked for re-alignment, because a narrow field may lead to a
10639 reduced column width."
10641 (if (and (org-table-p)
10643 (string-match "|" (buffer-substring (point-at-bol) (point)))
10644 (looking-at ".*?|"))
10645 (let ((pos (point)))
10646 (backward-delete-char N)
10647 (skip-chars-forward "^|")
10649 (goto-char (1- pos)))
10650 (backward-delete-char N)))
10652 (defun org-delete-char (N)
10653 "Like `delete-char', but insert whitespace at field end in tables.
10654 When deleting characters, in tables this function will insert whitespace in
10655 front of the next \"|\" separator, to keep the table aligned. The table
10656 will still be marked for re-alignment, because a narrow field may lead to
10657 a reduced column width."
10659 (if (and (org-table-p)
10661 (not (= (char-after) ?|))
10663 (if (looking-at ".*?|")
10664 (let ((pos (point)))
10665 (replace-match (concat
10666 (substring (match-string 0) 1 -1)
10671 ;; How to do this: Measure non-white length of current string
10672 ;; If equal to column width, we should realign.
10674 (defun org-remap (map &rest commands)
10675 "In MAP, remap the functions given in COMMANDS.
10676 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
10679 (setq old (pop commands) new (pop commands))
10680 (if (fboundp 'command-remapping)
10681 (define-key map (vector 'remap old) new)
10682 (substitute-key-definition old new map global-map)))))
10684 (when (eq org-enable-table-editor 'optimized)
10685 ;; If the user wants maximum table support, we need to hijack
10686 ;; some standard editing functions
10687 (org-remap org-mode-map
10688 'self-insert-command 'org-self-insert-command
10689 'delete-char 'org-delete-char
10690 'delete-backward-char 'org-delete-backward-char)
10691 (define-key org-mode-map "|" 'org-force-self-insert))
10693 (defun org-shiftcursor-error ()
10694 "Throw an error because Shift-Cursor command was applied in wrong context."
10695 (error "This command is active in special context like tables, headlines or timestamps"))
10697 (defun org-shifttab ()
10698 "Global visibility cycling or move to previous table field.
10699 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
10700 See the individual commands for more information."
10703 ((org-at-table-p) (org-table-previous-field))
10704 (t (org-cycle '(4)))))
10706 (defun org-shiftmetaleft ()
10707 "Promote subtree or delete table column.
10708 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
10709 See the individual commands for more information."
10712 ((org-at-table-p) (org-table-delete-column))
10713 ((org-on-heading-p) (org-promote-subtree))
10714 ((org-at-item-p) (call-interactively 'org-outdent-item))
10715 (t (org-shiftcursor-error))))
10717 (defun org-shiftmetaright ()
10718 "Demote subtree or insert table column.
10719 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
10720 See the individual commands for more information."
10723 ((org-at-table-p) (org-table-insert-column))
10724 ((org-on-heading-p) (org-demote-subtree))
10725 ((org-at-item-p) (call-interactively 'org-indent-item))
10726 (t (org-shiftcursor-error))))
10728 (defun org-shiftmetaup (&optional arg)
10729 "Move subtree up or kill table row.
10730 Calls `org-move-subtree-up' or `org-table-kill-row' or
10731 `org-move-item-up' depending on context. See the individual commands
10732 for more information."
10735 ((org-at-table-p) (org-table-kill-row))
10736 ((org-on-heading-p) (org-move-subtree-up arg))
10737 ((org-at-item-p) (org-move-item-up arg))
10738 (t (org-shiftcursor-error))))
10739 (defun org-shiftmetadown (&optional arg)
10740 "Move subtree down or insert table row.
10741 Calls `org-move-subtree-down' or `org-table-insert-row' or
10742 `org-move-item-down', depending on context. See the individual
10743 commands for more information."
10746 ((org-at-table-p) (org-table-insert-row arg))
10747 ((org-on-heading-p) (org-move-subtree-down arg))
10748 ((org-at-item-p) (org-move-item-down arg))
10749 (t (org-shiftcursor-error))))
10751 (defun org-metaleft (&optional arg)
10752 "Promote heading or move table column to left.
10753 Calls `org-do-promote' or `org-table-move-column', depending on context.
10754 With no specific context, calls the Emacs default `backward-word'.
10755 See the individual commands for more information."
10758 ((org-at-table-p) (org-table-move-column 'left))
10759 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
10760 (t (backward-word (prefix-numeric-value arg)))))
10762 (defun org-metaright (&optional arg)
10763 "Demote subtree or move table column to right.
10764 Calls `org-do-demote' or `org-table-move-column', depending on context.
10765 With no specific context, calls the Emacs default `forward-word'.
10766 See the individual commands for more information."
10769 ((org-at-table-p) (org-table-move-column nil))
10770 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
10771 (t (forward-word (prefix-numeric-value arg)))))
10773 (defun org-metaup (&optional arg)
10774 "Move subtree up or move table row up.
10775 Calls `org-move-subtree-up' or `org-table-move-row' or
10776 `org-move-item-up', depending on context. See the individual commands
10777 for more information."
10780 ((org-at-table-p) (org-table-move-row 'up))
10781 ((org-on-heading-p) (org-move-subtree-up arg))
10782 ((org-at-item-p) (org-move-item-up arg))
10783 (t (org-shiftcursor-error))))
10785 (defun org-metadown (&optional arg)
10786 "Move subtree down or move table row down.
10787 Calls `org-move-subtree-down' or `org-table-move-row' or
10788 `org-move-item-down', depending on context. See the individual
10789 commands for more information."
10792 ((org-at-table-p) (org-table-move-row nil))
10793 ((org-on-heading-p) (org-move-subtree-down arg))
10794 ((org-at-item-p) (org-move-item-down arg))
10795 (t (org-shiftcursor-error))))
10797 (defun org-shiftup (&optional arg)
10798 "Increase item in timestamp or increase priority of current item.
10799 Calls `org-timestamp-up' or `org-priority-up', depending on context.
10800 See the individual commands for more information."
10803 ((org-at-timestamp-p) (org-timestamp-up arg))
10804 (t (org-priority-up))))
10806 (defun org-shiftdown (&optional arg)
10807 "Decrease item in timestamp or decrease priority of current item.
10808 Calls `org-timestamp-down' or `org-priority-down', depending on context.
10809 See the individual commands for more information."
10812 ((org-at-timestamp-p) (org-timestamp-down arg))
10813 (t (org-priority-down))))
10815 (defun org-shiftright ()
10816 "Next TODO keyword or timestamp one day later, depending on context."
10819 ((org-at-timestamp-p) (org-timestamp-up-day))
10820 ((org-on-heading-p) (org-todo 'right))
10821 (t (org-shiftcursor-error))))
10823 (defun org-shiftleft ()
10824 "Previous TODO keyword or timestamp one day earlier, depending on context."
10827 ((org-at-timestamp-p) (org-timestamp-down-day))
10828 ((org-on-heading-p) (org-todo 'left))
10829 (t (org-shiftcursor-error))))
10831 (defun org-copy-special ()
10832 "Copy region in table or copy current subtree.
10833 Calls `org-table-copy' or `org-copy-subtree', depending on context.
10834 See the individual commands for more information."
10836 (call-interactively
10837 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
10839 (defun org-cut-special ()
10840 "Cut region in table or cut current subtree.
10841 Calls `org-table-copy' or `org-cut-subtree', depending on context.
10842 See the individual commands for more information."
10844 (call-interactively
10845 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
10847 (defun org-paste-special (arg)
10848 "Paste rectangular region into table, or past subtree relative to level.
10849 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
10850 See the individual commands for more information."
10852 (if (org-at-table-p)
10853 (org-table-paste-rectangle)
10854 (org-paste-subtree arg)))
10856 (defun org-ctrl-c-ctrl-c (&optional arg)
10857 "Call realign table, or recognize a table.el table, or update keywords.
10858 When the cursor is inside a table created by the table.el package,
10859 activate that table. Otherwise, if the cursor is at a normal table
10860 created with org.el, re-align that table. This command works even if
10861 the automatic table editor has been turned off.
10862 If the cursor is in one of the special #+KEYWORD lines, this triggers
10863 scanning the buffer for these lines and updating the information.
10864 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
10866 (let ((org-enable-table-editor t))
10868 ((org-at-table.el-p)
10870 (beginning-of-line 1)
10871 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
10872 (table-recognize-table))
10874 (org-table-maybe-eval-formula)
10876 (org-table-recalculate t)
10877 (org-table-maybe-recalculate-line))
10880 (org-renumber-ordered-list (prefix-numeric-value arg)))
10881 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
10883 ((equal (match-string 1) "TBLFM")
10884 ;; Recalculate the table before this line
10886 (beginning-of-line 1)
10887 (skip-chars-backward " \r\n\t")
10888 (if (org-at-table-p) (org-table-recalculate t))))
10890 (org-mode-restart))))
10891 ((org-region-active-p)
10892 (org-table-convert-region (region-beginning) (region-end) arg))
10893 ((condition-case nil
10894 (and (region-beginning) (region-end))
10896 (if (y-or-n-p "Convert inactive region to table? ")
10897 (org-table-convert-region (region-beginning) (region-end) arg)
10899 (t (error "C-c C-c can do nothing useful at this location.")))))
10901 (defun org-mode-restart ()
10902 "Restart Org-mode, to scan again for special lines.
10903 Also updates the keyword regular expressions."
10905 (let ((org-inhibit-startup t)) (org-mode))
10906 (message "Org-mode restarted to refresh keyword and special line setup"))
10908 (defun org-return ()
10909 "Goto next table row or insert a newline.
10910 Calls `org-table-next-row' or `newline', depending on context.
10911 See the individual commands for more information."
10915 (org-table-justify-field-maybe)
10916 (org-table-next-row))
10919 (defun org-meta-return (&optional arg)
10920 "Insert a new heading or wrap a region in a table.
10921 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
10922 See the individual commands for more information."
10926 (org-table-wrap-region arg))
10927 (t (org-insert-heading arg))))
10931 ;; Define the Org-mode menus
10932 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
10934 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
10935 ["Next Field" org-cycle (org-at-table-p)]
10936 ["Previous Field" org-shifttab (org-at-table-p)]
10937 ["Next Row" org-return (org-at-table-p)]
10939 ["Blank Field" org-table-blank-field (org-at-table-p)]
10940 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
10943 ["Move Column Left" org-metaleft (org-at-table-p)]
10944 ["Move Column Right" org-metaright (org-at-table-p)]
10945 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
10946 ["Insert Column" org-shiftmetaright (org-at-table-p)])
10948 ["Move Row Up" org-metaup (org-at-table-p)]
10949 ["Move Row Down" org-metadown (org-at-table-p)]
10950 ["Delete Row" org-shiftmetaup (org-at-table-p)]
10951 ["Insert Row" org-shiftmetadown (org-at-table-p)]
10952 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
10954 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
10956 ["Copy Rectangle" org-copy-special (org-at-table-p)]
10957 ["Cut Rectangle" org-cut-special (org-at-table-p)]
10958 ["Paste Rectangle" org-paste-special (org-at-table-p)]
10959 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
10962 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
10963 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10964 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
10966 ["Recalculate line" org-table-recalculate (org-at-table-p)]
10967 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
10968 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
10970 ["Sum Column/Rectangle" org-table-sum
10971 (or (org-at-table-p) (org-region-active-p))]
10972 ["Which Column?" org-table-current-column (org-at-table-p)])
10974 (setq org-table-formula-debug (not org-table-formula-debug))
10975 :style toggle :selected org-table-formula-debug]
10977 ["Invisible Vlines" org-table-toggle-vline-visibility
10978 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
10980 ["Create" org-table-create (and (not (org-at-table-p))
10981 org-enable-table-editor)]
10982 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
10983 ["Import from File" org-table-import (not (org-at-table-p))]
10984 ["Export to File" org-table-export (org-at-table-p)]
10986 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
10988 (easy-menu-define org-org-menu org-mode-map "Org menu"
10990 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
10991 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
10992 ["Sparse Tree" org-occur t]
10993 ["Show All" show-all t]
10995 ["New Heading" org-insert-heading t]
10996 ("Navigate Headings"
10997 ["Up" outline-up-heading t]
10998 ["Next" outline-next-visible-heading t]
10999 ["Previous" outline-previous-visible-heading t]
11000 ["Next Same Level" outline-forward-same-level t]
11001 ["Previous Same Level" outline-backward-same-level t]
11003 ["Jump" org-goto t])
11005 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
11006 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
11008 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
11009 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
11010 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
11012 ["Promote Heading" org-metaleft (not (org-at-table-p))]
11013 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
11014 ["Demote Heading" org-metaright (not (org-at-table-p))]
11015 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
11017 ["Archive Subtree" org-archive-subtree t])
11020 ["TODO/DONE/-" org-todo t]
11021 ["Show TODO Tree" org-show-todo-tree t]
11022 ["Global TODO list" org-todo-list t]
11024 ["Set Priority" org-priority t]
11025 ["Priority Up" org-shiftup t]
11026 ["Priority Down" org-shiftdown t])
11027 ("Dates and Scheduling"
11028 ["Timestamp" org-time-stamp t]
11029 ["Timestamp (inactive)" org-time-stamp-inactive t]
11031 ["1 Day Later" org-timestamp-up-day t]
11032 ["1 Day Earlier" org-timestamp-down-day t]
11033 ["1 ... Later" org-shiftup t]
11034 ["1 ... Earlier" org-shiftdown t])
11035 ["Compute Time Range" org-evaluate-time-range t]
11036 ["Schedule Item" org-schedule t]
11037 ["Deadline" org-deadline t]
11039 ["Goto Calendar" org-goto-calendar t]
11040 ["Date from Calendar" org-date-from-calendar t])
11043 ["Show TODO Tree this File" org-show-todo-tree t]
11044 ["Check Deadlines this File" org-check-deadlines t]
11045 ["Timeline Current File" org-timeline t]
11047 ["Agenda" org-agenda t])
11048 ("File List for Agenda")
11051 ["Store Link (Global)" org-store-link t]
11052 ["Insert Link" org-insert-link t]
11053 ["Follow Link" org-open-at-point t])
11056 ["ASCII" org-export-as-ascii t]
11057 ["Extract Visible Text" org-export-copy-visible t]
11058 ["HTML" org-export-as-html t]
11059 ["HTML and Open" org-export-as-html-and-open t]
11060 ; ["OPML" org-export-as-opml nil]
11062 ["iCalendar this file" org-export-icalendar-this-file t]
11063 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
11064 :active t :keys "C-c C-x C-i"]
11065 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
11067 ["Option Template" org-insert-export-options-template t]
11068 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
11071 ["Show Version" org-version t]
11072 ["Info Documentation" org-info t])
11074 ["Browse Org Group" org-customize t]
11076 ["Build Full Customize Menu" org-create-customize-menu
11077 (fboundp 'customize-menu-create)])
11079 ["Refresh setup" org-mode-restart t]
11082 (defun org-info (&optional node)
11083 "Read documentation for Org-mode in the info system.
11084 With optional NODE, go directly to that node."
11087 (Info-goto-node (format "(org)%s" (or node ""))))
11089 (defun org-install-agenda-files-menu ()
11091 '("Org") "File List for Agenda"
11094 ["Edit File List" (customize-variable 'org-agenda-files) t]
11095 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
11096 ["Remove Current File from List" org-remove-file t]
11097 ["Cycle through agenda files" org-cycle-agenda-files t]
11099 (mapcar 'org-file-menu-entry org-agenda-files))))
11103 (defun org-customize ()
11104 "Call the customize function with org as argument."
11106 (customize-browse 'org))
11108 (defun org-create-customize-menu ()
11109 "Create a full customization menu for Org-mode, insert it into the menu."
11111 (if (fboundp 'customize-menu-create)
11114 '("Org") "Customize"
11115 `(["Browse Org group" org-customize t]
11117 ,(customize-menu-create 'org)
11118 ["Set" Custom-set t]
11119 ["Save" Custom-save t]
11120 ["Reset to Current" Custom-reset-current t]
11121 ["Reset to Saved" Custom-reset-saved t]
11122 ["Reset to Standard Settings" Custom-reset-standard t]))
11123 (message "\"Org\"-menu now contains full customization menu"))
11124 (error "Cannot expand menu (outdated version of cus-edit.el)")))
11126 ;;; Miscellaneous stuff
11128 (defun org-move-line-down (arg)
11129 "Move the current line down. With prefix argument, move it past ARG lines."
11131 (let ((col (current-column))
11133 (beginning-of-line 1) (setq beg (point))
11134 (beginning-of-line 2) (setq end (point))
11135 (beginning-of-line (+ 1 arg))
11136 (setq pos (move-marker (make-marker) (point)))
11137 (insert (delete-and-extract-region beg end))
11139 (move-to-column col)))
11141 (defun org-move-line-up (arg)
11142 "Move the current line up. With prefix argument, move it past ARG lines."
11144 (let ((col (current-column))
11146 (beginning-of-line 1) (setq beg (point))
11147 (beginning-of-line 2) (setq end (point))
11148 (beginning-of-line (- arg))
11149 (setq pos (move-marker (make-marker) (point)))
11150 (insert (delete-and-extract-region beg end))
11152 (move-to-column col)))
11154 ;; Paragraph filling stuff.
11155 ;; We want this to be just right, so use the full arsenal.
11156 ;; FIXME: This very likely does not work correctly for XEmacs, because the
11157 ;; filladapt package works slightly differently.
11159 (defun org-set-autofill-regexps ()
11161 ;; In the paragraph separator we include headlines, because filling
11162 ;; text in a line directly attached to a headline would otherwise
11163 ;; fill the headline as well.
11164 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
11165 ;; The paragraph starter includes hand-formatted lists.
11166 (set (make-local-variable 'paragraph-start)
11167 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
11168 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
11169 ;; But only if the user has not turned off tables or fixed-width regions
11170 (set (make-local-variable 'auto-fill-inhibit-regexp)
11172 (if (or org-enable-table-editor org-enable-fixed-width-editor)
11175 (if org-enable-table-editor "|" "")
11176 (if org-enable-fixed-width-editor ":" "")
11178 ;; We use our own fill-paragraph function, to make sure that tables
11179 ;; and fixed-width regions are not wrapped. That function will pass
11180 ;; through to `fill-paragraph' when appropriate.
11181 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
11182 ;; Adaptive filling: To get full control, first make sure that
11183 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
11184 (setq adaptive-fill-regexp "\000")
11185 (setq adaptive-fill-function 'org-adaptive-fill-function))
11187 (defun org-fill-paragraph (&optional justify)
11188 "Re-align a table, pass through to fill-paragraph if no table."
11189 (let ((table-p (org-at-table-p))
11190 (table.el-p (org-at-table.el-p)))
11191 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
11192 (table.el-p t) ; skip table.el tables
11193 (table-p (org-table-align) t) ; align org-mode tables
11194 (t nil)))) ; call paragraph-fill
11196 ;; For reference, this is the default value of adaptive-fill-regexp
11197 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
11199 (defun org-adaptive-fill-function ()
11200 "Return a fill prefix for org-mode files.
11201 In particular, this makes sure hanging paragraphs for hand-formatted lists
11203 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
11204 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11206 ;; Functions needed for Emacs/XEmacs region compatibility
11208 (defun org-region-active-p ()
11209 "Is `transient-mark-mode' on and the region active?
11210 Works on both Emacs and XEmacs."
11211 (if org-ignore-region
11214 (and zmacs-regions (region-active-p))
11215 (and transient-mark-mode mark-active))))
11217 (defun org-add-to-invisibility-spec (arg)
11218 "Add elements to `buffer-invisibility-spec'.
11219 See documentation for `buffer-invisibility-spec' for the kind of elements
11220 that can be added."
11222 ((fboundp 'add-to-invisibility-spec)
11223 (add-to-invisibility-spec arg))
11224 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
11225 (setq buffer-invisibility-spec (list arg)))
11227 (setq buffer-invisibility-spec
11228 (cons arg buffer-invisibility-spec)))))
11230 (defun org-remove-from-invisibility-spec (arg)
11231 "Remove elements from `buffer-invisibility-spec'."
11232 (if (fboundp 'remove-from-invisibility-spec)
11233 (remove-from-invisibility-spec arg)
11234 (if (consp buffer-invisibility-spec)
11235 (setq buffer-invisibility-spec
11236 (delete arg buffer-invisibility-spec)))))
11238 (defun org-in-invisibility-spec-p (arg)
11239 "Is ARG a member of `buffer-invisibility-spec'?."
11240 (if (consp buffer-invisibility-spec)
11241 (member arg buffer-invisibility-spec)
11244 (defun org-image-file-name-regexp ()
11245 "Return regexp matching the file names of images."
11246 (if (fboundp 'image-file-name-regexp)
11247 (image-file-name-regexp)
11248 (let ((image-file-name-extensions
11249 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
11250 "xbm" "xpm" "pbm" "pgm" "ppm")))
11252 (regexp-opt (nconc (mapcar 'upcase
11253 image-file-name-extensions)
11254 image-file-name-extensions)
11258 ;; Functions needed for compatibility with old outline.el
11260 ;; The following functions capture almost the entire compatibility code
11261 ;; between the different versions of outline-mode. The only other place
11262 ;; where this is important are the font-lock-keywords. Search for
11263 ;; `org-noutline-p' to find it.
11265 ;; C-a should go to the beginning of a *visible* line, also in the
11266 ;; new outline.el. I guess this should be patched into Emacs?
11267 (defun org-beginning-of-line ()
11268 "Go to the beginning of the current line. If that is invisible, continue
11269 to a visible line beginning. This makes the function of C-a more intuitive."
11271 (beginning-of-line 1)
11275 (if (org-invisible-p)
11276 (while (and (not (bobp)) (org-invisible-p))
11278 (beginning-of-line 1))
11279 (forward-char 1))))
11280 (when org-noutline-p
11281 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
11283 (defun org-invisible-p ()
11284 "Check if point is at a character currently not visible."
11286 ;; Early versions of noutline don't have `outline-invisible-p'.
11287 (if (fboundp 'outline-invisible-p)
11288 (outline-invisible-p)
11289 (get-char-property (point) 'invisible))
11291 (skip-chars-backward "^\r\n")
11292 (equal (char-before) ?\r))))
11294 (defun org-back-to-heading (&optional invisible-ok)
11295 "Move to previous heading line, or beg of this line if it's a heading.
11296 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
11298 (outline-back-to-heading invisible-ok)
11299 (if (looking-at outline-regexp)
11301 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
11305 (progn (goto-char (match-end 1))
11306 (looking-at outline-regexp)))
11307 (error "Before first heading")))))
11309 (defun org-on-heading-p (&optional invisible-ok)
11310 "Return t if point is on a (visible) heading line.
11311 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
11313 (outline-on-heading-p 'invisible-ok)
11315 (skip-chars-backward "^\n\r")
11316 (and (looking-at outline-regexp)
11319 (equal (char-before) ?\n))))))
11321 (defun org-up-heading-all (arg)
11322 "Move to the heading line of which the present line is a subheading.
11323 This function considers both visible and invisible heading lines.
11324 With argument, move up ARG levels."
11326 (if (fboundp 'outline-up-heading-all)
11327 (outline-up-heading-all arg) ; emacs 21 version of outline.el
11328 (outline-up-heading arg t)) ; emacs 22 version of outline.el
11329 (org-back-to-heading t)
11330 (looking-at outline-regexp)
11331 (if (<= (- (match-end 0) (match-beginning 0)) arg)
11332 (error "Cannot move up %d levels" arg)
11333 (re-search-backward
11334 (concat "[\n\r]" (regexp-quote
11335 (make-string (- (match-end 0) (match-beginning 0) arg)
11338 (forward-char 1))))
11340 (defun org-show-hidden-entry ()
11341 "Show an entry where even the heading is hidden."
11343 (if (not org-noutline-p)
11345 (org-back-to-heading t)
11346 (org-flag-heading nil)))
11349 (defun org-check-occur-regexp (regexp)
11350 "If REGEXP starts with \"^\", modify it to check for \\r as well.
11351 Of course, only for the old outline mode."
11354 (if (string-match "^\\^" regexp)
11355 (concat "[\n\r]" (substring regexp 1))
11358 (defun org-flag-heading (flag &optional entry)
11359 "Flag the current heading. FLAG non-nil means make invisible.
11360 When ENTRY is non-nil, show the entire entry."
11362 (org-back-to-heading t)
11363 (if (not org-noutline-p)
11364 ;; Make the current headline visible
11365 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
11366 ;; Check if we should show the entire entry
11370 (save-excursion ;; FIXME: Is this the fix for points in the -|
11371 ;; middle of text? |
11372 (and (outline-next-heading) ;; |
11373 (org-flag-heading nil)))) ; show the next heading _|
11374 (outline-flag-region (max 1 (1- (point)))
11375 (save-excursion (outline-end-of-heading) (point))
11378 (if flag ?\r ?\n))))))
11380 (defun org-show-subtree ()
11381 "Show everything after this heading at deeper levels."
11382 (outline-flag-region
11385 (outline-end-of-subtree) (outline-next-heading) (point))
11386 (if org-noutline-p nil ?\n)))
11388 (defun org-show-entry ()
11389 "Show the body directly following this heading.
11390 Show the heading too, if it is currently invisible."
11393 (org-back-to-heading t)
11394 (outline-flag-region
11397 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
11398 (or (match-beginning 1) (point-max)))
11399 (if org-noutline-p nil ?\n))))
11402 (defun org-make-options-regexp (kwds)
11403 "Make a regular expression for keyword lines."
11405 (if org-noutline-p "^" "[\n\r]")
11407 (mapconcat 'regexp-quote kwds "\\|")
11409 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
11411 ;; Make `bookmark-jump' show the jump location if it was hidden.
11412 (eval-after-load "bookmark"
11413 '(if (boundp 'bookmark-after-jump-hook)
11414 ;; We can use the hook
11415 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
11416 ;; Hook not available, use advice
11417 (defadvice bookmark-jump (after org-make-visible activate)
11418 "Make the position visible."
11419 (org-bookmark-jump-unhide))))
11421 (defun org-bookmark-jump-unhide ()
11422 "Unhide the current position, to show the bookmark location."
11423 (and (eq major-mode 'org-mode)
11424 (or (org-invisible-p)
11425 (save-excursion (goto-char (max (point-min) (1- (point))))
11426 (org-invisible-p)))
11427 (org-show-hierarchy-above)))
11433 (run-hooks 'org-load-hook)
11435 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
11436 ;;; org.el ends here