1 ;; org.el --- Outline-based notes management and organizer
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., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
63 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
64 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
66 ;; This setup will put all files with extension ".org" into Org-mode. As
67 ;; an alternative, make the first line of a file look like this:
69 ;; MY PROJECTS -*- mode: org; -*-
71 ;; which will select Org-mode for this buffer no matter what the file's
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke.
84 ;; - Tables can store formulas (one per column) and compute fields.
85 ;; Not quite like a full spreadsheet, but very powerful.
86 ;; - table.el keybinding is now `C-c ~'.
87 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
88 ;; - Small changes to keys in agenda buffer. Affected keys:
89 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
93 ;; - Links inserted with C-c C-l are now by default enclosed in angle
94 ;; brackets. See the new variable `org-link-format'.
95 ;; - ">" terminates a link, this is a way to have several links in a line.
96 ;; Both "<" and ">" are no longer allowed as characters in a link.
97 ;; - Archiving of finished tasks.
98 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
99 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
100 ;; - Compatibility problems with viper-mode fixed.
101 ;; - Improved html export of tables.
102 ;; - Various clean-up changes.
105 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
108 ;; - Time-of-day specifications in agenda are extracted and placed
109 ;; into the prefix. Timed entries can be placed into a time grid for
113 ;; - "|" no longer allowed as part of a link, to allow links in tables.
114 ;; - The prefix of items in the agenda buffer can be configured.
118 ;; - Some folding incinsistencies removed.
119 ;; - BBDB links to company-only entries.
120 ;; - Bug fixes and global cleanup.
123 ;; - M-S-RET inserts a new TODO heading.
124 ;; - New startup option `content'.
125 ;; - Better visual response when TODO items in agenda change status.
126 ;; - Window positioning after visibility state changes optimized and made
127 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
130 ;; - Agenda entries from the diary are linked to the diary file, so
131 ;; adding and editing diary entries can be done directly from the agenda.
132 ;; - Many calendar/diary commands available directly from agenda.
133 ;; - Field copying in tables with S-RET does increment.
134 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
135 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
138 ;; - Table editor optimized to need fewer realignments, and to keep
139 ;; table shape when typing in fields.
140 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
141 ;; into arbitrary major modes.
142 ;; - Fixed bug with realignment in XEmacs.
143 ;; - Startup options can be set with special #+STARTUP line.
144 ;; - Heading following a match in org-occur can be suppressed.
147 ;; - Copyright transfer to the FSF.
148 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
149 ;; - Timeline now always contains today, and `.' jumps to it.
151 ;; - cut and paste of rectangular regions in tables
152 ;; - command to convert org-mode table to table.el table and back
153 ;; - command to treat several cells like a paragraph and fill it
154 ;; - command to convert a buffer region to a table
155 ;; - import/export tables as tab-separated files (exchange with Excel)
157 ;; - Sorting mechanism for agenda items rewritten from scratch.
158 ;; - Sorting fully configurable.
159 ;; - Entries specifying a time are sorted together.
160 ;; - Completion also covers option keywords after `#-'.
164 ;; - New reference card, thanks to Philip Rooke for creating it.
165 ;; - Single file agenda renamed to "Timeline". It no longer shows
166 ;; warnings about upcoming deadlines/overdue scheduled items.
167 ;; That functionality is now limited to the (multifile) agenda.
168 ;; - When reading a date, the calendar can be manipulated with keys.
169 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
170 ;; - Minor bug fixes and documentation improvements.
174 (eval-when-compile (require 'cl) (require 'calendar))
179 ;;; Customization variables
181 (defvar org-version "3.12"
182 "The version number of the file org.el.")
183 (defun org-version ()
185 (message "Org-mode version %s" org-version))
187 ;; The following two constants are for compatibility with different Emacs
188 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
189 ;; The compatibility code in org.el is based on these two constants.
190 (defconst org-xemacs-p (featurep 'xemacs)
191 "Are we running xemacs?")
192 (defconst org-noutline-p (featurep 'noutline)
193 "Are we using the new outline mode?")
196 "Outline-based notes management and organizer "
202 (defgroup org-startup nil
203 "Options concerning startup of Org-mode."
207 (defcustom org-CUA-compatible nil
208 "Non-nil means use alternative key bindings for S-<cursor movement>.
209 Org-mode used S-<cursor movement> for changing timestamps and priorities.
210 S-<cursor movement> is also used for example by `CUA-mode' to select text.
211 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
212 alternative bindings. Setting this variable to t will replace the following
213 keys both in Org-mode and in the Org-agenda buffer.
221 If you do not like the alternative keys, take a look at the variable
224 This option is only relevant at load-time of Org-mode. Changing it requires
225 a restart of Emacs to become effective."
229 (defvar org-disputed-keys
230 '((S-up [(shift up)] [(meta ?p)])
231 (S-down [(shift down)] [(meta ?n)])
232 (S-left [(shift left)] [(meta ?-)])
233 (S-right [(shift right)] [(meta ?+)])
234 (S-return [(shift return)] [(control shift return)]))
235 "Keys for which Org-mode and other modes compete.
236 This is an alist, cars are symbols for lookup, 1st element is the default key,
237 second element will be used when `org-CUA-compatible' is t.")
240 "Select a key according to `org-CUA-compatible'."
241 (nth (if org-CUA-compatible 2 1)
242 (or (assq key org-disputed-keys)
243 (error "Invalid Key %s in `org-key'" key))))
245 (defcustom org-startup-folded t
246 "Non-nil means, entering Org-mode will switch to OVERVIEW.
247 This can also be configured on a per-file basis by adding one of
248 the following lines anywhere in the buffer:
255 (const :tag "nofold: show all" nil)
256 (const :tag "fold: overview" t)
257 (const :tag "content: all headlines" content)))
259 (defcustom org-startup-truncated t
260 "Non-nil means, entering Org-mode will set `truncate-lines'.
261 This is useful since some lines containing links can be very long and
262 uninteresting. Also tables look terrible when wrapped."
266 (defcustom org-startup-with-deadline-check nil
267 "Non-nil means, entering Org-mode will run the deadline check.
268 This means, if you start editing an org file, you will get an
269 immediate reminder of any due deadlines.
270 This can also be configured on a per-file basis by adding one of
271 the following lines anywhere in the buffer:
274 #+STARTUP: nodlcheck"
278 (defcustom org-insert-mode-line-in-empty-file nil
279 "Non-nil means insert the first line setting Org-mode in empty files.
280 When the function `org-mode' is called interactively in an empty file, this
281 normally means that the file name does not automatically trigger Org-mode.
282 To ensure that the file will always be in Org-mode in the future, a
283 line enforcing Org-mode will be inserted into the buffer, if this option
288 (defgroup org-keywords nil
289 "Options concerning TODO items in Org-mode."
293 (defcustom org-todo-keywords '("TODO" "DONE")
294 "List of TODO entry keywords.
295 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
296 considered to mean that the entry is \"done\". All the other mean that
297 action is required, and will make the entry show up in todo lists, diaries
299 The command \\[org-todo] cycles an entry through these states, and an
300 additional state where no keyword is present. For details about this
301 cycling, see also the variable `org-todo-interpretation'
302 Changes become only effective after restarting Emacs."
304 :type '(repeat (string :tag "Keyword")))
306 (defcustom org-todo-interpretation 'sequence
307 "Controls how TODO keywords are interpreted.
308 \\<org-mode-map>Possible values are `sequence' and `type'.
309 This variable is only relevant if `org-todo-keywords' contains more than two
310 states. There are two ways how these keywords can be used:
312 - As a sequence in the process of working on a TODO item, for example
313 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
314 org-todo-interpretation 'sequence)
316 - As different types of TODO items, for example
317 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
318 org-todo-interpretation 'type)
320 When the states are interpreted as a sequence, \\[org-todo] always cycles
321 to the next state, in order to walk through all different states. So with
322 \\[org-todo], you turn an empty entry into the state TODO. When you started
323 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
324 later to VERIFY and finally to DONE.
326 When the states are interpreted as types, \\[org-todo] still cycles through
327 when it is called several times in direct succession, in order to initially
328 select the type. However, if not called immediately after a previous
329 \\[org-todo], it switches from each type directly to DONE. So with the
330 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
331 RELAXED. If you later return to this entry and press \\[org-todo] again,
332 RELAXED will not be changed REMIND, but directly to DONE.
334 You can create a large number of types. To initially select a
335 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
336 type with completion. Of course, you can also type the keyword
337 directly into the buffer. M-TAB completes TODO keywords at the
338 beginning of a headline."
340 :type '(choice (const sequence)
343 (defcustom org-default-priority ?B
344 "The default priority of TODO items.
345 This is the priority an item get if no explicit priority is given."
349 (defcustom org-lowest-priority ?C
350 "The lowest priority of TODO items. A character like ?A, ?B etc."
354 (defcustom org-deadline-string "DEADLINE:"
355 "String to mark deadline entries.
356 A deadline is this string, followed by a time stamp. Should be a word,
357 terminated by a colon. You can insert a schedule keyword and
358 a timestamp with \\[org-deadline].
359 Changes become only effective after restarting Emacs."
363 (defcustom org-scheduled-string "SCHEDULED:"
364 "String to mark scheduled TODO entries.
365 A schedule is this string, followed by a time stamp. Should be a word,
366 terminated by a colon. You can insert a schedule keyword and
367 a timestamp with \\[org-schedule].
368 Changes become only effective after restarting Emacs."
372 (defcustom org-comment-string "COMMENT"
373 "Entries starting with this keyword will never be exported.
374 An entry can be toggled between COMMENT and normal with
375 \\[org-toggle-comment].
376 Changes become only effective after restarting Emacs."
380 (defcustom org-after-todo-state-change-hook nil
381 "Hook which is run after the state of a TODO item was changed.
382 The new state (a string with a todo keyword, or nil) is available in the
383 Lisp variable `state'."
387 ;; Variables for pre-computed regular expressions, all buffer local
388 (defvar org-todo-kwd-priority-p nil
389 "Do TODO items have priorities?")
390 (make-variable-buffer-local 'org-todo-kwd-priority-p)
391 (defvar org-todo-kwd-max-priority nil
392 "Maximum priority of TODO items.")
393 (make-variable-buffer-local 'org-todo-kwd-max-priority)
394 (defvar org-ds-keyword-length 12
395 "Maximum length of the Deadline and SCHEDULED keywords.")
396 (make-variable-buffer-local 'org-ds-keyword-length)
397 (defvar org-done-string nil
398 "The last string in `org-todo-keywords', indicating an item is DONE.")
399 (make-variable-buffer-local 'org-done-string)
400 (defvar org-todo-regexp nil
401 "Matches any of the TODO state keywords.")
402 (make-variable-buffer-local 'org-todo-regexp)
403 (defvar org-not-done-regexp nil
404 "Matches any of the TODO state keywords except the last one.")
405 (make-variable-buffer-local 'org-not-done-regexp)
406 (defvar org-todo-line-regexp nil
407 "Matches a headline and puts TODO state into group 2 if present.")
408 (make-variable-buffer-local 'org-todo-line-regexp)
409 (defvar org-nl-done-regexp nil
410 "Matches newline followed by a headline with the DONE keyword.")
411 (make-variable-buffer-local 'org-nl-done-regexp)
412 (defvar org-looking-at-done-regexp nil
413 "Matches the DONE keyword a point.")
414 (make-variable-buffer-local 'org-looking-at-done-regexp)
415 (defvar org-deadline-regexp nil
416 "Matches the DEADLINE keyword.")
417 (make-variable-buffer-local 'org-deadline-regexp)
418 (defvar org-deadline-time-regexp nil
419 "Matches the DEADLINE keyword together with a time stamp.")
420 (make-variable-buffer-local 'org-deadline-time-regexp)
421 (defvar org-deadline-line-regexp nil
422 "Matches the DEADLINE keyword and the rest of the line.")
423 (make-variable-buffer-local 'org-deadline-line-regexp)
424 (defvar org-scheduled-regexp nil
425 "Matches the SCHEDULED keyword.")
426 (make-variable-buffer-local 'org-scheduled-regexp)
427 (defvar org-scheduled-time-regexp nil
428 "Matches the SCHEDULED keyword together with a time stamp.")
429 (make-variable-buffer-local 'org-scheduled-time-regexp)
431 (defvar org-category nil
432 "Variable used by org files to set a category for agenda display.
433 Such files should use a file variable to set it, for example
435 -*- mode: org; org-category: \"ELisp\"
437 or contain a special line
441 If the file does not specify a category, then file's base name
444 (defun org-set-regexps-and-options ()
445 "Precompute regular expressions for current buffer."
446 (when (eq major-mode 'org-mode)
447 (let ((re (org-make-options-regexp
448 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
449 "STARTUP" "ARCHIVE")))
451 kwds int key value cat arch)
455 (goto-char (point-min))
456 (while (re-search-forward re nil t)
457 (setq key (match-string 1) value (match-string 2))
459 ((equal key "CATEGORY")
460 (if (string-match "[ \t]+$" value)
461 (setq value (replace-match "" t t value)))
462 (setq cat (intern value)))
463 ((equal key "SEQ_TODO")
465 kwds (append kwds (org-split-string value splitre))))
466 ((equal key "PRI_TODO")
468 kwds (append kwds (org-split-string value splitre))))
469 ((equal key "TYP_TODO")
471 kwds (append kwds (org-split-string value splitre))))
472 ((equal key "STARTUP")
473 (let ((opts (org-split-string value splitre))
474 (set '(("fold" org-startup-folded t)
475 ("nofold" org-startup-folded nil)
476 ("content" org-startup-folded content)
477 ("dlcheck" org-startup-with-deadline-check t)
478 ("nodlcheck" org-startup-with-deadline-check nil)))
480 (while (setq l (assoc (pop opts) set))
481 (setq var (nth 1 l) val (nth 2 l))
482 (set (make-local-variable var) val))))
483 ((equal key "ARCHIVE")
484 (string-match " *$" value)
485 (setq arch (replace-match "" t t value))
486 (remove-text-properties 0 (length arch)
487 '(face t fontified t) arch)))
489 (and cat (set (make-local-variable 'org-category) cat))
490 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
491 (and arch (set (make-local-variable 'org-archive-location) arch))
492 (and int (set (make-local-variable 'org-todo-interpretation) int)))
493 ;; Compute the regular expressions and other local variables
494 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
495 org-todo-kwd-max-priority (1- (length org-todo-keywords))
496 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
497 (length org-scheduled-string)))
499 (nth (1- (length org-todo-keywords)) org-todo-keywords)
501 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
505 (mapconcat 'regexp-quote
506 (nreverse (cdr (reverse org-todo-keywords)))
510 (concat "^\\(\\*+\\)[ \t]*\\("
511 (mapconcat 'regexp-quote org-todo-keywords "\\|")
514 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
515 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
516 org-deadline-regexp (concat "\\<" org-deadline-string)
517 org-deadline-time-regexp
518 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
519 org-deadline-line-regexp
520 (concat "\\<\\(" org-deadline-string "\\).*")
522 (concat "\\<" org-scheduled-string)
523 org-scheduled-time-regexp
524 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
525 (org-set-font-lock-defaults)))
527 (defgroup org-time nil
528 "Options concerning time stamps and deadlines in Org-mode."
532 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
533 "Formats for `format-time-string' which are used for time stamps.
534 It is not recommended to change this constant.")
537 (defcustom org-deadline-warning-days 30
538 "No. of days before expiration during which a deadline becomes active.
539 This variable governs the display in the org file."
543 (defcustom org-popup-calendar-for-date-prompt t
544 "Non-nil means, pop up a calendar when prompting for a date.
545 In the calendar, the date can be selected with mouse-1. However, the
546 minibuffer will also be active, and you can simply enter the date as well.
547 When nil, only the minibuffer will be available."
551 (defcustom org-calendar-follow-timestamp-change t
552 "Non-nil means, make the calendar window follow timestamp changes.
553 When a timestamp is modified and the calendar window is visible, it will be
554 moved to the new date."
558 (defgroup org-agenda nil
559 "Options concerning agenda display Org-mode."
563 (defcustom org-agenda-files nil
564 "A list of org files for agenda/diary display.
565 Entries are added to this list with \\[org-add-file] and removed with
566 \\[org-remove-file]. You can also use customize to edit the list."
568 :type '(repeat file))
570 (defcustom org-select-timeline-window t
571 "Non-nil means, after creating a timeline, move cursor into Timeline window.
572 When nil, cursor will remain in the current window."
576 (defcustom org-select-agenda-window t
577 "Non-nil means, after creating an agenda, move cursor into Agenda window.
578 When nil, cursor will remain in the current window."
582 (defcustom org-fit-agenda-window t
583 "Non-nil means, change window size of agenda to fit content."
587 (defcustom org-agenda-show-all-dates t
588 "Non-nil means, `org-agenda' shows every day in the selected range.
589 When nil, only the days which actually have entries are shown."
593 ;; FIXME: First day of month works only for current month because it would
594 ;; require a variable ndays treatment.
595 (defcustom org-agenda-start-on-weekday 1
596 "Non-nil means, start the overview always on the specified weekday.
597 0 Denotes Sunday, 1 denotes Monday etc.
598 When nil, always start on the current day."
600 :type '(choice (const :tag "Today" nil)
601 (const :tag "First day of month" t)
602 (number :tag "Weekday No.")))
604 (defcustom org-agenda-ndays 7
605 "Number of days to include in overview display."
609 (defcustom org-agenda-include-all-todo t
610 "Non-nil means, the agenda will always contain all TODO entries.
611 When nil, date-less entries will only be shown if `org-agenda' is called
612 with a prefix argument.
613 When non-nil, the TODO entries will be listed at the top of the agenda, before
614 the entries for specific days."
618 (defcustom org-agenda-include-diary nil
619 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
623 (defcustom org-calendar-to-agenda-key [?c]
624 "The key to be installed in `calendar-mode-map' for switching to the agenda.
625 The command `org-calendar-goto-agenda' will be bound to this key. The
626 default is the character `c' because then`c' can be used to switch back and
627 force between agenda and calendar."
631 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
632 "Sorting structure for the agenda items of a single day.
633 This is a list of symbols which will be used in sequence to determine
634 if an entry should be listed before another entry. The following
635 symbols are recognized.
637 time-up Put entries with time-of-day indications first, early first
638 time-down Put entries with time-of-day indications first, late first
639 category-keep Keep the default order of categories, corresponding to the
640 sequence in `org-agenda-files'.
641 category-up Sort alphabetically by category, A-Z.
642 category-down Sort alphabetically by category, Z-A.
643 priority-up Sort numerically by priority, high priority last.
644 priority-down Sort numerically by priority, high priority first.
646 The different possibilities will be tried in sequence, and testing stops
647 if one comparison returns a \"not-equal\". For example, the default
648 '(time-up category-keep priority-down)
649 means: Pull out all entries having a specified time of day and sort them,
650 in order to make a time schedule for the current day the first thing in the
651 agenda listing for the day. Of the entries without a time indication, keep
652 the grouped in categories, don't sort the categories, but keep them in
653 the sequence given in `org-agenda-files'. Within each category sort by
656 Leaving out `category-keep' would mean that items will be sorted across
657 categories by priority."
663 (const category-keep)
665 (const category-down)
667 (const priority-down))))
669 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
670 "Format specification for the prefix of items in the agenda buffer.
671 This format works similar to a printf format, with the following meaning:
673 %c the category of the item, \"Diary\" for entries from the diary, or
674 as given by the CATEGORY keyword or derived from the file name.
675 %t the time-of-day specification if one applies to the entry, in the
677 %s Scheduling/Deadline information, a short string
679 All specifiers work basically like the standard `%s' of printf, but may
680 contain two additional characters: A question mark just after the `%' and
681 a whitespace/punctuation character just before the final letter.
683 If the first character after `%' is a question mark, the entire field
684 will only be included if the corresponding value applies to the
685 current entry. This is useful for fields which should have fixed
686 width when present, but zero width when absent. For example,
687 \"%?-12t\" will result in a 12 character time field if a time of the
688 day is specified, but will completely disappear in entries which do
691 If there is punctuation or whitespace character just before the final
692 format letter, this character will be appended to the field value if
693 the value is not empty. For example, the format \"%-12:c\" leads to
694 \"Diary: \" if the category is \"Diary\". If the category were be
695 empty, no additional colon would be interted.
697 The default value of this option is \" %-12:c%?-12t% s\", meaning:
698 - Indent the line with two space characters
699 - Give the category in a 12 chars wide field, padded with whitespace on
700 the right (because of `-'). Append a colon if there is a category
702 - If there is a time-of-day, put it into a 12 chars wide field. If no
703 time, don't put in an empty field, just skip it (because of '?').
704 - Finally, put the scheduling information and append a whitespace.
706 As another example, if you don't want the time-of-day of entries in
707 the prefix, you could use:
709 (setq org-agenda-prefix-format \" %-11:c% s\")
711 See also the variable `org-agenda-remove-times-when-in-prefix'."
715 (defcustom org-timeline-prefix-format " % s"
716 "Like `org-agenda-prefix-format', but for the timeline of a single file."
720 (defvar org-prefix-format-compiled nil
721 "The compiled version of the most recently used prefix format.
722 Depending on which command was used last, this may be the compiled version
723 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
725 (defcustom org-agenda-use-time-grid t
726 "Non-nil means, show a time grid in the agenda schedule.
727 A time grid is a set of lines for specific times (like every two hours between
728 8:00 and 20:00. The items scheduled for a day at specific times are
729 sorted in between these lines.
730 For deails about when the grid will be shown, and what it will look like, see
731 the variable `org-agenda-time-grid'."
735 (defcustom org-agenda-time-grid
736 '((daily today require-timed)
738 (800 1000 1200 1400 1600 1800 2000))
740 "The settings for time grid for agenda display.
741 This is a list of three items. The first item is again a list. It contains
742 symbols specifying conditions when the grid should be displayed:
744 daily if the agenda shows a single day
745 weekly if the agenda shows an entire week
746 today show grid on current date, independent of daily/weekly display
747 require-timed show grid only if at least on item has a time specification
749 The second item is a string which will be places behing the grid time.
751 The third item is a list of integers, indicating the times that should have
756 (set :greedy t :tag "Grid Display Options"
757 (const :tag "Show grid in single day agenda display" daily)
758 (const :tag "Show grid in weekly agenda display" weekly)
759 (const :tag "Always show grid for today" today)
760 (const :tag "Show grid only if any timed entries are present"
762 (const :tag "Skip grid times already present in an entry"
764 (string :tag "Grid String")
765 (repeat :tag "Grid Times" (integer :tag "Time"))))
767 (defcustom org-agenda-remove-times-when-in-prefix t
768 "Non-nil means, remove duplicate time specifications in agenda items.
769 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
770 time-of-day specification in a headline or diary entry is extracted and
771 placed into the prefix. If this option is non-nil, the original specification
772 \(a timestamp or -range, or just a plain time(range) specification like
773 11:30-4pm) will be removed for agenda display. This makes the agenda less
775 The option can be t or nil. It may also be the symbol `beg', indicating
776 that the time should only be removed what it is located at the beginning of
777 the headline/diary entry."
780 (const :tag "Always" t)
781 (const :tag "Never" nil)
782 (const :tag "When at beginning of entry" beg)))
784 (defcustom org-sort-agenda-notime-is-late t
785 "Non-nil means, items without time are considered late.
786 This is only relevant for sorting. When t, items which have no explicit
787 time like 15:30 will be considered as 24:01, i.e. later than any items which
788 do have a time. When nil, the default time is before 0:00. You can use this
789 option to decide if the schedule for today should come before or after timeless
794 (defgroup org-structure nil
795 "Options concerning structure editing in Org-mode."
799 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
800 "Hook that is run after `org-cycle' has changed the buffer visibility.
801 The function(s) in this hook must accept a single argument which indicates
802 the new state that was set by the most recent `org-cycle' command. The
803 argument is a symbol. After a global state change, it can have the values
804 `overview', `content', or `all'. After a local state change, it can have
805 the values `folded', `children', or `subtree'."
806 :group 'org-structure
809 (defcustom org-occur-hook '(org-first-headline-recenter)
810 "Hook that is run after `org-occur' has constructed a sparse tree.
811 This can be used to recenter the window to show as much of the structure
813 :group 'org-structure
816 (defcustom org-adapt-indentation t
817 "Non-nil means, adapt indentation when promoting and demoting.
818 When this is set and the *entire* text in an entry is indented, the
819 indentation is increased by one space in a demotion command, and
820 decreased by one in a promotion command. If any line in the entry
821 body starts at column 0, indentation is not changed at all."
822 :group 'org-structure
825 (defcustom org-cycle-emulate-tab t
826 "Where should `org-cycle' emulate TAB.
828 white Only in completely white lines
829 t Everywhere except in headlines"
830 :group 'org-structure
831 :type '(choice (const :tag "Never" nil)
832 (const :tag "Only in completely white lines" white)
833 (const :tag "Everywhere except in headlines" t)
836 (defcustom org-show-following-heading t
837 "Non-nil means, show heading following match in `org-occur'.
838 When doing an `org-occur' it is useful to show the headline which
839 follows the match, even if they do not match the regexp. This makes it
840 easier to edit directly inside the sparse tree. However, if you use
841 org-occur mainly as an overview, the following headlines are
842 unnecessary clutter."
843 :group 'org-structure
846 (defcustom org-archive-location "%s_archive::"
847 "The location where subtrees should be archived.
848 This string consists of two parts, separated by a double-colon.
850 The first part is a file name - when omitted, archiving happens in the same
851 file. %s will be replaced by the current file name (without directory part).
852 Archiving to a different file is useful to keep archived entries from
853 contributing to the Org-mode Agenda.
855 The part after the double colon is a headline. The archived entries will be
856 filed under that headline. When omitted, the subtrees are simply filed away
857 at the end of the file, as top-level entries.
859 Here are a few examples:
861 If the current file is Projects.org, archive in file
862 Projects.org_archive, as top-level trees. This is the default.
864 \"::* Archived Tasks\"
865 Archive in the current file, under the top-level headline
866 \"* Archived Tasks\".
868 \"~/org/archive.org::\"
869 Archive in file ~/org/archive.org (absolute path), as top-level trees.
871 \"basement::** Finished Tasks\"
872 Archive in file ./basement (relative path), as level 3 trees
873 below the level 2 heading \"** Finished Tasks\".
875 You may set this option on a per-file basis by adding to the buffer a
878 #+ARCHIVE: basement::** Finished Tasks"
879 :group 'org-structure
882 (defcustom org-archive-mark-done t
883 "Non-nil means, mark archived entries as DONE."
884 :group 'org-structure
887 (defcustom org-archive-stamp-time t
888 "Non-nil means, add a time stamp to archived entries.
889 The time stamp will be added directly after the TODO state keyword in the
890 first line, so it is probably best to use this in combinations with
891 `org-archive-mark-done'."
892 :group 'org-structure
895 (defgroup org-link nil
896 "Options concerning links in Org-mode."
900 (defcustom org-link-format "<%s>"
901 "Default format for linkes in the buffer.
902 This is a format string for printf, %s will be replaced by the link text.
903 If you want to make sure that your link is always properly terminated,
904 include angle brackets into this format, like \"<%s>\". Some people also
905 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
908 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
909 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
910 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
911 (string :tag "Other" :value "<%s>")))
913 (defcustom org-allow-space-in-links t
914 "Non-nil means, file names in links may contain space characters.
915 When nil, it becomes possible to put several links into a line.
916 Note that in tables, a link never extends accross fields, so in a table
917 it is always possible to put several links into a line.
918 Changing this varable requires a re-launch of Emacs of become effective."
922 (defcustom org-line-numbers-in-file-links t
923 "Non-nil means, file links from `org-store-link' contain line numbers.
924 The line number will be added to the file name with :NNN and interpreted
925 by the command `org-open-at-point'.
926 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
927 negates this setting for the duration of the command."
931 (defcustom org-keep-stored-link-after-insertion nil
932 "Non-nil means, keep link in list for entire session.
934 The command `org-store-link' adds a link pointing to the current
935 location to an internal list. These links accumulate during a session.
936 The command `org-insert-link' can be used to insert links into any
937 Org-mode file (offering completion for all stored links). When this
938 option is nil, every link which has been inserted once using \\[org-insert-link]
939 will be removed from the list, to make completing the unused links
944 (defcustom org-link-frame-setup
945 '((vm . vm-visit-folder-other-frame)
946 (gnus . gnus-other-frame)
947 (file . find-file-other-window))
948 "Setup the frame configuration for following links.
949 When following a link with Emacs, it may often be useful to display
950 this link in another window or frame. This variable can be used to
951 set this up for the different types of links.
954 `vm-visit-folder-other-frame'
960 `find-file-other-window'
961 `find-file-other-frame'
962 For the calendar, use the variable `calendar-setup'.
963 For BBDB, it is currently only possible to display the matches in
969 (const vm-visit-folder)
970 (const vm-visit-folder-other-window)
971 (const vm-visit-folder-other-frame)))
975 (const gnus-other-frame)))
979 (const find-file-other-window)
980 (const find-file-other-frame)))))
982 (defcustom org-usenet-links-prefer-google nil
983 "Non-nil means, `org-store-link' will create web links to google groups.
984 When nil, Gnus will be used for such links.
985 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
986 negates this setting for the duration of the command."
990 (defcustom org-open-non-existing-files nil
991 "Non-nil means, `org-open-file' will open non-existing file.
992 When nil, an error will be generated."
996 (defcustom org-confirm-shell-links t
997 "Non-nil means, ask for confirmation before executing shell links.
998 The default is true, to keep new users from shooting into their own foot."
1002 (defconst org-file-apps-defaults-linux
1014 ("eps.gz" . "gv %s")
1016 ("mpeg" . "plaympeg %s")
1017 ("mp3" . "plaympeg %s")
1019 ("pdf" . "acroread %s")
1020 ("doc" . "soffice %s")
1021 ("ppt" . "soffice %s")
1022 ("pps" . "soffice %s")
1023 ("html" . "netscape -remote openURL(%s,new-window)")
1024 ("htm" . "netscape -remote openURL(%s,new-window)")
1025 ("xs" . "soffice %s"))
1026 "Default file applications on a UNIX/LINUX system.
1027 See `org-file-apps'.")
1029 (defconst org-file-apps-defaults-macosx
1034 ("eps.gz" . "gv %s")
1036 ("fig" . "xfig %s"))
1037 "Default file applications on a MacOS X system.
1038 The system \"open\" is known as a default, but we use X11 applications
1039 for some files for which the OS does not have a good default.
1040 See `org-file-apps'.")
1042 (defconst org-file-apps-defaults-windowsnt
1043 '((t . (w32-shell-execute "open" file)))
1044 "Default file applications on a Windows NT system.
1045 The system \"open\" is used for most files.
1046 See `org-file-apps'.")
1048 (defcustom org-file-apps
1056 "External applications for opening `file:path' items in a document.
1057 Org-mode uses system defaults for different file types, but
1058 you can use this variable to set the application for a given file
1059 extension. The entries in this list are cons cells with a file extension
1060 and the corresponding command. Possible values for the command are:
1061 `emacs' The file will be visited by the current Emacs process.
1062 `default' Use the default application for this file type.
1063 string A command to be executed by a shell; %s will be replaced
1064 by the path to the file.
1065 sexp A Lisp form which will be evaluated. The file path will
1066 be available in the Lisp variable `file'.
1067 For more examples, see the system specific constants
1068 `org-file-apps-defaults-macosx'
1069 `org-file-apps-defaults-windowsnt'
1070 `org-file-apps-defaults-linux'."
1073 (cons (string :tag "Extension")
1075 (const :tag "Visit with Emacs" 'emacs)
1076 (const :tag "Use system default" 'default)
1077 (string :tag "Command")
1078 (sexp :tag "Lisp form")))))
1081 (defgroup org-remember nil
1082 "Options concerning interaction with remember.el."
1086 (defcustom org-directory "~/org"
1087 "Directory with org files.
1088 This directory will be used as default to prompt for org files.
1089 Used by the hooks for remember.el."
1090 :group 'org-remember
1093 (defcustom org-default-notes-file "~/.notes"
1094 "Default target for storing notes.
1095 Used by the hooks for remember.el. This can be a string, or nil to mean
1096 the value of `remember-data-file'."
1097 :group 'org-remember
1099 (const :tag "Default from remember-data-file" nil)
1102 (defcustom org-reverse-note-order nil
1103 "Non-nil means, store new notes at the beginning of a file or entry.
1104 When nil, new notes will be filed to the end of a file or entry."
1105 :group 'org-remember
1107 (const :tag "Reverse always" t)
1108 (const :tag "Reverse never" nil)
1109 (repeat :tag "By file name regexp"
1110 (cons regexp boolean))))
1112 (defgroup org-table nil
1113 "Options concerning tables in Org-mode."
1117 (defcustom org-enable-table-editor 'optimized
1118 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1119 When nil, such lines will be treated like ordinary lines.
1121 When equal to the symbol `optimized', the table editor will be optimized to
1123 - Use automatic overwrite mode in front of whitespace in table fields.
1124 This make the structure of the table stay in tact as long as the edited
1125 field does not exceed the column width.
1126 - Minimize the number of realigns. Normally, the table is aligned each time
1127 TAB or RET are pressed to move to another field. With optimization this
1128 happens only if changes to a field might have changed the column width.
1129 Optimization requires replacing the functions `self-insert-command',
1130 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1131 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1132 very good at guessing when a re-align will be necessary, but you can always
1133 force one with `C-c C-c'.
1135 If you would like to use the optimized version in Org-mode, but the
1136 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1138 This variable can be used to turn on and off the table editor during a session,
1139 but in order to toggle optimization, a restart is required."
1142 (const :tag "off" nil)
1144 (const :tag "on, optimized" optimized)))
1146 (defcustom org-table-default-size "5x2"
1147 "The default size for newly created tables, Columns x Rows."
1151 (defcustom org-table-automatic-realign t
1152 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1153 When nil, aligning is only done with \\[org-table-align], or after column
1158 (defcustom org-table-spaces-around-separators '(1 . 1)
1159 "The number of spaces to be placed before and after separators."
1161 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1163 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1164 "The number of spaces to be placed before and after separators.
1165 This option applies when the column separators have been made invisible."
1167 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1169 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1170 "Regular expression for recognizing numbers in table columns.
1171 If a table column contains mostly numbers, it will be aligned to the
1172 right. If not, it will be aligned to the left.
1174 The default value of this option is a regular expression which allows
1175 anything which looks remotely like a number as used in scientific
1176 context. For example, all of the following will be considered a
1178 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1180 Other options offered by the customize interface are more restrictive."
1183 (const :tag "Positive Integers"
1185 (const :tag "Integers"
1187 (const :tag "Floating Point Numbers"
1188 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1189 (const :tag "Floating Point Number or Integer"
1190 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1191 (const :tag "Exponential, Floating point, Integer"
1192 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1193 (const :tag "Very General Number-Like"
1194 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1195 (string :tag "Regexp:")))
1197 (defcustom org-table-number-fraction 0.5
1198 "Fraction of numbers in a column required to make the column align right.
1199 In a column all non-white fields are considered. If at least this
1200 fraction of fields is matched by `org-table-number-fraction',
1201 alignment to the right border applies."
1205 (defcustom org-export-highlight-first-table-line t
1206 "Non-nil means, highlight the first table line.
1207 In HTML export, this means use <th> instead of <td>.
1208 In tables created with table.el, this applies to the first table line.
1209 In Org-mode tables, all lines before the first horizontal separator
1210 line will be formatted with <th> tags."
1215 (defgroup org-table-calculation nil
1216 "Options concerning tables in Org-mode."
1217 :tag "Org Table Calculation"
1220 (defcustom org-table-copy-increment t
1221 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1222 :group 'org-table-calculation
1225 (defcustom org-calc-default-modes
1226 '(calc-internal-prec 12
1227 calc-float-format (float 5)
1229 calc-prefer-frac nil
1230 calc-symbolic-mode nil)
1231 "List with Calc mode settings for use in calc-eval for table formulas.
1232 The list must contain alternating symbols (calc modes variables and values.
1233 Don't remove any of the default settings, just change the values. Org-mode
1234 relies on the variables to be present in the list."
1235 :group 'org-table-calculation
1238 (defcustom org-table-formula-evaluate-inline t
1239 "Non-nil means, TAB and RET evaluate a formula in current table field.
1240 If the current field starts with an equal sign, it is assumed to be a formula
1241 which should be evaluated as described in the manual and in the documentation
1242 string of the command `org-table-eval-formula'. This feature requires the
1244 When this variable is nil, formula calculation is only available through
1245 the command \\[org-table-eval-formula]."
1246 :group 'org-table-calculation
1250 (defcustom org-table-formula-use-constants t
1251 "Non-nil means, interpret constants in formulas in tables.
1252 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1253 by the value given in `org-table-formula-constants', or by a value obtained
1254 from the `constants.el' package."
1255 :group 'org-table-calculation
1258 (defcustom org-table-formula-constants nil
1259 "Alist with constant names and values, for use in table formulas.
1260 The car of each element is a name of a constant, without the `$' before it.
1261 The cdr is the value as a string. For example, if you'd like to use the
1262 speed of light in a formula, you would configure
1264 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1266 and then use it in an equation like `$1*$c'."
1267 :group 'org-table-calculation
1269 (cons (string :tag "name")
1270 (string :tag "value"))))
1272 (defcustom org-table-formula-numbers-only nil
1273 "Non-nil means, calculate only with numbers in table formulas.
1274 Then all input fields will be converted to a number, and the result
1275 must also be a number. When nil, calc's full potential is available
1276 in table calculations, including symbolics etc."
1277 :group 'org-table-calculation
1280 (defcustom org-table-tab-recognizes-table.el t
1281 "Non-nil means, TAB will automatically notice a table.el table.
1282 When it sees such a table, it moves point into it and - if necessary -
1283 calls `table-recognize-table'."
1287 (defcustom org-export-prefer-native-exporter-for-tables nil
1288 "Non-nil means, always export tables created with table.el natively.
1289 Natively means, use the HTML code generator in table.el.
1290 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1291 the table does not use row- or column-spanning). This has the
1292 advantage, that the automatic HTML conversions for math symbols and
1293 sub/superscripts can be applied. Org-mode's HTML generator is also
1298 (defcustom org-enable-fixed-width-editor t
1299 "Non-nil means, lines starting with \":\" are treated as fixed-width.
1300 This currently only means, they are never auto-wrapped.
1301 When nil, such lines will be treated like ordinary lines."
1305 (defgroup org-export nil
1306 "Options for exporting org-listings."
1310 (defcustom org-export-language-setup
1311 '(("en" "Author" "Date" "Table of Contents")
1312 ("da" "Ophavsmand" "Dato" "Indhold")
1313 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1314 ("es" "Autor" "Fecha" "\xccndice")
1315 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1316 ("it" "Autore" "Data" "Indice")
1317 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1318 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1319 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1320 "Terms used in export text, translated to different languages.
1321 Use the variable `org-export-default-language' to set the language,
1322 or use the +OPTION lines for a per-file setting."
1326 (string :tag "HTML language tag")
1327 (string :tag "Author")
1328 (string :tag "Date")
1329 (string :tag "Table of Contents"))))
1331 (defcustom org-export-default-language "en"
1332 "The default language of HTML export, as a string.
1333 This should have an association in `org-export-language-setup'"
1337 (defcustom org-export-headline-levels 3
1338 "The last level which is still exported as a headline.
1339 Inferior levels will produce itemize lists when exported.
1340 Note that a numeric prefix argument to an exporter function overrides
1343 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1347 (defcustom org-export-with-section-numbers t
1348 "Non-nil means, add section numbers to headlines when exporting.
1350 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1354 (defcustom org-export-with-toc t
1355 "Non-nil means, create a table of contents in exported files.
1356 The TOC contains headlines with levels up to`org-export-headline-levels'.
1358 Headlines which contain any TODO items will be marked with \"(*)\" in
1359 ASCII export, and with red color in HTML output.
1361 In HTML output, the TOC will be clickable.
1363 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1367 (defcustom org-export-preserve-breaks nil
1368 "Non-nil means, preserve all line breaks when exporting.
1369 Normally, in HTML output paragraphs will be reformatted. In ASCII
1370 export, line breaks will always be preserved, regardless of this variable.
1372 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1376 (defcustom org-export-html-inline-images t
1377 "Non-nil means, inline images into exported HTML pages.
1378 The link will still be to the original location of the image file.
1379 So if you are moving the page, lets say to your public HTML site,
1380 you will have to move the image and maybe change the link."
1384 (defcustom org-export-html-expand t
1385 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1386 When nil, these tags will be exported as plain text and therefore
1387 not be interpreted by a browser.
1389 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1393 (defcustom org-export-with-fixed-width t
1394 "Non-nil means, lines starting with \":\" will be in fixed width font.
1395 This can be used to have pre-formatted text, fragments of code etc. For
1397 : ;; Some Lisp examples
1400 will be looking just like this in also HTML. In ASCII export, this option
1403 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1407 (defcustom org-export-with-tables t
1408 "If non-nil, lines starting with \"|\" define a table.
1411 | Name | Address | Birthday |
1412 |-------------+----------+-----------|
1413 | Arthur Dent | England | 29.2.2100 |
1415 In ASCII export, this option has no effect.
1417 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1421 (defcustom org-export-html-table-tag
1422 "<table border=1 cellspacing=0 cellpadding=6>"
1423 "The HTML tag used to start a table.
1424 This must be a <table> tag, but you may change the options like
1425 borders and spacing."
1429 (defcustom org-export-with-emphasize t
1430 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1431 If the export target supports emphasizing text, the word will be
1432 typeset in bold, italic, or underlined, respectively. Works only for
1433 single words, but you can say: I *really* *mean* *this*.
1434 In ASCII export, this option has no effect.
1436 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1440 (defcustom org-match-sexp-depth 3
1441 "Number of stacked braces for sub/superscript matching.
1442 This has to be set before loading org.el to be effective."
1446 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1447 (defcustom org-export-with-sub-superscripts t
1448 "Non-nil means, interpret \"_\" and \"^\" for export.
1449 When this option is turned on, you can use TeX-like syntax for sub- and
1450 superscripts. Several characters after \"_\" or \"^\" will be
1451 considered as a single item - so grouping with {} is normally not
1452 needed. For example, the following things will be parsed as single
1453 sub- or superscripts.
1455 10^24 or 10^tau several digits will be considered 1 item
1456 10^-12 or 10^-tau a leading sign with digits or a word
1457 x^2-y^3 will be read as x^2 - y^3, because items are
1458 terminated by almost any nonword/nondigit char.
1459 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1461 Still, ambiguity is possible - so when in doubt use {} to enclose the
1463 In ASCII export, this option has no effect.
1465 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1469 (defcustom org-export-with-TeX-macros t
1470 "Non-nil means, interpret simple TeX-like macros when exporting.
1471 For example, HTML export converts \\alpha to α and \\AA to Å.
1472 No only real TeX macros will work here, but the standard HTML entities
1473 for math can be used as macro names as well. For a list of supported
1474 names in HTML export, see the constant `org-html-entities'.
1475 In ASCII export, this option has no effect.
1477 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1481 (defcustom org-export-html-with-timestamp nil
1482 "If non-nil, write `org-export-html-html-helper-timestamp'
1483 into the exported html text. Otherwise, the buffer will just be saved
1488 (defcustom org-export-html-html-helper-timestamp
1489 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1490 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1494 (defcustom org-export-ascii-show-new-buffer t
1495 "Non-nil means, popup buffer containing the exported ASCII text.
1496 Otherwise the buffer will just be saved to a file and stay hidden."
1500 (defcustom org-export-html-show-new-buffer nil
1501 "Non-nil means, popup buffer containing the exported html text.
1502 Otherwise, the buffer will just be saved to a file and stay hidden."
1506 (defgroup org-faces nil
1507 "Faces for highlighting in Org-mode."
1511 (defface org-level-1 ;; font-lock-function-name-face
1512 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1513 (((class color) (background light)) (:foreground "Blue"))
1514 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1515 (t (:inverse-video t :bold t)))
1516 "Face used for level 1 headlines."
1519 (defface org-level-2 ;; font-lock-variable-name-face
1520 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1521 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1522 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1523 (t (:bold t :italic t)))
1524 "Face used for level 2 headlines."
1527 (defface org-level-3 ;; font-lock-keyword-face
1528 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1529 (((class color) (background light)) (:foreground "Purple"))
1530 (((class color) (background dark)) (:foreground "Cyan"))
1532 "Face used for level 3 headlines."
1535 (defface org-level-4 ;; font-lock-comment-face
1536 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1537 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1538 (((class color) (background light)) (:foreground "Firebrick"))
1539 (((class color) (background dark)) (:foreground "chocolate1"))
1540 (t (:bold t :italic t)))
1541 "Face used for level 4 headlines."
1544 (defface org-level-5 ;; font-lock-type-face
1545 '((((type tty) (class color)) (:foreground "green"))
1546 (((class color) (background light)) (:foreground "ForestGreen"))
1547 (((class color) (background dark)) (:foreground "PaleGreen"))
1548 (t (:bold t :underline t)))
1549 "Face used for level 5 headlines."
1552 (defface org-level-6 ;; font-lock-constant-face
1553 '((((type tty) (class color)) (:foreground "magenta"))
1554 (((class color) (background light)) (:foreground "CadetBlue"))
1555 (((class color) (background dark)) (:foreground "Aquamarine"))
1556 (t (:bold t :underline t)))
1557 "Face used for level 6 headlines."
1560 (defface org-level-7 ;; font-lock-builtin-face
1561 '((((type tty) (class color)) (:foreground "blue" :weight light))
1562 (((class color) (background light)) (:foreground "Orchid"))
1563 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1565 "Face used for level 7 headlines."
1568 (defface org-level-8 ;; font-lock-string-face
1569 '((((type tty) (class color)) (:foreground "green"))
1570 (((class color) (background light)) (:foreground "RosyBrown"))
1571 (((class color) (background dark)) (:foreground "LightSalmon"))
1573 "Face used for level 8 headlines."
1576 (defface org-warning ;; font-lock-warning-face
1577 '((((type tty) (class color)) (:foreground "red"))
1578 (((class color) (background light)) (:foreground "Red" :bold t))
1579 (((class color) (background dark)) (:foreground "Red1" :bold t))
1580 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1581 (t (:inverse-video t :bold t)))
1582 "Face for deadlines and TODO keywords."
1585 (defcustom org-fontify-done-headline nil
1586 "Non-nil means, change the face of a headline if it is marked DONE.
1587 Normally, only the TODO/DONE keyword indicates the state of a headline.
1588 When this is non-nil, the headline after the keyword is set to the
1589 `org-headline-done' as an additional indication."
1593 (defface org-headline-done ;; font-lock-string-face
1594 '((((type tty) (class color)) (:foreground "green"))
1595 (((class color) (background light)) (:foreground "RosyBrown"))
1596 (((class color) (background dark)) (:foreground "LightSalmon"))
1598 "Face used to indicate that a headline is DONE. See also the variable
1599 `org-fontify-done-headline'."
1602 ;; Inheritance does not yet work for xemacs. So we just copy...
1604 (defface org-deadline-announce
1605 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1606 (((class color) (background light)) (:foreground "Blue"))
1607 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1608 (t (:inverse-video t :bold t)))
1609 "Face for upcoming deadlines."
1612 (defface org-scheduled-today
1613 '((((type tty) (class color)) (:foreground "green"))
1614 (((class color) (background light)) (:foreground "DarkGreen"))
1615 (((class color) (background dark)) (:foreground "PaleGreen"))
1616 (t (:bold t :underline t)))
1617 "Face for items scheduled for a certain day."
1620 (defface org-scheduled-previously
1621 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1622 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1623 (((class color) (background light)) (:foreground "Firebrick"))
1624 (((class color) (background dark)) (:foreground "chocolate1"))
1625 (t (:bold t :italic t)))
1626 "Face for items scheduled previously, and not yet done."
1629 (defface org-formula
1630 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1631 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1632 (((class color) (background light)) (:foreground "Firebrick"))
1633 (((class color) (background dark)) (:foreground "chocolate1"))
1634 (t (:bold t :italic t)))
1635 "Face for items scheduled previously, and not yet done."
1639 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1640 (((class color) (background light)) (:foreground "Purple"))
1641 (((class color) (background dark)) (:foreground "Cyan"))
1646 (defface org-done ;; font-lock-type-face
1647 '((((type tty) (class color)) (:foreground "green"))
1648 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1649 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1650 (t (:bold t :underline t)))
1651 "Face used for DONE."
1654 (defface org-table ;; font-lock-function-name-face
1655 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1656 (((class color) (background light)) (:foreground "Blue"))
1657 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1658 (t (:inverse-video t :bold t)))
1659 "Face used for tables."
1662 (defface org-time-grid ;; font-lock-variable-name-face
1663 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1664 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1665 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1666 (t (:bold t :italic t)))
1667 "Face used for level 2 headlines."
1670 (defvar org-level-faces
1681 (defvar org-n-levels (length org-level-faces))
1683 ;; Tell the compiler about dynamically scoped variables,
1684 ;; and variables from other packages
1686 (defvar zmacs-regions)
1687 (defvar original-date)
1688 (defvar org-transient-mark-mode)
1689 (defvar org-old-auto-fill-inhibit-regexp)
1690 (defvar orgtbl-mode-menu)
1691 (defvar org-html-entities)
1692 (defvar org-goto-start-pos)
1693 (defvar org-cursor-color)
1694 (defvar org-time-was-given)
1695 (defvar org-ts-what)
1696 (defvar mark-active)
1698 (defvar levels-open)
1709 (defvar starting-day)
1710 (defvar include-all-loc)
1711 (defvar vm-message-pointer)
1712 (defvar vm-folder-directory)
1713 (defvar wl-summary-buffer-elmo-folder)
1714 (defvar wl-summary-buffer-folder-name)
1715 (defvar gnus-group-name)
1716 (defvar gnus-article-current)
1717 (defvar w3m-current-url)
1718 (defvar org-selected-point)
1719 (defvar calendar-mode-map)
1720 (defvar remember-save-after-remembering)
1721 (defvar remember-data-file))
1726 (defvar org-mode-map (copy-keymap outline-mode-map)
1727 "Keymap for Org-mode.")
1729 (defvar org-struct-menu)
1730 (defvar org-org-menu)
1731 (defvar org-tbl-menu)
1733 ;; We use a before-change function to check if a table might need
1735 (defvar org-table-may-need-update t
1736 "Indicates of a table might need an update.
1737 This variable is set by `org-before-change-function'. `org-table-align'
1738 sets it back to nil.")
1739 (defvar org-mode-hook nil)
1740 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1744 (define-derived-mode org-mode outline-mode "Org"
1745 "Outline-based notes management and organizer, alias
1746 \"Carstens outline-mode for keeping track of everything.\"
1748 Org-mode develops organizational tasks around a NOTES file which
1749 contains information about projects as plain text. Org-mode is
1750 implemented on top of outline-mode, which is ideal to keep the content
1751 of large files well structured. It supports ToDo items, deadlines and
1752 time stamps, which magically appear in the diary listing of the Emacs
1753 calendar. Tables are easily created with a built-in table editor.
1754 Plain text URL-like links connect to websites, emails (VM), Usenet
1755 messages (Gnus), BBDB entries, and any files related to the project.
1756 For printing and sharing of notes, an Org-mode file (or a part of it)
1757 can be exported as a structured ASCII or HTML file.
1759 The following commands are available:
1762 (easy-menu-add org-org-menu)
1763 (easy-menu-add org-tbl-menu)
1764 (org-install-agenda-files-menu)
1765 (setq outline-regexp "\\*+")
1766 (if org-startup-truncated (setq truncate-lines t))
1767 (org-set-regexps-and-options)
1768 (set (make-local-variable 'font-lock-unfontify-region-function)
1769 'org-unfontify-region)
1770 ;; Activate before-change-function
1771 (set (make-local-variable 'org-table-may-need-update) t)
1772 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1773 (add-hook 'before-change-functions 'org-before-change-function nil
1775 ;; Paragraph regular expressions
1776 (set (make-local-variable 'paragraph-separate) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1777 (set (make-local-variable 'paragraph-start) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1778 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1779 (set (make-local-variable 'auto-fill-inhibit-regexp)
1781 (if (or org-enable-table-editor org-enable-fixed-width-editor)
1784 (if org-enable-table-editor "|" "")
1785 (if org-enable-fixed-width-editor ":" "")
1787 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
1788 (if (and org-insert-mode-line-in-empty-file
1790 (= (point-min) (point-max)))
1791 (insert " -*- mode: org -*-\n\n"))
1793 ;; Get rid of Outline menus, they are not needed
1794 ;; Need to do this here because define-derived-mode sets up
1795 ;; the keymap so late.
1798 (delete-menu-item '("Headings"))
1799 (delete-menu-item '("Show"))
1800 (delete-menu-item '("Hide"))
1801 (set-menubar-dirty-flag))
1802 (define-key org-mode-map [menu-bar headings] 'undefined)
1803 (define-key org-mode-map [menu-bar hide] 'undefined)
1804 (define-key org-mode-map [menu-bar show] 'undefined))
1806 (unless org-inhibit-startup
1807 (if org-startup-with-deadline-check
1808 (call-interactively 'org-check-deadlines)
1810 ((eq org-startup-folded t)
1812 ((eq org-startup-folded 'content)
1813 (let ((this-command 'org-cycle) (last-command 'org-cycle))
1814 (org-cycle '(4)) (org-cycle '(4))))))))
1816 (defun org-fill-paragraph (&optional justify)
1817 "Re-align a table, pass through to fill-paragraph if no table."
1819 (beginning-of-line 1)
1820 (looking-at "\\s-*\\(|\\|\\+-+\\)")))
1822 (defsubst org-current-line (&optional pos)
1823 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
1827 (defvar org-mouse-map (make-sparse-keymap))
1828 (define-key org-mouse-map
1829 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
1830 (define-key org-mouse-map
1831 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1833 (require 'font-lock)
1835 (defconst org-non-link-chars "\t\n\r|<>\000")
1836 (defconst org-link-regexp
1837 (if org-allow-space-in-links
1839 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
1841 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
1843 "Regular expression for matching links.")
1844 (defconst org-link-maybe-angles-regexp
1845 (concat "<?\\(" org-link-regexp "\\)>?")
1846 "Matches a link and optionally surrounding angle brackets.")
1847 (defconst org-protected-link-regexp
1848 (concat "\000" org-link-regexp "\000")
1849 "Matches a link and optionally surrounding angle brackets.")
1851 (defconst org-ts-lengths
1852 (cons (length (format-time-string (car org-time-stamp-formats)))
1853 (length (format-time-string (cdr org-time-stamp-formats))))
1854 "This holds the lengths of the two different time formats.")
1855 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1856 "Regular expression for fast time stamp matching.")
1857 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1858 "Regular expression matching time strings for analysis.")
1859 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1860 "Regular expression matching time stamps, with groups.")
1861 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1862 "Regular expression matching a time stamp range.")
1863 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1864 org-ts-regexp "\\)?")
1865 "Regular expression matching a time stamp or time stamp range.")
1867 (defun org-activate-links (limit)
1868 "Run through the buffer and add overlays to links."
1869 (if (re-search-forward org-link-regexp limit t)
1871 (add-text-properties (match-beginning 0) (match-end 0)
1872 (list 'mouse-face 'highlight
1873 'keymap org-mouse-map))
1876 (defun org-activate-dates (limit)
1877 "Run through the buffer and add overlays to dates."
1878 (if (re-search-forward org-tsr-regexp limit t)
1880 (add-text-properties (match-beginning 0) (match-end 0)
1881 (list 'mouse-face 'highlight
1882 'keymap org-mouse-map))
1885 (defun org-font-lock-level ()
1887 (org-back-to-heading t)
1888 (- (match-end 0) (match-beginning 0))))
1890 (defvar org-font-lock-keywords nil)
1892 (defun org-set-font-lock-defaults ()
1893 (let ((org-font-lock-extra-keywords
1895 '(org-activate-links (0 'org-link))
1896 '(org-activate-dates (0 'org-link))
1897 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
1898 '(1 'org-warning t))
1899 (list (concat "\\[#[A-Z]\\]") '(0 'org-warning t))
1900 (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
1901 (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
1902 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
1904 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
1906 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
1908 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
1909 '(1 'org-warning t))
1910 '("^#.*" (0 'font-lock-comment-face t))
1911 (if org-fontify-done-headline
1912 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
1913 '(1 'org-done t) '(2 'org-headline-done t))
1914 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
1916 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
1918 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
1919 '("| *\\(=[^|\n]*\\)" (1 'org-formula t))
1920 '("^[ \t]*| *\\([#!$*]\\) *|" (1 'org-formula t))
1922 (set (make-local-variable 'org-font-lock-keywords)
1924 (if org-noutline-p ; FIXME: I am not sure if eval will work
1925 ; on XEmacs if noutline is ever ported
1926 '((eval . (list "^\\(\\*+\\).*"
1928 (% (- (match-end 1) (match-beginning 1) 1)
1932 '(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
1933 (1 (nth (% (- (match-end 2) (match-beginning 2) 1)
1937 org-font-lock-extra-keywords))
1938 (set (make-local-variable 'font-lock-defaults)
1939 '(org-font-lock-keywords t nil nil backward-paragraph))
1940 (kill-local-variable 'font-lock-keywords) nil))
1942 (defun org-unfontify-region (beg end &optional maybe_loudly)
1943 "Remove fontification and activation overlays from links."
1944 (font-lock-default-unfontify-region beg end)
1945 (let* ((buffer-undo-list t)
1946 (inhibit-read-only t) (inhibit-point-motion-hooks t)
1947 (inhibit-modification-hooks t)
1948 deactivate-mark buffer-file-name buffer-file-truename)
1949 (remove-text-properties beg end '(mouse-face nil keymap nil))))
1951 ;;; Visibility cycling
1953 (defvar org-cycle-global-status nil)
1954 (defvar org-cycle-subtree-status nil)
1955 (defun org-cycle (&optional arg)
1956 "Visibility cycling for Org-mode.
1958 - When this function is called with a prefix argument, rotate the entire
1959 buffer through 3 states (global cycling)
1960 1. OVERVIEW: Show only top-level headlines.
1961 2. CONTENTS: Show all headlines of all levels, but no body text.
1962 3. SHOW ALL: Show everything.
1964 - When point is at the beginning of a headline, rotate the subtree started
1965 by this line through 3 different states (local cycling)
1966 1. FOLDED: Only the main headline is shown.
1967 2. CHILDREN: The main headline and the direct children are shown. From
1968 this state, you can move to one of the children and
1970 3. SUBTREE: Show the entire subtree, including body text.
1972 - When there is a numeric prefix, go up to a heading with level ARG, do
1973 a `show-subtree' and return to the previous cursor position. If ARG
1974 is negative, go up that many levels.
1976 - When point is not at the beginning of a headline, execute
1977 `indent-relative', like TAB normally does. See the option
1978 `org-cycle-emulate-tab' for details.
1980 - Special case: if point is the the beginning of the buffer and there is
1981 no headline in line 1, this function will act as if called with prefix arg."
1984 (if (or (and (bobp) (not (looking-at outline-regexp)))
1986 ;; special case: use global cycling
1991 ((org-at-table-p 'any)
1992 ;; Enter the table or move to the next field in the table
1993 (or (org-table-recognize-table.el)
1995 (org-table-justify-field-maybe)
1996 (org-table-next-field))))
1998 ((eq arg t) ;; Global cycling
2001 ((and (eq last-command this-command)
2002 (eq org-cycle-global-status 'overview))
2003 ;; We just created the overview - now do table of contents
2004 ;; This can be slow in very large buffers, so indicate action
2005 (message "CONTENTS...")
2007 ;; Visit all headings and show their offspring
2008 (goto-char (point-max))
2010 (while (and (progn (condition-case nil
2011 (outline-previous-visible-heading 1)
2012 (error (goto-char (point-min))))
2014 (looking-at outline-regexp))
2016 (if (bobp) (throw 'exit nil))))
2017 (message "CONTENTS...done"))
2018 (setq org-cycle-global-status 'contents)
2019 (run-hook-with-args 'org-cycle-hook 'contents))
2021 ((and (eq last-command this-command)
2022 (eq org-cycle-global-status 'contents))
2023 ;; We just showed the table of contents - now show everything
2025 (message "SHOW ALL")
2026 (setq org-cycle-global-status 'all)
2027 (run-hook-with-args 'org-cycle-hook 'all))
2030 ;; Default action: go to overview
2032 (message "OVERVIEW")
2033 (setq org-cycle-global-status 'overview)
2034 (run-hook-with-args 'org-cycle-hook 'overview))))
2037 ;; Show-subtree, ARG levels up from here.
2039 (org-back-to-heading)
2040 (outline-up-heading (if (< arg 0) (- arg)
2041 (- (outline-level) arg)))
2042 (org-show-subtree)))
2044 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2045 ;; At a heading: rotate between three different views
2046 (org-back-to-heading)
2047 (let ((goal-column 0) eoh eol eos)
2048 ;; First, some boundaries
2050 (org-back-to-heading)
2052 (beginning-of-line 2)
2053 (while (and (not (eobp)) ;; this is like `next-line'
2054 (get-char-property (1- (point)) 'invisible))
2055 (beginning-of-line 2)) (setq eol (point)))
2056 (outline-end-of-heading) (setq eoh (point))
2057 (outline-end-of-subtree) (setq eos (point))
2058 (outline-next-heading))
2059 ;; Find out what to do next and set `this-command'
2062 ;; Nothing is hidden behind this heading
2063 (message "EMPTY ENTRY")
2064 (setq org-cycle-subtree-status nil))
2066 ;; Entire subtree is hidden in one line: open it
2069 (message "CHILDREN")
2070 (setq org-cycle-subtree-status 'children)
2071 (run-hook-with-args 'org-cycle-hook 'children))
2072 ((and (eq last-command this-command)
2073 (eq org-cycle-subtree-status 'children))
2074 ;; We just showed the children, now show everything.
2077 (setq org-cycle-subtree-status 'subtree)
2078 (run-hook-with-args 'org-cycle-hook 'subtree))
2080 ;; Default action: hide the subtree.
2083 (setq org-cycle-subtree-status 'folded)
2084 (run-hook-with-args 'org-cycle-hook 'folded)))))
2087 (buffer-read-only (org-back-to-heading))
2088 ((if (and (eq org-cycle-emulate-tab 'white)
2089 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2091 (eq org-cycle-emulate-tab t))
2092 (if (and (looking-at "[ \n\r\t]")
2093 (string-match "^[ \t]*$" (buffer-substring
2094 (point-at-bol) (point))))
2096 (beginning-of-line 1)
2097 (and (looking-at "[ \t]+") (replace-match ""))))
2101 (org-back-to-heading)
2104 (defun org-optimize-window-after-visibility-change (state)
2105 "Adjust the window after a change in outline visibility.
2106 This function is the default value of the hook `org-cycle-hook'."
2108 ((eq state 'overview) (org-first-headline-recenter 1))
2109 ((eq state 'content) nil)
2110 ((eq state 'all) nil)
2111 ((eq state 'folded) nil)
2112 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2113 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2115 (defun org-subtree-end-visible-p ()
2116 "Is the end of the current subtree visible?"
2117 (pos-visible-in-window-p
2118 (save-excursion (outline-end-of-subtree) (point))))
2120 (defun org-first-headline-recenter (&optional N)
2121 "Move cursor to the first headline and recenter the headline.
2122 Optional argument N means, put the headline into the Nth line of the window."
2123 (goto-char (point-min))
2124 (when (re-search-forward (concat "^" outline-regexp) nil t)
2126 (recenter (prefix-numeric-value N))))
2128 (defvar org-goto-window-configuration nil)
2129 (defvar org-goto-marker nil)
2130 (defvar org-goto-map (make-sparse-keymap))
2131 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2132 (while (setq cmd (pop cmds))
2133 (substitute-key-definition cmd cmd org-goto-map global-map)))
2134 (define-key org-goto-map "\C-m" 'org-goto-ret)
2135 (define-key org-goto-map [(left)] 'org-goto-left)
2136 (define-key org-goto-map [(right)] 'org-goto-right)
2137 (define-key org-goto-map [(?q)] 'org-goto-quit)
2138 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2139 (define-key org-goto-map "\C-i" 'org-cycle)
2140 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2141 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2142 (define-key org-goto-map "n" 'outline-next-visible-heading)
2143 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2144 (define-key org-goto-map "f" 'outline-forward-same-level)
2145 (define-key org-goto-map "b" 'outline-backward-same-level)
2146 (define-key org-goto-map "u" 'outline-up-heading)
2147 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2148 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2149 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2150 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2151 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2152 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2153 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2155 (defconst org-goto-help
2156 "Select a location to jump to, press RET
2157 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2160 "Go to a different location of the document, keeping current visibility.
2162 When you want to go to a different location in a document, the fastest way
2163 is often to fold the entire buffer and then dive into the tree. This
2164 method has the disadvantage, that the previous location will be folded,
2165 which may not be what you want.
2167 This command works around this by showing a copy of the current buffer in
2168 overview mode. You can dive into the tree in that copy, to find the
2169 location you want to reach. When pressing RET, the command returns to the
2170 original buffer in which the visibility is still unchanged. It then jumps
2171 to the new location, making it and the headline hierarchy above it visible."
2173 (let* ((org-goto-start-pos (point))
2175 (org-get-location (current-buffer) org-goto-help)))
2178 (goto-char selected-point)
2179 (if (org-invisible-p) (org-show-hierarchy-above)))
2182 (defun org-get-location (buf help)
2183 "Let the user select a location in the Org-mode buffer BUF.
2184 This function uses a recursive edit. It returns the selected position
2186 (let (org-selected-point)
2188 (save-window-excursion
2189 (delete-other-windows)
2190 (switch-to-buffer (get-buffer-create "*org-goto*"))
2191 (with-output-to-temp-buffer "*Help*"
2193 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2194 (setq buffer-read-only nil)
2197 (let ((org-startup-truncated t)
2198 (org-startup-folded t)
2199 (org-startup-with-deadline-check nil))
2201 (setq buffer-read-only t)
2202 (if (boundp 'org-goto-start-pos)
2203 (goto-char org-goto-start-pos)
2204 (goto-char (point-min)))
2205 (org-beginning-of-line)
2206 (message "Select location and press RET")
2207 ;; now we make sure that during selection, ony very few keys work
2208 ;; and that it is impossible to switch to another window.
2209 (let ((gm (current-global-map))
2210 (overriding-local-map org-goto-map))
2213 (use-global-map org-goto-map)
2215 (use-global-map gm)))))
2216 (kill-buffer "*org-goto*")
2217 org-selected-point))
2219 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2220 (defun org-goto-ret (&optional arg)
2221 "Finish org-goto by going to the new location."
2223 (setq org-selected-point (point)
2224 current-prefix-arg arg)
2227 (defun org-goto-left ()
2228 "Finish org-goto by going to the new location."
2230 (if (org-on-heading-p)
2232 (beginning-of-line 1)
2233 (setq org-selected-point (point)
2234 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2236 (error "Not on a heading")))
2238 (defun org-goto-right ()
2239 "Finish org-goto by going to the new location."
2241 (if (org-on-heading-p)
2243 (outline-end-of-subtree)
2244 (or (eobp) (forward-char 1))
2245 (setq org-selected-point (point)
2246 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2248 (error "Not on a heading")))
2250 (defun org-goto-quit ()
2251 "Finish org-goto without cursor motion."
2253 (setq org-selected-point nil)
2256 ;;; Promotion, Demotion, Inserting new headlines
2258 (defvar org-ignore-region nil
2259 "To temporarily disable the active region.")
2261 (defun org-insert-heading ()
2262 "Insert a new heading with same depth at point."
2264 (let* ((head (save-excursion
2266 (org-back-to-heading)
2267 (error (outline-next-heading)))
2268 (prog1 (match-string 0)
2269 (funcall outline-level)))))
2270 (unless (bolp) (newline))
2273 (save-excursion (newline-and-indent)))
2274 (unless (equal (char-before) ?\ )
2276 (run-hooks 'org-insert-heading-hook)))
2278 (defun org-insert-todo-heading (arg)
2279 "Insert a new heading with the same level and TODO state as current heading.
2280 If the heading has no TODO state, or if the state is DONE, use the first
2281 state (TODO by default). Also with prefix arg, force first state."
2283 (org-insert-heading)
2285 (org-back-to-heading)
2286 (outline-previous-heading)
2287 (looking-at org-todo-line-regexp))
2289 (not (match-beginning 2))
2290 (equal (match-string 2) org-done-string))
2291 (insert (car org-todo-keywords) " ")
2292 (insert (match-string 2) " ")))
2294 (defun org-promote-subtree ()
2295 "Promote the entire subtree.
2296 See also `org-promote'."
2299 (org-map-tree 'org-promote)))
2301 (defun org-demote-subtree ()
2302 "Demote the entire subtree. See `org-demote'.
2303 See also `org-promote'."
2306 (org-map-tree 'org-demote)))
2308 (defun org-do-promote ()
2309 "Promote the current heading higher up the tree.
2310 If the region is active in `transient-mark-mode', promote all headings
2314 (if (org-region-active-p)
2315 (org-map-region 'org-promote (region-beginning) (region-end))
2317 (org-fix-position-after-promote))
2319 (defun org-do-demote ()
2320 "Demote the current heading lower down the tree.
2321 If the region is active in `transient-mark-mode', demote all headings
2325 (if (org-region-active-p)
2326 (org-map-region 'org-demote (region-beginning) (region-end))
2328 (org-fix-position-after-promote))
2330 (defun org-fix-position-after-promote ()
2331 "Make sure that after pro/demotion cursor position is right."
2332 (and (equal (char-after) ?\ )
2333 (equal (char-before) ?*)
2336 (defun org-promote ()
2337 "Promote the current heading higher up the tree.
2338 If the region is active in `transient-mark-mode', promote all headings
2340 (org-back-to-heading t)
2341 (let* ((level (save-match-data (funcall outline-level)))
2342 (up-head (make-string (1- level) ?*)))
2343 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2344 (replace-match up-head nil t)
2345 (if org-adapt-indentation
2346 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2348 (defun org-demote ()
2349 "Demote the current heading lower down the tree.
2350 If the region is active in `transient-mark-mode', demote all headings
2352 (org-back-to-heading t)
2353 (let* ((level (save-match-data (funcall outline-level)))
2354 (down-head (make-string (1+ level) ?*)))
2355 (replace-match down-head nil t)
2356 (if org-adapt-indentation
2357 (org-fixup-indentation "^ " " " "^\\S-"))))
2359 (defun org-map-tree (fun)
2360 "Call FUN for every heading underneath the current one."
2361 (org-back-to-heading)
2362 (let ((level (outline-level)))
2366 (outline-next-heading)
2367 (> (funcall outline-level) level))
2371 (defun org-map-region (fun beg end)
2372 "Call FUN for every heading between BEG and END."
2373 (let ((org-ignore-region t))
2375 (setq end (copy-marker end))
2377 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2381 (outline-next-heading)
2386 (defun org-fixup-indentation (from to prohibit)
2387 "Change the indentation in the current entry by re-replacing FROM with TO.
2388 However, if the regexp PROHIBIT matches at all, don't do anything.
2389 This is being used to change indentation along with the length of the
2390 heading marker. But if there are any lines which are not indented, nothing
2393 (let ((end (save-excursion (outline-next-heading)
2395 (unless (save-excursion (re-search-forward prohibit end t))
2396 (while (re-search-forward from end t)
2398 (beginning-of-line 2)))
2399 (move-marker end nil))))
2401 ;;; Vertical tree motion, cutting and pasting of subtrees
2403 (defun org-move-subtree-up (&optional arg)
2404 "Move the current subtree up past ARG headlines of the same level."
2406 (org-move-subtree-down (- (prefix-numeric-value arg))))
2408 (defun org-move-subtree-down (&optional arg)
2409 "Move the current subtree down past ARG headlines of the same level."
2411 (setq arg (prefix-numeric-value arg))
2412 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2413 'outline-get-last-sibling))
2414 (ins-point (make-marker))
2418 (org-back-to-heading)
2421 (save-excursion (outline-end-of-heading)
2422 (setq folded (org-invisible-p)))
2423 (outline-end-of-subtree))
2424 (outline-next-heading)
2426 ;; Find insertion point, with error handling
2429 (or (and (funcall movfunc) (looking-at outline-regexp))
2430 (progn (goto-char beg)
2431 (error "Cannot move past superior level or buffer limit")))
2432 (setq cnt (1- cnt)))
2434 ;; Moving forward - still need to move over subtree
2435 (progn (outline-end-of-subtree)
2436 (outline-next-heading)
2437 (if (not (or (looking-at (concat "^" outline-regexp))
2440 (move-marker ins-point (point))
2441 (setq txt (buffer-substring beg end))
2442 (delete-region beg end)
2444 (goto-char ins-point)
2445 (if folded (hide-subtree))
2446 (move-marker ins-point nil)))
2448 (defvar org-subtree-clip ""
2449 "Clipboard for cut and paste of subtrees.
2450 This is actually only a copy of the kill, because we use the normal kill
2451 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2453 (defvar org-subtree-clip-folded nil
2454 "Was the last copied subtree folded?
2455 This is used to fold the tree back after pasting.")
2457 (defun org-cut-subtree ()
2458 "Cut the current subtree into the clipboard.
2459 This is a short-hand for marking the subtree and then cutting it."
2461 (org-copy-subtree 'cut))
2463 (defun org-copy-subtree (&optional cut)
2464 "Cut the current subtree into the clipboard.
2465 This is a short-hand for marking the subtree and then copying it.
2466 If CUT is non nil, actually cut the subtree."
2468 (let (beg end folded)
2469 (org-back-to-heading)
2472 (save-excursion (outline-end-of-heading)
2473 (setq folded (org-invisible-p)))
2474 (outline-end-of-subtree))
2475 (if (equal (char-after) ?\n) (forward-char 1))
2479 (setq org-subtree-clip-folded folded)
2480 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2481 (setq org-subtree-clip (current-kill 0))
2482 (message "%s: Subtree with %d characters"
2483 (if cut "Cut" "Copied")
2484 (length org-subtree-clip)))))
2486 (defun org-paste-subtree (&optional level tree)
2487 "Paste the clipboard as a subtree, with modification of headline level.
2488 The entire subtree is promoted or demoted in order to match a new headline
2489 level. By default, the new level is derived from the visible headings
2490 before and after the insertion point, and taken to be the inferior headline
2491 level of the two. So if the previous visible heading is level 3 and the
2492 next is level 4 (or vice versa), level 4 will be used for insertion.
2493 This makes sure that the subtree remains an independent subtree and does
2494 not swallow low level entries.
2496 You can also force a different level, either by using a numeric prefix
2497 argument, or by inserting the heading marker by hand. For example, if the
2498 cursor is after \"*****\", then the tree will be shifted to level 5.
2500 If you want to insert the tree as is, just use \\[yank].
2502 If optional TREE is given, use this text instead of the kill ring."
2504 (unless (org-kill-is-subtree-p tree)
2506 (substitute-command-keys
2507 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2508 (let* ((txt (or tree (current-kill 0)))
2509 (^re (concat "^\\(" outline-regexp "\\)"))
2510 (re (concat "\\(" outline-regexp "\\)"))
2511 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2513 (old-level (if (string-match ^re txt)
2514 (- (match-end 0) (match-beginning 0))
2516 (force-level (cond (level (prefix-numeric-value level))
2518 ^re_ (buffer-substring (point-at-bol) (point)))
2519 (- (match-end 0) (match-beginning 0)))
2521 (previous-level (save-excursion
2524 (outline-previous-visible-heading 1)
2526 (- (match-end 0) (match-beginning 0))
2529 (next-level (save-excursion
2532 (outline-next-visible-heading 1)
2534 (- (match-end 0) (match-beginning 0))
2537 (new-level (or force-level (max previous-level next-level)))
2538 (shift (if (or (= old-level -1)
2540 (= old-level new-level))
2542 (- new-level old-level)))
2544 (delta (if (> shift 0) -1 1))
2545 (func (if (> shift 0) 'org-demote 'org-promote))
2547 ;; Remove the forces level indicator
2549 (delete-region (point-at-bol) (point)))
2550 ;; Make sure we start at the beginning of an empty line
2551 (if (not (bolp)) (insert "\n"))
2552 (if (not (looking-at "[ \t]*$"))
2553 (progn (insert "\n") (backward-char 1)))
2559 ;; Shift if necessary
2561 (message "Pasted at level %d, without shift" new-level)
2563 (narrow-to-region beg end)
2564 (while (not (= shift 0))
2565 (org-map-region func (point-min) (point-max))
2566 (setq shift (+ delta shift)))
2567 (goto-char (point-min))
2568 (message "Pasted at level %d, with shift by %d levels"
2570 (if (and (eq org-subtree-clip (current-kill 0))
2571 org-subtree-clip-folded)
2572 ;; The tree was folded before it was killed/copied
2575 (defun org-kill-is-subtree-p (&optional txt)
2576 "Check if the current kill is an outline subtree, or a set of trees.
2577 Returns nil if kill does not start with a headline, or if the first
2578 headline level is not the largest headline level in the tree.
2579 So this will actually accept several entries of equal levels as well,
2580 which is OK for `org-paste-subtree'.
2581 If optional TXT is given, check this string instead of the current kill."
2582 (let* ((kill (or txt (current-kill 0) ""))
2583 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2584 (- (match-end 0) (match-beginning 0))))
2585 (re (concat "^" outline-regexp))
2587 (if (not start-level)
2588 nil ;; does not even start with a heading
2590 (while (setq start (string-match re kill (1+ start)))
2591 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2595 (defun org-archive-subtree ()
2596 "Move the current subtree to the archive.
2597 The archive can be a certain top-level heading in the current file, or in
2598 a different file. The tree will be moved to that location, the subtree
2599 heading be marked DONE, and the current time will be added."
2601 ;; Save all relevant TODO keyword-relatex variables
2602 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
2603 (tr-org-todo-keywords org-todo-keywords)
2604 (tr-org-todo-interpretation org-todo-interpretation)
2605 (tr-org-done-string org-done-string)
2606 (tr-org-todo-regexp org-todo-regexp)
2607 (tr-org-todo-line-regexp org-todo-line-regexp)
2608 (this-buffer (current-buffer))
2609 file heading buffer level newfile-p)
2610 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
2612 (setq file (format (match-string 1 org-archive-location)
2613 (file-name-nondirectory (buffer-file-name)))
2614 heading (match-string 2 org-archive-location)))
2615 (error "Invalid `org-archive-location'"))
2616 (if (> (length file) 0)
2617 (setq newfile-p (not (file-exists-p file))
2618 buffer (find-file-noselect file))
2619 (setq buffer (current-buffer)))
2621 (error "Cannot access file \"%s\"" file))
2622 (if (and (> (length heading) 0)
2623 (string-match "^\\*+" heading))
2624 (setq level (match-end 0))
2625 (setq heading nil level 0))
2627 (org-copy-subtree) ; We first only copy, in case something goes wrong
2629 ;; Enforce org-mode for the archive buffer
2630 (if (not (eq major-mode 'org-mode))
2631 ;; Force the mode for future visits.
2632 (let ((org-insert-mode-line-in-empty-file t))
2633 (call-interactively 'org-mode)))
2635 (goto-char (point-max))
2636 (insert (format "\nArchived entries from file %s\n\n"
2637 (buffer-file-name this-buffer))))
2638 ;; Force the TODO keywords of the original buffer
2639 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
2640 (org-todo-keywords tr-org-todo-keywords)
2641 (org-todo-interpretation tr-org-todo-interpretation)
2642 (org-done-string tr-org-done-string)
2643 (org-todo-regexp tr-org-todo-regexp)
2644 (org-todo-line-regexp tr-org-todo-line-regexp))
2645 (goto-char (point-min))
2648 (if (re-search-forward
2649 (concat "\\(^\\|\r\\)"
2650 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
2652 (goto-char (match-end 0))
2653 ;; Heading not found, just insert it at the end
2654 (goto-char (point-max))
2655 (or (bolp) (insert "\n"))
2656 (insert "\n" heading "\n")
2658 ;; Make the heading visible, and the following as well
2659 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
2660 (if (re-search-forward
2661 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
2663 (progn (goto-char (match-beginning 0)) (insert "\n")
2664 (beginning-of-line 0))
2665 (goto-char (point-max)) (insert "\n")))
2666 (goto-char (point-max)) (insert "\n"))
2668 (org-paste-subtree (1+ level))
2669 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
2670 (if org-archive-mark-done
2671 (org-todo (length org-todo-keywords)))
2672 ;; Move cursor to right after the TODO keyword
2673 (when org-archive-stamp-time
2674 (beginning-of-line 1)
2675 (looking-at org-todo-line-regexp)
2676 (goto-char (or (match-end 2) (match-beginning 3)))
2677 (insert "(" (format-time-string (cdr org-time-stamp-formats)
2680 ;; Save the buffer, if it is not the same buffer.
2681 (if (not (eq this-buffer buffer)) (save-buffer))))
2682 ;; Here we are back in the original buffer. Everything seems to have
2683 ;; worked. So now cut the tree and finish up.
2685 (if (looking-at "[ \t]*$") (kill-line))
2686 (message "Subtree archived %s"
2687 (if (eq this-buffer buffer)
2688 (concat "under heading: " heading)
2689 (concat "in file: " (abbreviate-file-name file))))))
2693 (defun org-complete (&optional arg)
2694 "Perform completion on word at point.
2695 At the beginning of a headline, this completes TODO keywords as given in
2696 `org-todo-keywords'.
2697 If the current word is preceded by a backslash, completes the TeX symbols
2698 that are supported for HTML support.
2699 If the current word is preceded by \"#+\", completes special words for
2700 setting file options.
2701 At all other locations, this simply calls `ispell-complete-word'."
2704 (let* ((end (point))
2705 (beg (save-excursion
2706 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2707 (skip-chars-backward "a-zA-Z0-9_:$")
2709 (texp (equal (char-before beg) ?\\))
2710 (form (equal (char-before beg) ?=))
2711 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2714 (pattern (buffer-substring-no-properties beg end))
2715 (completion-ignore-case opt)
2721 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2722 (cons (match-string 2 x) (match-string 1 x)))
2723 (org-split-string (org-get-current-options) "\n")))
2729 '(("sum") ("sumv") ("sumh")))
2730 ((string-match "\\`\\*+[ \t]*\\'"
2731 (buffer-substring (point-at-bol) beg))
2733 (mapcar 'list org-todo-keywords))
2734 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2735 (completion (try-completion pattern table)))
2736 (cond ((eq completion t)
2737 (if (equal type :opt)
2738 (insert (substring (cdr (assoc (upcase pattern) table))
2739 (length pattern)))))
2741 (message "Can't find completion for \"%s\"" pattern)
2743 ((not (string= pattern completion))
2744 (delete-region beg end)
2745 (if (string-match " +$" completion)
2746 (setq completion (replace-match "" t t completion)))
2748 (if (get-buffer-window "*Completions*")
2749 (delete-window (get-buffer-window "*Completions*")))
2750 (if (and (eq type :todo)
2751 (assoc completion table))
2753 (if (and (equal type :opt) (assoc completion table))
2754 (message (substitute-command-keys
2755 "Press \\[org-complete] again to insert example settings"))))
2757 (message "Making completion list...")
2758 (let ((list (sort (all-completions pattern table) 'string<)))
2759 (with-output-to-temp-buffer "*Completions*"
2760 (display-completion-list list)))
2761 (message "Making completion list...%s" "done"))))))
2763 ;;; Comments, TODO and DEADLINE
2765 (defun org-toggle-comment ()
2766 "Change the COMMENT state of an entry."
2769 (org-back-to-heading)
2770 (if (looking-at (concat outline-regexp
2771 "\\( +\\<" org-comment-string "\\>\\)"))
2772 (replace-match "" t t nil 1)
2773 (if (looking-at outline-regexp)
2775 (goto-char (match-end 0))
2776 (insert " " org-comment-string))))))
2778 (defvar org-last-todo-state-is-todo nil
2779 "This is non-nil when the last TODO state change led to a TODO state.
2780 If the last change removed the TODO tag or switched to DONE, then
2783 (defun org-todo (&optional arg)
2784 "Change the TODO state of an item.
2785 The state of an item is given by a keyword at the start of the heading,
2787 *** TODO Write paper
2790 The different keywords are specified in the variable `org-todo-keywords'. By
2791 default the available states are \"TODO\" and \"DONE\".
2792 So for this example: when the item starts with TODO, it is changed to DONE.
2793 When it starts with DONE, the DONE is removed. And when neither TODO nor
2794 DONE are present, add TODO at the beginning of the heading.
2796 With prefix arg, use completion to determined the new state. With numeric
2797 prefix arg, switch to that state."
2800 (org-back-to-heading)
2801 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2802 (or (looking-at (concat " +" org-todo-regexp " *"))
2804 (let* ((this (match-string 1))
2805 (completion-ignore-case t)
2806 (member (member this org-todo-keywords))
2810 ;; Read a state with completion
2811 (completing-read "State: " (mapcar (lambda(x) (list x))
2815 ;; user requests a specific state
2816 (nth (1- (prefix-numeric-value arg))
2818 ((null member) (car org-todo-keywords))
2819 ((null tail) nil) ;; -> first entry
2820 ((eq org-todo-interpretation 'sequence)
2822 ((memq org-todo-interpretation '(type priority))
2823 (if (eq this-command last-command)
2825 (if (> (length tail) 0) org-done-string nil)))
2827 (next (if state (concat " " state " ") " ")))
2828 (replace-match next t t)
2829 (setq org-last-todo-state-is-todo
2830 (not (equal state org-done-string)))
2831 (run-hooks 'org-after-todo-state-change-hook)))
2832 ;; Fixup cursor location if close to the keyword
2833 (if (and (outline-on-heading-p)
2835 (save-excursion (beginning-of-line 1)
2836 (looking-at org-todo-line-regexp))
2837 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2839 (goto-char (or (match-end 2) (match-end 1)))
2842 (defun org-show-todo-tree (arg)
2843 "Make a compact tree which shows all headlines marked with TODO.
2844 The tree will show the lines where the regexp matches, and all higher
2845 headlines above the match."
2847 (let ((case-fold-search nil)
2848 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2849 (message "%d TODO entries found"
2850 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2852 (defun org-deadline ()
2853 "Insert the DEADLINE: string to make a deadline.
2854 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2855 to modify it to the correct date."
2858 org-deadline-string " "
2859 (format-time-string (car org-time-stamp-formats)
2860 (org-read-date nil 'to-time)))
2861 (message (substitute-command-keys
2862 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2864 (defun org-schedule ()
2865 "Insert the SCHEDULED: string to schedule a TODO item.
2866 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2867 to modify it to the correct date."
2870 org-scheduled-string " "
2871 (format-time-string (car org-time-stamp-formats)
2872 (org-read-date nil 'to-time)))
2873 (message (substitute-command-keys
2874 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2877 (defun org-occur (regexp &optional callback)
2878 "Make a compact tree which shows all matches of REGEXP.
2879 The tree will show the lines where the regexp matches, and all higher
2880 headlines above the match. It will also show the heading after the match,
2881 to make sure editing the matching entry is easy.
2882 if CALLBACK is non-nil, it is a function which is called to confirm
2883 that the match should indeed be shown."
2884 (interactive "sRegexp: ")
2885 (setq regexp (org-check-occur-regexp regexp))
2888 (goto-char (point-min))
2890 (while (re-search-forward regexp nil t)
2891 (when (or (not callback)
2894 (org-show-hierarchy-above))))
2895 (run-hooks 'org-occur-hook)
2897 (message "%d match(es) for regexp %s" cnt regexp))
2900 (defun org-show-hierarchy-above ()
2901 "Make sure point and the headings hierarchy above is visible."
2902 (if (org-on-heading-p t)
2903 (org-flag-heading nil) ; only show the heading
2904 (org-show-hidden-entry)) ; show entire entry
2906 (and org-show-following-heading
2907 (outline-next-heading)
2908 (org-flag-heading nil))) ; show the next heading
2909 (save-excursion ; show all higher headings
2910 (while (condition-case nil
2911 (progn (org-up-heading-all 1) t)
2913 (org-flag-heading nil))))
2917 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
2918 "Regular expression matching the priority indicator.")
2920 (defvar org-remove-priority-next-time nil)
2922 (defun org-priority-up ()
2923 "Increase the priority of the current item."
2927 (defun org-priority-down ()
2928 "Decrease the priority of the current item."
2930 (org-priority 'down))
2932 (defun org-priority (&optional action)
2933 "Change the priority of an item by ARG.
2934 ACTION can be set, up, or down."
2936 (setq action (or action 'set))
2937 (let (current new news have remove)
2939 (org-back-to-heading)
2940 (if (looking-at org-priority-regexp)
2941 (setq current (string-to-char (match-string 2))
2943 (setq current org-default-priority))
2946 (message (format "Priority A-%c, SPC to remove: " org-lowest-priority))
2947 (setq new (read-char-exclusive))
2948 (cond ((equal new ?\ ) (setq remove t))
2949 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
2950 (error "Priority must be between `%c' and `%c'"
2951 ?A org-lowest-priority))))
2953 (setq new (1- current)))
2955 (setq new (1+ current)))
2956 (t (error "Invalid action")))
2957 (setq new (min (max ?A (upcase new)) org-lowest-priority))
2958 (setq news (format "%c" new))
2961 (replace-match "" t t nil 1)
2962 (replace-match news t t nil 2))
2964 (error "No priority cookie found in line")
2965 (looking-at org-todo-line-regexp)
2968 (goto-char (match-end 2))
2969 (insert " [#" news "]"))
2970 (goto-char (match-beginning 3))
2971 (insert "[#" news "] ")))))
2973 (message "Priority removed")
2974 (message "Priority of current item set to %s" news))))
2977 (defun org-get-priority (s)
2978 "Find priority cookie and return priority."
2980 (if (not (string-match org-priority-regexp s))
2981 (* 1000 (- org-lowest-priority org-default-priority))
2982 (* 1000 (- org-lowest-priority
2983 (string-to-char (match-string 2 s)))))))
2987 (defvar org-last-changed-timestamp nil)
2989 (defun org-time-stamp (arg)
2990 "Prompt for a date/time and insert a time stamp.
2991 If the user specifies a time like HH:MM, or if this command is called
2992 with a prefix argument, the time stamp will contain date and time.
2993 Otherwise, only the date will be included. All parts of a date not
2994 specified by the user will be filled in from the current date/time.
2995 So if you press just return without typing anything, the time stamp
2996 will represent the current date/time. If there is already a timestamp
2997 at the cursor, it will be modified."
2999 (let ((fmt (if arg (cdr org-time-stamp-formats)
3000 (car org-time-stamp-formats)))
3001 (org-time-was-given nil)
3004 ((and (org-at-timestamp-p)
3005 (eq last-command 'org-time-stamp)
3006 (eq this-command 'org-time-stamp))
3008 (setq time (let ((this-command this-command))
3009 (org-read-date arg 'totime)))
3010 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3011 (insert (format-time-string fmt time)))
3012 ((org-at-timestamp-p)
3013 (setq time (let ((this-command this-command))
3014 (org-read-date arg 'totime)))
3015 (and (org-at-timestamp-p) (replace-match
3016 (setq org-last-changed-timestamp
3017 (format-time-string fmt time))
3019 (message "Timestamp updated"))
3021 (setq time (let ((this-command this-command))
3022 (org-read-date arg 'totime)))
3023 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3024 (insert (format-time-string fmt time))))))
3026 ;;; FIXME: Make the function take "Fri" as "next friday"
3027 (defun org-read-date (&optional with-time to-time)
3028 "Read a date and make things smooth for the user.
3029 The prompt will suggest to enter an ISO date, but you can also enter anything
3030 which will at least partially be understood by `parse-time-string'.
3031 Unrecognized parts of the date will default to the current day, month ,year,
3032 hour and minute. For example,
3033 3-2-5 --> 2003-02-05
3034 feb 15 --> currentyear-02-15
3035 sep 12 9 --> 2009-09-12
3036 12:45 --> today 12:45
3037 22 sept 0:34 --> currentyear-09-22 0:34
3038 12 --> currentyear-currentmonth-12
3040 The function understands only English month and weekday abbreviations,
3041 but this can be configured with the variables `parse-time-months' and
3042 `parse-time-weekdays'.
3044 While prompting, a calendar is popped up - you can also select the
3045 date with the mouse (button 1). The calendar shows a period of three
3046 month. To scroll it to other months, use the keys `>' and `<'.
3047 If you don't like the calendar, turn it off with
3048 \(setq org-popup-calendar-for-date-prompt nil).
3050 With optional argument TO-TIME, the date will immediately be converted
3051 to an internal time.
3052 With an optional argument WITH-TIME, the prompt will suggest to also
3053 insert a time. Note that when WITH-TIME is not set, you can still
3054 enter a time, and this function will inform the calling routine about
3055 this change. The calling routine may then choose to change the format
3056 used to insert the time stamp into the buffer to include the time."
3057 (let* ((default-time
3058 ;; Default time is either today, or, when entering a range,
3062 (concat org-ts-regexp "--\\=")
3066 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3067 (parse-time-string (match-string 1))))
3069 (timestr (format-time-string
3070 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3071 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3073 second minute hour day month year tl)
3075 (if org-popup-calendar-for-date-prompt
3076 ;; Also show a calendar for date selection
3077 ;; Copied (with modifications) from planner.el by John Wiegley
3079 (save-window-excursion
3081 (calendar-forward-day (- (time-to-days default-time)
3082 (calendar-absolute-from-gregorian
3083 (calendar-current-date))))
3084 (let* ((old-map (current-local-map))
3085 (map (copy-keymap calendar-mode-map))
3086 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3087 (define-key map (kbd "RET") 'org-calendar-select)
3088 (define-key map (if org-xemacs-p [button1] [mouse-1])
3089 'org-calendar-select)
3090 (define-key minibuffer-local-map [(meta shift left)]
3091 (lambda () (interactive)
3092 (org-eval-in-calendar '(calendar-backward-month 1))))
3093 (define-key minibuffer-local-map [(meta shift right)]
3094 (lambda () (interactive)
3095 (org-eval-in-calendar '(calendar-forward-month 1))))
3096 (define-key minibuffer-local-map [(shift up)]
3097 (lambda () (interactive)
3098 (org-eval-in-calendar '(calendar-backward-week 1))))
3099 (define-key minibuffer-local-map [(shift down)]
3100 (lambda () (interactive)
3101 (org-eval-in-calendar '(calendar-forward-week 1))))
3102 (define-key minibuffer-local-map [(shift left)]
3103 (lambda () (interactive)
3104 (org-eval-in-calendar '(calendar-backward-day 1))))
3105 (define-key minibuffer-local-map [(shift right)]
3106 (lambda () (interactive)
3107 (org-eval-in-calendar '(calendar-forward-day 1))))
3108 (define-key minibuffer-local-map ">"
3109 (lambda () (interactive)
3110 (org-eval-in-calendar '(scroll-calendar-left 1))))
3111 (define-key minibuffer-local-map "<"
3112 (lambda () (interactive)
3113 (org-eval-in-calendar '(scroll-calendar-right 1))))
3117 (setq ans (read-string prompt "" nil nil))
3118 (setq ans (or ans1 ans2 ans)))
3119 (use-local-map old-map)))))
3120 ;; Naked prompt only
3121 (setq ans (read-string prompt "" nil timestr)))
3124 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3126 (setq year (if (match-end 2)
3127 (string-to-number (match-string 2 ans))
3128 (string-to-number (format-time-string "%Y")))
3129 month (string-to-number (match-string 3 ans))
3130 day (string-to-number (match-string 4 ans)))
3131 (if (< year 100) (setq year (+ 2000 year)))
3132 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3134 (setq tl (parse-time-string ans)
3135 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3136 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3137 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3138 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3139 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3140 second (or (nth 0 tl) 0))
3141 (if (and (boundp 'org-time-was-given)
3143 (setq org-time-was-given t))
3144 (if (< year 100) (setq year (+ 2000 year)))
3146 (encode-time second minute hour day month year)
3147 (if (or (nth 1 tl) (nth 2 tl))
3148 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3149 (format "%04d-%02d-%02d" year month day)))))
3151 (defun org-eval-in-calendar (form)
3152 "Eval FORM in the calendar window and return to current window.
3153 Also, store the cursor date in variable ans2."
3154 (let ((sw (selected-window)))
3155 (select-window (get-buffer-window "*Calendar*"))
3157 (when (calendar-cursor-to-date)
3158 (let* ((date (calendar-cursor-to-date))
3159 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3160 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3161 (select-window sw)))
3163 (defun org-calendar-select ()
3164 "Return to `org-read-date' with the date currently selected.
3165 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3167 (when (calendar-cursor-to-date)
3168 (let* ((date (calendar-cursor-to-date))
3169 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3170 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3171 (if (active-minibuffer-window) (exit-minibuffer))))
3173 (defun org-check-deadlines (ndays)
3174 "Check if there are any deadlines due or past due.
3175 A deadline is considered due if it happens within `org-deadline-warning-days'
3176 days from today's date. If the deadline appears in an entry marked DONE,
3177 it is not shown. The prefix arg NDAYS can be used to test that many
3178 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3180 (let* ((org-warn-days
3182 ((equal ndays '(4)) 100000)
3183 (ndays (prefix-numeric-value ndays))
3184 (t org-deadline-warning-days)))
3185 (case-fold-search nil)
3186 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3189 (and (let ((d1 (time-to-days (current-time)))
3191 (org-time-string-to-time (match-string 1)))))
3192 (< (- d2 d1) org-warn-days))
3193 (not (org-entry-is-done-p))))))
3194 (message "%d deadlines past-due or due within %d days"
3195 (org-occur regexp callback)
3198 (defun org-evaluate-time-range (&optional to-buffer)
3199 "Evaluate a time range by computing the difference between start and end.
3200 Normally the result is just printed in the echo area, but with prefix arg
3201 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3202 If the time range is actually in a table, the result is inserted into the
3204 For time difference computation, a year is assumed to be exactly 365
3205 days in order to avoid rounding problems."
3208 (unless (org-at-date-range-p)
3209 (goto-char (point-at-bol))
3210 (re-search-forward org-tr-regexp (point-at-eol) t))
3211 (if (not (org-at-date-range-p))
3212 (error "Not at a time-stamp range, and none found in current line")))
3213 (let* ((ts1 (match-string 1))
3214 (ts2 (match-string 2))
3215 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3216 (match-end (match-end 0))
3217 (time1 (org-time-string-to-time ts1))
3218 (time2 (org-time-string-to-time ts2))
3219 (t1 (time-to-seconds time1))
3220 (t2 (time-to-seconds time2))
3221 (diff (abs (- t2 t1)))
3222 (negative (< (- t2 t1) 0))
3223 ;; (ys (floor (* 365 24 60 60)))
3226 (fy "%dy %dd %02d:%02d")
3228 (fd "%dd %02d:%02d")
3232 ;; FIXME: Should I re-introduce years, make year refer to same date?
3233 ;; This would be the only useful way to have years, actually.
3235 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3237 d (floor (/ diff ds)) diff (mod diff ds)
3238 h (floor (/ diff hs)) diff (mod diff hs)
3239 m (floor (/ diff 60)))
3240 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3242 d (floor (+ (/ diff ds) 0.5))
3245 (message (org-make-tdiff-string y d h m))
3246 (when (org-at-table-p)
3247 (goto-char match-end)
3249 (and (looking-at " *|") (goto-char (match-end 0))))
3251 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3253 (if negative (insert " -"))
3254 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3255 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3256 (insert " " (format fh h m))))
3257 (if align (org-table-align))
3258 (message "Time difference inserted"))))
3260 (defun org-make-tdiff-string (y d h m)
3263 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3265 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3267 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3269 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3271 (apply 'format fmt (nreverse l))))
3273 (defun org-time-string-to-time (s)
3274 (apply 'encode-time (org-parse-time-string s)))
3276 (defun org-parse-time-string (s &optional nodefault)
3277 "Parse the standard Org-mode time string.
3278 This should be a lot faster than the normal `parse-time-string'.
3279 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3280 hour and minute fields will be nil if not given."
3281 (if (string-match org-ts-regexp1 s)
3283 (if (or (match-beginning 8) (not nodefault))
3284 (string-to-number (or (match-string 8 s) "0")))
3285 (if (or (match-beginning 7) (not nodefault))
3286 (string-to-number (or (match-string 7 s) "0")))
3287 (string-to-number (match-string 4 s))
3288 (string-to-number (match-string 3 s))
3289 (string-to-number (match-string 2 s))
3293 (defun org-timestamp-up (&optional arg)
3294 "Increase the date item at the cursor by one.
3295 If the cursor is on the year, change the year. If it is on the month or
3296 the day, change that.
3297 With prefix ARG, change by that many units."
3299 (org-timestamp-change (prefix-numeric-value arg)))
3301 (defun org-timestamp-down (&optional arg)
3302 "Decrease the date item at the cursor by one.
3303 If the cursor is on the year, change the year. If it is on the month or
3304 the day, change that.
3305 With prefix ARG, change by that many units."
3307 (org-timestamp-change (- (prefix-numeric-value arg))))
3309 (defun org-timestamp-up-day (&optional arg)
3310 "Increase the date in the time stamp by one day.
3311 With prefix ARG, change that many days."
3313 (org-timestamp-change (prefix-numeric-value arg) 'day))
3315 (defun org-timestamp-down-day (&optional arg)
3316 "Decrease the date in the time stamp by one day.
3317 With prefix ARG, change that many days."
3319 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
3321 (defsubst org-pos-in-match-range (pos n)
3322 (and (match-beginning n)
3323 (<= (match-beginning n) pos)
3324 (>= (match-end n) pos)))
3326 (defun org-at-timestamp-p ()
3327 "Determine if the cursor is or at a timestamp."
3329 (let* ((tsr org-ts-regexp2)
3331 (ans (or (looking-at tsr)
3333 (skip-chars-backward "^<\n\r\t")
3334 (if (> (point) 1) (backward-char 1))
3335 (and (looking-at tsr)
3336 (> (- (match-end 0) pos) -1))))))
3337 (and (boundp 'org-ts-what)
3340 ((org-pos-in-match-range pos 2) 'year)
3341 ((org-pos-in-match-range pos 3) 'month)
3342 ((org-pos-in-match-range pos 7) 'hour)
3343 ((org-pos-in-match-range pos 8) 'minute)
3344 ((or (org-pos-in-match-range pos 4)
3345 (org-pos-in-match-range pos 5)) 'day)
3349 (defun org-timestamp-change (n &optional what)
3350 "Change the date in the time stamp at point.
3351 The date will be changed by N times WHAT. WHAT can be `day', `month',
3352 `year', `minute', `second'. If WHAT is not given, the cursor position
3353 in the timestamp determines what will be changed."
3354 (let ((fmt (car org-time-stamp-formats))
3358 (if (not (org-at-timestamp-p))
3359 (error "Not at a timestamp"))
3360 (setq org-ts-what (or what org-ts-what))
3361 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3362 (- (match-end 0) (match-beginning 0))))
3364 (cdr org-time-stamp-formats)
3365 (car org-time-stamp-formats)))
3366 (setq ts (match-string 0))
3368 (setq time0 (org-parse-time-string ts))
3372 (list (or (car time0) 0))
3373 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3374 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3375 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3376 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3377 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3379 (if (eq what 'calendar)
3383 (set-buffer "*Calendar*")
3384 (calendar-cursor-to-date)))))
3385 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3386 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3387 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3388 (setcar time0 (or (car time0) 0))
3389 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3390 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3391 (setq time (apply 'encode-time time0))))
3392 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3394 ;; Try to recenter the calendar window, if any
3395 (if (and org-calendar-follow-timestamp-change
3396 (get-buffer-window "*Calendar*" t)
3397 (memq org-ts-what '(day month year)))
3398 (org-recenter-calendar (time-to-days time)))))
3400 (defun org-recenter-calendar (date)
3401 "If the calendar is visible, recenter it to DATE."
3402 (let* ((win (selected-window))
3403 (cwin (get-buffer-window "*Calendar*" t)))
3405 (select-window cwin)
3406 (calendar-goto-date (if (listp date) date
3407 (calendar-gregorian-from-absolute date)))
3408 (select-window win))))
3410 (defun org-goto-calendar (&optional arg)
3411 "Go to the Emacs calendar at the current date.
3412 If there is a time stamp in the current line, go to that date.
3413 A prefix ARG can be used force the current date."
3415 (let ((tsr org-ts-regexp) diff)
3416 (if (or (org-at-timestamp-p)
3418 (beginning-of-line 1)
3419 (looking-at (concat ".*" tsr))))
3420 (let ((d1 (time-to-days (current-time)))
3422 (org-time-string-to-time (match-string 1)))))
3423 (setq diff (- d2 d1))))
3425 (calendar-goto-today)
3426 (if (and diff (not arg)) (calendar-forward-day diff))))
3428 (defun org-date-from-calendar ()
3429 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
3430 If there is already a time stamp at the cursor position, update it."
3432 (org-timestamp-change 0 'calendar))
3434 ;;; Agenda, and Diary Integration
3438 (defvar org-agenda-mode-map (make-sparse-keymap)
3439 "Keymap for `org-agenda-mode'.")
3441 (defvar org-agenda-menu)
3442 (defvar org-agenda-follow-mode nil)
3443 (defvar org-agenda-buffer-name "*Org Agenda*")
3444 (defvar org-agenda-redo-command nil)
3445 (defvar org-agenda-mode-hook nil)
3448 (defun org-agenda-mode ()
3449 "Mode for time-sorted view on action items in Org-mode files.
3451 The following commands are available:
3453 \\{org-agenda-mode-map}"
3455 (kill-all-local-variables)
3456 (setq major-mode 'org-agenda-mode)
3457 (setq mode-name "Org-Agenda")
3458 (use-local-map org-agenda-mode-map)
3459 (easy-menu-add org-agenda-menu)
3460 (if org-startup-truncated (setq truncate-lines t))
3461 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
3462 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
3463 (setq org-agenda-follow-mode nil)
3465 '("Agenda") "Agenda Files"
3468 ["Edit File List" (customize-variable 'org-agenda-files) t]
3470 (mapcar 'org-file-menu-entry org-agenda-files)))
3471 (org-agenda-set-mode-name)
3473 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
3474 org-agenda-mode-hook))
3476 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
3477 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
3478 (define-key org-agenda-mode-map " " 'org-agenda-show)
3479 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
3480 (define-key org-agenda-mode-map "o" 'delete-other-windows)
3481 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
3482 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
3483 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
3484 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
3485 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
3486 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
3487 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
3489 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
3490 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3491 (while l (define-key org-agenda-mode-map
3492 (int-to-string (pop l)) 'digit-argument)))
3494 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
3495 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
3496 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
3497 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
3498 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
3499 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
3500 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
3501 (define-key org-agenda-mode-map "n" 'next-line)
3502 (define-key org-agenda-mode-map "p" 'previous-line)
3503 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
3504 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
3505 (define-key org-agenda-mode-map "," 'org-agenda-priority)
3506 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
3507 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
3508 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
3509 (eval-after-load "calendar"
3510 '(define-key calendar-mode-map org-calendar-to-agenda-key
3511 'org-calendar-goto-agenda))
3512 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
3513 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
3514 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3515 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3516 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3517 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3518 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3519 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3520 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3521 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
3522 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
3523 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3524 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3526 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3527 "Local keymap for agenda entries from Org-mode.")
3529 (define-key org-agenda-keymap
3530 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3531 (define-key org-agenda-keymap
3532 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3534 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3538 ["Show" org-agenda-show t]
3539 ["Go To (other window)" org-agenda-goto t]
3540 ["Go To (one window)" org-agenda-switch-to t]
3541 ["Follow Mode" org-agenda-follow-mode
3542 :style toggle :selected org-agenda-follow-mode :active t]
3544 ["Cycle TODO" org-agenda-todo t]
3546 ["Reschedule +1 day" org-agenda-date-later t]
3547 ["Reschedule -1 day" org-agenda-date-earlier t]
3549 ["Reschedule to ..." org-agenda-date-prompt t])
3551 ["Set Priority" org-agenda-priority t]
3552 ["Increase Priority" org-agenda-priority-up t]
3553 ["Decrease Priority" org-agenda-priority-down t]
3554 ["Show Priority" org-agenda-show-priority t])
3556 ["Rebuild buffer" org-agenda-redo t]
3557 ["Goto Today" org-agenda-goto-today t]
3558 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3559 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3561 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
3562 :style radio :selected (equal org-agenda-ndays 1)]
3563 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
3564 :style radio :selected (equal org-agenda-ndays 7)]
3566 ["Include Diary" org-agenda-toggle-diary
3567 :style toggle :selected org-agenda-include-diary :active t]
3568 ["Use Time Grid" org-agenda-toggle-time-grid
3569 :style toggle :selected org-agenda-use-time-grid :active t]
3571 ["New Diary Entry" org-agenda-diary-entry t]
3572 ("Calendar Commands"
3573 ["Goto Calendar" org-agenda-goto-calendar t]
3574 ["Phases of the Moon" org-agenda-phases-of-moon t]
3575 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3576 ["Holidays" org-agenda-holidays t]
3577 ["Convert" org-agenda-convert-date t])
3579 ["Quit" org-agenda-quit t]
3580 ["Exit and Release Buffers" org-agenda-exit t]
3583 (defvar org-agenda-markers nil
3584 "List of all currently active markers created by `org-agenda'.")
3585 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3586 "Creation time of the last agenda marker.")
3588 (defun org-agenda-new-marker (&optional pos)
3589 "Return a new agenda marker.
3590 Org-mode keeps a list of these markers and resets them when they are
3592 (let ((m (copy-marker (or pos (point)))))
3593 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3594 (push m org-agenda-markers)
3597 (defun org-agenda-maybe-reset-markers (&optional force)
3598 "Reset markers created by `org-agenda'. But only if they are old enough."
3600 (> (- (time-to-seconds (current-time))
3601 org-agenda-last-marker-time)
3603 (while org-agenda-markers
3604 (move-marker (pop org-agenda-markers) nil))))
3606 (defvar org-agenda-new-buffers nil
3607 "Buffers created to visit agenda files.")
3609 (defun org-get-agenda-file-buffer (file)
3610 "Get a buffer visiting FILE. If the buffer needs to be created, add
3611 it to the list of buffers which might be released later."
3612 (let ((buf (find-buffer-visiting file)))
3614 buf ; just return it
3615 ;; Make a new buffer and remember it
3616 (setq buf (find-file-noselect file))
3617 (if buf (push buf org-agenda-new-buffers))
3620 (defun org-release-buffers (blist)
3621 "Release all buffers in list, asking the user for confirmation when needed.
3622 When a buffer is unmodified, it is just killed. When modified, it is saved
3623 \(if the user agrees) and then killed."
3625 (while (setq buf (pop blist))
3626 (setq file (buffer-file-name buf))
3627 (when (and (buffer-modified-p buf)
3629 (y-or-n-p (format "Save file %s? " file)))
3630 (with-current-buffer buf (save-buffer)))
3631 (kill-buffer buf))))
3633 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
3635 (defun org-timeline (&optional include-all)
3636 "Show a time-sorted view of the entries in the current org file.
3637 Only entries with a time stamp of today or later will be listed. With
3638 one \\[universal-argument] prefix argument, past entries will also be listed.
3639 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
3640 under the current date.
3641 If the buffer contains an active region, only check the region for
3645 (org-agenda-maybe-reset-markers 'force)
3646 (org-compile-prefix-format org-timeline-prefix-format)
3647 (let* ((dopast include-all)
3648 (dotodo (equal include-all '(16)))
3649 (entry (buffer-file-name))
3650 (org-agenda-files (list (buffer-file-name)))
3651 (date (calendar-current-date))
3652 (win (selected-window))
3654 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3655 (end (if (org-region-active-p) (region-end) (point-max)))
3656 (day-numbers (org-get-all-dates beg end 'no-ranges
3657 t)) ; always include today
3658 (today (time-to-days (current-time)))
3659 (org-respect-restriction t)
3662 (setq org-agenda-redo-command
3664 (list 'switch-to-buffer-other-window (current-buffer))
3665 (list 'org-timeline include-all)))
3667 ;; Remove past dates from the list of dates.
3668 (setq day-numbers (delq nil (mapcar (lambda(x)
3669 (if (>= x today) x nil))
3671 (switch-to-buffer-other-window
3672 (get-buffer-create org-agenda-buffer-name))
3673 (setq buffer-read-only nil)
3675 (org-agenda-mode) (setq buffer-read-only nil)
3676 (while (setq d (pop day-numbers))
3677 (if (and (>= d today)
3682 (insert (make-string 79 ?-) "\n")))
3683 (setq date (calendar-gregorian-from-absolute d))
3686 (setq rtn (org-agenda-get-day-entries
3687 entry date :todo :timestamp))
3688 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3689 (if (or rtn (equal d today))
3691 (insert (calendar-day-name date) " "
3692 (number-to-string (extract-calendar-day date)) " "
3693 (calendar-month-name (extract-calendar-month date)) " "
3694 (number-to-string (extract-calendar-year date)) "\n")
3695 (put-text-property s (1- (point)) 'face
3698 (put-text-property s (1- (point)) 'org-today t))
3699 (insert (org-finalize-agenda-entries rtn) "\n")
3700 (put-text-property s (1- (point)) 'day d))))
3701 (goto-char (point-min))
3702 (setq buffer-read-only t)
3703 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3705 (when (not org-select-timeline-window)
3710 (defun org-agenda (&optional include-all start-day ndays)
3711 "Produce a weekly view from all files in variable `org-agenda-files'.
3712 The view will be for the current week, but from the overview buffer you
3713 will be able to go to other weeks.
3714 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
3715 also be shown, under the current date.
3716 START-DAY defaults to TODAY, or to the most recent match for the weekday
3717 given in `org-agenda-start-on-weekday'.
3718 NDAYS defaults to `org-agenda-ndays'."
3720 (org-agenda-maybe-reset-markers 'force)
3721 (org-compile-prefix-format org-agenda-prefix-format)
3723 (let* ((org-agenda-start-on-weekday
3724 (if (or (equal ndays 1)
3725 (and (null ndays) (equal 1 org-agenda-ndays)))
3726 nil org-agenda-start-on-weekday))
3727 (files (copy-sequence org-agenda-files))
3728 (win (selected-window))
3729 (today (time-to-days (current-time)))
3730 (sd (or start-day today))
3731 (start (if (or (null org-agenda-start-on-weekday)
3732 (< org-agenda-ndays 7))
3734 (let* ((nt (calendar-day-of-week
3735 (calendar-gregorian-from-absolute sd)))
3736 (n1 org-agenda-start-on-weekday)
3738 (- sd (+ (if (< d 0) 7 0) d)))))
3739 (day-numbers (list start))
3740 (inhibit-redisplay t)
3741 s e rtn rtnall file date d start-pos end-pos todayp nd)
3742 (setq org-agenda-redo-command
3743 (list 'org-agenda include-all start-day ndays))
3744 ;; Make the list of days
3745 (setq ndays (or ndays org-agenda-ndays)
3748 (push (1+ (car day-numbers)) day-numbers)
3749 (setq ndays (1- ndays)))
3750 (setq day-numbers (nreverse day-numbers))
3751 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3753 (delete-other-windows)
3754 (switch-to-buffer-other-window
3755 (get-buffer-create org-agenda-buffer-name))))
3756 (setq buffer-read-only nil)
3758 (org-agenda-mode) (setq buffer-read-only nil)
3759 (set (make-local-variable 'starting-day) (car day-numbers))
3760 (set (make-local-variable 'include-all-loc) include-all)
3761 (when (and (or include-all org-agenda-include-all-todo)
3762 (member today day-numbers))
3763 (setq files org-agenda-files
3765 (while (setq file (pop files))
3767 (org-check-agenda-file file)
3768 (setq date (calendar-gregorian-from-absolute today)
3769 rtn (org-agenda-get-day-entries
3771 (setq rtnall (append rtnall rtn))))
3773 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
3774 (add-text-properties (point-min) (1- (point))
3775 (list 'face 'org-link))
3776 (insert (org-finalize-agenda-entries rtnall) "\n")))
3777 (while (setq d (pop day-numbers))
3778 (setq date (calendar-gregorian-from-absolute d)
3780 (if (or (setq todayp (= d today))
3781 (and (not start-pos) (= d sd)))
3782 (setq start-pos (point))
3783 (if (and start-pos (not end-pos))
3784 (setq end-pos (point))))
3785 (setq files org-agenda-files
3787 (while (setq file (pop files))
3789 (org-check-agenda-file file)
3790 (setq rtn (org-agenda-get-day-entries file date))
3791 (setq rtnall (append rtnall rtn))))
3792 (if org-agenda-include-diary
3794 (require 'diary-lib)
3795 (setq rtn (org-get-entries-from-diary date))
3796 (setq rtnall (append rtnall rtn))))
3797 (if (or rtnall org-agenda-show-all-dates)
3799 (insert (format "%-9s %2d %s %4d\n"
3800 (calendar-day-name date)
3801 (extract-calendar-day date)
3802 (calendar-month-name (extract-calendar-month date))
3803 (extract-calendar-year date)))
3804 (put-text-property s (1- (point)) 'face
3807 (org-finalize-agenda-entries ;; FIXME: condition needed
3808 (org-agenda-add-time-grid-maybe
3811 (put-text-property s (1- (point)) 'day d))))
3812 (goto-char (point-min))
3813 (setq buffer-read-only t)
3814 (if org-fit-agenda-window
3815 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3816 (/ (frame-height) 2)))
3817 (unless (and (pos-visible-in-window-p (point-min))
3818 (pos-visible-in-window-p (point-max)))
3819 (goto-char (1- (point-max)))
3821 (if (not (pos-visible-in-window-p (or start-pos 1)))
3823 (goto-char (or start-pos 1))
3825 (goto-char (or start-pos 1))
3826 (if (not org-select-agenda-window) (select-window win))
3829 (defun org-check-agenda-file (file)
3830 "Make sure FILE exists. If not, ask user what to do."
3831 ;; FIXME: this does not correctly change the menus
3832 ;; Could probably be fixed by explicitly going to the buffer.
3833 (when (not (file-exists-p file))
3834 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3836 (let ((r (downcase (read-char-exclusive))))
3839 (org-remove-file file)
3840 (throw 'nextfile t))
3841 (t (error "Abort"))))))
3843 (defun org-agenda-quit ()
3844 "Exit agenda by removing the window or the buffer."
3846 (let ((buf (current-buffer)))
3847 (if (not (one-window-p)) (delete-window))
3849 (org-agenda-maybe-reset-markers 'force)))
3851 (defun org-agenda-exit ()
3852 "Exit agenda by removing the window or the buffer.
3853 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3854 Org-mode buffers visited directly by the user will not be touched."
3856 (org-release-buffers org-agenda-new-buffers)
3857 (setq org-agenda-new-buffers nil)
3860 (defun org-agenda-redo ()
3863 (eval org-agenda-redo-command))
3865 (defun org-agenda-goto-today ()
3868 (if (boundp 'starting-day)
3869 (let ((cmd (car org-agenda-redo-command))
3870 (iall (nth 1 org-agenda-redo-command))
3871 (nday (nth 3 org-agenda-redo-command)))
3872 (eval (list cmd iall nil nday)))
3873 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3876 (defun org-agenda-later (arg)
3877 "Go forward in time by `org-agenda-ndays' days.
3878 With prefix ARG, go forward that many times `org-agenda-ndays'."
3880 (unless (boundp 'starting-day)
3881 (error "Not allowed"))
3882 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3883 (+ starting-day (* arg org-agenda-ndays))))
3885 (defun org-agenda-earlier (arg)
3886 "Go back in time by `org-agenda-ndays' days.
3887 With prefix ARG, go back that many times `org-agenda-ndays'."
3889 (unless (boundp 'starting-day)
3890 (error "Not allowed"))
3891 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3892 (- starting-day (* arg org-agenda-ndays))))
3894 (defun org-agenda-week-view ()
3895 "Switch to weekly view for agenda."
3897 (unless (boundp 'starting-day)
3898 (error "Not allowed"))
3899 (setq org-agenda-ndays 7)
3900 (org-agenda include-all-loc
3901 (or (get-text-property (point) 'day)
3903 (org-agenda-set-mode-name)
3904 (message "Switched to week view"))
3906 (defun org-agenda-day-view ()
3907 "Switch to weekly view for agenda."
3909 (unless (boundp 'starting-day)
3910 (error "Not allowed"))
3911 (setq org-agenda-ndays 1)
3912 (org-agenda include-all-loc
3913 (or (get-text-property (point) 'day)
3915 (org-agenda-set-mode-name)
3916 (message "Switched to day view"))
3918 (defun org-agenda-next-date-line (&optional arg)
3919 "Jump to the next line indicating a date in agenda buffer."
3921 (beginning-of-line 1)
3922 (if (looking-at "^\\S-") (forward-char 1))
3923 (if (not (re-search-forward "^\\S-" nil t arg))
3926 (error "No next date after this line in this buffer")))
3927 (goto-char (match-beginning 0)))
3929 (defun org-agenda-previous-date-line (&optional arg)
3930 "Jump to the next line indicating a date in agenda buffer."
3932 (beginning-of-line 1)
3933 (if (not (re-search-backward "^\\S-" nil t arg))
3934 (error "No previous date before this line in this buffer")))
3936 ;; Initialize the highlight
3937 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
3938 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
3941 (defun org-highlight (begin end &optional buffer)
3942 "Highlight a region with overlay."
3943 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
3944 org-hl begin end (or buffer (current-buffer))))
3946 (defun org-unhighlight ()
3947 "Detach overlay INDEX."
3948 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
3951 (defun org-agenda-follow-mode ()
3952 "Toggle follow mode in an agenda buffer."
3954 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
3955 (org-agenda-set-mode-name)
3956 (message "Follow mode is %s"
3957 (if org-agenda-follow-mode "on" "off")))
3959 (defun org-agenda-toggle-diary ()
3960 "Toggle follow mode in an agenda buffer."
3962 (setq org-agenda-include-diary (not org-agenda-include-diary))
3964 (org-agenda-set-mode-name)
3965 (message "Diary inclusion turned %s"
3966 (if org-agenda-include-diary "on" "off")))
3968 (defun org-agenda-toggle-time-grid ()
3969 "Toggle follow mode in an agenda buffer."
3971 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
3973 (org-agenda-set-mode-name)
3974 (message "Time-grid turned %s"
3975 (if org-agenda-use-time-grid "on" "off")))
3977 (defun org-agenda-set-mode-name ()
3978 "Set the mode name to indicate all the small mode settings."
3980 (concat "Org-Agenda"
3981 (if (equal org-agenda-ndays 1) " Day" "")
3982 (if (equal org-agenda-ndays 7) " Week" "")
3983 (if org-agenda-follow-mode " Follow" "")
3984 (if org-agenda-include-diary " Diary" "")
3985 (if org-agenda-use-time-grid " Grid" "")))
3986 (force-mode-line-update))
3988 (defun org-agenda-post-command-hook ()
3989 (and (eolp) (not (bolp)) (backward-char 1))
3990 (if (and org-agenda-follow-mode
3991 (get-text-property (point) 'org-marker))
3994 (defvar org-disable-diary nil) ;Dynamically-scoped param.
3996 (defun org-get-entries-from-diary (date)
3997 "Get the (Emacs Calendar) diary entries for DATE."
3998 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
3999 (diary-display-hook '(fancy-diary-display))
4000 (list-diary-entries-hook
4001 (cons 'org-diary-default-entry list-diary-entries-hook))
4003 (org-disable-diary t))
4005 (save-window-excursion
4006 (list-diary-entries date 1)))
4007 (if (not (get-buffer fancy-diary-buffer))
4009 (with-current-buffer fancy-diary-buffer
4010 (setq buffer-read-only nil)
4011 (if (= (point-max) 1)
4014 ;; Omit the date and other unnecessary stuff
4015 (org-agenda-cleanup-fancy-diary)
4016 ;; Add prefix to each line and extend the text properties
4017 (if (= (point-max) 1)
4019 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4020 (set-buffer-modified-p nil)
4021 (kill-buffer fancy-diary-buffer)))
4023 (setq entries (org-split-string entries "\n"))
4027 (setq x (org-format-agenda-item "" x "Diary" 'time))
4028 ;; Extend the text properties to the beginning of the line
4029 (add-text-properties
4031 (text-properties-at (1- (length x)) x)
4036 (defun org-agenda-cleanup-fancy-diary ()
4037 "Remove unwanted stuff in buffer created by fancy-diary-display.
4038 This gets rid of the date, the underline under the date, and
4039 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4040 date. Itt also removes lines that contain only whitespace."
4041 (goto-char (point-min))
4042 (if (looking-at ".*?:[ \t]*")
4045 (re-search-forward "\n=+$" nil t)
4047 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4048 (re-search-forward "\n=+$" nil t)
4049 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4050 (goto-char (point-min))
4051 (while (re-search-forward "^ +\n" nil t)
4053 (goto-char (point-min))
4054 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4055 (replace-match "")))
4057 ;; Advise the add-to-diary-list function to allow org to jump to
4058 ;; diary entries. Wrapped into eval-after-load to avoid loading
4059 ;; advice unnecessarily
4060 (eval-after-load "diary-lib"
4061 '(defadvice add-to-diary-list (before org-mark-diary-entry activate)
4062 "Make the position visible."
4063 (if (and org-disable-diary ;; called from org-agenda
4066 (add-text-properties
4068 (list 'mouse-face 'highlight
4069 'keymap org-agenda-keymap
4072 "mouse-2 or RET jump to diary file %s"
4073 (abbreviate-file-name (buffer-file-name)))
4074 'org-agenda-diary-link t
4075 'org-marker (org-agenda-new-marker (point-at-bol)))
4078 (defun org-diary-default-entry ()
4079 "Add a dummy entry to the diary.
4080 Needed to avoid empty dates which mess up holiday display."
4081 ;; Catch the error if dealing with the new add-to-diary-alist
4083 (add-to-diary-list original-date "Org-mode dummy" "")
4085 (add-to-diary-list original-date "Org-mode dummy" "" nil))))
4087 (defun org-add-file (&optional file)
4088 "Add current file to the list of files in variable `org-agenda-files'.
4089 These are the files which are being checked for agenda entries.
4090 Optional argument FILE means, use this file instead of the current.
4091 It is possible (but not recommended) to add this function to the
4095 (let* ((file (or file (buffer-file-name)
4097 (error "Buffer is not visiting a file")
4098 (throw 'exit nil))))
4099 (true-file (file-truename file))
4100 (afile (abbreviate-file-name file))
4101 (present (delq nil (mapcar
4103 (equal true-file (file-truename x)))
4104 org-agenda-files))))
4107 (setq org-agenda-files
4108 (cons afile org-agenda-files))
4109 ;; Make sure custom.el does not end up with Org-mode
4110 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4111 (customize-save-variable 'org-agenda-files org-agenda-files))
4112 (org-install-agenda-files-menu)
4113 (message "Added file: %s" afile))
4114 (message "File was already in list: %s" afile)))))
4116 (defun org-remove-file (&optional file)
4117 "Remove current file from the list of files in variable `org-agenda-files'.
4118 These are the files which are being checked for agenda entries.
4119 Optional argument FILE means, use this file instead of the current."
4121 (let* ((file (or file (buffer-file-name)))
4122 (true-file (file-truename file))
4123 (afile (abbreviate-file-name file))
4124 (files (delq nil (mapcar
4126 (if (equal true-file
4129 org-agenda-files))))
4130 (if (not (= (length files) (length org-agenda-files)))
4132 (setq org-agenda-files files)
4133 (customize-save-variable 'org-agenda-files org-agenda-files)
4134 (org-install-agenda-files-menu)
4135 (message "Removed file: %s" afile))
4136 (message "File was not in list: %s" afile))))
4138 (defun org-file-menu-entry (file)
4139 (vector file (list 'find-file file) t))
4141 (defun org-get-all-dates (beg end &optional no-ranges force-today)
4142 "Return a list of all relevant day numbers from BEG to END buffer positions.
4143 If NO-RANGES is non-nil, include only the start and end dates of a range,
4144 not every single day in the range. If FORCE-TODAY is non-nil, make
4145 sure that TODAY is included in the list."
4146 (let (dates date day day1 day2 ts1 ts2)
4148 (setq dates (list (time-to-days (current-time)))))
4151 (while (re-search-forward org-ts-regexp end t)
4152 (setq day (time-to-days (org-time-string-to-time
4153 (substring (match-string 1) 0 10))))
4154 (or (memq day dates) (push day dates)))
4157 (while (re-search-forward org-tr-regexp end t)
4158 (setq ts1 (substring (match-string 1) 0 10)
4159 ts2 (substring (match-string 2) 0 10)
4160 day1 (time-to-days (org-time-string-to-time ts1))
4161 day2 (time-to-days (org-time-string-to-time ts2)))
4162 (while (< (setq day1 (1+ day1)) day2)
4163 (or (memq day1 dates) (push day1 dates)))))
4167 (defun org-diary (&rest args)
4168 "Return diary information from org-files.
4169 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4170 It accesses org files and extracts information from those files to be
4172 listed in the diary. The function accepts arguments specifying what
4173 items should be listed. The following arguments are allowed:
4175 :timestamp List the headlines of items containing a date stamp or
4176 date range matching the selected date. Deadlines will
4177 also be listed, on the expiration day.
4179 :deadline List any deadlines past due, or due within
4180 `org-deadline-warning-days'. The listing occurs only
4181 in the diary for *today*, not at any other date. If
4182 an entry is marked DONE, it is no longer listed.
4184 :scheduled List all items which are scheduled for the given date.
4185 The diary for *today* also contains items which were
4186 scheduled earlier and are not yet marked DONE.
4188 :todo List all TODO items from the org-file. This may be a
4189 long list - so this is not turned on by default.
4190 Like deadlines, these entries only show up in the
4191 diary for *today*, not at any other date.
4193 The call in the diary file should look like this:
4195 &%%(org-diary) ~/path/to/some/orgfile.org
4197 Use a separate line for each org file to check. Or, if you omit the file name,
4198 all files listed in `org-agenda-files' will be checked automatically:
4202 If you don't give any arguments (as in the example above), the default
4203 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4206 &%%(org-diary :deadline :timestamp :scheduled)
4208 The function expects the lisp variables `entry' and `date' to be provided
4209 by the caller, because this is how the calendar works. Don't use this
4210 function from a program - use `org-agenda-get-day-entries' instead."
4211 (org-agenda-maybe-reset-markers)
4212 (org-compile-prefix-format org-agenda-prefix-format)
4213 (setq args (or args '(:deadline :scheduled :timestamp)))
4214 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4218 ;; If this is called during org-agenda, don't return any entries to
4219 ;; the calendar. Org Agenda will list these entries itself.
4220 (if org-disable-diary (setq files nil))
4221 (while (setq file (pop files))
4222 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4223 (setq results (append results rtn)))
4224 (concat (org-finalize-agenda-entries results) "\n")))
4226 (defun org-agenda-get-day-entries (file date &rest args)
4227 "Does the work for `org-diary' and `org-agenda'.
4228 FILE is the path to a file to be checked for entries. DATE is date like
4229 the one returned by `calendar-current-date'. ARGS are symbols indicating
4230 which kind of entries should be extracted. For details about these, see
4231 the documentation of `org-diary'."
4232 (setq args (or args '(:deadline :scheduled :timestamp)))
4233 (let* ((org-startup-with-deadline-check nil)
4234 (org-startup-folded nil)
4235 (buffer (if (file-exists-p file)
4236 (org-get-agenda-file-buffer file)
4237 (error "No such file %s" file)))
4240 ;; If file does not exist, make sure an error message ends up in diary
4241 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4242 (with-current-buffer buffer
4243 (unless (eq major-mode 'org-mode)
4244 (error "Agenda file %s is not in `org-mode'" file))
4245 (let ((case-fold-search nil))
4248 (if org-respect-restriction
4249 (if (org-region-active-p)
4250 ;; Respect a region to restrict search
4251 (narrow-to-region (region-beginning) (region-end)))
4252 ;; If we work for the calendar or many files,
4253 ;; get rid of any restriction
4255 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4256 (while (setq arg (pop args))
4258 ((and (eq arg :todo)
4259 (equal date (calendar-current-date)))
4260 (setq rtn (org-agenda-get-todos))
4261 (setq results (append results rtn)))
4262 ((eq arg :timestamp)
4263 (setq rtn (org-agenda-get-blocks))
4264 (setq results (append results rtn))
4265 (setq rtn (org-agenda-get-timestamps))
4266 (setq results (append results rtn)))
4267 ((eq arg :scheduled)
4268 (setq rtn (org-agenda-get-scheduled))
4269 (setq results (append results rtn)))
4270 ((and (eq arg :deadline)
4271 (equal date (calendar-current-date)))
4272 (setq rtn (org-agenda-get-deadlines))
4273 (setq results (append results rtn))))))))
4276 (defun org-entry-is-done-p ()
4277 "Is the current entry marked DONE?"
4279 (and (re-search-backward "[\r\n]\\*" nil t)
4280 (looking-at org-nl-done-regexp))))
4282 (defun org-at-date-range-p ()
4283 "Is the cursor inside a date range?"
4287 (let ((pos (point)))
4288 (skip-chars-backward "^<\r\n")
4289 (skip-chars-backward "<")
4290 (and (looking-at org-tr-regexp)
4291 (>= (match-end 0) pos)
4293 (skip-chars-backward "^<\r\n")
4294 (skip-chars-backward "<")
4295 (and (looking-at org-tr-regexp)
4296 (>= (match-end 0) pos)
4300 (defun org-agenda-get-todos ()
4301 "Return the TODO information for agenda display."
4302 (let* ((props (list 'face nil
4303 'done-face 'org-done
4304 'mouse-face 'highlight
4305 'keymap org-agenda-keymap
4307 (format "mouse-2 or RET jump to org file %s"
4308 (abbreviate-file-name (buffer-file-name)))))
4309 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
4313 (goto-char (point-min))
4314 (while (re-search-forward regexp nil t)
4315 (goto-char (match-beginning 1))
4316 (setq marker (org-agenda-new-marker (point-at-bol))
4317 txt (org-format-agenda-item "" (match-string 1))
4319 (+ (org-get-priority txt)
4320 (if org-todo-kwd-priority-p
4321 (- org-todo-kwd-max-priority -2
4323 (member (match-string 2) org-todo-keywords)))
4325 (add-text-properties
4326 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
4331 (goto-char (match-end 1)))
4334 (defconst org-agenda-no-heading-message
4335 "No heading for this item in buffer or region")
4337 (defun org-agenda-get-timestamps ()
4338 "Return the date stamp information for agenda display."
4339 (let* ((props (list 'face nil
4340 'mouse-face 'highlight
4341 'keymap org-agenda-keymap
4343 (format "mouse-2 or RET jump to org file %s"
4344 (abbreviate-file-name (buffer-file-name)))))
4345 (regexp (regexp-quote
4348 (car org-time-stamp-formats)
4349 (apply 'encode-time ; DATE bound by calendar
4350 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
4352 marker hdmarker deadlinep scheduledp donep tmp priority
4354 (goto-char (point-min))
4355 (while (re-search-forward regexp nil t)
4356 (if (not (save-match-data (org-at-date-range-p)))
4358 (setq marker (org-agenda-new-marker (match-beginning 0))
4359 tmp (buffer-substring (max (point-min)
4360 (- (match-beginning 0)
4361 org-ds-keyword-length))
4362 (match-beginning 0))
4363 timestr (buffer-substring (match-beginning 0) (point-at-eol))
4364 deadlinep (string-match org-deadline-regexp tmp)
4365 scheduledp (string-match org-scheduled-regexp tmp)
4366 donep (org-entry-is-done-p))
4367 (if (string-match ">" timestr)
4368 ;; substring should only run to end of time stamp
4369 (setq timestr (substring timestr 0 (match-end 0))))
4371 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4373 (goto-char (match-end 1))
4374 (setq hdmarker (org-agenda-new-marker))
4375 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4376 (setq txt (org-format-agenda-item
4378 (if deadlinep "Deadline: " "")
4379 (if scheduledp "Scheduled: " ""))
4380 (match-string 1) nil timestr)))
4381 (setq txt org-agenda-no-heading-message))
4382 (setq priority (org-get-priority txt))
4383 (add-text-properties
4384 0 (length txt) (append (list 'org-marker marker
4385 'org-hd-marker hdmarker) props)
4388 (add-text-properties
4391 (if donep 'org-done 'org-warning)
4392 'undone-face 'org-warning
4393 'done-face 'org-done
4394 'priority (+ 100 priority))
4397 (add-text-properties
4399 (list 'face 'org-scheduled-today
4400 'undone-face 'org-scheduled-today
4401 'done-face 'org-done
4402 priority (+ 99 priority))
4404 (add-text-properties
4406 (list 'priority priority) txt)))
4408 (outline-next-heading))))
4411 (defun org-agenda-get-deadlines ()
4412 "Return the deadline information for agenda display."
4413 (let* ((wdays org-deadline-warning-days)
4414 (props (list 'mouse-face 'highlight
4415 'keymap org-agenda-keymap
4417 (format "mouse-2 or RET jump to org file %s"
4418 (abbreviate-file-name (buffer-file-name)))))
4419 (regexp org-deadline-time-regexp)
4420 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4421 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4424 (goto-char (point-min))
4425 (while (re-search-forward regexp nil t)
4426 (setq pos (1- (match-beginning 1))
4428 (org-time-string-to-time (match-string 1)))
4430 ;; When to show a deadline in the calendar:
4431 ;; If the expiration is within wdays warning time.
4432 ;; Past-due deadlines are only shown on the current date
4433 (if (and (< diff wdays) todayp (not (= diff 0)))
4435 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4437 (goto-char (match-end 0))
4438 (setq pos1 (match-end 1))
4439 (setq head (buffer-substring-no-properties
4441 (progn (skip-chars-forward "^\r\n")
4443 (if (string-match org-looking-at-done-regexp head)
4445 (setq txt (org-format-agenda-item
4446 (format "In %3d d.: " diff) head))))
4447 (setq txt org-agenda-no-heading-message))
4449 (add-text-properties
4452 (list 'org-marker (org-agenda-new-marker pos)
4453 'org-hd-marker (org-agenda-new-marker pos1)
4454 'priority (+ (- 10 diff) (org-get-priority txt))
4455 'face (cond ((<= diff 0) 'org-warning)
4456 ((<= diff 5) 'org-scheduled-previously)
4459 ((<= diff 0) 'org-warning)
4460 ((<= diff 5) 'org-scheduled-previously)
4462 'done-face 'org-done)
4468 (defun org-agenda-get-scheduled ()
4469 "Return the scheduled information for agenda display."
4470 (let* ((props (list 'face 'org-scheduled-previously
4471 'undone-face 'org-scheduled-previously
4472 'done-face 'org-done
4473 'mouse-face 'highlight
4474 'keymap org-agenda-keymap
4476 (format "mouse-2 or RET jump to org file %s"
4477 (abbreviate-file-name (buffer-file-name)))))
4478 (regexp org-scheduled-time-regexp)
4479 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4480 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4483 (goto-char (point-min))
4484 (while (re-search-forward regexp nil t)
4485 (setq pos (1- (match-beginning 1))
4487 (org-time-string-to-time (match-string 1)))
4489 ;; When to show a scheduled item in the calendar:
4490 ;; If it is on or past the date.
4491 (if (and (< diff 0) todayp)
4493 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4495 (goto-char (match-end 0))
4496 (setq pos1 (match-end 1))
4497 (setq head (buffer-substring-no-properties
4499 (progn (skip-chars-forward "^\r\n") (point))))
4500 (if (string-match org-looking-at-done-regexp head)
4502 (setq txt (org-format-agenda-item
4503 (format "Sched.%2dx: " (- 1 diff)) head))))
4504 (setq txt org-agenda-no-heading-message))
4506 (add-text-properties
4508 (append (list 'org-marker (org-agenda-new-marker pos)
4509 'org-hd-marker (org-agenda-new-marker pos1)
4510 'priority (+ (- 5 diff) (org-get-priority txt)))
4515 (defun org-agenda-get-blocks ()
4516 "Return the date-range information for agenda display."
4517 (let* ((props (list 'face nil
4518 'mouse-face 'highlight
4519 'keymap org-agenda-keymap
4521 (format "mouse-2 or RET jump to org file %s"
4522 (abbreviate-file-name (buffer-file-name)))))
4523 (regexp org-tr-regexp)
4524 (d0 (calendar-absolute-from-gregorian date))
4525 marker hdmarker ee txt d1 d2 s1 s2 timestr)
4526 (goto-char (point-min))
4527 (while (re-search-forward regexp nil t)
4528 (setq timestr (match-string 0)
4531 d1 (time-to-days (org-time-string-to-time s1))
4532 d2 (time-to-days (org-time-string-to-time s2)))
4533 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4534 ;; Only allow days between the limits, because the normal
4535 ;; date stamps will catch the limits.
4537 (setq marker (org-agenda-new-marker (point)))
4538 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4540 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4541 (goto-char (match-end 1))
4542 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4543 (setq txt (org-format-agenda-item
4544 (format (if (= d1 d2) "" "(%d/%d): ")
4545 (1+ (- d0 d1)) (1+ (- d2 d1)))
4546 (match-string 1) nil (if (= d0 d1) timestr))))
4547 (setq txt org-agenda-no-heading-message))
4548 (add-text-properties
4549 0 (length txt) (append (list 'org-marker marker
4550 'org-hd-marker hdmarker
4551 'priority (org-get-priority txt))
4555 (outline-next-heading))
4556 ;; Sort the entries by expiration date.
4561 (defconst org-plain-time-of-day-regexp
4564 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4567 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4569 "Regular expression to match a plain time or time range.
4570 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4571 groups carry important information:
4573 1 the first time, range or not
4574 8 the second time, if it is a range.")
4576 (defconst org-stamp-time-of-day-regexp
4578 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
4579 "\\([012][0-9]:[0-5][0-9]\\)>"
4581 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4582 "Regular expression to match a timestamp time or time range.
4583 After a match, the following groups carry important information:
4585 1 date plus weekday, for backreferencing to make sure both times on same day
4586 2 the first time, range or not
4587 4 the second time, if it is a range.")
4589 (defvar org-prefix-has-time nil
4590 "A flag, set by `org-compile-prefix-format'.
4591 The flag is set if the currently compiled format contains a `%t'.")
4593 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
4594 "Format TXT to be inserted into the agenda buffer.
4595 In particular, it adds the prefix and corresponding text properties. EXTRA
4596 must be a string and replaces the `%s' specifier in the prefix format.
4597 CATEGORY (string, symbol or nil) may be used to overule the default
4598 category taken from local variable or file name. It will replace the `%c'
4599 specifier in the format. DOTIME, when non-nil, indicates that a
4600 time-of-day should be extracted from TXT for sorting of this entry, and for
4601 the `%t' specifier in the format. When DOTIME is a string, this string is
4602 searched for a time before TXT is. NOPREFIX is a flag and indicates that
4603 only the correctly processes TXT should be returned - this is used by
4604 `org-agenda-change-all-lines'."
4606 ;; Diary entries sometimes have extra whitespace at the beginning
4607 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
4608 (let* ((category (or category
4610 (if (buffer-file-name)
4611 (file-name-sans-extension
4612 (file-name-nondirectory (buffer-file-name)))
4614 time ;; needed for the eval of the prefix format
4615 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
4616 (time-of-day (and dotime (org-get-time-of-day ts)))
4617 stamp plain s0 s1 s2 rtn)
4618 (when (and dotime time-of-day org-prefix-has-time)
4619 ;; Extract starting and ending time and move them to prefix
4620 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
4621 (setq plain (string-match org-plain-time-of-day-regexp ts)))
4622 (setq s0 (match-string 0 ts)
4623 s1 (match-string (if plain 1 2) ts)
4624 s2 (match-string (if plain 8 4) ts))
4626 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
4627 ;; them, we might want to remove them there to avoid duplication.
4628 ;; The user can turn this off with a variable.
4629 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
4630 (string-match (concat (regexp-quote s0) " *") txt)
4631 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
4632 (= (match-beginning 0) 0)
4634 (setq txt (replace-match "" nil nil txt))))
4635 ;; Normalize the time(s) to 24 hour
4636 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
4637 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
4639 ;; Create the final string
4642 ;; Prepare the variables needed in the eval of the compiled format
4643 (setq time (cond (s2 (concat s1 "-" s2))
4644 (s1 (concat s1 "......"))
4647 category (if (symbolp category) (symbol-name category) category))
4648 ;; Evaluate the compiled format
4649 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
4651 ;; And finally add the text properties
4652 (add-text-properties
4653 0 (length rtn) (list 'category (downcase category)
4654 'prefix-length (- (length rtn) (length txt))
4655 'time-of-day time-of-day
4660 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
4662 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
4663 ((and todayp (member 'today (car org-agenda-time-grid))))
4664 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
4665 ((member 'weekly (car org-agenda-time-grid)))
4666 (t (throw 'exit list)))
4667 (let* ((have (delq nil (mapcar
4668 (lambda (x) (get-text-property 1 'time-of-day x))
4670 (string (nth 1 org-agenda-time-grid))
4671 (gridtimes (nth 2 org-agenda-time-grid))
4672 (req (car org-agenda-time-grid))
4673 (remove (member 'remove-match req))
4675 (if (and (member 'require-timed req) (not have))
4676 ;; don't show empty grid
4678 (while (setq time (pop gridtimes))
4679 (unless (and remove (member time have))
4680 (setq time (int-to-string time))
4681 (push (org-format-agenda-item
4682 nil string "" ;; FIXME: put a category?
4683 (concat (substring time 0 -2) ":" (substring time -2)))
4686 1 (length (car new)) 'face 'org-time-grid (car new))))
4687 (if (member 'time-up org-agenda-sorting-strategy)
4689 (append list new)))))
4691 (defun org-compile-prefix-format (format)
4692 "Compile the prefix format into a Lisp form that can be evaluated.
4693 The resulting form is returned and stored in the variable
4694 `org-prefix-format-compiled'."
4695 (setq org-prefix-has-time nil)
4696 (let ((start 0) varform vars var (s format) c f opt)
4697 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4699 (setq var (cdr (assoc (match-string 4 s)
4700 '(("c" . category) ("t" . time) ("s" . extra))))
4701 c (or (match-string 3 s) "")
4702 opt (match-beginning 1)
4703 start (1+ (match-beginning 0)))
4704 (if (equal var 'time) (setq org-prefix-has-time t))
4705 (setq f (concat "%" (match-string 2 s) "s"))
4708 `(if (equal "" ,var)
4710 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
4711 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
4712 (setq s (replace-match "%s" t nil s))
4713 (push varform vars))
4714 (setq vars (nreverse vars))
4715 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4717 (defun org-get-time-of-day (s &optional string)
4718 "Check string S for a time of day.
4719 If found, return it as a military time number between 0 and 2400.
4720 If not found, return nil.
4721 The optional STRING argument forces conversion into a 5 character wide string
4727 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
4729 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
4730 (let* ((t0 (+ (* 100
4731 (+ (string-to-number (match-string 1 s))
4732 (if (and (match-beginning 4)
4733 (equal (downcase (match-string 4 s)) "pm"))
4735 (if (match-beginning 3)
4736 (string-to-number (match-string 3 s))
4738 (t1 (concat " " (int-to-string t0))))
4739 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
4741 (defun org-finalize-agenda-entries (list)
4742 "Sort and concatenate the agenda items."
4743 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4745 (defsubst org-cmp-priority (a b)
4746 "Compare the priorities of string a and b."
4747 (let ((pa (or (get-text-property 1 'priority a) 0))
4748 (pb (or (get-text-property 1 'priority b) 0)))
4749 (cond ((> pa pb) +1)
4753 (defsubst org-cmp-category (a b)
4754 "Compare the string values of categories of strings a and b."
4755 (let ((ca (or (get-text-property 1 'category a) ""))
4756 (cb (or (get-text-property 1 'category b) "")))
4757 (cond ((string-lessp ca cb) -1)
4758 ((string-lessp cb ca) +1)
4761 (defsubst org-cmp-time (a b)
4762 "Compare the time-of-day values of strings a and b."
4763 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4764 (ta (or (get-text-property 1 'time-of-day a) def))
4765 (tb (or (get-text-property 1 'time-of-day b) def)))
4766 (cond ((< ta tb) -1)
4770 (defun org-entries-lessp (a b)
4771 "Predicate for sorting agenda entries."
4772 ;; The following variables will be used when the form is evaluated.
4773 (let* ((time-up (org-cmp-time a b))
4774 (time-down (if time-up (- time-up) nil))
4775 (priority-up (org-cmp-priority a b))
4776 (priority-down (if priority-up (- priority-up) nil))
4777 (category-up (org-cmp-category a b))
4778 (category-down (if category-up (- category-up) nil))
4779 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4781 (eval (cons 'or org-agenda-sorting-strategy))
4782 '((-1 . t) (1 . nil) (nil . nil))))))
4784 (defun org-agenda-show-priority ()
4785 "Show the priority of the current item.
4786 This priority is composed of the main priority given with the [#A] cookies,
4787 and by additional input from the age of a schedules or deadline entry."
4789 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4790 (message "Priority is %d" (if pri pri -1000))))
4792 (defun org-agenda-goto (&optional highlight)
4793 "Go to the Org-mode file which contains the item at point."
4795 (let* ((marker (or (get-text-property (point) 'org-marker)
4796 (org-agenda-error)))
4797 (buffer (marker-buffer marker))
4798 (pos (marker-position marker)))
4799 (switch-to-buffer-other-window buffer)
4802 (when (eq major-mode 'org-mode)
4803 (org-show-hidden-entry)
4805 (and (outline-next-heading)
4806 (org-flag-heading nil)))) ; show the next heading
4807 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4809 (defun org-agenda-switch-to ()
4810 "Go to the Org-mode file which contains the item at point."
4812 (let* ((marker (or (get-text-property (point) 'org-marker)
4813 (org-agenda-error)))
4814 (buffer (marker-buffer marker))
4815 (pos (marker-position marker)))
4816 (switch-to-buffer buffer)
4817 (delete-other-windows)
4820 (when (eq major-mode 'org-mode)
4821 (org-show-hidden-entry)
4823 (and (outline-next-heading)
4824 (org-flag-heading nil)))))) ; show the next heading
4826 (defun org-agenda-goto-mouse (ev)
4827 "Go to the Org-mode file which contains the item at the mouse click."
4829 (mouse-set-point ev)
4832 (defun org-agenda-show ()
4833 "Display the Org-mode file which contains the item at point."
4835 (let ((win (selected-window)))
4837 (select-window win)))
4839 (defun org-agenda-recenter (arg)
4840 "Display the Org-mode file which contains the item at point and recenter."
4842 (let ((win (selected-window)))
4845 (select-window win)))
4847 (defun org-agenda-show-mouse (ev)
4848 "Display the Org-mode file which contains the item at the mouse click."
4850 (mouse-set-point ev)
4853 (defun org-agenda-check-no-diary ()
4854 "Check if the entry is a diary link and abort if yes."
4855 (if (get-text-property (point) 'org-agenda-diary-link)
4856 (org-agenda-error)))
4858 (defun org-agenda-error ()
4859 (error "Command not allowed in this line"))
4861 (defvar org-last-heading-marker (make-marker)
4862 "Marker pointing to the headline that last changed its TODO state
4863 by a remote command from the agenda.")
4865 (defun org-agenda-todo ()
4866 "Cycle TODO state of line at point, also in Org-mode file.
4867 This changes the line at point, all other lines in the agenda referring to
4868 the same tree node, and the headline of the tree node in the Org-mode file."
4870 (org-agenda-check-no-diary)
4871 (let* ((col (current-column))
4872 (marker (or (get-text-property (point) 'org-marker)
4873 (org-agenda-error)))
4874 (buffer (marker-buffer marker))
4875 (pos (marker-position marker))
4876 (hdmarker (get-text-property (point) 'org-hd-marker))
4877 (buffer-read-only nil)
4879 (with-current-buffer buffer
4882 (org-show-hidden-entry)
4884 (and (outline-next-heading)
4885 (org-flag-heading nil))) ; show the next heading
4888 (setq newhead (org-get-heading))
4890 (org-back-to-heading)
4891 (move-marker org-last-heading-marker (point))))
4892 (beginning-of-line 1)
4894 (org-agenda-change-all-lines newhead hdmarker 'fixface))
4895 (move-to-column col)))
4897 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
4898 "Change all lines in the agenda buffer which match hdmarker.
4899 The new content of the line will be NEWHEAD (as modified by
4900 `org-format-agenda-item'). HDMARKER is checked with
4901 `equal' against all `org-hd-marker' text properties in the file.
4902 If FIXFACE is non-nil, the face of each item is modified acording to
4903 the new TODO state."
4904 (let* (props m pl undone-face done-face finish new dotime)
4905 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
4907 (goto-char (point-max))
4908 (beginning-of-line 1)
4910 (setq finish (bobp))
4911 (when (and (setq m (get-text-property (point) 'org-hd-marker))
4913 (setq props (text-properties-at (point))
4914 dotime (get-text-property (point) 'dotime)
4915 new (org-format-agenda-item "x" newhead "x" dotime 'noprefix)
4916 pl (get-text-property (point) 'prefix-length)
4917 undone-face (get-text-property (point) 'undone-face)
4918 done-face (get-text-property (point) 'done-face))
4920 (if (looking-at ".*")
4922 (replace-match new t t)
4923 (beginning-of-line 1)
4924 (add-text-properties (point-at-bol) (point-at-eol) props)
4926 (add-text-properties
4927 (point-at-bol) (point-at-eol)
4929 (if org-last-todo-state-is-todo
4930 undone-face done-face))))
4931 (beginning-of-line 1))
4932 (error "Line update did not work")))
4933 (beginning-of-line 0)))))
4935 (defun org-agenda-priority-up ()
4936 "Increase the priority of line at point, also in Org-mode file."
4938 (org-agenda-priority 'up))
4940 (defun org-agenda-priority-down ()
4941 "Decrease the priority of line at point, also in Org-mode file."
4943 (org-agenda-priority 'down))
4945 (defun org-agenda-priority (&optional force-direction)
4946 "Set the priority of line at point, also in Org-mode file.
4947 This changes the line at point, all other lines in the agenda referring to
4948 the same tree node, and the headline of the tree node in the Org-mode file."
4950 (org-agenda-check-no-diary)
4951 (let* ((marker (or (get-text-property (point) 'org-marker)
4952 (org-agenda-error)))
4953 (buffer (marker-buffer marker))
4954 (pos (marker-position marker))
4955 (hdmarker (get-text-property (point) 'org-hd-marker))
4956 (buffer-read-only nil)
4958 (with-current-buffer buffer
4961 (org-show-hidden-entry)
4963 (and (outline-next-heading)
4964 (org-flag-heading nil))) ; show the next heading
4965 (funcall 'org-priority force-direction)
4967 (setq newhead (org-get-heading)))
4968 (org-agenda-change-all-lines newhead hdmarker)
4969 (beginning-of-line 1)))
4971 (defun org-agenda-date-later (arg &optional what)
4972 "Change the date of this item to one day later."
4974 (org-agenda-check-no-diary)
4975 (let* ((marker (or (get-text-property (point) 'org-marker)
4976 (org-agenda-error)))
4977 (buffer (marker-buffer marker))
4978 (pos (marker-position marker)))
4979 (with-current-buffer buffer
4982 (if (not (org-at-timestamp-p))
4983 (error "Cannot find time stamp"))
4984 (org-timestamp-change arg (or what 'day))
4985 (message "Time stamp changed to %s" org-last-changed-timestamp))))
4987 (defun org-agenda-date-earlier (arg &optional what)
4988 "Change the date of this item to one day earlier."
4990 (org-agenda-date-later (- arg) what))
4992 (defun org-agenda-date-prompt (arg)
4993 "Change the date of this item. Date is prompted for, with default today.
4994 The prefix ARG is passed to the `org-time-stamp' command and can therefore
4995 be used to request time specification in the time stamp."
4997 (org-agenda-check-no-diary)
4998 (let* ((marker (or (get-text-property (point) 'org-marker)
4999 (org-agenda-error)))
5000 (buffer (marker-buffer marker))
5001 (pos (marker-position marker)))
5002 (with-current-buffer buffer
5005 (if (not (org-at-timestamp-p))
5006 (error "Cannot find time stamp"))
5007 (org-time-stamp arg)
5008 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5010 (defun org-get-heading ()
5011 "Return the heading of the current entry, without the stars."
5013 (if (and (re-search-backward "[\r\n]\\*" nil t)
5014 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5018 (defun org-agenda-diary-entry ()
5019 "Make a diary entry, like the `i' command from the calendar.
5020 All the standard commands work: block, weekly etc"
5022 (require 'diary-lib)
5024 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5025 (read-char-exclusive)))
5026 (cmd (cdr (assoc char
5027 '((?d . insert-diary-entry)
5028 (?w . insert-weekly-diary-entry)
5029 (?m . insert-monthly-diary-entry)
5030 (?y . insert-yearly-diary-entry)
5031 (?a . insert-anniversary-diary-entry)
5032 (?b . insert-block-diary-entry)
5033 (?c . insert-cyclic-diary-entry)))))
5034 (oldf (symbol-function 'calendar-cursor-to-date))
5036 (mark (or (mark t) (point))))
5038 (error "No command associated with <%c>" char))
5039 (unless (and (get-text-property point 'day)
5040 (or (not (equal ?b char))
5041 (get-text-property mark 'day)))
5042 (error "Don't know which date to use for diary entry"))
5043 ;; We implement this by hacking the `calendar-cursor-to-date' function
5044 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5045 (let ((calendar-mark-ring
5046 (list (calendar-gregorian-from-absolute
5047 (or (get-text-property mark 'day)
5048 (get-text-property point 'day))))))
5051 (fset 'calendar-cursor-to-date
5052 (lambda (&optional error)
5053 (calendar-gregorian-from-absolute
5054 (get-text-property point 'day))))
5055 (call-interactively cmd))
5056 (fset 'calendar-cursor-to-date oldf)))))
5059 (defun org-agenda-execute-calendar-command (cmd)
5060 "Execute a calendar command from the agenda, with the date associated to
5061 the cursor position."
5062 (require 'diary-lib)
5063 (unless (get-text-property (point) 'day)
5064 (error "Don't know which date to use for calendar command"))
5065 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5067 (date (calendar-gregorian-from-absolute
5068 (get-text-property point 'day)))
5069 (displayed-day (extract-calendar-day date))
5070 (displayed-month (extract-calendar-month date))
5071 (displayed-year (extract-calendar-year date)))
5074 (fset 'calendar-cursor-to-date
5075 (lambda (&optional error)
5076 (calendar-gregorian-from-absolute
5077 (get-text-property point 'day))))
5078 (call-interactively cmd))
5079 (fset 'calendar-cursor-to-date oldf))))
5081 (defun org-agenda-phases-of-moon ()
5082 "Display the phases of the moon for the 3 months around the cursor date."
5084 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5086 (defun org-agenda-holidays ()
5087 "Display the holidays for the 3 months around the cursor date."
5089 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5091 (defun org-agenda-sunrise-sunset (arg)
5092 "Display sunrise and sunset for the cursor date.
5093 Latitude and longitude can be specified with the variables
5094 `calendar-latitude' and `calendar-longitude'. When called with prefix
5095 argument, latitude and longitude will be prompted for."
5097 (let ((calendar-longitude (if arg nil calendar-longitude))
5098 (calendar-latitude (if arg nil calendar-latitude))
5099 (calendar-location-name
5100 (if arg "the given coordinates" calendar-location-name)))
5101 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5103 (defun org-agenda-goto-calendar ()
5104 "Open the Emacs calendar with the date at the cursor."
5106 (let* ((day (or (get-text-property (point) 'day)
5107 (error "Don't know which date to open in calendar")))
5108 (date (calendar-gregorian-from-absolute day)))
5110 (calendar-goto-date date)))
5112 (defun org-calendar-goto-agenda ()
5113 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5114 This is a command that has to be installed in `calendar-mode-map'."
5116 (org-agenda nil (calendar-absolute-from-gregorian
5117 (calendar-cursor-to-date))))
5119 (defun org-agenda-convert-date ()
5121 (let ((day (get-text-property (point) 'day))
5124 (error "Don't know which date to convert"))
5125 (setq date (calendar-gregorian-from-absolute day))
5127 "Gregorian: " (calendar-date-string date) "\n"
5128 "ISO: " (calendar-iso-date-string date) "\n"
5129 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5130 "Julian: " (calendar-julian-date-string date) "\n"
5131 "Astron. JD: " (calendar-astro-date-string date)
5132 " (Julian date number at noon UTC)\n"
5133 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5134 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5135 "French: " (calendar-french-date-string date) "\n"
5136 "Mayan: " (calendar-mayan-date-string date) "\n"
5137 "Coptic: " (calendar-coptic-date-string date) "\n"
5138 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5139 "Persian: " (calendar-persian-date-string date) "\n"
5140 "Chinese: " (calendar-chinese-date-string date) "\n"))
5141 (with-output-to-temp-buffer "*Dates*"
5143 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5147 (defun org-find-file-at-mouse (ev)
5148 "Open file link or URL at mouse."
5150 (mouse-set-point ev)
5151 (org-open-at-point 'in-emacs))
5153 (defun org-open-at-mouse (ev)
5154 "Open file link or URL at mouse."
5156 (mouse-set-point ev)
5157 (org-open-at-point))
5159 (defun org-open-at-point (&optional in-emacs)
5160 "Open link at or after point.
5161 If there is no link at point, this function will search forward up to
5162 the end of the current subtree.
5163 Normally, files will be opened by an appropriate application. If the
5164 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5166 (if (org-at-timestamp-p)
5167 (org-agenda nil (time-to-days (org-time-string-to-time
5168 (substring (match-string 1) 0 10)))
5170 (let (type path line (pos (point)))
5172 (skip-chars-backward
5173 (concat (if org-allow-space-in-links "^" "^ ")
5174 org-non-link-chars))
5175 (if (re-search-forward
5179 (progn (outline-end-of-subtree) (max pos (point)))
5180 (error (end-of-line 1) (point))))
5182 (setq type (match-string 1)
5183 path (match-string 2)))
5185 (error "No link found"))
5186 ;; Remove any trailing spaces in path
5187 (if (string-match " +\\'" path)
5188 (setq path (replace-match "" t t path)))
5192 ((string= type "file")
5193 (if (string-match ":\\([0-9]+\\)\\'" path)
5194 (setq line (string-to-number (match-string 1 path))
5195 path (substring path 0 (match-beginning 0))))
5196 (org-open-file path in-emacs line))
5198 ((string= type "news")
5199 (org-follow-gnus-link path))
5201 ((string= type "bbdb")
5202 (org-follow-bbdb-link path))
5204 ((string= type "gnus")
5205 (let (group article)
5206 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5207 (error "Error in Gnus link"))
5208 (setq group (match-string 1 path)
5209 article (match-string 3 path))
5210 (org-follow-gnus-link group article)))
5212 ((string= type "vm")
5213 (let (folder article)
5214 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5215 (error "Error in VM link"))
5216 (setq folder (match-string 1 path)
5217 article (match-string 3 path))
5218 ;; in-emacs is the prefix arg, will be interpreted as read-only
5219 (org-follow-vm-link folder article in-emacs)))
5221 ((string= type "wl")
5222 (let (folder article)
5223 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5224 (error "Error in Wanderlust link"))
5225 (setq folder (match-string 1 path)
5226 article (match-string 3 path))
5227 (org-follow-wl-link folder article)))
5229 ((string= type "rmail")
5230 (let (folder article)
5231 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5232 (error "Error in RMAIL link"))
5233 (setq folder (match-string 1 path)
5234 article (match-string 3 path))
5235 (org-follow-rmail-link folder article)))
5237 ((string= type "shell")
5239 (while (string-match "@{" cmd)
5240 (setq cmd (replace-match "<" t t cmd)))
5241 (while (string-match "@}" cmd)
5242 (setq cmd (replace-match ">" t t cmd)))
5243 (if (or (not org-confirm-shell-links)
5244 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
5249 (browse-url-at-point)))))))
5251 (defun org-follow-bbdb-link (name)
5252 "Follow a BBDB link to NAME."
5254 (let ((inhibit-redisplay t))
5256 ;; Exact match on name
5257 (bbdb-name (concat "\\`" name "\\'") nil)
5258 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5259 ;; Exact match on name
5260 (bbdb-company (concat "\\`" name "\\'") nil)
5261 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5262 ;; Partial match on name
5263 (bbdb-name name nil)
5264 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5265 ;; Partial match on company
5266 (bbdb-company name nil)
5267 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5268 ;; General match including network address and notes
5270 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
5271 (delete-window (get-buffer-window "*BBDB*"))
5272 (error "No matching BBDB record")))))
5274 (defun org-follow-gnus-link (&optional group article)
5275 "Follow a Gnus link to GROUP and ARTICLE."
5277 (funcall (cdr (assq 'gnus org-link-frame-setup)))
5278 (if group (gnus-fetch-group group))
5280 (or (gnus-summary-goto-article article nil 'force)
5281 (if (fboundp 'gnus-summary-insert-cached-articles)
5283 (gnus-summary-insert-cached-articles)
5284 (gnus-summary-goto-article article nil 'force))
5285 (message "Message could not be found.")))))
5287 (defun org-follow-vm-link (&optional folder article readonly)
5288 "Follow a VM link to FOLDER and ARTICLE."
5290 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
5291 ;; ange-ftp or efs or tramp access
5292 (let ((user (or (match-string 1 folder) (user-login-name)))
5293 (host (match-string 2 folder))
5294 (file (match-string 3 folder)))
5297 ;; use tramp to access the file
5299 (setq folder (format "[%s@%s]%s" user host file))
5300 (setq folder (format "/%s@%s:%s" user host file))))
5302 ;; use ange-ftp or efs
5303 (require (if org-xemacs-p 'efs 'ange-ftp))
5304 (setq folder (format "/%s@%s:%s" user host file))))))
5306 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
5309 (vm-select-folder-buffer)
5311 (let ((case-fold-search t))
5312 (goto-char (point-min))
5313 (if (not (re-search-forward
5314 (concat "^" "message-id: *" (regexp-quote article))))
5315 (error "Could not find the specified message in this folder"))
5318 (vm-beginning-of-message)
5321 (defun org-follow-wl-link (folder article)
5322 "Follow a Wanderlust link to FOLDER and ARTICLE."
5323 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
5324 (if article (wl-summary-jump-to-msg-by-message-id article))
5325 (wl-summary-redisplay))
5327 (defun org-follow-rmail-link (folder article)
5328 "Follow an RMAIL link to FOLDER and ARTICLE."
5329 (let (message-number)
5331 (save-window-excursion
5332 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5333 (setq message-number
5336 (goto-char (point-max))
5337 (if (re-search-backward
5338 (concat "^Message-ID:\\s-+" (regexp-quote
5341 (rmail-what-message))))))
5344 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5345 (rmail-show-message message-number)
5347 (error "Message not found"))))
5349 (defun org-open-file (path &optional in-emacs line)
5350 "Open the file at PATH.
5351 First, this expands any special file name abbreviations. Then the
5352 configuration variable `org-file-apps' is checked if it contains an
5353 entry for this file type, and if yes, the corresponding command is launched.
5354 If no application is found, Emacs simply visits the file.
5355 With optional argument IN-EMACS, Emacs will visit the file.
5356 If the file does not exist, an error is thrown."
5357 (let* ((file (convert-standard-filename (org-expand-file-name path)))
5358 (dfile (downcase file))
5360 (if (and (not (file-exists-p file))
5361 (not org-open-non-existing-files))
5362 (error "No such file: %s" file))
5363 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
5364 (setq ext (match-string 1 dfile))
5365 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
5366 (setq ext (match-string 1 dfile))))
5367 (setq apps (append org-file-apps (org-default-apps)))
5370 (setq cmd (or (cdr (assoc ext apps))
5371 (cdr (assoc t apps)))))
5373 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
5374 (setq cmd (format cmd (concat "\"" file "\"")))
5375 (save-window-excursion
5376 (shell-command (concat cmd " & &"))))
5379 (funcall (cdr (assq 'file org-link-frame-setup)) file)
5380 (if line (goto-line line)))
5383 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
5385 (defun org-default-apps ()
5386 "Return the default applications for this operating system."
5388 ((eq system-type 'darwin)
5389 org-file-apps-defaults-macosx)
5390 ((eq system-type 'windows-nt)
5391 org-file-apps-defaults-windowsnt)
5392 ((eq system-type 'linux)
5393 org-file-apps-defaults-linux)
5394 (t org-file-apps-defaults-linux)))
5396 (defun org-expand-file-name (path)
5397 "Replace special path abbreviations and expand the file name."
5398 (expand-file-name path))
5401 (defvar org-insert-link-history nil
5402 "Minibuffer history for links inserted with `org-insert-link'.")
5404 (defvar org-stored-links nil
5405 "Contains the links stored with `org-store-link'.")
5408 (defun org-store-link (arg)
5409 "\\<org-mode-map>Store an org-link to the current location.
5410 This link can later be inserted into an org-buffer with
5411 \\[org-insert-link].
5412 For some link types, a prefix arg is interpreted:
5413 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5414 For file links, arg negates `org-line-numbers-in-file-links'."
5419 ((eq major-mode 'bbdb-mode)
5420 (setq cpltxt (concat
5422 (or (bbdb-record-name (bbdb-current-record))
5423 (bbdb-record-company (bbdb-current-record))))
5424 link (org-make-link cpltxt)))
5426 ((eq major-mode 'calendar-mode)
5427 (let ((cd (calendar-cursor-to-date)))
5430 (car org-time-stamp-formats)
5432 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5435 ((or (eq major-mode 'vm-summary-mode)
5436 (eq major-mode 'vm-presentation-mode))
5437 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
5438 (vm-follow-summary-cursor)
5440 (vm-select-folder-buffer)
5441 (let* ((message (car vm-message-pointer))
5442 (folder (buffer-file-name))
5443 (subject (vm-su-subject message))
5444 (author (vm-su-full-name message))
5445 (message-id (vm-su-message-id message)))
5446 (setq folder (abbreviate-file-name folder))
5447 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
5449 (setq folder (replace-match "" t t folder)))
5450 (setq cpltxt (concat author " on: " subject))
5451 (setq link (concat cpltxt "\n "
5453 "vm:" folder "#" message-id))))))
5455 ((eq major-mode 'wl-summary-mode)
5456 (let* ((msgnum (wl-summary-message-number))
5457 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
5458 msgnum 'message-id))
5459 (wl-message-entity (elmo-msgdb-overview-get-entity
5460 msgnum (wl-summary-buffer-msgdb)))
5461 (author (wl-summary-line-from)) ; FIXME: how to get author name?
5462 (subject "???")) ; FIXME: How to get subject of email?
5463 (setq cpltxt (concat author " on: " subject))
5464 (setq link (concat cpltxt "\n "
5466 "wl:" wl-summary-buffer-folder-name
5469 ((eq major-mode 'rmail-mode)
5472 (rmail-narrow-to-non-pruned-header)
5473 (let ((folder (buffer-file-name))
5474 (message-id (mail-fetch-field "message-id"))
5475 (author (mail-fetch-field "from"))
5476 (subject (mail-fetch-field "subject")))
5477 (setq cpltxt (concat author " on: " subject))
5478 (setq link (concat cpltxt "\n "
5480 "rmail:" folder "#" message-id)))))))
5482 ((eq major-mode 'gnus-group-mode)
5483 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
5484 (gnus-group-group-name)) ; version
5485 ((fboundp 'gnus-group-name)
5488 (setq cpltxt (concat
5489 (if (org-xor arg org-usenet-links-prefer-google)
5490 "http://groups.google.com/groups?group="
5493 link (org-make-link cpltxt))))
5495 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
5496 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
5497 (gnus-summary-beginning-of-article)
5498 (let* ((group (car gnus-article-current))
5499 (article (cdr gnus-article-current))
5500 (header (gnus-summary-article-header article))
5501 (author (mail-header-from header))
5502 (message-id (mail-header-id header))
5503 (date (mail-header-date header))
5504 (subject (gnus-summary-subject-string)))
5505 (setq cpltxt (concat author " on: " subject))
5506 (if (org-xor arg org-usenet-links-prefer-google)
5510 (format "http://groups.google.com/groups?as_umsgid=%s"
5511 (org-fixup-message-id-for-http message-id))))
5512 (setq link (concat cpltxt "\n"
5515 "#" (number-to-string article)))))))
5517 ((eq major-mode 'w3-mode)
5518 (setq cpltxt (url-view-url t)
5519 link (org-make-link cpltxt)))
5520 ((eq major-mode 'w3m-mode)
5521 (setq cpltxt w3m-current-url
5522 link (org-make-link cpltxt)))
5525 ;; Just link to this file here.
5526 (setq cpltxt (concat "file:"
5527 (abbreviate-file-name (buffer-file-name))))
5528 ;; Add the line number?
5529 (if (org-xor org-line-numbers-in-file-links arg)
5533 (+ (if (bolp) 1 0) (count-lines
5534 (point-min) (point)))))))
5535 (setq link (org-make-link cpltxt)))
5538 (error "Cannot link to a buffer which is not visiting a file"))
5540 (t (setq link nil)))
5542 (if (and (interactive-p) link)
5544 (setq org-stored-links
5545 (cons (cons (or cpltxt link) link) org-stored-links))
5546 (message "Stored: %s" (or cpltxt link)))
5549 (defun org-make-link (&rest strings)
5550 "Concatenate STRINGS, format resulting string with `org-link-format'."
5551 (format org-link-format (apply 'concat strings)))
5553 (defun org-xor (a b)
5557 (defun org-get-header (header)
5558 "Find a header field in the current buffer."
5560 (goto-char (point-min))
5561 (let ((case-fold-search t) s)
5564 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
5565 (setq s (match-string 1)))
5566 (while (string-match "\"" s)
5567 (setq s (replace-match "" t t s)))
5568 (if (string-match "[<(].*" s)
5569 (setq s (replace-match "" t t s))))
5570 ((eq header 'message-id)
5571 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
5572 (setq s (match-string 1))))
5573 ((eq header 'subject)
5574 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
5575 (setq s (match-string 1)))))
5576 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
5577 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
5581 (defun org-fixup-message-id-for-http (s)
5582 "Replace special characters in a message id, so it can be used in an http query."
5583 (while (string-match "<" s)
5584 (setq s (replace-match "%3C" t t s)))
5585 (while (string-match ">" s)
5586 (setq s (replace-match "%3E" t t s)))
5587 (while (string-match "@" s)
5588 (setq s (replace-match "%40" t t s)))
5591 (defun org-insert-link (&optional complete-file)
5592 "Insert a link. At the prompt, enter the link.
5594 Completion can be used to select a link previously stored with
5595 `org-store-link'. When the empty string is entered (i.e. if you just
5596 press RET at the prompt), the link defaults to the most recently
5597 stored link. As SPC triggers completion in the minibuffer, you need to
5598 use M-SPC or C-q SPC to force the insertion of a space character.
5600 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
5601 selected using completion. The path to the file will be relative to
5602 the current directory if the file is in the current directory or a
5603 subdirectory. Otherwise, the link will be the absolute path as
5604 completed in the minibuffer (i.e. normally ~/path/to/file).
5606 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
5607 is in the current directory or below."
5609 (let ((link (if complete-file
5610 (read-file-name "File: ")
5612 "Link: " org-stored-links nil nil nil
5613 org-insert-link-history
5614 (or (car (car org-stored-links))))))
5616 (if (or (not link) (equal link ""))
5617 (error "No links available"))
5619 (let ((pwd (file-name-as-directory (expand-file-name "."))))
5621 ((equal complete-file '(16))
5624 "file:" (abbreviate-file-name (expand-file-name link)))))
5625 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
5626 (expand-file-name link))
5629 "file:" (match-string 1 (expand-file-name link)))))
5630 (t (insert (org-make-link "file:" link)))))
5631 (setq linktxt (cdr (assoc link org-stored-links)))
5632 (if (not org-keep-stored-link-after-insertion)
5633 (setq org-stored-links (delq (assoc link org-stored-links)
5635 (if (not linktxt) (setq link (org-make-link link)))
5636 (let ((lines (org-split-string (or linktxt link) "\n")))
5637 (insert (car lines))
5638 (setq matched (string-match org-link-regexp (car lines)))
5639 (setq lines (cdr lines))
5643 (beginning-of-line 0)
5644 (looking-at "[ \t]+\\S-"))
5646 (setq matched (or matched
5647 (string-match org-link-regexp (car lines))))
5648 (insert (car lines))
5649 (setq lines (cdr lines))))
5651 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5653 ;;; Hooks for remember.el
5655 (defun org-remember-annotation ()
5656 "Return a link to the current location as an annotation for remember.el.
5657 If you are using Org-mode files as target for data storage with
5658 remember.el, then the annotations should include a link compatible with the
5659 conventions in Org-mode. This function returns such a link."
5660 (org-store-link nil))
5662 (defconst org-remember-help
5663 "Select a destination location for the note.
5664 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5665 RET at beg-of-buf -> Append to file as level 2 headline
5666 RET on headline -> Store as sublevel entry to current headline
5667 <left>/<right> -> before/after current headline, same headings level")
5670 (defun org-remember-handler ()
5671 "Store stuff from remember.el into an org file.
5672 First prompts for an org file. If the user just presses return, the value
5673 of `org-default-notes-file' is used.
5674 Then the command offers the headings tree of the selected file in order to
5675 file the text at a specific location.
5676 You can either immediately press RET to get the note appended to the
5677 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5678 find a better place. Then press RET or <left> or <right> in insert the note.
5680 Key Cursor position Note gets inserted
5681 -----------------------------------------------------------------------------
5682 RET buffer-start as level 2 heading at end of file
5683 RET on headline as sublevel of the heading at cursor
5684 RET no heading at cursor position, level taken from context.
5685 Or use prefix arg to specify level manually.
5686 <left> on headline as same level, before current heading
5687 <right> on headline as same level, after current heading
5689 So the fastest way to store the note is to press RET RET to append it to
5690 the default file. This way your current train of thought is not
5691 interrupted, in accordance with the principles of remember.el. But with
5692 little extra effort, you can push it directly to the correct location.
5694 Before being stored away, the function ensures that the text has a
5695 headline, i.e. a first line that starts with a \"*\". If not, a headline
5696 is constructed from the current date and some additional data.
5698 If the variable `org-adapt-indentation' is non-nil, the entire text is
5699 also indented so that it starts in the same column as the headline
5700 \(i.e. after the stars).
5702 See also the variable `org-reverse-note-order'."
5704 (let* ((txt (buffer-substring (point-min) (point-max)))
5705 (fastp current-prefix-arg)
5706 (file (if fastp org-default-notes-file (org-get-org-file)))
5707 (visiting (find-buffer-visiting file))
5708 (org-startup-with-deadline-check nil)
5709 (org-startup-folded nil)
5710 spos level indent reversed)
5711 ;; Modify text so that it becomes a nice subtree which can be inserted
5712 ;; into an org tree.
5713 (let* ((lines (split-string txt "\n"))
5715 (lines (cdr lines)))
5716 (if (string-match "^\\*+" first)
5717 ;; Is already a headline
5718 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5720 ;; We need to add a headline: Use time and first buffer line
5721 (setq lines (cons first lines)
5722 first (concat "* " (current-time-string)
5723 " (" (remember-buffer-desc) ")")
5725 (if org-adapt-indentation
5726 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5727 (setq txt (concat first "\n"
5728 (mapconcat 'identity lines "\n"))))
5731 (find-file-noselect file))
5732 (with-current-buffer (get-file-buffer file)
5733 (setq reversed (org-notes-order-reversed-p))
5737 ;; Ask the User for a location
5738 (setq spos (if fastp 1 (org-get-location
5740 org-remember-help)))
5741 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5742 ; not handle this note
5745 ;; Put it at the start or end, as level 2
5748 (goto-char (if reversed (point-min) (point-max)))
5749 (if (not (bolp)) (newline))
5750 (org-paste-subtree (or current-prefix-arg 2) txt)))
5751 ((and (org-on-heading-p nil) (not current-prefix-arg))
5752 ;; Put it below this entry, at the beg/end of the subtree
5753 (org-back-to-heading)
5754 (setq level (outline-level))
5756 (outline-end-of-heading)
5757 (outline-end-of-subtree))
5758 (if (not (bolp)) (newline))
5759 (beginning-of-line 1)
5760 (org-paste-subtree (1+ level) txt))
5762 ;; Put it right there, with automatic level determined by
5763 ;; org-paste-subtree or from prefix arg
5764 (org-paste-subtree current-prefix-arg txt)))
5765 (when remember-save-after-remembering
5767 (if (not visiting) (kill-buffer (current-buffer)))))))))
5768 t) ;; return t to indicate that we took care of this note.
5770 (defun org-get-org-file ()
5771 "Read a filename, with default directory `org-directory'."
5772 (let ((default (or org-default-notes-file remember-data-file)))
5773 (read-file-name (format "File name [%s]: " default)
5774 (file-name-as-directory org-directory)
5777 (defun org-notes-order-reversed-p ()
5778 "Check if the current file should receive notes in reversed order."
5780 ((not org-reverse-note-order) nil)
5781 ((eq t org-reverse-note-order) t)
5782 ((not (listp org-reverse-note-order)) nil)
5784 (let ((all org-reverse-note-order)
5786 (while (setq entry (pop all))
5787 (if (string-match (car entry) (buffer-file-name))
5788 (throw 'exit (cdr entry))))
5793 ;; Watch out: Here we are talking about two different kind of tables.
5794 ;; Most of the code is for the tables created with the Org-mode table editor.
5795 ;; Sometimes, we talk about tables created and edited with the table.el
5796 ;; Emacs package. We call the former org-type tables, and the latter
5797 ;; table.el-type tables.
5800 (defun org-before-change-function (beg end)
5801 "Every change indicates that a table might need an update."
5802 (setq org-table-may-need-update t))
5804 (defconst org-table-line-regexp "^[ \t]*|"
5805 "Detects an org-type table line.")
5806 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5807 "Detects an org-type table line.")
5808 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5809 "Detects a table line marked for automatic recalculation.")
5810 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5811 "Detects a table line marked for automatic recalculation.")
5812 (defconst org-table-hline-regexp "^[ \t]*|-"
5813 "Detects an org-type table hline.")
5814 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5815 "Detects a table-type table hline.")
5816 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5817 "Detects an org-type or table-type table.")
5818 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5819 "Searching from within a table (any type) this finds the first line
5820 outside the table.")
5821 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5822 "Searching from within a table (any type) this finds the first line
5823 outside the table.")
5825 (defun org-table-create-with-table.el ()
5826 "Use the table.el package to insert a new table.
5827 If there is already a table at point, convert between Org-mode tables
5828 and table.el tables."
5832 ((org-at-table.el-p)
5833 (if (y-or-n-p "Convert table to Org-mode table? ")
5834 (org-table-convert)))
5836 (if (y-or-n-p "Convert table to table.el table? ")
5837 (org-table-convert)))
5838 (t (call-interactively 'table-insert))))
5840 (defun org-table-create (&optional size)
5841 "Query for a size and insert a table skeleton.
5842 SIZE is a string Columns x Rows like for example \"3x2\"."
5845 (setq size (read-string
5846 (concat "Table size Columns x Rows [e.g. "
5847 org-table-default-size "]: ")
5848 "" nil org-table-default-size)))
5850 (let* ((pos (point))
5851 (indent (make-string (current-column) ?\ ))
5852 (split (org-split-string size " *x *"))
5853 (rows (string-to-number (nth 1 split)))
5854 (columns (string-to-number (car split)))
5855 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5857 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5858 (point-at-bol) (point)))
5859 (beginning-of-line 1)
5861 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5862 (dotimes (i rows) (insert line))
5865 ;; Insert a hline after the first row.
5872 (defun org-table-convert-region (beg0 end0 nspace)
5873 "Convert region to a table.
5874 The region goes from BEG0 to END0, but these borders will be moved
5875 slightly, to make sure a beginning of line in the first line is included.
5876 When NSPACE is non-nil, it indicates the minimum number of spaces that
5877 separate columns (default: just one space)"
5878 (let* ((beg (min beg0 end0))
5879 (end (max beg0 end0))
5883 (beginning-of-line 1)
5884 (setq beg (move-marker (make-marker) (point)))
5886 (if (bolp) (backward-char 1) (end-of-line 1))
5887 (setq end (move-marker (make-marker) (point)))
5888 ;; Lets see if this is tab-separated material. If every nonempty line
5889 ;; contains a tab, we will assume that it is tab-separated material
5893 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5894 (if nspace (setq tabsep nil))
5897 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5898 (max 1 (prefix-numeric-value nspace)))))
5900 (while (re-search-forward re end t)
5901 (replace-match "|" t t))
5906 (defun org-table-import (file arg)
5907 "Import FILE as a table.
5908 The file is assumed to be tab-separated. Such files can be produced by most
5909 spreadsheet and database applications. If no tabs (at least one per line)
5910 are found, lines will be split on whitespace into fields."
5911 (interactive "f\nP")
5912 (or (bolp) (newline))
5915 (insert-file-contents file)
5916 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5918 (defun org-table-export ()
5919 "Export table as a tab-separated file.
5920 Such a file can be imported into a spreadsheet program like Excel."
5922 (let* ((beg (org-table-begin))
5923 (end (org-table-end))
5924 (table (buffer-substring beg end))
5925 (file (read-file-name "Export table to: "))
5927 (unless (or (not (file-exists-p file))
5928 (y-or-n-p (format "Overwrite file %s? " file)))
5930 (with-current-buffer (find-file-noselect file)
5931 (setq buf (current-buffer))
5935 (goto-char (point-min))
5936 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5937 (replace-match "" t t)
5939 (goto-char (point-min))
5940 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5941 (replace-match "" t t)
5942 (goto-char (min (1+ (point)) (point-max))))
5943 (goto-char (point-min))
5944 (while (re-search-forward "^-[-+]*$" nil t)
5946 (if (looking-at "\n")
5948 (goto-char (point-min))
5949 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5950 (replace-match "\t" t t))
5954 (defvar org-table-aligned-begin-marker (make-marker)
5955 "Marker at the beginning of the table last aligned.
5956 Used to check if cursor still is in that table, to minimize realignment.")
5957 (defvar org-table-aligned-end-marker (make-marker)
5958 "Marker at the end of the table last aligned.
5959 Used to check if cursor still is in that table, to minimize realignment.")
5960 (defvar org-table-last-alignment nil
5961 "List of flags for flushright alignment, from the last re-alignment.
5962 This is being used to correctly align a single field after TAB or RET.")
5963 ;; FIXME: The following is currently not used.
5964 (defvar org-table-last-column-widths nil
5965 "List of max width of fields in each column.
5966 This is being used to correctly align a single field after TAB or RET.")
5968 (defvar org-last-recalc-line nil)
5970 (defun org-table-align ()
5971 "Align the table at point by aligning all vertical bars."
5975 (beg (org-table-begin))
5976 (end (org-table-end))
5977 ;; Current cursor position
5978 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5979 (colpos (org-table-current-column))
5980 (winstart (window-start))
5981 text lines (new "") lengths l typenums ty fields maxfields i
5983 (indent "") cnt frac
5985 (spaces (if (org-in-invisibility-spec-p '(org-table))
5986 org-table-spaces-around-invisible-separators
5987 org-table-spaces-around-separators))
5991 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
5993 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
5996 ;; (message "Aligning table...")
5998 (setq lines (org-split-string
5999 (buffer-substring-no-properties beg end) "\n"))
6000 ;; Store the indentation of the first line
6001 (if (string-match "^ *" (car lines))
6002 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6004 (setq lines (mapcar (lambda (l)
6005 (if (string-match "^ *|-" l)
6007 (if (string-match "[ \t]+$" l)
6008 (substring l 0 (match-beginning 0))
6011 ;; Get the data fields
6012 (setq fields (mapcar
6014 (org-split-string l " *| *"))
6015 (delq nil (copy-sequence lines))))
6016 ;; How many fields in the longest line?
6018 (setq maxfields (apply 'max (mapcar 'length fields)))
6020 (kill-region beg end)
6021 (org-table-create org-table-default-size)
6022 (error "Empty table - created default table")))
6023 ;; A list of empty string to fill any short rows on output
6024 (setq emptystrings (make-list maxfields ""))
6025 ;; Get the maximum length of a field and the most common datatype
6028 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6029 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6031 (push (apply 'max 1 (mapcar 'length column)) lengths)
6032 ;; compute the fraction stepwise, ignoring empty fields
6033 (setq cnt 0 frac 0.0)
6038 (setq frac ( / (+ (* frac cnt)
6039 (if (string-match org-table-number-regexp x) 1 0))
6040 (setq cnt (1+ cnt))))))
6042 (push (>= frac org-table-number-fraction) typenums))
6043 (setq lengths (nreverse lengths)
6044 typenums (nreverse typenums))
6045 (setq org-table-last-alignment typenums
6046 org-table-last-column-widths lengths)
6047 ;; Compute the formats needed for output of the table
6048 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6049 (while (setq l (pop lengths))
6050 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6051 (setq rfmt (concat rfmt (format rfmt1 ty l))
6052 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6053 (setq rfmt (concat rfmt "\n")
6054 hfmt (concat (substring hfmt 0 -1) "|\n"))
6055 ;; Produce the new table
6057 ;; (setq l (pop lines))
6059 ;; (setq new (concat new (apply 'format rfmt
6060 ;; (append (pop fields) emptystrings))))
6061 ;; (setq new (concat new hfmt))))
6062 (setq new (mapconcat
6064 (if l (apply 'format rfmt
6065 (append (pop fields) emptystrings))
6068 ;; Replace the old one
6069 (delete-region beg end)
6070 (move-marker end nil)
6071 (move-marker org-table-aligned-begin-marker (point))
6073 (move-marker org-table-aligned-end-marker (point))
6074 ;; Try to move to the old location (approximately)
6076 (set-window-start (selected-window) winstart 'noforce)
6077 (org-table-goto-column colpos)
6078 (setq org-table-may-need-update nil)
6079 (if (org-in-invisibility-spec-p '(org-table))
6080 (org-table-add-invisible-to-vertical-lines))
6083 (defun org-table-begin (&optional table-type)
6084 "Find the beginning of the table and return its position.
6085 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6087 (if (not (re-search-backward
6088 (if table-type org-table-any-border-regexp
6089 org-table-border-regexp)
6091 (error "Can't find beginning of table")
6092 (goto-char (match-beginning 0))
6093 (beginning-of-line 2)
6096 (defun org-table-end (&optional table-type)
6097 "Find the end of the table and return its position.
6098 With argument TABLE-TYPE, go to the end of a table.el-type table."
6100 (if (not (re-search-forward
6101 (if table-type org-table-any-border-regexp
6102 org-table-border-regexp)
6104 (goto-char (point-max))
6105 (goto-char (match-beginning 0)))
6108 (defun org-table-justify-field-maybe ()
6109 "Justify the current field, text to left, number to right."
6111 (org-table-may-need-update) ; Realignment will happen anyway, don't bother
6112 ((org-at-table-hline-p)
6113 ;; This is pretty stupid, but I don't know how to deal with hlines
6114 (setq org-table-may-need-update t))
6115 ((or (not (equal (marker-buffer org-table-aligned-begin-marker)
6117 (< (point) org-table-aligned-begin-marker)
6118 (>= (point) org-table-aligned-end-marker))
6119 ;; This is not the same table, force a full re-align
6120 (setq org-table-may-need-update t))
6121 (t ;; realign the current field, based on previous full realign
6122 (let* ((pos (point)) s org-table-may-need-update
6123 (col (org-table-current-column))
6124 (num (nth (1- col) org-table-last-alignment))
6127 (skip-chars-backward "^|\n")
6128 (if (looking-at " *\\([^|\n]*?\\) *|")
6130 (setq s (match-string 1)
6132 l (max 1 (- (match-end 0) (match-beginning 0) 3)))
6133 (setq f (format (if num " %%%ds |" " %%-%ds |") l)
6135 (or (equal n o) (replace-match n)))
6136 (setq org-table-may-need-update t))
6137 (goto-char pos))))))
6139 (defun org-table-next-field ()
6140 "Go to the next field in the current table.
6141 Before doing so, re-align the table if necessary."
6143 (org-table-maybe-eval-formula)
6144 (org-table-maybe-recalculate-line)
6145 (if (and org-table-automatic-realign
6146 org-table-may-need-update)
6148 (if (org-at-table-hline-p)
6152 (re-search-forward "|" (org-table-end))
6153 (if (looking-at "[ \t]*$")
6154 (re-search-forward "|" (org-table-end)))
6155 (if (looking-at "-")
6157 (beginning-of-line 0)
6158 (org-table-insert-row 'below))
6159 (if (looking-at " ") (forward-char 1))))
6161 (org-table-insert-row 'below))))
6163 (defun org-table-previous-field ()
6164 "Go to the previous field in the table.
6165 Before doing so, re-align the table if necessary."
6167 (org-table-justify-field-maybe)
6168 (org-table-maybe-recalculate-line)
6169 (if (and org-table-automatic-realign
6170 org-table-may-need-update)
6172 (if (org-at-table-hline-p)
6174 (re-search-backward "|" (org-table-begin))
6175 (re-search-backward "|" (org-table-begin))
6176 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6177 (re-search-backward "|" (org-table-begin)))
6178 (if (looking-at "| ?")
6179 (goto-char (match-end 0))))
6181 (defun org-table-next-row ()
6182 "Go to the next row (same column) in the current table.
6183 Before doing so, re-align the table if necessary."
6185 (org-table-maybe-eval-formula)
6186 (org-table-maybe-recalculate-line)
6187 (if (or (looking-at "[ \t]*$")
6188 (save-excursion (skip-chars-backward " \t") (bolp)))
6190 (if (and org-table-automatic-realign
6191 org-table-may-need-update)
6193 (let ((col (org-table-current-column)))
6194 (beginning-of-line 2)
6195 (if (or (not (org-at-table-p))
6196 (org-at-table-hline-p))
6198 (beginning-of-line 0)
6199 (org-table-insert-row 'below)))
6200 (org-table-goto-column col)
6201 (skip-chars-backward "^|\n\r")
6202 (if (looking-at " ") (forward-char 1)))))
6204 (defun org-table-copy-down (n)
6205 "Copy a field down in the current column.
6206 If the field at the cursor is empty, copy into it the content of the nearest
6207 non-empty field above. With argument N, use the Nth non-empty field.
6208 If the current field is not empty, it is copied down to the next row, and
6209 the cursor is moved with it. Therefore, repeating this command causes the
6210 column to be filled row-by-row.
6211 If the variable `org-table-copy-increment' is non-nil and the field is an
6212 integer, it will be incremented while copying."
6214 (let* ((colpos (org-table-current-column))
6215 (field (org-table-get-field))
6216 (non-empty (string-match "[^ \t]" field))
6217 (beg (org-table-begin))
6219 (org-table-check-inside-data-field)
6222 (setq txt (org-trim field))
6223 (org-table-next-row)
6224 (org-table-blank-field))
6228 (while (progn (beginning-of-line 1)
6229 (re-search-backward org-table-dataline-regexp
6231 (org-table-goto-column colpos t)
6232 (if (and (looking-at
6233 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6234 (= (setq n (1- n)) 0))
6235 (throw 'exit (match-string 1))))))))
6238 (if (and org-table-copy-increment
6239 (string-match "^[0-9]+$" txt))
6240 (setq txt (format "%d" (+ (string-to-int txt) 1))))
6242 (org-table-maybe-recalculate-line)
6244 (error "No non-empty field found"))))
6246 (defun org-table-check-inside-data-field ()
6247 "Is point inside a table data field?
6248 I.e. not on a hline or before the first or after the last column?"
6249 (if (or (not (org-at-table-p))
6250 (= (org-table-current-column) 0)
6251 (org-at-table-hline-p)
6252 (looking-at "[ \t]*$"))
6253 (error "Not in table data field")))
6255 (defvar org-table-clip nil
6256 "Clipboard for table regions.")
6258 (defun org-table-blank-field ()
6259 "Blank the current table field or active region."
6261 (org-table-check-inside-data-field)
6262 (if (and (interactive-p) (org-region-active-p))
6263 (let (org-table-clip)
6264 (org-table-cut-region (region-beginning) (region-end)))
6265 (skip-chars-backward "^|")
6267 (if (looking-at "|[^|\n]+")
6268 (let* ((pos (match-beginning 0))
6269 (match (match-string 0))
6270 (len (length match)))
6271 (replace-match (concat "|" (make-string (1- len) ?\ )))
6272 (goto-char (+ 2 pos))
6273 (substring match 1)))))
6275 (defun org-table-get-field (&optional n replace)
6276 "Return the value of the field in column N of current row.
6277 N defaults to current field.
6278 If REPLACE is a string, replace field with this value. The return value
6279 is always the old value."
6280 (and n (org-table-goto-column n))
6281 (skip-chars-backward "^|\n")
6283 (if (looking-at "|[^|\r\n]*")
6284 (let* ((pos (match-beginning 0))
6285 (val (buffer-substring (1+ pos) (match-end 0))))
6287 (replace-match (concat "|" replace)))
6288 (goto-char (min (point-at-eol) (+ 2 pos)))
6290 (forward-char 1) ""))
6292 (defun org-table-current-column ()
6293 "Find out which column we are in.
6294 When called interactively, column is also displayed in echo area."
6296 (if (interactive-p) (org-table-check-inside-data-field))
6298 (let ((cnt 0) (pos (point)))
6299 (beginning-of-line 1)
6300 (while (search-forward "|" pos t)
6301 (setq cnt (1+ cnt)))
6302 (if (interactive-p) (message "This is table column %d" cnt))
6305 (defun org-table-goto-column (n &optional on-delim force)
6306 "Move the cursor to the Nth column in the current table line.
6307 With optional argument ON-DELIM, stop with point before the left delimiter
6309 If there are less than N fields, just go to after the last delimiter.
6310 However, when FORCE is non-nil, create new columns if necessary."
6311 (let ((pos (point-at-eol)))
6312 (beginning-of-line 1)
6314 (while (and (> (setq n (1- n)) -1)
6315 (or (search-forward "|" pos t)
6317 (progn (end-of-line 1)
6318 (skip-chars-backward "^|")
6320 ; (backward-char 2) t)))))
6321 (when (and force (not (looking-at ".*|")))
6322 (save-excursion (end-of-line 1) (insert " | ")))
6325 (if (looking-at " ") (forward-char 1))))))
6327 (defun org-at-table-p (&optional table-type)
6328 "Return t if the cursor is inside an org-type table.
6329 If TABLE-TYPE is non-nil, also chack for table.el-type tables."
6330 (if org-enable-table-editor
6332 (beginning-of-line 1)
6333 (looking-at (if table-type org-table-any-line-regexp
6334 org-table-line-regexp)))
6337 (defun org-table-recognize-table.el ()
6338 "If there is a table.el table nearby, recognize it and move into it."
6339 (if org-table-tab-recognizes-table.el
6340 (if (org-at-table.el-p)
6342 (beginning-of-line 1)
6343 (if (looking-at org-table-dataline-regexp)
6345 (if (looking-at org-table1-hline-regexp)
6347 (beginning-of-line 2)
6348 (if (looking-at org-table-any-border-regexp)
6349 (beginning-of-line -1)))))
6350 (if (re-search-forward "|" (org-table-end t) t)
6353 (if (table--at-cell-p (point))
6355 (message "recognizing table.el table...")
6356 (table-recognize-table)
6357 (message "recognizing table.el table...done")))
6358 (error "This should not happen..."))
6363 (defun org-at-table.el-p ()
6364 "Return t if the cursor is inside a table.el-type table."
6366 (if (org-at-table-p 'any)
6368 (goto-char (org-table-begin 'any))
6369 (looking-at org-table1-hline-regexp))
6372 (defun org-at-table-hline-p ()
6373 "Return t if the cursor is inside a hline in a table."
6374 (if org-enable-table-editor
6376 (beginning-of-line 1)
6377 (looking-at org-table-hline-regexp))
6380 (defun org-table-insert-column ()
6381 "Insert a new column into the table."
6383 (if (not (org-at-table-p))
6384 (error "Not at a table"))
6385 (org-table-find-dataline)
6386 (let* ((col (max 1 (org-table-current-column)))
6387 (beg (org-table-begin))
6388 (end (org-table-end))
6389 ;; Current cursor position
6390 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6393 (while (< (point) end)
6394 (if (org-at-table-hline-p)
6396 (org-table-goto-column col t)
6398 (beginning-of-line 2))
6399 (move-marker end nil)
6401 (org-table-goto-column colpos)
6403 (org-table-modify-formulas 'insert col)))
6405 (defun org-table-find-dataline ()
6406 "Find a dataline in the current table, which is needed for column commands."
6407 (if (and (org-at-table-p)
6408 (not (org-at-table-hline-p)))
6410 (let ((col (current-column))
6411 (end (org-table-end)))
6412 (move-to-column col)
6413 (while (and (< (point) end)
6414 (or (not (= (current-column) col))
6415 (org-at-table-hline-p)))
6416 (beginning-of-line 2)
6417 (move-to-column col))
6418 (if (and (org-at-table-p)
6419 (not (org-at-table-hline-p)))
6422 "Please position cursor in a data line for column operations")))))
6424 (defun org-table-delete-column ()
6425 "Delete a column into the table."
6427 (if (not (org-at-table-p))
6428 (error "Not at a table"))
6429 (org-table-find-dataline)
6430 (org-table-check-inside-data-field)
6431 (let* ((col (org-table-current-column))
6432 (beg (org-table-begin))
6433 (end (org-table-end))
6434 ;; Current cursor position
6435 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6438 (while (< (point) end)
6439 (if (org-at-table-hline-p)
6441 (org-table-goto-column col t)
6442 (and (looking-at "|[^|\n]+|")
6443 (replace-match "|")))
6444 (beginning-of-line 2))
6445 (move-marker end nil)
6447 (org-table-goto-column colpos)
6449 (org-table-modify-formulas 'remove col)))
6451 (defun org-table-move-column-right ()
6452 "Move column to the right."
6454 (org-table-move-column nil))
6455 (defun org-table-move-column-left ()
6456 "Move column to the left."
6458 (org-table-move-column 'left))
6460 (defun org-table-move-column (&optional left)
6461 "Move the current column to the right. With arg LEFT, move to the left."
6463 (if (not (org-at-table-p))
6464 (error "Not at a table"))
6465 (org-table-find-dataline)
6466 (org-table-check-inside-data-field)
6467 (let* ((col (org-table-current-column))
6468 (col1 (if left (1- col) col))
6469 (beg (org-table-begin))
6470 (end (org-table-end))
6471 ;; Current cursor position
6472 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6473 (colpos (if left (1- col) (1+ col))))
6474 (if (and left (= col 1))
6475 (error "Cannot move column further left"))
6476 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6477 (error "Cannot move column further right"))
6479 (while (< (point) end)
6480 (if (org-at-table-hline-p)
6482 (org-table-goto-column col1 t)
6483 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6484 (replace-match "|\\2|\\1|")))
6485 (beginning-of-line 2))
6486 (move-marker end nil)
6488 (org-table-goto-column colpos)
6490 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6492 (defun org-table-move-row-down ()
6493 "move table row down."
6495 (org-table-move-row nil))
6496 (defun org-table-move-row-up ()
6497 "move table row up."
6499 (org-table-move-row 'up))
6501 (defun org-table-move-row (&optional up)
6502 "Move the current table line down. With arg UP, move it up."
6504 (let ((col (current-column))
6508 (beginning-of-line tonew)
6509 (if (not (org-at-table-p))
6512 (error "Cannot move row further")))
6514 (beginning-of-line 1)
6516 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6517 (delete-region (point) (1+ (point-at-eol)))
6518 (beginning-of-line tonew)
6520 (beginning-of-line 0)
6521 (move-to-column col)))
6523 (defun org-table-insert-row (&optional arg)
6524 "Insert a new row above the current line into the table.
6525 With prefix ARG, insert below the current line."
6527 (if (not (org-at-table-p))
6528 (error "Not at a table"))
6529 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6531 (if (string-match "^[ \t]*|-" line)
6532 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
6533 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
6534 ;; Fix the first field if necessary
6535 (setq new (concat new))
6536 (if (string-match "^[ \t]*| *[#$] *|" line)
6537 (setq new (replace-match (match-string 0 line) t t new)))
6538 (beginning-of-line (if arg 2 1))
6539 (let (org-table-may-need-update)
6540 (insert-before-markers new)
6541 (insert-before-markers "\n"))
6542 (beginning-of-line 0)
6543 (re-search-forward "| ?" (point-at-eol) t)
6544 (and org-table-may-need-update (org-table-align))))
6546 (defun org-table-insert-hline (&optional arg)
6547 "Insert a horizontal-line below the current line into the table.
6548 With prefix ARG, insert above the current line."
6550 (if (not (org-at-table-p))
6551 (error "Not at a table"))
6552 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6553 (col (current-column))
6555 (if (string-match "^[ \t]*|-" line)
6557 (mapcar (lambda (x) (if (member x '(?| ?+))
6558 (prog1 (if start ?+ ?|) (setq start t))
6562 (mapcar (lambda (x) (if (equal x ?|)
6563 (prog1 (if start ?+ ?|) (setq start t))
6566 (beginning-of-line (if arg 1 2))
6567 (apply 'insert line)
6568 (if (equal (char-before (point)) ?+)
6569 (progn (backward-delete-char 1) (insert "|")))
6571 (beginning-of-line 0)
6572 (move-to-column col)))
6574 (defun org-table-kill-row ()
6575 "Delete the current row or horizontal line from the table."
6577 (if (not (org-at-table-p))
6578 (error "Not at a table"))
6579 (let ((col (current-column)))
6580 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6581 (if (not (org-at-table-p)) (beginning-of-line 0))
6582 (move-to-column col)))
6585 (defun org-table-cut-region (beg end)
6586 "Copy region in table to the clipboard and blank all relevant fields."
6588 (org-table-copy-region beg end 'cut))
6590 (defun org-table-copy-region (beg end &optional cut)
6591 "Copy rectangular region in table to clipboard.
6592 A special clipboard is used which can only be accessed
6593 with `org-table-paste-rectangle'"
6595 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6597 (rpl (if cut " " nil)))
6599 (org-table-check-inside-data-field)
6600 (setq l01 (count-lines (point-min) (point))
6601 c01 (org-table-current-column))
6603 (org-table-check-inside-data-field)
6604 (setq l02 (count-lines (point-min) (point))
6605 c02 (org-table-current-column))
6606 (setq l1 (min l01 l02) l2 (max l01 l02)
6607 c1 (min c01 c02) c2 (max c01 c02))
6611 (if (> l1 l2) (throw 'exit t))
6613 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6614 (setq cols nil ic1 c1 ic2 c2)
6615 (while (< ic1 (1+ ic2))
6616 (push (org-table-get-field ic1 rpl) cols)
6617 (setq ic1 (1+ ic1)))
6618 (push (nreverse cols) region)
6619 (setq l1 (1+ l1)))))
6620 (setq org-table-clip (nreverse region))
6621 (if cut (org-table-align))
6624 (defun org-table-paste-rectangle ()
6625 "Paste a rectangular region into a table.
6626 The upper right corner ends up in the current field. All involved fields
6627 will be overwritten. If the rectangle does not fit into the present table,
6628 the table is enlarged as needed. The process ignores horizontal separator
6631 (unless (and org-table-clip (listp org-table-clip))
6632 (error "First cut/copy a region to paste!"))
6633 (org-table-check-inside-data-field)
6634 (let* ((clip org-table-clip)
6635 (line (count-lines (point-min) (point)))
6636 (col (org-table-current-column))
6637 (org-enable-table-editor t)
6638 (org-table-automatic-realign nil)
6640 (while (setq cols (pop clip))
6641 (while (org-at-table-hline-p) (beginning-of-line 2))
6642 (if (not (org-at-table-p))
6643 (progn (end-of-line 0) (org-table-next-field)))
6645 (while (setq field (pop cols))
6646 (org-table-goto-column c nil 'force)
6647 (org-table-get-field nil field)
6649 (beginning-of-line 2))
6651 (org-table-goto-column col)
6654 (defun org-table-convert ()
6655 "Convert from `org-mode' table to table.el and back.
6656 Obviously, this only works within limits. When an Org-mode table is
6657 converted to table.el, all horizontal separator lines get lost, because
6658 table.el uses these as cell boundaries and has no notion of horizontal lines.
6659 A table.el table can be converted to an Org-mode table only if it does not
6660 do row or column spanning. Multiline cells will become multiple cells.
6661 Beware, Org-mode does not test if the table can be successfully converted - it
6662 blindly applies a recipe that works for simple tables."
6665 (if (org-at-table.el-p)
6666 ;; convert to Org-mode table
6667 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6668 (end (move-marker (make-marker) (org-table-end t))))
6669 (table-unrecognize-region beg end)
6671 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6674 (if (org-at-table-p)
6675 ;; convert to table.el table
6676 (let ((beg (move-marker (make-marker) (org-table-begin)))
6677 (end (move-marker (make-marker) (org-table-end))))
6678 ;; first, get rid of all horizontal lines
6680 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6682 ;; insert a hline before first
6684 (org-table-insert-hline 'above)
6685 ;; insert a hline after each line
6686 (while (progn (beginning-of-line 2) (< (point) end))
6687 (org-table-insert-hline))
6689 (setq end (move-marker end (org-table-end)))
6690 ;; replace "+" at beginning and ending of hlines
6691 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6692 (replace-match "\\1+-"))
6694 (while (re-search-forward "-|[ \t]*$" end t)
6695 (replace-match "-+"))
6698 (defun org-table-wrap-region (arg)
6699 "Wrap several fields in a column like a paragraph.
6700 This is useful if you'd like to spread the contents of a field over several
6701 lines, in order to keep the table compact.
6703 If there is an active region, and both point and mark are in the same column,
6704 the text in the column is wrapped to minimum width for the given number of
6705 lines. Generally, this makes the table more compact. A prefix ARG may be
6706 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6707 formats the selected text to two lines. If the region was longer than 2
6708 lines, the remaining lines remain empty. A negative prefix argument reduces
6709 the current number of lines by that amount. The wrapped text is pasted back
6710 into the table. If you formatted it to more lines than it was before, fields
6711 further down in the table get overwritten - so you might need to make space in
6714 If there is no region, the current field is split at the cursor position and
6715 the text fragment to the right of the cursor is prepended to the field one
6718 If there is no region, but you specify a prefix ARG, the current field gets
6719 blank, and the content is appended to the field above."
6721 (org-table-check-inside-data-field)
6722 (if (org-region-active-p)
6723 ;; There is a region: fill as a paragraph
6724 (let ((beg (region-beginning))
6726 (org-table-cut-region (region-beginning) (region-end))
6727 (if (> (length (car org-table-clip)) 1)
6728 (error "Region must be limited to single column"))
6729 (setq nlines (if arg
6731 (+ (length org-table-clip) arg)
6733 (length org-table-clip)))
6734 (setq org-table-clip
6735 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6738 (org-table-paste-rectangle))
6739 ;; No region, split the current field at point
6741 ;; combine with field above
6742 (let ((s (org-table-blank-field))
6743 (col (org-table-current-column)))
6744 (beginning-of-line 0)
6745 (while (org-at-table-hline-p) (beginning-of-line 0))
6746 (org-table-goto-column col)
6747 (skip-chars-forward "^|")
6748 (skip-chars-backward " ")
6749 (insert " " (org-trim s))
6752 (when (looking-at "\\([^|]+\\)+|")
6753 (let ((s (match-string 1)))
6754 (replace-match " |")
6755 (goto-char (match-beginning 0))
6756 (org-table-next-row)
6757 (insert (org-trim s) " ")
6758 (org-table-align))))))
6761 "Remove whitespace at beginning and end of string."
6762 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6763 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6766 (defun org-wrap (string &optional width lines)
6767 "Wrap string to either a number of lines, or a width in characters.
6768 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6769 that costs. If there is a word longer than WIDTH, the text is actually
6770 wrapped to the length of that word.
6771 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6772 many lines, whatever width that takes.
6773 The return value is a list of lines, without newlines at the end."
6774 (let* ((words (org-split-string string "[ \t\n]+"))
6775 (maxword (apply 'max (mapcar 'length words)))
6778 (org-do-wrap words (max maxword width)))
6781 (setq ll (org-do-wrap words maxword))
6782 (if (<= (length ll) lines)
6785 (while (> (length ll) lines)
6787 (setq ll (org-do-wrap words w)))
6789 (t (error "Cannot wrap this")))))
6792 (defun org-do-wrap (words width)
6793 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6796 (setq line (pop words))
6797 (while (and words (< (+ (length line) (length (car words))) width))
6798 (setq line (concat line " " (pop words))))
6799 (setq lines (push line lines)))
6802 ;; FIXME: I think I can make this more efficient
6803 (defun org-split-string (string &optional separators)
6804 "Splits STRING into substrings at SEPARATORS.
6805 No empty strings are returned if there are matches at the beginning
6807 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6811 (while (and (string-match rexp string
6813 (= start (match-beginning 0))
6814 (< start (length string)))
6816 (< (match-beginning 0) (length string)))
6818 (or (eq (match-beginning 0) 0)
6819 (and (eq (match-beginning 0) (match-end 0))
6820 (eq (match-beginning 0) start))
6822 (cons (substring string start (match-beginning 0))
6824 (setq start (match-end 0)))
6825 (or (eq start (length string))
6827 (cons (substring string start)
6831 (defun org-table-add-invisible-to-vertical-lines ()
6832 "Add an `invisible' property to vertical lines of current table."
6834 (let* ((beg (org-table-begin))
6835 (end (org-table-end))
6839 (while (< (point) end)
6840 (setq end1 (point-at-eol))
6841 (if (looking-at org-table-dataline-regexp)
6842 (while (re-search-forward "|" end1 t)
6843 (add-text-properties (1- (point)) (point)
6844 '(invisible org-table)))
6845 (while (re-search-forward "[+|]" end1 t)
6846 (add-text-properties (1- (point)) (point)
6847 '(invisible org-table))))
6848 (beginning-of-line 2)))))
6850 (defun org-table-toggle-vline-visibility (&optional arg)
6851 "Toggle the visibility of table vertical lines.
6852 The effect is immediate and on all tables in the file.
6853 With prefix ARG, make lines invisible when ARG is positive, make lines
6854 visible when ARG is not positive"
6857 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
6858 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
6859 (t (if (org-in-invisibility-spec-p '(org-table))
6862 (if (eq action 'off)
6864 (org-remove-from-invisibility-spec '(org-table))
6865 (org-table-map-tables 'org-table-align)
6866 (message "Vertical table lines visible")
6867 (if (org-at-table-p)
6869 (org-add-to-invisibility-spec '(org-table))
6870 (org-table-map-tables 'org-table-align)
6871 (message "Vertical table lines invisible"))
6872 (redraw-frame (selected-frame))))
6874 (defun org-table-map-tables (function)
6875 "Apply FUNCTION to the start of all tables in the buffer."
6879 (goto-char (point-min))
6880 (while (re-search-forward org-table-any-line-regexp nil t)
6881 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6882 (beginning-of-line 1)
6883 (if (looking-at org-table-line-regexp)
6884 (save-excursion (funcall function)))
6885 (re-search-forward org-table-any-border-regexp nil 1)))))
6887 (defun org-table-sum (&optional beg end nlast)
6888 "Sum numbers in region of current table column.
6889 The result will be displayed in the echo area, and will be available
6890 as kill to be inserted with \\[yank].
6892 If there is an active region, it is interpreted as a rectangle and all
6893 numbers in that rectangle will be summed. If there is no active
6894 region and point is located in a table column, sum all numbers in that
6897 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6898 numbers are assumed to be times as well (in decimal hours) and the
6899 numbers are added as such.
6901 If NLAST is a number, only the NLAST fields will actually be summed."
6904 (let (col (timecnt 0) diff h m s org-table-clip)
6906 ((and beg end)) ; beg and end given explicitly
6907 ((org-region-active-p)
6908 (setq beg (region-beginning) end (region-end)))
6910 (setq col (org-table-current-column))
6911 (goto-char (org-table-begin))
6912 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
6913 (error "No table data"))
6914 (org-table-goto-column col)
6915 ;not needed? (skip-chars-backward "^|")
6917 (goto-char (org-table-end))
6918 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
6919 (error "No table data"))
6920 (org-table-goto-column col)
6921 ;not needed? (skip-chars-forward "^|")
6922 (setq end (point))))
6923 (let* ((items (apply 'append (org-table-copy-region beg end)))
6924 (items1 (cond ((not nlast) items)
6925 ((>= nlast (length items)) items)
6926 (t (setq items (reverse items))
6927 (setcdr (nthcdr (1- nlast) items) nil)
6929 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
6931 (res (apply '+ numbers))
6932 (sres (if (= timecnt 0)
6934 (setq diff (* 3600 res)
6935 h (floor (/ diff 3600)) diff (mod diff 3600)
6936 m (floor (/ diff 60)) diff (mod diff 60)
6938 (format "%d:%02d:%02d" h m s))))
6941 (message (substitute-command-keys
6942 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
6943 (length numbers) sres))))
6946 (defun org-table-get-number-for-summing (s)
6948 (if (string-match "^ *|? *" s)
6949 (setq s (replace-match "" nil nil s)))
6950 (if (string-match " *|? *$" s)
6951 (setq s (replace-match "" nil nil s)))
6952 (setq n (string-to-number s))
6954 ((and (string-match "0" s)
6955 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
6956 ((string-match "\\`[ \t]+\\'" s) nil)
6957 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
6958 (let ((h (string-to-number (or (match-string 1 s) "0")))
6959 (m (string-to-number (or (match-string 2 s) "0")))
6960 (s (string-to-number (or (match-string 4 s) "0"))))
6961 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
6962 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
6966 (defvar org-table-formula-history nil)
6968 (defun org-table-get-formula (&optional equation)
6969 "Read a formula from the minibuffer, offer stored formula as default."
6970 (let* ((col (org-table-current-column))
6971 (stored-list (org-table-get-stored-formulas))
6972 (stored (cdr (assoc col stored-list)))
6974 ((and stored equation (string-match "^ *= *$" equation))
6979 "Formula: " (or stored "") 'org-table-formula-history
6981 (if (not (string-match "\\S-" eq))
6982 (error "Empty formula"))
6983 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
6984 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
6986 (setcdr (assoc col stored-list) eq)
6987 (setq stored-list (cons (cons col eq) stored-list)))
6988 (if (not (equal stored eq))
6989 (org-table-store-formulas stored-list))
6992 (defun org-table-store-formulas (alist)
6993 "Store the list of formulas below the current table."
6994 (setq alist (sort alist (lambda (a b) (< (car a) (car b)))))
6996 (goto-char (org-table-end))
6997 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
6998 (delete-region (point) (match-end 0)))
7000 (mapconcat (lambda (x)
7001 (concat "$" (int-to-string (car x)) "=" (cdr x)))
7005 (defun org-table-get-stored-formulas ()
7006 "Return an alist withh the t=stored formulas directly after current table."
7008 (let (col eq eq-alist strings string)
7010 (goto-char (org-table-end))
7011 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7012 (setq strings (org-split-string (match-string 2) " *:: *"))
7013 (while (setq string (pop strings))
7014 (if (string-match "\\$\\([0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7015 (setq col (string-to-number (match-string 1 string))
7016 eq (match-string 2 string)
7017 eq-alist (cons (cons col eq) eq-alist))))))
7020 (defun org-table-modify-formulas (action &rest columns)
7021 "Modify the formulas stored below the current table.
7022 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7023 expected, for the other action only a single column number is needed."
7024 (let ((list (org-table-get-stored-formulas))
7025 (nmax (length (org-split-string (buffer-substring (point-at-bol) (point-at-eol))
7029 ((null list)) ; No action needed if there are no stored formulas
7030 ((eq action 'remove)
7031 (setq col (car columns))
7032 (org-table-replace-in-formulas list col "INVALID")
7033 (if (assoc col list) (setq list (delq (assoc col list) list)))
7034 (loop for i from (1+ col) upto nmax by 1 do
7035 (org-table-replace-in-formulas list i (1- i))
7036 (if (assoc i list) (setcar (assoc i list) (1- i)))))
7037 ((eq action 'insert)
7038 (setq col (car columns))
7039 (loop for i from nmax downto col by 1 do
7040 (org-table-replace-in-formulas list i (1+ i))
7041 (if (assoc i list) (setcar (assoc i list) (1+ i)))))
7043 (setq col1 (car columns) col2 (nth 1 columns))
7044 (org-table-replace-in-formulas list col1 "Z")
7045 (org-table-replace-in-formulas list col2 col1)
7046 (org-table-replace-in-formulas list "Z" col2)
7047 (if (assoc col1 list) (setcar (assoc col1 list) "Z"))
7048 (if (assoc col2 list) (setcar (assoc col2 list) col1))
7049 (if (assoc "Z" list) (setcar (assoc "Z" list) col2)))
7050 (t (error "Invalid action in `org-table-modify-formulas'")))
7051 (if list (org-table-store-formulas list))))
7053 (defun org-table-replace-in-formulas (list s1 s2)
7055 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7056 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7057 re (concat (regexp-quote s1) "\\>"))
7058 (while (setq elt (pop list))
7060 (while (string-match re s)
7061 (setq s (replace-match s2 t t s)))
7064 (defvar org-table-column-names nil
7065 "Alist with column names, derived from the `!' line.")
7066 (defvar org-table-column-name-regexp nil
7067 "Regular expression matching the current column names.")
7068 (defvar org-table-local-parameters nil
7069 "Alist with parameter names, derived from the `$' line.")
7071 (defun org-table-get-specials ()
7072 "Get the column nmaes and local parameters for this table."
7074 (let ((beg (org-table-begin)) (end (org-table-end))
7075 names name fields field cnt)
7076 (setq org-table-column-names nil
7077 org-table-local-parameters nil)
7079 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7080 (setq names (org-split-string (match-string 1) " *| *")
7082 (while (setq name (pop names))
7084 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7085 (push (cons name (int-to-string cnt)) org-table-column-names))))
7086 (setq org-table-column-names (nreverse org-table-column-names))
7087 (setq org-table-column-name-regexp
7088 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7090 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7091 (setq fields (org-split-string (match-string 1) " *| *"))
7092 (while (setq field (pop fields))
7093 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\) *= *\\(.*\\)" field)
7094 (push (cons (match-string 1 field) (match-string 2 field))
7095 org-table-local-parameters)))))))
7097 (defun org-this-word ()
7098 ;; Get the current word
7100 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7101 (end (progn (skip-chars-forward "^ \t\n") (point))))
7102 (buffer-substring-no-properties beg end))))
7104 (defun org-table-maybe-eval-formula ()
7105 "Check if the current field starts with \"=\" and evaluate the formula."
7106 ;; We already know we are in a table. Get field will only return a formula
7107 ;; when appropriate. It might return a separator line, but no problem.
7108 (when org-table-formula-evaluate-inline
7109 (let* ((field (org-trim (or (org-table-get-field) "")))
7110 (dfield (downcase field))
7112 (when (equal (string-to-char field) ?=)
7113 (if (string-match "^\\(=sum[vh]?\\)\\([0-9]+\\)$" dfield)
7114 (setq nlast (1+ (string-to-number (match-string 2 dfield)))
7115 dfield (match-string 1 dfield)))
7117 ((equal dfield "=sumh")
7118 (org-table-get-field
7120 (save-excursion (org-table-goto-column 1) (point))
7122 ((member dfield '("=sum" "=sumv"))
7123 (setq col (org-table-current-column)
7124 bolpos (point-at-bol))
7125 (org-table-get-field
7128 (goto-char (org-table-begin))
7129 (if (re-search-forward org-table-dataline-regexp bolpos t)
7131 (goto-char (match-beginning 0))
7132 (org-table-goto-column col)
7134 (error "No datalines above current")))
7136 ((and (string-match "^ *=" field)
7137 (fboundp 'calc-eval))
7138 (org-table-eval-formula nil field)))))))
7140 (defvar org-last-recalc-undo-list nil)
7141 (defcustom org-table-allow-line-recalculation t
7146 (defvar org-recalc-commands nil
7147 "List of commands triggering the reccalculation of a line.
7148 Will be filled automatically during use.")
7150 (defvar org-recalc-marks
7151 '((" " . "Unmarked: no special line, no automatic recalculation")
7152 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7153 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7154 ("!" . "Column name definition line. Reference in formula as $name.")
7155 ("$" . "Parameter definition line name=value. Reference in formula as $name.")))
7157 (defun org-table-rotate-recalc-marks (&optional newchar)
7158 "Rotate the recalculation mark in the first column.
7159 If in any row, the first field is not consistent with a mark,
7160 insert a new column for the makers.
7161 When there is an active region, change all the lines in the region,
7162 after prompting for the marking character.
7163 After each change, a message will be displayed indication the meaning
7166 (unless (org-at-table-p) (error "Not at a table"))
7167 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7168 (beg (org-table-begin))
7169 (end (org-table-end))
7170 (l (org-current-line))
7171 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7172 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7176 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*| \t][^|]*|" end t))))
7177 (col (org-table-current-column))
7178 (forcenew (car (assoc newchar org-recalc-marks)))
7180 (if l1 (setq newchar (char-to-string (read-char-exclusive "Change region to what mark? Type # * ! $ or SPC: "))
7181 forcenew (car (assoc newchar org-recalc-marks))))
7182 (if (and newchar (not forcenew))
7183 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7185 (if l1 (goto-line l1))
7187 (beginning-of-line 1)
7188 (unless (looking-at org-table-dataline-regexp)
7189 (error "Not at a table data line")))
7191 (org-table-goto-column 1)
7192 (org-table-insert-column)
7193 (org-table-goto-column (1+ col)))
7194 (setq epos (point-at-eol))
7196 (beginning-of-line 1)
7197 (org-table-get-field
7198 1 (if (looking-at "^[ \t]*| *\\([#!$* ]\\) *|")
7200 (setq new (or forcenew
7201 (cadr (member (match-string 1) marks))))
7207 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7208 (and (looking-at org-table-dataline-regexp)
7209 (org-table-get-field 1 (concat " " new " "))))
7211 (if (not (= epos (point-at-eol))) (org-table-align))
7213 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7215 (defun org-table-maybe-recalculate-line ()
7216 "Recompute the current line if marked for it, and if we haven't just done it."
7218 (and org-table-allow-line-recalculation
7219 (not (and (memq last-command org-recalc-commands)
7220 (equal org-last-recalc-line (org-current-line))))
7221 (save-excursion (beginning-of-line 1)
7222 (looking-at org-table-auto-recalculate-regexp))
7223 (fboundp 'calc-eval)
7224 (org-table-recalculate) t))
7226 (defvar org-table-formula-debug nil
7227 "Non-nil means, debug table formulas.
7228 When nil, simply write \"#ERROR\" in corrupted fields.")
7231 (defsubst org-set-calc-mode (var value)
7232 (setcar (or (cdr (memq var modes)) (cons nil nil)) value))
7234 (defun org-table-eval-formula (&optional ndown equation
7235 suppress-align suppress-const
7237 "Replace the table field value at the cursor by the result of a calculation.
7239 This function makes use of Dave Gillespie's calc package, in my view the
7240 most exciting program ever written for GNU Emacs. So you need to have calc
7241 installed in order to use this function.
7243 In a table, this command replaces the value in the current field with the
7244 result of a formula. While nowhere near the computation options of a
7245 spreadsheet program, this is still very useful. There is no automatic
7246 updating of a calculated field, but the table will remember the last
7247 formula for each column. The command needs to be applied again after
7248 changing input fields.
7250 When called, the command first prompts for a formula, which is read in the
7251 minibuffer. Previously entered formulas are available through the history
7252 list, and the last used formula for each column is offered as a default.
7253 These stored formulas are adapted correctly when moving, inserting, or
7254 deleting columns with the corresponding commands.
7256 The formula can be any algebraic expression understood by the calc package.
7257 Before evaluation, variable substitution takes place: \"$\" is replaced by
7258 the field the cursor is currently in, and $1..$n reference the fields in
7259 the current row. Values from a *different* row can *not* be referenced
7260 here, so the command supports only horizontal computing. The formula can
7261 contain an optional printf format specifier after a semicolon, to reformat
7264 A few examples for formulas:
7265 $1+$2 Sum of first and second field
7266 $1+$2;%.2f Same, and format result to two digits after dec.point
7267 exp($2)+exp($1) Math functions can be used
7268 $;%.1f Reformat current cell to 1 digit after dec.point
7269 ($3-32)*5/9 degrees F -> C conversion
7271 When called with a raw \\[universal-argument] prefix, the formula is applied to the current
7272 field, and to the same same column in all following rows, until reaching a
7273 horizontal line or the end of the table. When the command is called with a
7274 numeric prefix argument (like M-3 or C-7 or \\[universal-argument] 24), the formula is applied
7275 to the current row, and to the following n-1 rows (but not beyond a
7278 This function can also be called from Lisp programs and offers two additional
7279 Arguments: EQUATION can be the formula to apply. If this argument is given,
7280 the user will not be prompted. SUPPRESS-ALIGN is used to speed-up
7281 recursive calls by by-passing unnecessary aligns. SUPPRESS-CONST suppresses
7282 the interpretation of constants in the formula. SUPPRESS-STORE means the
7283 formula should not be stored, either because it is already stored, or because
7284 it is a modified equation that should not overwrite the stored one."
7286 (setq ndown (if (equal ndown '(4)) 10000 (prefix-numeric-value ndown)))
7288 (org-table-check-inside-data-field)
7289 (org-table-get-specials)
7291 (org-table-automatic-realign nil)
7292 (case-fold-search nil)
7294 (formula (if (and equation suppress-store)
7296 (org-table-get-formula equation)))
7297 (n0 (org-table-current-column))
7298 (modes (copy-sequence org-calc-default-modes))
7299 n form fmt x ev orig c)
7301 (if (string-match ";" formula)
7302 (let ((tmp (org-split-string formula ";")))
7303 (setq formula (car tmp) fmt (or (nth 1 tmp) ""))
7304 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
7305 (setq c (string-to-char (match-string 1 fmt))
7306 n (string-to-number (or (match-string 1 fmt) "")))
7307 (if (= c ?p) (org-set-calc-mode 'calc-internal-prec n)
7308 (org-set-calc-mode 'calc-float-format
7309 (list (cdr (assoc c '((?n. float) (?f. fix)
7310 (?s. sci) (?e. eng))))
7312 (setq fmt (replace-match "" t t fmt)))
7313 (when (string-match "[DR]" fmt)
7314 (org-set-calc-mode 'calc-angle-mode
7315 (if (equal (match-string 0 fmt) "D")
7317 (setq fmt (replace-match "" t t fmt)))
7318 (when (string-match "F" fmt)
7319 (org-set-calc-mode 'calc-prefer-frac t)
7320 (setq fmt (replace-match "" t t fmt)))
7321 (when (string-match "S" fmt)
7322 (org-set-calc-mode 'calc-symbolic-mode t)
7323 (setq fmt (replace-match "" t t fmt)))
7324 (unless (string-match "\\S-" fmt)
7326 (if (and (not suppress-const) org-table-formula-use-constants)
7327 (setq formula (org-table-formula-substitute-names formula)))
7328 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7330 (setq fields (org-split-string
7332 (point-at-bol) (point-at-eol)) " *| *"))
7333 (if org-table-formula-numbers-only
7334 (setq fields (mapcar
7335 (lambda (x) (number-to-string (string-to-number x)))
7337 (setq ndown (1- ndown))
7338 (setq form (copy-sequence formula))
7339 (while (string-match "\\$\\([0-9]+\\)?" form)
7340 (setq n (if (match-beginning 1)
7341 (string-to-int (match-string 1 form))
7343 x (nth (1- n) fields))
7344 (unless x (error "Invalid field specifier \"%s\""
7345 (match-string 0 form)))
7346 (if (equal x "") (setq x "0"))
7347 (setq form (replace-match (concat "(" x ")") t t form)))
7348 (setq ev (calc-eval (cons form modes)
7349 (if org-table-formula-numbers-only 'num)))
7351 (when org-table-formula-debug
7352 (with-output-to-temp-buffer "*Help*"
7353 (princ (format "Substitution history of formula
7356 $1-> %s\n" orig formula form))
7358 (princ (format " %s^\nError: %s"
7359 (make-string (car ev) ?\-) (nth 1 ev)))
7360 (princ (format "Result: %s" ev))))
7361 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7362 (unless (and (interactive-p) (not ndown))
7363 (unless (let (inhibit-redisplay)
7364 (y-or-n-p "Debugging Formula. Continue to next? "))
7367 (delete-window (get-buffer-window "*Help*"))
7370 (setq fmt nil ev "#ERROR"))
7371 (org-table-blank-field)
7373 (insert (format fmt (string-to-number ev)))
7375 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7376 (call-interactively 'org-return)
7378 (or suppress-align (org-table-align))))
7380 (defun org-table-recalculate (&optional all noalign)
7381 "Recalculate the current table line by applying all stored formulas."
7383 (or (memq this-command org-recalc-commands)
7384 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7385 (unless (org-at-table-p) (error "Not at a table"))
7386 (org-table-get-specials)
7387 (let* ((eqlist (sort (org-table-get-stored-formulas)
7388 (lambda (a b) (< (car a) (car b)))))
7389 (inhibit-redisplay t)
7390 (line-re org-table-dataline-regexp)
7391 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7392 (thiscol (org-table-current-column))
7393 beg end entry eql (cnt 0))
7394 ;; Insert constants in all formulas
7397 (setcdr x (org-table-formula-substitute-names (cdr x)))
7402 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7403 (goto-char (setq beg (org-table-begin)))
7404 (if (re-search-forward org-table-recalculate-regexp end t)
7405 (setq line-re org-table-recalculate-regexp)
7406 (if (and (re-search-forward org-table-dataline-regexp end t)
7407 (re-search-forward org-table-hline-regexp end t)
7408 (re-search-forward org-table-dataline-regexp end t))
7409 (setq beg (match-beginning 0))
7410 nil))) ;; just leave beg where it is
7411 (setq beg (point-at-bol)
7412 end (move-marker (make-marker) (1+ (point-at-eol)))))
7414 (and all (message "Re-applying formulas to full table..."))
7415 (while (re-search-forward line-re end t)
7416 (unless (string-match "^ *[!$] *$" (org-table-get-field 1))
7417 ;; Unprotected line, recalculate
7418 (and all (message "Re-applying formulas to full table...(line %d)"
7419 (setq cnt (1+ cnt))))
7420 (setq org-last-recalc-line (org-current-line))
7422 (while (setq entry (pop eql))
7423 (goto-line org-last-recalc-line)
7424 (org-table-goto-column (car entry) nil 'force)
7425 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7426 (goto-line thisline)
7427 (org-table-goto-column thiscol)
7428 (or noalign (org-table-align)
7429 (and all (message "Re-applying formulas to %d lines...done" cnt)))))
7431 (defun org-table-formula-substitute-names (f)
7432 "Replace $const with values in stirng F."
7433 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7434 ;; First, check for column names
7435 (while (setq start (string-match org-table-column-name-regexp f start))
7436 (setq start (1+ start))
7437 (setq a (assoc (match-string 1 f) org-table-column-names))
7438 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7439 ;; Expand ranges to vectors
7440 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7441 (setq n1 (string-to-number (match-string 1 f))
7442 n2 (string-to-number (match-string 2 f))
7443 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7444 s (concat "[($" (number-to-string (1- nn1)) ")"))
7445 (loop for i from nn1 upto nn2 do
7446 (setq s (concat s ",($" (int-to-string i) ")")))
7447 (setq s (concat s "]"))
7448 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7449 (setq f (replace-match s t t f)))
7450 ;; Parameters and constants
7452 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7453 (setq start (1+ start))
7454 (if (setq a (save-match-data
7455 (org-table-get-constant (match-string 1 f))))
7456 (setq f (replace-match (concat "(" a ")") t t f))))
7457 (if org-table-formula-debug
7458 (put-text-property 0 (length f) :orig-formula f1 f))
7461 (defun org-table-get-constant (const)
7462 "Find the value for a parameter or constant in a formula.
7463 Parameters get priority."
7464 (or (cdr (assoc const org-table-local-parameters))
7465 (cdr (assoc const org-table-formula-constants))
7466 (and (fboundp 'constants-get) (constants-get const))
7469 ;;; The orgtbl minor mode
7471 ;; Define a minor mode which can be used in other modes in order to
7472 ;; integrate the org-mode table editor.
7474 ;; This is really a hack, because the org-mode table editor uses several
7475 ;; keys which normally belong to the major mode, for example the TAB and
7476 ;; RET keys. Here is how it works: The minor mode defines all the keys
7477 ;; necessary to operate the table editor, but wraps the commands into a
7478 ;; function which tests if the cursor is currently inside a table. If that
7479 ;; is the case, the table editor command is executed. However, when any of
7480 ;; those keys is used outside a table, the function uses `key-binding' to
7481 ;; look up if the key has an associated command in another currently active
7482 ;; keymap (minor modes, major mode, global), and executes that command.
7483 ;; There might be problems if any of the keys used by the table editor is
7484 ;; otherwise used as a prefix key.
7486 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7487 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7488 ;; addresses this by checking explicitly for both bindings.
7490 ;; The optimized version (see variable `orgtbl-optimized') takes over
7491 ;; all keys which are bound to `self-insert-command' in the *global map*.
7492 ;; Some modes bind other commands to simple characters, for example
7493 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7494 ;; active, this binding is ignored inside tables and replaced with a
7495 ;; modified self-insert.
7497 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
7498 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
7499 In the optimized version, the table editor takes over all simple keys that
7500 normally just insert a character. In tables, the characters are inserted
7501 in a way to minimize disturbing the table structure (i.e. in overwrite mode
7502 for empty fields). Outside tables, the correct binding of the keys is
7505 The default for this option is t if the optimized version is also used in
7506 Org-mode. See the variable `org-enable-table-editor' for details. Changing
7507 this variable requires a restart of Emacs to become effective."
7511 (defvar orgtbl-mode nil
7512 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7513 table editor in arbitrary modes.")
7514 (make-variable-buffer-local 'orgtbl-mode)
7516 (defvar orgtbl-mode-map (make-sparse-keymap)
7517 "Keymap for `orgtbl-mode'.")
7520 (defun turn-on-orgtbl ()
7521 "Unconditionally turn on `orgtbl-mode'."
7525 (defun orgtbl-mode (&optional arg)
7526 "The `org-mode' table editor as a minor mode for use in other modes."
7528 (if (eq major-mode 'org-mode)
7529 ;; Exit without error, in case some hook functions calls this
7530 ;; by accident in org-mode.
7531 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7533 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7536 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7537 ;; Make sure we are first in minor-mode-map-alist
7538 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7539 (and c (setq minor-mode-map-alist
7540 (cons c (delq c minor-mode-map-alist)))))
7541 (set (make-local-variable (quote org-table-may-need-update)) t)
7542 (make-local-hook (quote before-change-functions))
7543 (add-hook 'before-change-functions 'org-before-change-function
7545 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
7546 auto-fill-inhibit-regexp)
7547 (set (make-local-variable 'auto-fill-inhibit-regexp)
7548 (if auto-fill-inhibit-regexp
7549 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7551 (easy-menu-add orgtbl-mode-menu)
7552 (run-hooks 'orgtbl-mode-hook))
7553 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7554 (remove-hook 'before-change-functions 'org-before-change-function t)
7555 (easy-menu-remove orgtbl-mode-menu)
7556 (force-mode-line-update 'all))))
7558 ;; Install it as a minor mode.
7559 (put 'orgtbl-mode :included t)
7560 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7561 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7563 (defun orgtbl-make-binding (fun n &rest keys)
7564 "Create a function for binding in the table minor mode.
7565 FUN is the command to call inside a table. N is used to create a unique
7566 command name. KEYS are keys that should be checked in for a command
7567 to execute outside of tables."
7570 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7572 (concat "In tables, run `" (symbol-name fun) "'.\n"
7573 "Outside of tables, run the binding of `"
7574 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7579 (list 'call-interactively (list 'quote fun))
7580 (list 'let '(orgtbl-mode)
7581 (list 'call-interactively
7584 (list 'key-binding k))
7586 '('orgtbl-error))))))))
7588 (defun orgtbl-error ()
7589 "Error when there is no default binding for a table key."
7591 (error "This key is has no function outside tables"))
7593 (defun orgtbl-setup ()
7594 "Setup orgtbl keymaps."
7598 '([(meta shift left)] org-table-delete-column)
7599 '([(meta left)] org-table-move-column-left)
7600 '([(meta right)] org-table-move-column-right)
7601 '([(meta shift right)] org-table-insert-column)
7602 '([(meta shift up)] org-table-kill-row)
7603 '([(meta shift down)] org-table-insert-row)
7604 '([(meta up)] org-table-move-row-up)
7605 '([(meta down)] org-table-move-row-down)
7606 '("\C-c\C-w" org-table-cut-region)
7607 '("\C-c\M-w" org-table-copy-region)
7608 '("\C-c\C-y" org-table-paste-rectangle)
7609 '("\C-c-" org-table-insert-hline)
7610 '([(shift tab)] org-table-previous-field)
7611 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7612 '("\C-m" org-table-next-row)
7613 (list (org-key 'S-return) 'org-table-copy-down)
7614 '([(meta return)] org-table-wrap-region)
7615 '("\C-c\C-q" org-table-wrap-region)
7616 '("\C-c?" org-table-current-column)
7617 '("\C-c " org-table-blank-field)
7618 '("\C-c+" org-table-sum)
7619 '("\C-c|" org-table-toggle-vline-visibility)
7620 '("\C-c=" org-table-eval-formula)
7621 '("\C-c*" org-table-recalculate)
7622 '([(control ?#)] org-table-rotate-recalc-marks)))
7624 (while (setq elt (pop bindings))
7625 (setq nfunc (1+ nfunc))
7628 cmd (orgtbl-make-binding fun nfunc key))
7629 (define-key orgtbl-mode-map key cmd))
7630 ;; Special treatment needed for TAB and RET
7631 (define-key orgtbl-mode-map [(return)]
7632 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
7633 (define-key orgtbl-mode-map "\C-m"
7634 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
7635 (define-key orgtbl-mode-map [(tab)]
7636 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
7637 (define-key orgtbl-mode-map "\C-i"
7638 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
7639 (when orgtbl-optimized
7640 ;; If the user wants maximum table support, we need to hijack
7641 ;; some standard editing functions
7642 (substitute-key-definition 'self-insert-command 'orgtbl-self-insert-command
7643 orgtbl-mode-map global-map)
7644 (substitute-key-definition 'delete-char 'orgtbl-delete-char
7645 orgtbl-mode-map global-map)
7646 (substitute-key-definition 'delete-backward-char 'orgtbl-delete-backward-char
7647 orgtbl-mode-map global-map)
7648 (define-key org-mode-map "|" 'self-insert-command))
7649 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
7651 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
7652 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
7653 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
7654 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
7656 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
7657 ["Copy Field from Above"
7658 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
7661 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
7662 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
7663 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
7664 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
7666 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
7667 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
7668 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
7669 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
7671 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
7673 ["Copy Rectangle" org-copy-special :active (org-at-table-p) :keys "C-c M-w"]
7674 ["Cut Rectangle" org-cut-special :active (org-at-table-p) :keys "C-c C-w"]
7675 ["Paste Rectangle" org-paste-special :active (org-at-table-p) :keys "C-c C-y"]
7676 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p) :keys "C-c C-q"])
7678 ["Eval Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
7679 ["Eval Formula Down " (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
7680 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
7681 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
7682 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
7683 ["Sum Column/Rectangle" org-table-sum
7684 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
7685 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
7687 (setq org-table-formula-debug (not org-table-formula-debug))
7688 :style toggle :selected org-table-formula-debug]
7692 (defun orgtbl-tab ()
7693 "Justification and field motion for `orgtbl-mode'."
7695 (org-table-justify-field-maybe)
7696 (org-table-next-field))
7698 (defun orgtbl-ret ()
7699 "Justification and field motion for `orgtbl-mode'."
7701 (org-table-justify-field-maybe)
7702 (org-table-next-row))
7704 (defun orgtbl-self-insert-command (N)
7705 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
7706 If the cursor is in a table looking at whitespace, the whitespace is
7707 overwritten, and the table is not marked as requiring realignment."
7709 (if (and (org-at-table-p)
7711 (looking-at "[^|\n]* +|"))
7712 (let (org-table-may-need-update)
7713 (goto-char (1- (match-end 0)))
7714 (delete-backward-char 1)
7715 (goto-char (match-beginning 0))
7716 (self-insert-command N))
7717 (setq org-table-may-need-update t)
7719 (call-interactively (key-binding (vector last-input-event))))))
7721 (defun orgtbl-delete-backward-char (N)
7722 "Like `delete-backward-char', insert whitespace at field end in tables.
7723 When deleting backwards, in tables this function will insert whitespace in
7724 front of the next \"|\" separator, to keep the table aligned. The table will
7725 still be marked for re-alignment, because a narrow field may lead to a
7726 reduced column width."
7728 (if (and (org-at-table-p)
7730 (string-match "|" (buffer-substring (point-at-bol) (point)))
7731 (looking-at ".*?|"))
7732 (let ((pos (point)))
7733 (backward-delete-char N)
7734 (skip-chars-forward "^|")
7736 (goto-char (1- pos)))
7737 (delete-backward-char N)))
7739 (defun orgtbl-delete-char (N)
7740 "Like `delete-char', but insert whitespace at field end in tables.
7741 When deleting characters, in tables this function will insert whitespace in
7742 front of the next \"|\" separator, to keep the table aligned. The table
7743 will still be marked for re-alignment, because a narrow field may lead to
7744 a reduced column width."
7746 (if (and (org-at-table-p)
7748 (not (= (char-after) ?|))
7750 (if (looking-at ".*?|")
7751 (let ((pos (point)))
7752 (replace-match (concat
7753 (substring (match-string 0) 1 -1)
7760 (defconst org-level-max 20)
7762 (defun org-export-find-first-heading-line (list)
7763 "Remove all lines from LIST which are before the first headline."
7764 (let ((orig-list list)
7765 (re (concat "^" outline-regexp)))
7767 (not (string-match re (car list))))
7769 (or list orig-list)))
7771 (defun org-skip-comments (lines)
7772 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
7773 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
7774 (re2 "^\\(\\*+\\)[ \t\n\r]")
7776 (while (setq line (pop lines))
7778 ((and (string-match re1 line)
7779 (setq level (- (match-end 1) (match-beginning 1))))
7780 ;; Beginning of a COMMENT subtree. Skip it.
7781 (while (and (setq line (pop lines))
7782 (or (not (string-match re2 line))
7783 (> (- (match-end 1) (match-beginning 1)) level))))
7784 (setq lines (cons line lines)))
7785 ((string-match "^#" line)
7786 ;; an ordinary comment line
7788 (t (setq rtn (cons line rtn)))))
7793 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
7794 "Characters for underlining headings in ASCII export.")
7796 (defconst org-html-entities
7836 ("Aring") ("AA"."Å")
7925 ("varepsilon"."ε")
7938 ("sigmaf") ("varsigma"."ς")
7946 ("thetasym") ("vartheta"."ϑ")
7949 ("bull") ("bullet"."•")
7950 ("hellip") ("dots"."…")
7960 ("larr") ("leftarrow"."←") ("gets"."←")
7961 ("uarr") ("uparrow"."↑")
7962 ("rarr") ("to"."→") ("rightarrow"."→")
7963 ("darr")("downarrow"."↓")
7964 ("harr") ("leftrightarrow"."↔")
7965 ("crarr") ("hookleftarrow"."↵") ; has round hook, not quite CR
7966 ("lArr") ("Leftarrow"."⇐")
7967 ("uArr") ("Uparrow"."⇑")
7968 ("rArr") ("Rightarrow"."⇒")
7969 ("dArr") ("Downarrow"."⇓")
7970 ("hArr") ("Leftrightarrow"."⇔")
7972 ("part") ("partial"."∂")
7973 ("exist") ("exists"."∃")
7974 ("empty") ("emptyset"."∅")
7976 ("isin") ("in"."∈")
7982 ("lowast") ("ast"."∗")
7984 ("prop") ("proptp"."∝")
7985 ("infin") ("infty"."∞")
7986 ("ang") ("angle"."∠")
7987 ("and") ("vee"."∧")
7988 ("or") ("wedge"."∨")
7994 ("cong") ("simeq"."≅")
7995 ("asymp")("approx"."≈")
7996 ("ne") ("neq"."≠")
8000 ("sub") ("subset"."⊂")
8001 ("sup") ("supset"."⊃")
8008 ("sdot") ("cdot"."⋅")
8015 ("loz") ("Diamond"."◊")
8016 ("spades") ("spadesuit"."♠")
8017 ("clubs") ("clubsuit"."♣")
8018 ("hearts") ("diamondsuit"."♥")
8019 ("diams") ("diamondsuit"."♦")
8086 "Entities for TeX->HTML translation.
8087 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
8088 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
8089 In that case, \"\\ent\" will be translated to \"&other;\".
8090 The list contains HTML entities for Latin-1, Greek and other symbols.
8091 It is supplemented by a number of commonly used TeX macros with appropriate
8092 translations. There is currently no way for users to extend this.")
8094 (defvar org-last-level nil) ; dynamically scoped variable
8096 (defun org-export-as-ascii (arg)
8097 "Export the outline as a pretty ASCII file.
8098 If there is an active region, export only the region.
8099 The prefix ARG specifies how many levels of the outline should become
8100 underlined headlines. The default is 3."
8102 (setq-default org-todo-line-regexp org-todo-line-regexp)
8105 (if (org-region-active-p) (region-beginning) (point-min))
8106 (if (org-region-active-p) (region-end) (point-max))))
8107 (lines (org-export-find-first-heading-line
8108 (org-skip-comments (org-split-string region "[\r\n]"))))
8109 (org-startup-with-deadline-check nil)
8112 (case-fold-search nil)
8113 (filename (concat (file-name-sans-extension (buffer-file-name))
8115 (buffer (find-file-noselect filename))
8116 (levels-open (make-vector org-level-max nil))
8117 (date (format-time-string "%Y/%m/%d" (current-time)))
8118 (time (format-time-string "%X" (current-time)))
8119 (author user-full-name)
8120 (title (buffer-name))
8122 (email user-mail-address)
8123 (language org-export-default-language)
8128 (setq org-last-level 1)
8129 (org-init-section-numbers)
8131 (find-file-noselect filename)
8133 ;; Search for the export key lines
8134 (org-parse-key-lines)
8136 (setq lang-words (or (assoc language org-export-language-setup)
8137 (assoc "en" org-export-language-setup)))
8138 (if org-export-ascii-show-new-buffer
8139 (switch-to-buffer-other-window buffer)
8140 (set-buffer buffer))
8143 (if options (org-parse-export-options options))
8144 (setq umax (if arg (prefix-numeric-value arg)
8145 org-export-headline-levels))
8148 (if title (org-insert-centered title ?=))
8150 (if (or author email)
8151 (insert (concat (nth 1 lang-words) ": " (or author "")
8152 (if email (concat " <" email ">") "")
8155 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
8156 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
8160 (if org-export-with-toc
8162 (insert (nth 3 lang-words) "\n"
8163 (make-string (length (nth 3 lang-words)) ?=) "\n")
8164 (mapcar '(lambda (line)
8165 (if (string-match org-todo-line-regexp
8167 ;; This is a headline
8169 (setq level (- (match-end 1) (match-beginning 1))
8170 txt (match-string 3 line)
8172 (or (and (match-beginning 2)
8173 (not (equal (match-string 2 line)
8177 (org-search-todo-below
8178 line lines level))))
8179 (setq txt (org-html-expand-for-ascii txt))
8181 (if org-export-with-section-numbers
8182 (setq txt (concat (org-section-number level)
8187 (make-string (* (1- level) 4) ?\ )
8188 (format (if todo "%s (*)\n" "%s\n") txt))
8189 (setq org-last-level level))
8193 (org-init-section-numbers)
8194 (while (setq line (pop lines))
8195 ;; Remove the quoted HTML tags.
8196 (setq line (org-html-expand-for-ascii line))
8198 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8200 (setq level (- (match-end 1) (match-beginning 1))
8201 txt (match-string 2 line))
8202 (org-ascii-level-start level txt umax))
8203 (t (insert line "\n"))))
8206 (goto-char (point-min))))
8208 (defun org-search-todo-below (line lines level)
8209 "Search the subtree below LINE for any TODO entries."
8210 (let ((rest (cdr (memq line lines)))
8211 (re org-todo-line-regexp)
8214 (while (setq line (pop rest))
8215 (if (string-match re line)
8217 (setq lv (- (match-end 1) (match-beginning 1))
8218 todo (and (match-beginning 2)
8219 (not (equal (match-string 2 line)
8222 (if (<= lv level) (throw 'exit nil))
8223 (if todo (throw 'exit t))))))))
8225 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
8226 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
8227 (defun org-html-expand-for-ascii (line)
8228 "Handle quoted HTML for ASCII export."
8229 (if org-export-html-expand
8230 (while (string-match "@<[^<>\n]*>" line)
8231 ;; We just remove the tags for now.
8232 (setq line (replace-match "" nil nil line))))
8235 (defun org-insert-centered (s &optional underline)
8236 "Insert the string S centered and underline it with character UNDERLINE."
8237 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
8238 (insert (make-string ind ?\ ) s "\n")
8240 (insert (make-string ind ?\ )
8241 (make-string (length s) underline)
8244 (defun org-ascii-level-start (level title umax)
8245 "Insert a new level in ASCII export."
8248 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
8249 (if (or (not (equal (char-before) ?\n))
8250 (not (equal (char-before (1- (point))) ?\n)))
8252 (setq char (nth (- umax level) (reverse org-ascii-underline)))
8253 (if org-export-with-section-numbers
8254 (setq title (concat (org-section-number level) " " title)))
8255 (insert title "\n" (make-string (string-width title) char) "\n"))))
8257 (defun org-export-copy-visible ()
8258 "Copy the visible part of the buffer to another buffer, for printing.
8259 Also removes the first line of the buffer if it specifies a mode,
8260 and all options lines."
8262 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
8264 (buffer (find-file-noselect filename))
8266 (org-make-options-regexp
8267 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
8269 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
8270 (if org-noutline-p "\\(\n\\|$\\)" "")))
8272 (with-current-buffer buffer
8276 (setq s (goto-char (point-min)))
8277 (while (not (= (point) (point-max)))
8278 (goto-char (org-find-invisible))
8279 (append-to-buffer buffer s (point))
8280 (setq s (goto-char (org-find-visible)))))
8281 (switch-to-buffer-other-window buffer)
8283 (goto-char (point-min))
8284 (if (looking-at ".*-\\*- mode:.*\n")
8286 (while (re-search-forward ore nil t)
8288 (goto-char (point-min))))
8290 (defun org-find-visible ()
8291 (if (featurep 'noutline)
8293 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8294 (get-char-property s 'invisible)))
8296 (skip-chars-forward "^\n")
8298 (defun org-find-invisible ()
8299 (if (featurep 'noutline)
8301 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8302 (not (get-char-property s 'invisible))))
8304 (skip-chars-forward "^\r")
8309 (defun org-get-current-options ()
8310 "Return a string with current options as keyword options.
8311 Does include HTML export options as well as TODO and CATEGORY stuff."
8317 #+TEXT: Some descriptive text to be emitted. Several lines OK.
8318 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
8325 (buffer-name) (user-full-name) user-mail-address org-export-default-language
8326 org-export-headline-levels
8327 org-export-with-section-numbers
8329 org-export-preserve-breaks
8330 org-export-html-expand
8331 org-export-with-fixed-width
8332 org-export-with-tables
8333 org-export-with-sub-superscripts
8334 org-export-with-emphasize
8335 org-export-with-TeX-macros
8336 (file-name-nondirectory (buffer-file-name))
8337 (if (equal org-todo-interpretation 'sequence)
8338 (mapconcat 'identity org-todo-keywords " ")
8339 "TODO FEEDBACK VERIFY DONE")
8340 (if (equal org-todo-interpretation 'type)
8341 (mapconcat 'identity org-todo-keywords " ")
8342 "Me Jason Marie DONE")
8343 (cdr (assoc org-startup-folded
8344 '((nil . "nofold")(t . "fold")(content . "content"))))
8345 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
8346 org-archive-location
8349 (defun org-insert-export-options-template ()
8350 "Insert into the buffer a template with information for exporting."
8352 (if (not (bolp)) (newline))
8353 (let ((s (org-get-current-options)))
8354 (and (string-match "#\\+CATEGORY" s)
8355 (setq s (substring s 0 (match-beginning 0))))
8358 (defun org-toggle-fixed-width-section (arg)
8359 "Toggle the fixed-width indicator at the beginning of lines in the region.
8360 If there is no active region, only acts on the current line.
8361 If the first non-white character in the first line of the region is a
8362 vertical bar \"|\", then the command removes the bar from all lines in
8363 the region. If the first character is not a bar, the command adds a
8364 bar to all lines, in the column given by the beginning of the region.
8366 If there is a numerical prefix ARG, create ARG new lines starting with \"|\"."
8369 (regionp (org-region-active-p))
8370 (beg (if regionp (region-beginning) (point)))
8371 (end (if regionp (region-end)))
8372 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
8373 (re "[ \t]*\\(:\\)")
8377 (setq cc (current-column))
8378 (beginning-of-line 1)
8379 (setq off (looking-at re))
8381 (setq nlines (1- nlines))
8382 (beginning-of-line 1)
8385 (move-to-column cc t)
8388 ((and off (looking-at re))
8389 (replace-match "" t t nil 1))
8390 ((not off) (move-to-column cc t) (insert ":")))
8391 (forward-line 1)))))
8393 (defun org-export-as-html-and-open (arg)
8394 "Export the outline as HTML and immediately open it with a browser.
8395 If there is an active region, export only the region.
8396 The prefix ARG specifies how many levels of the outline should become
8397 headlines. The default is 3. Lower levels will become bulleted lists."
8399 (org-export-as-html arg 'hidden)
8400 (org-open-file (buffer-file-name)))
8402 (defun org-export-as-html-batch ()
8403 "Call `org-export-as-html', may be used in batch processing as
8405 --load=$HOME/lib/emacs/org.el
8406 --eval \"(setq org-export-headline-levels 2)\"
8407 --visit=MyFile --funcall org-export-as-html-batch"
8408 (org-export-as-html org-export-headline-levels 'hidden))
8410 (defun org-export-as-html (arg &optional hidden)
8411 "Export the outline as a pretty HTML file.
8412 If there is an active region, export only the region.
8413 The prefix ARG specifies how many levels of the outline should become
8414 headlines. The default is 3. Lower levels will become bulleted lists."
8416 (setq-default org-todo-line-regexp org-todo-line-regexp)
8417 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
8418 (setq-default org-done-string org-done-string)
8419 (let* ((region-p (org-region-active-p))
8422 (if region-p (region-beginning) (point-min))
8423 (if region-p (region-end) (point-max))))
8425 (org-skip-comments (org-split-string region "[\r\n]")))
8426 (lines (org-export-find-first-heading-line all_lines))
8427 (level 0) (line "") (origline "") txt todo
8429 (filename (concat (file-name-sans-extension (buffer-file-name))
8431 (buffer (find-file-noselect filename))
8432 (levels-open (make-vector org-level-max nil))
8433 (date (format-time-string "%Y/%m/%d" (current-time)))
8434 (time (format-time-string "%X" (current-time)))
8435 (author user-full-name)
8436 (title (buffer-name))
8438 (email user-mail-address)
8439 (language org-export-default-language)
8445 table-buffer table-orig-buffer
8447 (message "Exporting...")
8449 (setq org-last-level 1)
8450 (org-init-section-numbers)
8452 ;; Search for the export key lines
8453 (org-parse-key-lines)
8454 (setq lang-words (or (assoc language org-export-language-setup)
8455 (assoc "en" org-export-language-setup)))
8457 ;; Switch to the output buffer
8458 (if (or hidden (not org-export-html-show-new-buffer))
8460 (switch-to-buffer-other-window buffer))
8463 (let ((case-fold-search nil))
8464 (if options (org-parse-export-options options))
8465 (setq umax (if arg (prefix-numeric-value arg)
8466 org-export-headline-levels))
8470 "<html lang=\"%s\"><head>
8472 <meta http-equiv=\"Content-Type\" content=\"text/html\">
8473 <meta name=generator content=\"Org-mode\">
8474 <meta name=generated content=\"%s %s\">
8475 <meta name=author content=\"%s\">
8478 language (org-html-expand title) date time author))
8479 (if title (insert (concat "<H1 align=\"center\">"
8480 (org-html-expand title) "</H1>\n")))
8481 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
8482 (if email (insert (concat "<a href=\"mailto:" email "\"><"
8483 email "></a>\n")))
8484 (if (or author email) (insert "<br>\n"))
8485 (if (and date time) (insert (concat (nth 2 lang-words) ": "
8486 date " " time "<br>\n")))
8487 (if text (insert (concat "<p>\n" (org-html-expand text))))
8488 (if org-export-with-toc
8490 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
8492 (mapcar '(lambda (line)
8493 (if (string-match org-todo-line-regexp line)
8494 ;; This is a headline
8496 (setq level (- (match-end 1) (match-beginning 1))
8497 txt (save-match-data
8499 (match-string 3 line)))
8501 (or (and (match-beginning 2)
8502 (not (equal (match-string 2 line)
8506 (org-search-todo-below
8507 line lines level))))
8508 (if org-export-with-section-numbers
8509 (setq txt (concat (org-section-number level)
8513 (setq head-count (+ head-count 1))
8514 (if (> level org-last-level)
8516 (setq cnt (- level org-last-level))
8517 (while (>= (setq cnt (1- cnt)) 0)
8520 (if (< level org-last-level)
8522 (setq cnt (- org-last-level level))
8523 (while (>= (setq cnt (1- cnt)) 0)
8529 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
8530 "<li><a href=\"#sec-%d\">%s</a></li>\n")
8532 (setq org-last-level level))
8535 (while (> org-last-level 0)
8536 (setq org-last-level (1- org-last-level))
8540 (org-init-section-numbers)
8541 (while (setq line (pop lines) origline line)
8542 ;; Protect the links
8544 (while (string-match org-link-maybe-angles-regexp line start)
8545 (setq start (match-end 0))
8546 (setq line (replace-match
8547 (concat "\000" (match-string 1 line) "\000")
8550 ;; replace "<" and ">" by "<" and ">"
8551 ;; handle @<..> HTML tags (replace "@>..<" by "<..>")
8552 (setq line (org-html-expand line))
8555 (if (and org-export-with-fixed-width
8556 (string-match "^[ \t]*:\\(.*\\)" line))
8558 (let ((l (match-string 1 line)))
8559 (while (string-match " " l)
8560 (setq l (replace-match " " t t l)))
8561 (insert "\n<span style='font-family:Courier'>"
8564 (not (string-match "^[ \t]+\\(:.*\\)"
8568 (while (string-match org-protected-link-regexp line start)
8569 (setq start (- (match-end 0) 2))
8570 (setq type (match-string 1 line))
8572 ((member type '("http" "https" "ftp" "mailto" "news"))
8574 (setq line (replace-match
8575 ; "<a href=\"\\1:\\2\"><\\1:\\2></a>"
8576 "<a href=\"\\1:\\2\">\\1:\\2</a>"
8578 ((string= type "file")
8580 (let* ((filename (match-string 2 line))
8581 (abs-p (file-name-absolute-p filename))
8582 (thefile (if abs-p (expand-file-name filename) filename))
8583 (thefile (save-match-data
8584 (if (string-match ":[0-9]+$" thefile)
8585 (replace-match "" t t thefile)
8589 (string-match (org-image-file-name-regexp) thefile))))
8590 (setq line (replace-match
8591 (if (and org-export-html-inline-images
8593 (concat "<img src=\"" thefile "\"/>")
8594 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
8597 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
8598 (setq line (replace-match
8599 "<i><\\1:\\2></i>" nil nil line)))))
8602 (if (and (string-match org-todo-line-regexp line)
8603 (match-beginning 2))
8604 (if (equal (match-string 2 line) org-done-string)
8605 (setq line (replace-match
8606 "<span style='color:green'>\\2</span>"
8608 (setq line (replace-match "<span style='color:red'>\\2</span>"
8612 (if (string-match org-deadline-line-regexp line)
8614 (if (save-match-data
8615 (string-match "<a href"
8616 (substring line 0 (match-beginning 0))))
8617 nil ; Don't do the replacement - it is inside a link
8618 (setq line (replace-match "<span style='color:red'>\\&</span>"
8622 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8623 ;; This is a headline
8624 (setq level (- (match-end 1) (match-beginning 1))
8625 txt (match-string 2 line))
8626 (if (<= level umax) (setq head-count (+ head-count 1)))
8627 (org-html-level-start level txt umax
8628 (and org-export-with-toc (<= level umax))
8631 ((and org-export-with-tables
8632 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
8633 (if (not table-open)
8635 (setq table-open t table-buffer nil table-orig-buffer nil))
8637 (setq table-buffer (cons line table-buffer)
8638 table-orig-buffer (cons origline table-orig-buffer))
8639 (when (or (not lines)
8640 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
8642 (setq table-open nil
8643 table-buffer (nreverse table-buffer)
8644 table-orig-buffer (nreverse table-orig-buffer))
8645 (insert (org-format-table-html table-buffer table-orig-buffer))))
8648 ;; Lines starting with "-", and empty lines make new paragraph.
8649 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
8650 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
8652 (if org-export-html-with-timestamp
8653 (insert org-export-html-html-helper-timestamp))
8654 (insert "</body>\n</html>\n")
8657 (goto-char (point-min)))))
8659 (defun org-format-table-html (lines olines)
8660 "Find out which HTML converter to use and return the HTML code."
8661 (if (string-match "^[ \t]*|" (car lines))
8662 ;; A normal org table
8663 (org-format-org-table-html lines)
8664 ;; Table made by table.el - test for spanning
8665 (let* ((hlines (delq nil (mapcar
8667 (if (string-match "^[ \t]*\\+-" x) x
8670 (first (car hlines))
8671 (ll (and (string-match "\\S-+" first)
8672 (match-string 0 first)))
8673 (re (concat "^[ \t]*" (regexp-quote ll)))
8674 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
8676 (if (and (not spanning)
8677 (not org-export-prefer-native-exporter-for-tables))
8678 ;; We can use my own converter with HTML conversions
8679 (org-format-table-table-html lines)
8680 ;; Need to use the code generator in table.el, with the original text.
8681 (org-format-table-table-html-using-table-generate-source olines)))))
8683 (defun org-format-org-table-html (lines)
8684 "Format a table into html."
8685 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
8686 (setq lines (nreverse lines))
8687 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
8688 (setq lines (nreverse lines))
8689 (let ((head (and org-export-highlight-first-table-line
8691 (lambda (x) (string-match "^[ \t]*|-" x))
8694 (setq html (concat org-export-html-table-tag "\n"))
8695 (while (setq line (pop lines))
8697 (if (string-match "^[ \t]*|-" line)
8699 (setq head nil) ;; head ends here, first time around
8701 (throw 'next-line t)))
8702 ;; Break the line into fields
8703 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
8707 (mapconcat (lambda (x)
8709 (concat "<th>" x "</th>")
8710 (concat "<td valign=\"top\">" x "</td>")))
8713 (setq html (concat html "</table>\n"))
8716 (defun org-fake-empty-table-line (line)
8717 "Replace everything except \"|\" with spaces."
8718 (let ((i (length line))
8719 (newstr (copy-sequence line)))
8722 (if (not (eq (aref newstr i) ?|))
8723 (aset newstr i ?\ )))
8726 (defun org-format-table-table-html (lines)
8727 "Format a table generated by table.el into html.
8728 This conversion does *not* use `table-generate-source' from table.el.
8729 This has the advantage that Org-mode's HTML conversions can be used.
8730 But it has the disadvantage, that no cell- or row-spanning is allowed."
8731 (let (line field-buffer
8732 (head org-export-highlight-first-table-line)
8734 (setq html (concat org-export-html-table-tag "\n"))
8735 (while (setq line (pop lines))
8736 (setq empty " ")
8738 (if (string-match "^[ \t]*\\+-" line)
8747 (if (equal x "") (setq x empty))
8749 (concat "<th valign=\"top\">" x
8751 (concat "<td valign=\"top\">" x
8756 (setq field-buffer nil)))
8758 (throw 'next-line t)))
8759 ;; Break the line into fields and store the fields
8760 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
8762 (setq field-buffer (mapcar
8764 (concat x "<br>" (pop fields)))
8766 (setq field-buffer fields))))
8767 (setq html (concat html "</table>\n"))
8770 (defun org-format-table-table-html-using-table-generate-source (lines)
8771 "Format a table into html, using `table-generate-source' from table.el.
8772 This has the advantage that cell- or row-spanning is allowed.
8773 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
8775 (with-current-buffer (get-buffer-create " org-tmp1 ")
8777 (insert (mapconcat 'identity lines "\n"))
8778 (goto-char (point-min))
8779 (if (not (re-search-forward "|[^+]" nil t))
8780 (error "Error processing table"))
8781 (table-recognize-table)
8782 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
8783 (table-generate-source 'html " org-tmp2 ")
8784 (set-buffer " org-tmp2 ")
8785 (buffer-substring (point-min) (point-max))))
8787 (defun org-html-expand (string)
8788 "Prepare STRING for HTML export. Applies all active conversions."
8789 ;; First check if there is a link in the line - if yes, apply conversions
8790 ;; only before the start of the link.
8791 (let* ((m (string-match org-link-regexp string))
8792 (s (if m (substring string 0 m) string))
8793 (r (if m (substring string m) "")))
8794 ;; convert < to < and > to >
8795 (while (string-match "<" s)
8796 (setq s (replace-match "<" t t s)))
8797 (while (string-match ">" s)
8798 (setq s (replace-match ">" t t s)))
8799 (if org-export-html-expand
8800 (while (string-match "@<\\([^&]*\\)>" s)
8801 (setq s (replace-match "<\\1>" nil nil s))))
8802 (if org-export-with-emphasize
8803 (setq s (org-export-html-convert-emphasize s)))
8804 (if org-export-with-sub-superscripts
8805 (setq s (org-export-html-convert-sub-super s)))
8806 (if org-export-with-TeX-macros
8807 (let ((start 0) wd ass)
8808 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
8809 (setq wd (match-string 1 s))
8810 (if (setq ass (assoc wd org-html-entities))
8811 (setq s (replace-match (or (cdr ass)
8812 (concat "&" (car ass) ";"))
8814 (setq start (+ start (length wd)))))))
8817 (defun org-create-multibrace-regexp (left right n)
8818 "Create a regular expression which will match a balanced sexp.
8819 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
8820 as single character strings.
8821 The regexp returned will match the entire expression including the
8822 delimiters. It will also define a single group which contains the
8823 match except for the outermost delimiters. The maximum depth of
8824 stacked delimiters is N. Escaping delimiters is not possible."
8825 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
8828 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
8831 re (concat re or next)
8832 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
8833 (concat left "\\(" re "\\)" right)))
8835 (defvar org-match-substring-regexp
8837 "\\([^\\]\\)\\([_^]\\)\\("
8838 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
8840 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
8842 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
8843 "The regular expression matching a sub- or superscript.")
8845 (defun org-export-html-convert-sub-super (string)
8846 "Convert sub- and superscripts in STRING to HTML."
8848 (while (string-match org-match-substring-regexp string)
8849 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
8850 (setq c (or (match-string 8 string)
8851 (match-string 6 string)
8852 (match-string 5 string)))
8853 (setq string (replace-match
8854 (concat (match-string 1 string)
8855 "<" key ">" c "</" key ">")
8857 (while (string-match "\\\\\\([_^]\\)" string)
8858 (setq string (replace-match (match-string 1 string) t t string))))
8861 (defun org-export-html-convert-emphasize (string)
8862 (while (string-match
8863 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
8865 (setq string (replace-match
8866 (concat "<b>" (match-string 3 string) "</b>")
8868 (while (string-match
8869 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
8871 (setq string (replace-match
8872 (concat "<i>" (match-string 3 string) "</i>")
8874 (while (string-match
8875 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
8877 (setq string (replace-match
8878 (concat "<u>" (match-string 3 string) "</u>")
8882 (defun org-parse-key-lines ()
8883 "Find the special key lines with the information for exporters."
8886 (let ((re (org-make-options-regexp
8887 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
8889 (while (re-search-forward re nil t)
8890 (setq key (match-string 1))
8891 (cond ((string-equal key "TITLE")
8892 (setq title (match-string 2)))
8893 ((string-equal key "AUTHOR")
8894 (setq author (match-string 2)))
8895 ((string-equal key "EMAIL")
8896 (setq email (match-string 2)))
8897 ((string-equal key "LANGUAGE")
8898 (setq language (match-string 2)))
8899 ((string-equal key "TEXT")
8900 (setq text (concat text "\n" (match-string 2))))
8901 ((string-equal key "OPTIONS")
8902 (setq options (match-string 2))))))))
8904 (defun org-parse-export-options (s)
8905 "Parse the export options line."
8906 (let ((op '(("H" . org-export-headline-levels)
8907 ("num" . org-export-with-section-numbers)
8908 ("toc" . org-export-with-toc)
8909 ("\\n" . org-export-preserve-breaks)
8910 ("@" . org-export-html-expand)
8911 (":" . org-export-with-fixed-width)
8912 ("|" . org-export-with-tables)
8913 ("^" . org-export-with-sub-superscripts)
8914 ("*" . org-export-with-emphasize)
8915 ("TeX" . org-export-with-TeX-macros)))
8917 (while (setq o (pop op))
8918 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
8920 (set (make-local-variable (cdr o))
8921 (car (read-from-string (match-string 1 s))))))))
8923 (defun org-html-level-start (level title umax with-toc head-count)
8924 "Insert a new level in HTML export."
8925 (let ((l (1+ (max level umax))))
8926 (while (<= l org-level-max)
8927 (if (aref levels-open (1- l))
8929 (org-html-level-close l)
8930 (aset levels-open (1- l) nil)))
8934 (if (aref levels-open (1- level))
8935 (insert "<li>" title "<p>\n")
8936 (aset levels-open (1- level) t)
8937 (insert "<ul><li>" title "<p>\n")))
8938 (if org-export-with-section-numbers
8939 (setq title (concat (org-section-number level) " " title)))
8940 (setq level (+ level 1))
8942 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
8943 level head-count title level))
8944 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
8946 (defun org-html-level-close (&rest args)
8947 "Terminate one level in HTML export."
8951 ;; Variable holding the vector with section numbers
8952 (defvar org-section-numbers (make-vector org-level-max 0))
8954 (defun org-init-section-numbers ()
8955 "Initialize the vector for the section numbers."
8957 (numbers (nreverse (org-split-string "" "\\.")))
8958 (depth (1- (length org-section-numbers)))
8959 (i depth) number-string)
8962 (aset org-section-numbers i 0)
8963 (setq number-string (or (car numbers) "0"))
8964 (if (string-match "\\`[A-Z]\\'" number-string)
8965 (aset org-section-numbers i
8966 (- (string-to-char number-string) ?A -1))
8967 (aset org-section-numbers i (string-to-int number-string)))
8971 (defun org-section-number (&optional level)
8972 "Return a string with the current section number.
8973 When LEVEL is non-nil, increase section numbers on that level."
8974 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
8977 (aset org-section-numbers
8978 level (1+ (aref org-section-numbers level))))
8979 (setq idx (1+ level))
8980 (while (<= idx depth)
8982 (aset org-section-numbers idx 0))
8983 (setq idx (1+ idx))))
8985 (while (<= idx depth)
8986 (setq n (aref org-section-numbers idx))
8987 (setq string (concat string (if (not (string= string "")) "." "")
8989 (setq idx (1+ idx)))
8991 (if (string-match "\\`\\([@0]\\.\\)+" string)
8992 (setq string (replace-match "" nil nil string)))
8993 (if (string-match "\\(\\.0\\)+\\'" string)
8994 (setq string (replace-match "" nil nil string))))
9000 ;; - Bindings in Org-mode map are currently
9001 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
9002 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
9003 ;; e (?) useful from outline-mode
9004 ;; i k @ expendable from outline-mode
9005 ;; 0123456789 ! %^& ()_{} " `' free
9007 (define-key org-mode-map "\C-i" 'org-cycle)
9008 (define-key org-mode-map [(meta tab)] 'org-complete)
9009 (define-key org-mode-map "\M-\C-i" 'org-complete)
9010 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
9011 (define-key org-mode-map [(meta left)] 'org-metaleft)
9012 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
9013 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
9014 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
9015 (define-key org-mode-map [(meta right)] 'org-metaright)
9016 (define-key org-mode-map [(meta up)] 'org-metaup)
9017 (define-key org-mode-map [(meta down)] 'org-metadown)
9018 ;(define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-subtree)
9019 ;(define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-subtree)
9020 ;(define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-subtree)
9021 (define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-special)
9022 (define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-special)
9023 (define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-special)
9024 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
9025 (define-key org-mode-map "\C-c\C-j" 'org-goto)
9026 (define-key org-mode-map "\C-c\C-t" 'org-todo)
9027 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
9028 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
9029 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
9030 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
9031 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
9032 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
9033 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
9034 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
9035 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
9036 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
9037 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
9038 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
9039 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
9040 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
9041 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
9042 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
9043 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
9044 (define-key org-mode-map "\C-c[" 'org-add-file)
9045 (define-key org-mode-map "\C-c]" 'org-remove-file)
9046 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
9047 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
9048 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
9049 (define-key org-mode-map (org-key 'S-left) 'org-timestamp-down-day)
9050 (define-key org-mode-map (org-key 'S-right) 'org-timestamp-up-day)
9051 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
9052 ;; The following line is e.g. necessary for German keyboards under Suse Linux
9053 (unless org-xemacs-p
9054 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
9055 (define-key org-mode-map [(shift tab)] 'org-shifttab)
9056 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
9057 (define-key org-mode-map "\C-m" 'org-return)
9058 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
9059 (define-key org-mode-map [(meta return)] 'org-meta-return)
9060 (define-key org-mode-map "\C-c?" 'org-table-current-column)
9061 (define-key org-mode-map "\C-c " 'org-table-blank-field)
9062 (define-key org-mode-map "\C-c+" 'org-table-sum)
9063 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
9064 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
9065 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
9066 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
9067 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
9068 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
9069 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
9070 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
9071 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
9072 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
9073 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
9074 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
9075 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
9076 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
9077 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
9078 (define-key org-mode-map "\C-c\C-x\C-h" 'org-export-as-html-and-open)
9080 (defsubst org-table-p () (org-at-table-p))
9082 (defun org-self-insert-command (N)
9083 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9084 If the cursor is in a table looking at whitespace, the whitespace is
9085 overwritten, and the table is not marked as requiring realignment."
9087 (if (and (org-table-p)
9089 (looking-at "[^|\n]* +|"))
9090 (let (org-table-may-need-update)
9091 (goto-char (1- (match-end 0)))
9092 (delete-backward-char 1)
9093 (goto-char (match-beginning 0))
9094 (self-insert-command N))
9095 (setq org-table-may-need-update t)
9096 (self-insert-command N)))
9099 ;; The following two functions might still be optimized to trigger
9100 ;; re-alignment less frequently.
9102 (defun org-delete-backward-char (N)
9103 "Like `delete-backward-char', insert whitespace at field end in tables.
9104 When deleting backwards, in tables this function will insert whitespace in
9105 front of the next \"|\" separator, to keep the table aligned. The table will
9106 still be marked for re-alignment, because a narrow field may lead to a
9107 reduced column width."
9109 (if (and (org-table-p)
9111 (string-match "|" (buffer-substring (point-at-bol) (point)))
9112 (looking-at ".*?|"))
9113 (let ((pos (point)))
9114 (backward-delete-char N)
9115 (skip-chars-forward "^|")
9117 (goto-char (1- pos)))
9118 (backward-delete-char N)))
9120 (defun org-delete-char (N)
9121 "Like `delete-char', but insert whitespace at field end in tables.
9122 When deleting characters, in tables this function will insert whitespace in
9123 front of the next \"|\" separator, to keep the table aligned. The table
9124 will still be marked for re-alignment, because a narrow field may lead to
9125 a reduced column width."
9127 (if (and (org-table-p)
9129 (not (= (char-after) ?|))
9131 (if (looking-at ".*?|")
9132 (let ((pos (point)))
9133 (replace-match (concat
9134 (substring (match-string 0) 1 -1)
9139 ;; How to do this: Measure non-white length of current string
9140 ;; If equal to column width, we should realign.
9142 (when (eq org-enable-table-editor 'optimized)
9143 ;; If the user wants maximum table support, we need to hijack
9144 ;; some standard editing functions
9145 (substitute-key-definition 'self-insert-command 'org-self-insert-command
9146 org-mode-map global-map)
9147 (substitute-key-definition 'delete-char 'org-delete-char
9148 org-mode-map global-map)
9149 (substitute-key-definition 'delete-backward-char 'org-delete-backward-char
9150 org-mode-map global-map)
9151 (define-key org-mode-map "|" 'self-insert-command))
9153 (defun org-shiftcursor-error ()
9154 "Throw an error because Shift-Cursor command was applied in wrong context."
9155 (error "This command is only active in tables and on headlines"))
9157 (defun org-shifttab ()
9158 "Call `(org-cycle t)' or `org-table-previous-field'."
9161 ((org-at-table-p) (org-table-previous-field))
9162 (t (org-cycle '(4)))))
9164 (defun org-shiftmetaleft ()
9165 "Call `org-promote-subtree' or `org-table-delete-column'."
9168 ((org-at-table-p) (org-table-delete-column))
9169 ((org-on-heading-p) (org-promote-subtree))
9170 (t (org-shiftcursor-error))))
9172 (defun org-shiftmetaright ()
9173 "Call `org-demote-subtree' or `org-table-insert-column'."
9176 ((org-at-table-p) (org-table-insert-column))
9177 ((org-on-heading-p) (org-demote-subtree))
9178 (t (org-shiftcursor-error))))
9180 (defun org-shiftmetaup (&optional arg)
9181 "Call `org-move-subtree-up' or `org-table-kill-row'."
9184 ((org-at-table-p) (org-table-kill-row))
9185 ((org-on-heading-p) (org-move-subtree-up arg))
9186 (t (org-shiftcursor-error))))
9187 (defun org-shiftmetadown (&optional arg)
9188 "Call `org-move-subtree-down' or `org-table-insert-row'."
9191 ((org-at-table-p) (org-table-insert-row arg))
9192 ((org-on-heading-p) (org-move-subtree-down arg))
9193 (t (org-shiftcursor-error))))
9195 (defun org-metaleft (&optional arg)
9196 "Call `org-do-promote' or `org-table-move-column' to left."
9199 ((org-at-table-p) (org-table-move-column 'left))
9200 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
9201 (t (backward-word (prefix-numeric-value arg)))))
9203 (defun org-metaright (&optional arg)
9204 "Call `org-do-demote' or `org-table-move-column' to right."
9207 ((org-at-table-p) (org-table-move-column nil))
9208 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
9209 (t (forward-word (prefix-numeric-value arg)))))
9211 (defun org-metaup (&optional arg)
9212 "Call `org-move-subtree-up' or `org-table-move-row' up."
9215 ((org-at-table-p) (org-table-move-row 'up))
9216 ((org-on-heading-p) (org-move-subtree-up arg))
9217 (t (org-shiftcursor-error))))
9219 (defun org-metadown (&optional arg)
9220 "Call `org-move-subtree-down' or `org-table-move-row' down."
9223 ((org-at-table-p) (org-table-move-row nil))
9224 ((org-on-heading-p) (org-move-subtree-down arg))
9225 (t (org-shiftcursor-error))))
9227 (defun org-shiftup (&optional arg)
9228 "Call `org-timestamp-up' or `org-priority-up'."
9231 ((org-at-timestamp-p) (org-timestamp-up arg))
9232 (t (org-priority-up))))
9234 (defun org-shiftdown (&optional arg)
9235 "Call `org-timestamp-down' or `org-priority-down'."
9238 ((org-at-timestamp-p) (org-timestamp-down arg))
9239 (t (org-priority-down))))
9241 (defun org-copy-special ()
9242 "Call either `org-table-copy' or `org-copy-subtree'."
9245 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
9247 (defun org-cut-special ()
9248 "Call either `org-table-copy' or `org-cut-subtree'."
9251 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
9253 (defun org-paste-special (arg)
9254 "Call either `org-table-paste-rectangle' or `org-paste-subtree'."
9256 (if (org-at-table-p)
9257 (org-table-paste-rectangle)
9258 (org-paste-subtree arg)))
9260 (defun org-ctrl-c-ctrl-c (&optional arg)
9261 "Call realign table, or recognize a table.el table, or update keywords.
9262 When the cursor is inside a table created by the table.el package,
9263 activate that table. Otherwise, if the cursor is at a normal table
9264 created with org.el, re-align that table. This command works even if
9265 the automatic table editor has been turned off.
9266 If the cursor is in one of the special #+KEYWORD lines, this triggers
9267 scanning the buffer for these lines and updating the information."
9269 (let ((org-enable-table-editor t))
9271 ((org-at-table.el-p)
9273 (beginning-of-line 1)
9274 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
9275 (table-recognize-table))
9277 (org-table-maybe-eval-formula)
9279 (org-table-recalculate t)
9280 (org-table-maybe-recalculate-line))
9282 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
9284 ((equal (match-string 1) "TBLFM")
9285 ;; Recalculate the table before this line
9287 (beginning-of-line 1)
9288 (skip-chars-backward " \r\n\t")
9289 (if (org-at-table-p) (org-table-recalculate t))))
9291 (let ((org-inhibit-startup t)) (org-mode)))))
9292 ((org-region-active-p)
9293 (org-table-convert-region (region-beginning) (region-end) arg))
9294 ((and (region-beginning) (region-end))
9295 (if (y-or-n-p "Convert inactive region to table? ")
9296 (org-table-convert-region (region-beginning) (region-end) arg)
9298 (t (error "No table at point, and no region to make one")))))
9300 (defun org-return ()
9301 "Call `org-table-next-row' or `newline'."
9305 (org-table-justify-field-maybe)
9306 (org-table-next-row))
9309 (defun org-meta-return (&optional arg)
9310 "Call `org-insert-heading' or `org-table-wrap-region'."
9314 (org-table-wrap-region arg))
9315 (t (org-insert-heading))))
9319 ;; Define the Org-mode menus
9320 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
9322 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
9323 ["Next Field" org-cycle (org-at-table-p)]
9324 ["Previous Field" org-shifttab (org-at-table-p)]
9325 ["Next Row" org-return (org-at-table-p)]
9327 ["Blank Field" org-table-blank-field (org-at-table-p)]
9328 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
9331 ["Move Column Left" org-metaleft (org-at-table-p)]
9332 ["Move Column Right" org-metaright (org-at-table-p)]
9333 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
9334 ["Insert Column" org-shiftmetaright (org-at-table-p)])
9336 ["Move Row Up" org-metaup (org-at-table-p)]
9337 ["Move Row Down" org-metadown (org-at-table-p)]
9338 ["Delete Row" org-shiftmetaup (org-at-table-p)]
9339 ["Insert Row" org-shiftmetadown (org-at-table-p)]
9341 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
9343 ["Copy Rectangle" org-copy-special (org-at-table-p)]
9344 ["Cut Rectangle" org-cut-special (org-at-table-p)]
9345 ["Paste Rectangle" org-paste-special (org-at-table-p)]
9346 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
9349 ["Eval Formula" org-table-eval-formula (org-at-table-p)]
9350 ["Eval Formula Down" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9351 ["Recalculate line" org-table-recalculate (org-at-table-p)]
9352 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
9353 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
9354 ["Sum Column/Rectangle" org-table-sum
9355 (or (org-at-table-p) (org-region-active-p))]
9356 ["Which Column?" org-table-current-column (org-at-table-p)])
9358 (setq org-table-formula-debug (not org-table-formula-debug))
9359 :style toggle :selected org-table-formula-debug]
9361 ["Invisible Vlines" org-table-toggle-vline-visibility
9362 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
9364 ["Create" org-table-create (and (not (org-at-table-p))
9365 org-enable-table-editor)]
9366 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
9367 ["Import from File" org-table-import (not (org-at-table-p))]
9368 ["Export to File" org-table-export (org-at-table-p)]
9370 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
9372 (easy-menu-define org-org-menu org-mode-map "Org menu"
9374 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
9375 ["Sparse Tree" org-occur t]
9376 ["Show All" show-all t]
9378 ["New Heading" org-insert-heading t]
9379 ("Navigate Headings"
9380 ["Up" outline-up-heading t]
9381 ["Next" outline-next-visible-heading t]
9382 ["Previous" outline-previous-visible-heading t]
9383 ["Next Same Level" outline-forward-same-level t]
9384 ["Previous Same Level" outline-backward-same-level t]
9386 ["Jump" org-goto t])
9388 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
9389 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
9391 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
9392 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
9393 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
9395 ["Promote Heading" org-metaleft (not (org-at-table-p))]
9396 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
9397 ["Demote Heading" org-metaright (not (org-at-table-p))]
9398 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
9400 ["Archive Subtree" org-archive-subtree t])
9403 ["TODO/DONE/-" org-todo t]
9404 ["Show TODO Tree" org-show-todo-tree t]
9406 ["Set Priority" org-priority t]
9407 ["Priority Up" org-shiftup t]
9408 ["Priority Down" org-shiftdown t])
9409 ("Dates and Scheduling"
9410 ["Timestamp" org-time-stamp t]
9412 ["1 Day Later" org-timestamp-up-day t]
9413 ["1 Day Earlier" org-timestamp-down-day t]
9414 ["1 ... Later" org-shiftup t]
9415 ["1 ... Earlier" org-shiftdown t])
9416 ["Compute Time Range" org-evaluate-time-range t]
9417 ["Schedule Item" org-schedule t]
9418 ["Deadline" org-deadline t]
9420 ["Goto Calendar" org-goto-calendar t]
9421 ["Date from Calendar" org-date-from-calendar t])
9424 ["Show TODO Tree this File" org-show-todo-tree t]
9425 ["Check Deadlines this File" org-check-deadlines t]
9426 ["Timeline Current File" org-timeline t]
9428 ["Agenda" org-agenda t])
9429 ("File List for Agenda")
9432 ["Store Link (Global)" org-store-link t]
9433 ["Insert Link" org-insert-link t]
9434 ["Follow Link" org-open-at-point t])
9437 ["ASCII" org-export-as-ascii t]
9438 ["Extract Visible Text" org-export-copy-visible t]
9439 ["HTML" org-export-as-html t]
9440 ["HTML and Open" org-export-as-html-and-open t]
9441 ; ["OPML" org-export-as-opml nil]
9443 ["Option Template" org-insert-export-options-template t]
9444 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
9447 ["Show Version" org-version t]
9448 ["Info Documentation" org-info t])
9450 ["Browse Org Group" org-customize t]
9452 ["Build Full Customize Menu" org-create-customize-menu
9453 (fboundp 'customize-menu-create)])
9456 (defun org-info (&optional node)
9457 "Read documentation for Org-mode in the info system.
9458 With optional NODE, go directly to that node."
9461 (Info-goto-node (format "(org)%s" (or node ""))))
9463 (defun org-install-agenda-files-menu ()
9465 '("Org") "File List for Agenda"
9468 ["Edit File List" (customize-variable 'org-agenda-files) t]
9469 ["Add Current File to List" org-add-file t]
9470 ["Remove Current File from List" org-remove-file t]
9472 (mapcar 'org-file-menu-entry org-agenda-files))))
9476 (defun org-customize ()
9477 "Call the customize function with org as argument."
9479 (customize-browse 'org))
9481 (defun org-create-customize-menu ()
9482 "Create a full customization menu for Org-mode, insert it into the menu."
9484 (if (fboundp 'customize-menu-create)
9487 '("Org") "Customize"
9488 `(["Browse Org group" org-customize t]
9490 ,(customize-menu-create 'org)
9491 ["Set" Custom-set t]
9492 ["Save" Custom-save t]
9493 ["Reset to Current" Custom-reset-current t]
9494 ["Reset to Saved" Custom-reset-saved t]
9495 ["Reset to Standard Settings" Custom-reset-standard t]))
9496 (message "\"Org\"-menu now contains full customization menu"))
9497 (error "Cannot expand menu (outdated version of cus-edit.el)")))
9499 ;;; Miscellaneous stuff
9501 (defun org-move-line-down (arg)
9502 "Move the current line down. With prefix argument, move it past ARG lines."
9504 (let ((col (current-column))
9506 (beginning-of-line 1) (setq beg (point))
9507 (beginning-of-line 2) (setq end (point))
9508 (beginning-of-line (+ 1 arg))
9509 (setq pos (move-marker (make-marker) (point)))
9510 (insert (delete-and-extract-region beg end))
9512 (move-to-column col)))
9514 (defun org-move-line-up (arg)
9515 "Move the current line up. With prefix argument, move it past ARG lines."
9517 (let ((col (current-column))
9519 (beginning-of-line 1) (setq beg (point))
9520 (beginning-of-line 2) (setq end (point))
9521 (beginning-of-line (- arg))
9522 (setq pos (move-marker (make-marker) (point)))
9523 (insert (delete-and-extract-region beg end))
9525 (move-to-column col)))
9527 ;; Functions needed for Emacs/XEmacs region compatibility
9529 (defun org-region-active-p ()
9530 "Is `transient-mark-mode' on and the region active?
9531 Works on both Emacs and XEmacs."
9532 (if org-ignore-region
9535 (and zmacs-regions (region-active-p))
9536 (and transient-mark-mode mark-active))))
9538 (defun org-add-to-invisibility-spec (arg)
9539 "Add elements to `buffer-invisibility-spec'.
9540 See documentation for `buffer-invisibility-spec' for the kind of elements
9543 ((fboundp 'add-to-invisibility-spec)
9544 (add-to-invisibility-spec arg))
9545 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
9546 (setq buffer-invisibility-spec (list arg)))
9548 (setq buffer-invisibility-spec
9549 (cons arg buffer-invisibility-spec)))))
9551 (defun org-remove-from-invisibility-spec (arg)
9552 "Remove elements from `buffer-invisibility-spec'."
9553 (if (fboundp 'remove-from-invisibility-spec)
9554 (remove-from-invisibility-spec arg)
9555 (if (consp buffer-invisibility-spec)
9556 (setq buffer-invisibility-spec
9557 (delete arg buffer-invisibility-spec)))))
9559 (defun org-in-invisibility-spec-p (arg)
9560 "Is ARG a member of `buffer-invisibility-spec'?."
9561 (if (consp buffer-invisibility-spec)
9562 (member arg buffer-invisibility-spec)
9565 (defun org-image-file-name-regexp ()
9566 "Return regexp matching the file names of images."
9567 (if (fboundp 'image-file-name-regexp)
9568 (image-file-name-regexp)
9569 (let ((image-file-name-extensions
9570 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
9571 "xbm" "xpm" "pbm" "pgm" "ppm")))
9573 (regexp-opt (nconc (mapcar 'upcase
9574 image-file-name-extensions)
9575 image-file-name-extensions)
9579 ;; Functions needed for compatibility with old outline.el
9581 ;; The following functions capture almost the entire compatibility code
9582 ;; between the different versions of outline-mode. The only other place
9583 ;; where this is important are the font-lock-keywords. Search for
9584 ;; `org-noutline-p' to find it.
9586 ;; C-a should go to the beginning of a *visible* line, also in the
9587 ;; new outline.el. I guess this should be patched into Emacs?
9588 (defun org-beginning-of-line ()
9589 "Go to the beginning of the current line. If that is invisible, continue
9590 to a visible line beginning. This makes the function of C-a more intuitive."
9592 (beginning-of-line 1)
9596 (if (org-invisible-p)
9597 (while (and (not (bobp)) (org-invisible-p))
9599 (beginning-of-line 1))
9601 (when org-noutline-p
9602 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
9604 (defun org-invisible-p ()
9605 "Check if point is at a character currently not visible."
9607 ;; Early versions of noutline don't have `outline-invisible-p'.
9608 (if (fboundp 'outline-invisible-p)
9609 (outline-invisible-p)
9610 (get-char-property (point) 'invisible))
9612 (skip-chars-backward "^\r\n")
9613 (equal (char-before) ?\r))))
9615 (defun org-back-to-heading (&optional invisible-ok)
9616 "Move to previous heading line, or beg of this line if it's a heading.
9617 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
9619 (outline-back-to-heading invisible-ok)
9620 (if (looking-at outline-regexp)
9622 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
9626 (progn (goto-char (match-end 1))
9627 (looking-at outline-regexp)))
9628 (error "Before first heading")))))
9630 (defun org-on-heading-p (&optional invisible-ok)
9631 "Return t if point is on a (visible) heading line.
9632 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
9634 (outline-on-heading-p 'invisible-ok)
9636 (skip-chars-backward "^\n\r")
9637 (and (looking-at outline-regexp)
9640 (equal (char-before) ?\n))))))
9642 (defun org-up-heading-all (arg)
9643 "Move to the heading line of which the present line is a subheading.
9644 This function considers both visible and invisible heading lines.
9645 With argument, move up ARG levels."
9647 (if (fboundp 'outline-up-heading-all)
9648 (outline-up-heading-all arg) ; emacs 21 version of outline.el
9649 (outline-up-heading arg t)) ; emacs 22 version of outline.el
9650 (org-back-to-heading t)
9651 (looking-at outline-regexp)
9652 (if (<= (- (match-end 0) (match-beginning 0)) arg)
9653 (error "Cannot move up %d levels" arg)
9655 (concat "[\n\r]" (regexp-quote
9656 (make-string (- (match-end 0) (match-beginning 0) arg)
9661 (defun org-show-hidden-entry ()
9662 "Show an entry where even the heading is hidden."
9664 (if (not org-noutline-p)
9666 (org-back-to-heading t)
9667 (org-flag-heading nil)))
9670 (defun org-check-occur-regexp (regexp)
9671 "If REGEXP starts with \"^\", modify it to check for \\r as well.
9672 Of course, only for the old outline mode."
9675 (if (string-match "^\\^" regexp)
9676 (concat "[\n\r]" (substring regexp 1))
9679 (defun org-flag-heading (flag &optional entry)
9680 "Flag the current heading. FLAG non-nil means make invisible.
9681 When ENTRY is non-nil, show the entire entry."
9683 (org-back-to-heading t)
9684 (if (not org-noutline-p)
9685 ;; Make the current headline visible
9686 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
9687 ;; Check if we should show the entire entry
9691 (save-excursion ;; FIXME: Is this the fix for points in the -|
9692 ;; middle of text? |
9693 (and (outline-next-heading) ;; |
9694 (org-flag-heading nil)))) ; show the next heading _|
9695 (outline-flag-region (max 1 (1- (point)))
9696 (save-excursion (outline-end-of-heading) (point))
9699 (if flag ?\r ?\n))))))
9701 (defun org-show-subtree ()
9702 "Show everything after this heading at deeper levels."
9703 (outline-flag-region
9706 (outline-end-of-subtree) (outline-next-heading) (point))
9707 (if org-noutline-p nil ?\n)))
9709 (defun org-show-entry ()
9710 "Show the body directly following this heading.
9711 Show the heading too, if it is currently invisible."
9714 (org-back-to-heading t)
9715 (outline-flag-region
9718 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
9719 (or (match-beginning 1) (point-max)))
9720 (if org-noutline-p nil ?\n))))
9723 (defun org-make-options-regexp (kwds)
9724 "Make a regular expression for keyword lines."
9726 (if org-noutline-p "^" "[\n\r]")
9728 (mapconcat 'regexp-quote kwds "\\|")
9730 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
9732 ;; Advise the bookmark-jump function to make jump position visible
9733 ;; Wrapped into eval-after-load to avoid loading advice unnecessarily
9734 (eval-after-load "bookmark"
9735 '(defadvice bookmark-jump (after org-make-visible activate)
9736 "Make the position visible."
9737 (and (eq major-mode 'org-mode)
9739 (org-show-hierarchy-above))))
9745 (run-hooks 'org-load-hook)
9747 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
9748 ;;; org.el ends here