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 forth 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 details 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 variable requires a re-launch of Emacs to 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 makes the structure of the table stay intact 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 time grids."
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 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 daily 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 diary inclusion 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 time-grid 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. It 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
4171 listed in the diary. The function accepts arguments specifying what
4172 items should be listed. The following arguments are allowed:
4174 :timestamp List the headlines of items containing a date stamp or
4175 date range matching the selected date. Deadlines will
4176 also be listed, on the expiration day.
4178 :deadline List any deadlines past due, or due within
4179 `org-deadline-warning-days'. The listing occurs only
4180 in the diary for *today*, not at any other date. If
4181 an entry is marked DONE, it is no longer listed.
4183 :scheduled List all items which are scheduled for the given date.
4184 The diary for *today* also contains items which were
4185 scheduled earlier and are not yet marked DONE.
4187 :todo List all TODO items from the org-file. This may be a
4188 long list - so this is not turned on by default.
4189 Like deadlines, these entries only show up in the
4190 diary for *today*, not at any other date.
4192 The call in the diary file should look like this:
4194 &%%(org-diary) ~/path/to/some/orgfile.org
4196 Use a separate line for each org file to check. Or, if you omit the file name,
4197 all files listed in `org-agenda-files' will be checked automatically:
4201 If you don't give any arguments (as in the example above), the default
4202 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4205 &%%(org-diary :deadline :timestamp :scheduled)
4207 The function expects the lisp variables `entry' and `date' to be provided
4208 by the caller, because this is how the calendar works. Don't use this
4209 function from a program - use `org-agenda-get-day-entries' instead."
4210 (org-agenda-maybe-reset-markers)
4211 (org-compile-prefix-format org-agenda-prefix-format)
4212 (setq args (or args '(:deadline :scheduled :timestamp)))
4213 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4217 ;; If this is called during org-agenda, don't return any entries to
4218 ;; the calendar. Org Agenda will list these entries itself.
4219 (if org-disable-diary (setq files nil))
4220 (while (setq file (pop files))
4221 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4222 (setq results (append results rtn)))
4223 (concat (org-finalize-agenda-entries results) "\n")))
4225 (defun org-agenda-get-day-entries (file date &rest args)
4226 "Does the work for `org-diary' and `org-agenda'.
4227 FILE is the path to a file to be checked for entries. DATE is date like
4228 the one returned by `calendar-current-date'. ARGS are symbols indicating
4229 which kind of entries should be extracted. For details about these, see
4230 the documentation of `org-diary'."
4231 (setq args (or args '(:deadline :scheduled :timestamp)))
4232 (let* ((org-startup-with-deadline-check nil)
4233 (org-startup-folded nil)
4234 (buffer (if (file-exists-p file)
4235 (org-get-agenda-file-buffer file)
4236 (error "No such file %s" file)))
4239 ;; If file does not exist, make sure an error message ends up in diary
4240 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4241 (with-current-buffer buffer
4242 (unless (eq major-mode 'org-mode)
4243 (error "Agenda file %s is not in `org-mode'" file))
4244 (let ((case-fold-search nil))
4247 (if org-respect-restriction
4248 (if (org-region-active-p)
4249 ;; Respect a region to restrict search
4250 (narrow-to-region (region-beginning) (region-end)))
4251 ;; If we work for the calendar or many files,
4252 ;; get rid of any restriction
4254 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4255 (while (setq arg (pop args))
4257 ((and (eq arg :todo)
4258 (equal date (calendar-current-date)))
4259 (setq rtn (org-agenda-get-todos))
4260 (setq results (append results rtn)))
4261 ((eq arg :timestamp)
4262 (setq rtn (org-agenda-get-blocks))
4263 (setq results (append results rtn))
4264 (setq rtn (org-agenda-get-timestamps))
4265 (setq results (append results rtn)))
4266 ((eq arg :scheduled)
4267 (setq rtn (org-agenda-get-scheduled))
4268 (setq results (append results rtn)))
4269 ((and (eq arg :deadline)
4270 (equal date (calendar-current-date)))
4271 (setq rtn (org-agenda-get-deadlines))
4272 (setq results (append results rtn))))))))
4275 (defun org-entry-is-done-p ()
4276 "Is the current entry marked DONE?"
4278 (and (re-search-backward "[\r\n]\\*" nil t)
4279 (looking-at org-nl-done-regexp))))
4281 (defun org-at-date-range-p ()
4282 "Is the cursor inside a date range?"
4286 (let ((pos (point)))
4287 (skip-chars-backward "^<\r\n")
4288 (skip-chars-backward "<")
4289 (and (looking-at org-tr-regexp)
4290 (>= (match-end 0) pos)
4292 (skip-chars-backward "^<\r\n")
4293 (skip-chars-backward "<")
4294 (and (looking-at org-tr-regexp)
4295 (>= (match-end 0) pos)
4299 (defun org-agenda-get-todos ()
4300 "Return the TODO information for agenda display."
4301 (let* ((props (list 'face nil
4302 'done-face 'org-done
4303 'mouse-face 'highlight
4304 'keymap org-agenda-keymap
4306 (format "mouse-2 or RET jump to org file %s"
4307 (abbreviate-file-name (buffer-file-name)))))
4308 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
4312 (goto-char (point-min))
4313 (while (re-search-forward regexp nil t)
4314 (goto-char (match-beginning 1))
4315 (setq marker (org-agenda-new-marker (point-at-bol))
4316 txt (org-format-agenda-item "" (match-string 1))
4318 (+ (org-get-priority txt)
4319 (if org-todo-kwd-priority-p
4320 (- org-todo-kwd-max-priority -2
4322 (member (match-string 2) org-todo-keywords)))
4324 (add-text-properties
4325 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
4330 (goto-char (match-end 1)))
4333 (defconst org-agenda-no-heading-message
4334 "No heading for this item in buffer or region.")
4336 (defun org-agenda-get-timestamps ()
4337 "Return the date stamp information for agenda display."
4338 (let* ((props (list 'face nil
4339 'mouse-face 'highlight
4340 'keymap org-agenda-keymap
4342 (format "mouse-2 or RET jump to org file %s"
4343 (abbreviate-file-name (buffer-file-name)))))
4344 (regexp (regexp-quote
4347 (car org-time-stamp-formats)
4348 (apply 'encode-time ; DATE bound by calendar
4349 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
4351 marker hdmarker deadlinep scheduledp donep tmp priority
4353 (goto-char (point-min))
4354 (while (re-search-forward regexp nil t)
4355 (if (not (save-match-data (org-at-date-range-p)))
4357 (setq marker (org-agenda-new-marker (match-beginning 0))
4358 tmp (buffer-substring (max (point-min)
4359 (- (match-beginning 0)
4360 org-ds-keyword-length))
4361 (match-beginning 0))
4362 timestr (buffer-substring (match-beginning 0) (point-at-eol))
4363 deadlinep (string-match org-deadline-regexp tmp)
4364 scheduledp (string-match org-scheduled-regexp tmp)
4365 donep (org-entry-is-done-p))
4366 (if (string-match ">" timestr)
4367 ;; substring should only run to end of time stamp
4368 (setq timestr (substring timestr 0 (match-end 0))))
4370 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4372 (goto-char (match-end 1))
4373 (setq hdmarker (org-agenda-new-marker))
4374 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4375 (setq txt (org-format-agenda-item
4377 (if deadlinep "Deadline: " "")
4378 (if scheduledp "Scheduled: " ""))
4379 (match-string 1) nil timestr)))
4380 (setq txt org-agenda-no-heading-message))
4381 (setq priority (org-get-priority txt))
4382 (add-text-properties
4383 0 (length txt) (append (list 'org-marker marker
4384 'org-hd-marker hdmarker) props)
4387 (add-text-properties
4390 (if donep 'org-done 'org-warning)
4391 'undone-face 'org-warning
4392 'done-face 'org-done
4393 'priority (+ 100 priority))
4396 (add-text-properties
4398 (list 'face 'org-scheduled-today
4399 'undone-face 'org-scheduled-today
4400 'done-face 'org-done
4401 priority (+ 99 priority))
4403 (add-text-properties
4405 (list 'priority priority) txt)))
4407 (outline-next-heading))))
4410 (defun org-agenda-get-deadlines ()
4411 "Return the deadline information for agenda display."
4412 (let* ((wdays org-deadline-warning-days)
4413 (props (list 'mouse-face 'highlight
4414 'keymap org-agenda-keymap
4416 (format "mouse-2 or RET jump to org file %s"
4417 (abbreviate-file-name (buffer-file-name)))))
4418 (regexp org-deadline-time-regexp)
4419 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4420 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4423 (goto-char (point-min))
4424 (while (re-search-forward regexp nil t)
4425 (setq pos (1- (match-beginning 1))
4427 (org-time-string-to-time (match-string 1)))
4429 ;; When to show a deadline in the calendar:
4430 ;; If the expiration is within wdays warning time.
4431 ;; Past-due deadlines are only shown on the current date
4432 (if (and (< diff wdays) todayp (not (= diff 0)))
4434 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4436 (goto-char (match-end 0))
4437 (setq pos1 (match-end 1))
4438 (setq head (buffer-substring-no-properties
4440 (progn (skip-chars-forward "^\r\n")
4442 (if (string-match org-looking-at-done-regexp head)
4444 (setq txt (org-format-agenda-item
4445 (format "In %3d d.: " diff) head))))
4446 (setq txt org-agenda-no-heading-message))
4448 (add-text-properties
4451 (list 'org-marker (org-agenda-new-marker pos)
4452 'org-hd-marker (org-agenda-new-marker pos1)
4453 'priority (+ (- 10 diff) (org-get-priority txt))
4454 'face (cond ((<= diff 0) 'org-warning)
4455 ((<= diff 5) 'org-scheduled-previously)
4458 ((<= diff 0) 'org-warning)
4459 ((<= diff 5) 'org-scheduled-previously)
4461 'done-face 'org-done)
4467 (defun org-agenda-get-scheduled ()
4468 "Return the scheduled information for agenda display."
4469 (let* ((props (list 'face 'org-scheduled-previously
4470 'undone-face 'org-scheduled-previously
4471 'done-face 'org-done
4472 'mouse-face 'highlight
4473 'keymap org-agenda-keymap
4475 (format "mouse-2 or RET jump to org file %s"
4476 (abbreviate-file-name (buffer-file-name)))))
4477 (regexp org-scheduled-time-regexp)
4478 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4479 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4482 (goto-char (point-min))
4483 (while (re-search-forward regexp nil t)
4484 (setq pos (1- (match-beginning 1))
4486 (org-time-string-to-time (match-string 1)))
4488 ;; When to show a scheduled item in the calendar:
4489 ;; If it is on or past the date.
4490 (if (and (< diff 0) todayp)
4492 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4494 (goto-char (match-end 0))
4495 (setq pos1 (match-end 1))
4496 (setq head (buffer-substring-no-properties
4498 (progn (skip-chars-forward "^\r\n") (point))))
4499 (if (string-match org-looking-at-done-regexp head)
4501 (setq txt (org-format-agenda-item
4502 (format "Sched.%2dx: " (- 1 diff)) head))))
4503 (setq txt org-agenda-no-heading-message))
4505 (add-text-properties
4507 (append (list 'org-marker (org-agenda-new-marker pos)
4508 'org-hd-marker (org-agenda-new-marker pos1)
4509 'priority (+ (- 5 diff) (org-get-priority txt)))
4514 (defun org-agenda-get-blocks ()
4515 "Return the date-range information for agenda display."
4516 (let* ((props (list 'face nil
4517 'mouse-face 'highlight
4518 'keymap org-agenda-keymap
4520 (format "mouse-2 or RET jump to org file %s"
4521 (abbreviate-file-name (buffer-file-name)))))
4522 (regexp org-tr-regexp)
4523 (d0 (calendar-absolute-from-gregorian date))
4524 marker hdmarker ee txt d1 d2 s1 s2 timestr)
4525 (goto-char (point-min))
4526 (while (re-search-forward regexp nil t)
4527 (setq timestr (match-string 0)
4530 d1 (time-to-days (org-time-string-to-time s1))
4531 d2 (time-to-days (org-time-string-to-time s2)))
4532 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4533 ;; Only allow days between the limits, because the normal
4534 ;; date stamps will catch the limits.
4536 (setq marker (org-agenda-new-marker (point)))
4537 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4539 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4540 (goto-char (match-end 1))
4541 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4542 (setq txt (org-format-agenda-item
4543 (format (if (= d1 d2) "" "(%d/%d): ")
4544 (1+ (- d0 d1)) (1+ (- d2 d1)))
4545 (match-string 1) nil (if (= d0 d1) timestr))))
4546 (setq txt org-agenda-no-heading-message))
4547 (add-text-properties
4548 0 (length txt) (append (list 'org-marker marker
4549 'org-hd-marker hdmarker
4550 'priority (org-get-priority txt))
4554 (outline-next-heading))
4555 ;; Sort the entries by expiration date.
4560 (defconst org-plain-time-of-day-regexp
4563 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4566 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4568 "Regular expression to match a plain time or time range.
4569 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4570 groups carry important information:
4572 1 the first time, range or not
4573 8 the second time, if it is a range.")
4575 (defconst org-stamp-time-of-day-regexp
4577 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
4578 "\\([012][0-9]:[0-5][0-9]\\)>"
4580 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4581 "Regular expression to match a timestamp time or time range.
4582 After a match, the following groups carry important information:
4584 1 date plus weekday, for backreferencing to make sure both times on same day
4585 2 the first time, range or not
4586 4 the second time, if it is a range.")
4588 (defvar org-prefix-has-time nil
4589 "A flag, set by `org-compile-prefix-format'.
4590 The flag is set if the currently compiled format contains a `%t'.")
4592 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
4593 "Format TXT to be inserted into the agenda buffer.
4594 In particular, it adds the prefix and corresponding text properties. EXTRA
4595 must be a string and replaces the `%s' specifier in the prefix format.
4596 CATEGORY (string, symbol or nil) may be used to overule the default
4597 category taken from local variable or file name. It will replace the `%c'
4598 specifier in the format. DOTIME, when non-nil, indicates that a
4599 time-of-day should be extracted from TXT for sorting of this entry, and for
4600 the `%t' specifier in the format. When DOTIME is a string, this string is
4601 searched for a time before TXT is. NOPREFIX is a flag and indicates that
4602 only the correctly processes TXT should be returned - this is used by
4603 `org-agenda-change-all-lines'."
4605 ;; Diary entries sometimes have extra whitespace at the beginning
4606 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
4607 (let* ((category (or category
4609 (if (buffer-file-name)
4610 (file-name-sans-extension
4611 (file-name-nondirectory (buffer-file-name)))
4613 time ;; needed for the eval of the prefix format
4614 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
4615 (time-of-day (and dotime (org-get-time-of-day ts)))
4616 stamp plain s0 s1 s2 rtn)
4617 (when (and dotime time-of-day org-prefix-has-time)
4618 ;; Extract starting and ending time and move them to prefix
4619 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
4620 (setq plain (string-match org-plain-time-of-day-regexp ts)))
4621 (setq s0 (match-string 0 ts)
4622 s1 (match-string (if plain 1 2) ts)
4623 s2 (match-string (if plain 8 4) ts))
4625 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
4626 ;; them, we might want to remove them there to avoid duplication.
4627 ;; The user can turn this off with a variable.
4628 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
4629 (string-match (concat (regexp-quote s0) " *") txt)
4630 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
4631 (= (match-beginning 0) 0)
4633 (setq txt (replace-match "" nil nil txt))))
4634 ;; Normalize the time(s) to 24 hour
4635 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
4636 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
4638 ;; Create the final string
4641 ;; Prepare the variables needed in the eval of the compiled format
4642 (setq time (cond (s2 (concat s1 "-" s2))
4643 (s1 (concat s1 "......"))
4646 category (if (symbolp category) (symbol-name category) category))
4647 ;; Evaluate the compiled format
4648 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
4650 ;; And finally add the text properties
4651 (add-text-properties
4652 0 (length rtn) (list 'category (downcase category)
4653 'prefix-length (- (length rtn) (length txt))
4654 'time-of-day time-of-day
4659 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
4661 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
4662 ((and todayp (member 'today (car org-agenda-time-grid))))
4663 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
4664 ((member 'weekly (car org-agenda-time-grid)))
4665 (t (throw 'exit list)))
4666 (let* ((have (delq nil (mapcar
4667 (lambda (x) (get-text-property 1 'time-of-day x))
4669 (string (nth 1 org-agenda-time-grid))
4670 (gridtimes (nth 2 org-agenda-time-grid))
4671 (req (car org-agenda-time-grid))
4672 (remove (member 'remove-match req))
4674 (if (and (member 'require-timed req) (not have))
4675 ;; don't show empty grid
4677 (while (setq time (pop gridtimes))
4678 (unless (and remove (member time have))
4679 (setq time (int-to-string time))
4680 (push (org-format-agenda-item
4681 nil string "" ;; FIXME: put a category?
4682 (concat (substring time 0 -2) ":" (substring time -2)))
4685 1 (length (car new)) 'face 'org-time-grid (car new))))
4686 (if (member 'time-up org-agenda-sorting-strategy)
4688 (append list new)))))
4690 (defun org-compile-prefix-format (format)
4691 "Compile the prefix format into a Lisp form that can be evaluated.
4692 The resulting form is returned and stored in the variable
4693 `org-prefix-format-compiled'."
4694 (setq org-prefix-has-time nil)
4695 (let ((start 0) varform vars var (s format) c f opt)
4696 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4698 (setq var (cdr (assoc (match-string 4 s)
4699 '(("c" . category) ("t" . time) ("s" . extra))))
4700 c (or (match-string 3 s) "")
4701 opt (match-beginning 1)
4702 start (1+ (match-beginning 0)))
4703 (if (equal var 'time) (setq org-prefix-has-time t))
4704 (setq f (concat "%" (match-string 2 s) "s"))
4707 `(if (equal "" ,var)
4709 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
4710 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
4711 (setq s (replace-match "%s" t nil s))
4712 (push varform vars))
4713 (setq vars (nreverse vars))
4714 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4716 (defun org-get-time-of-day (s &optional string)
4717 "Check string S for a time of day.
4718 If found, return it as a military time number between 0 and 2400.
4719 If not found, return nil.
4720 The optional STRING argument forces conversion into a 5 character wide string
4726 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
4728 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
4729 (let* ((t0 (+ (* 100
4730 (+ (string-to-number (match-string 1 s))
4731 (if (and (match-beginning 4)
4732 (equal (downcase (match-string 4 s)) "pm"))
4734 (if (match-beginning 3)
4735 (string-to-number (match-string 3 s))
4737 (t1 (concat " " (int-to-string t0))))
4738 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
4740 (defun org-finalize-agenda-entries (list)
4741 "Sort and concatenate the agenda items."
4742 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4744 (defsubst org-cmp-priority (a b)
4745 "Compare the priorities of strings A and B."
4746 (let ((pa (or (get-text-property 1 'priority a) 0))
4747 (pb (or (get-text-property 1 'priority b) 0)))
4748 (cond ((> pa pb) +1)
4752 (defsubst org-cmp-category (a b)
4753 "Compare the string values of categories of strings A and B."
4754 (let ((ca (or (get-text-property 1 'category a) ""))
4755 (cb (or (get-text-property 1 'category b) "")))
4756 (cond ((string-lessp ca cb) -1)
4757 ((string-lessp cb ca) +1)
4760 (defsubst org-cmp-time (a b)
4761 "Compare the time-of-day values of strings A and B."
4762 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4763 (ta (or (get-text-property 1 'time-of-day a) def))
4764 (tb (or (get-text-property 1 'time-of-day b) def)))
4765 (cond ((< ta tb) -1)
4769 (defun org-entries-lessp (a b)
4770 "Predicate for sorting agenda entries."
4771 ;; The following variables will be used when the form is evaluated.
4772 (let* ((time-up (org-cmp-time a b))
4773 (time-down (if time-up (- time-up) nil))
4774 (priority-up (org-cmp-priority a b))
4775 (priority-down (if priority-up (- priority-up) nil))
4776 (category-up (org-cmp-category a b))
4777 (category-down (if category-up (- category-up) nil))
4778 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4780 (eval (cons 'or org-agenda-sorting-strategy))
4781 '((-1 . t) (1 . nil) (nil . nil))))))
4783 (defun org-agenda-show-priority ()
4784 "Show the priority of the current item.
4785 This priority is composed of the main priority given with the [#A] cookies,
4786 and by additional input from the age of a schedules or deadline entry."
4788 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4789 (message "Priority is %d" (if pri pri -1000))))
4791 (defun org-agenda-goto (&optional highlight)
4792 "Go to the Org-mode file which contains the item at point."
4794 (let* ((marker (or (get-text-property (point) 'org-marker)
4795 (org-agenda-error)))
4796 (buffer (marker-buffer marker))
4797 (pos (marker-position marker)))
4798 (switch-to-buffer-other-window buffer)
4801 (when (eq major-mode 'org-mode)
4802 (org-show-hidden-entry)
4804 (and (outline-next-heading)
4805 (org-flag-heading nil)))) ; show the next heading
4806 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4808 (defun org-agenda-switch-to ()
4809 "Go to the Org-mode file which contains the item at point."
4811 (let* ((marker (or (get-text-property (point) 'org-marker)
4812 (org-agenda-error)))
4813 (buffer (marker-buffer marker))
4814 (pos (marker-position marker)))
4815 (switch-to-buffer buffer)
4816 (delete-other-windows)
4819 (when (eq major-mode 'org-mode)
4820 (org-show-hidden-entry)
4822 (and (outline-next-heading)
4823 (org-flag-heading nil)))))) ; show the next heading
4825 (defun org-agenda-goto-mouse (ev)
4826 "Go to the Org-mode file which contains the item at the mouse click."
4828 (mouse-set-point ev)
4831 (defun org-agenda-show ()
4832 "Display the Org-mode file which contains the item at point."
4834 (let ((win (selected-window)))
4836 (select-window win)))
4838 (defun org-agenda-recenter (arg)
4839 "Display the Org-mode file which contains the item at point and recenter."
4841 (let ((win (selected-window)))
4844 (select-window win)))
4846 (defun org-agenda-show-mouse (ev)
4847 "Display the Org-mode file which contains the item at the mouse click."
4849 (mouse-set-point ev)
4852 (defun org-agenda-check-no-diary ()
4853 "Check if the entry is a diary link and abort if yes."
4854 (if (get-text-property (point) 'org-agenda-diary-link)
4855 (org-agenda-error)))
4857 (defun org-agenda-error ()
4858 (error "Command not allowed in this line"))
4860 (defvar org-last-heading-marker (make-marker)
4861 "Marker pointing to the headline that last changed its TODO state
4862 by a remote command from the agenda.")
4864 (defun org-agenda-todo ()
4865 "Cycle TODO state of line at point, also in Org-mode file.
4866 This changes the line at point, all other lines in the agenda referring to
4867 the same tree node, and the headline of the tree node in the Org-mode file."
4869 (org-agenda-check-no-diary)
4870 (let* ((col (current-column))
4871 (marker (or (get-text-property (point) 'org-marker)
4872 (org-agenda-error)))
4873 (buffer (marker-buffer marker))
4874 (pos (marker-position marker))
4875 (hdmarker (get-text-property (point) 'org-hd-marker))
4876 (buffer-read-only nil)
4878 (with-current-buffer buffer
4881 (org-show-hidden-entry)
4883 (and (outline-next-heading)
4884 (org-flag-heading nil))) ; show the next heading
4887 (setq newhead (org-get-heading))
4889 (org-back-to-heading)
4890 (move-marker org-last-heading-marker (point))))
4891 (beginning-of-line 1)
4893 (org-agenda-change-all-lines newhead hdmarker 'fixface))
4894 (move-to-column col)))
4896 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
4897 "Change all lines in the agenda buffer which match HDMARKER.
4898 The new content of the line will be NEWHEAD (as modified by
4899 `org-format-agenda-item'). HDMARKER is checked with
4900 `equal' against all `org-hd-marker' text properties in the file.
4901 If FIXFACE is non-nil, the face of each item is modified acording to
4902 the new TODO state."
4903 (let* (props m pl undone-face done-face finish new dotime)
4904 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
4906 (goto-char (point-max))
4907 (beginning-of-line 1)
4909 (setq finish (bobp))
4910 (when (and (setq m (get-text-property (point) 'org-hd-marker))
4912 (setq props (text-properties-at (point))
4913 dotime (get-text-property (point) 'dotime)
4914 new (org-format-agenda-item "x" newhead "x" dotime 'noprefix)
4915 pl (get-text-property (point) 'prefix-length)
4916 undone-face (get-text-property (point) 'undone-face)
4917 done-face (get-text-property (point) 'done-face))
4919 (if (looking-at ".*")
4921 (replace-match new t t)
4922 (beginning-of-line 1)
4923 (add-text-properties (point-at-bol) (point-at-eol) props)
4925 (add-text-properties
4926 (point-at-bol) (point-at-eol)
4928 (if org-last-todo-state-is-todo
4929 undone-face done-face))))
4930 (beginning-of-line 1))
4931 (error "Line update did not work")))
4932 (beginning-of-line 0)))))
4934 (defun org-agenda-priority-up ()
4935 "Increase the priority of line at point, also in Org-mode file."
4937 (org-agenda-priority 'up))
4939 (defun org-agenda-priority-down ()
4940 "Decrease the priority of line at point, also in Org-mode file."
4942 (org-agenda-priority 'down))
4944 (defun org-agenda-priority (&optional force-direction)
4945 "Set the priority of line at point, also in Org-mode file.
4946 This changes the line at point, all other lines in the agenda referring to
4947 the same tree node, and the headline of the tree node in the Org-mode file."
4949 (org-agenda-check-no-diary)
4950 (let* ((marker (or (get-text-property (point) 'org-marker)
4951 (org-agenda-error)))
4952 (buffer (marker-buffer marker))
4953 (pos (marker-position marker))
4954 (hdmarker (get-text-property (point) 'org-hd-marker))
4955 (buffer-read-only nil)
4957 (with-current-buffer buffer
4960 (org-show-hidden-entry)
4962 (and (outline-next-heading)
4963 (org-flag-heading nil))) ; show the next heading
4964 (funcall 'org-priority force-direction)
4966 (setq newhead (org-get-heading)))
4967 (org-agenda-change-all-lines newhead hdmarker)
4968 (beginning-of-line 1)))
4970 (defun org-agenda-date-later (arg &optional what)
4971 "Change the date of this item to one day later."
4973 (org-agenda-check-no-diary)
4974 (let* ((marker (or (get-text-property (point) 'org-marker)
4975 (org-agenda-error)))
4976 (buffer (marker-buffer marker))
4977 (pos (marker-position marker)))
4978 (with-current-buffer buffer
4981 (if (not (org-at-timestamp-p))
4982 (error "Cannot find time stamp"))
4983 (org-timestamp-change arg (or what 'day))
4984 (message "Time stamp changed to %s" org-last-changed-timestamp))))
4986 (defun org-agenda-date-earlier (arg &optional what)
4987 "Change the date of this item to one day earlier."
4989 (org-agenda-date-later (- arg) what))
4991 (defun org-agenda-date-prompt (arg)
4992 "Change the date of this item. Date is prompted for, with default today.
4993 The prefix ARG is passed to the `org-time-stamp' command and can therefore
4994 be used to request time specification in the time stamp."
4996 (org-agenda-check-no-diary)
4997 (let* ((marker (or (get-text-property (point) 'org-marker)
4998 (org-agenda-error)))
4999 (buffer (marker-buffer marker))
5000 (pos (marker-position marker)))
5001 (with-current-buffer buffer
5004 (if (not (org-at-timestamp-p))
5005 (error "Cannot find time stamp"))
5006 (org-time-stamp arg)
5007 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5009 (defun org-get-heading ()
5010 "Return the heading of the current entry, without the stars."
5012 (if (and (re-search-backward "[\r\n]\\*" nil t)
5013 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5017 (defun org-agenda-diary-entry ()
5018 "Make a diary entry, like the `i' command from the calendar.
5019 All the standard commands work: block, weekly etc."
5021 (require 'diary-lib)
5023 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5024 (read-char-exclusive)))
5025 (cmd (cdr (assoc char
5026 '((?d . insert-diary-entry)
5027 (?w . insert-weekly-diary-entry)
5028 (?m . insert-monthly-diary-entry)
5029 (?y . insert-yearly-diary-entry)
5030 (?a . insert-anniversary-diary-entry)
5031 (?b . insert-block-diary-entry)
5032 (?c . insert-cyclic-diary-entry)))))
5033 (oldf (symbol-function 'calendar-cursor-to-date))
5035 (mark (or (mark t) (point))))
5037 (error "No command associated with <%c>" char))
5038 (unless (and (get-text-property point 'day)
5039 (or (not (equal ?b char))
5040 (get-text-property mark 'day)))
5041 (error "Don't know which date to use for diary entry"))
5042 ;; We implement this by hacking the `calendar-cursor-to-date' function
5043 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5044 (let ((calendar-mark-ring
5045 (list (calendar-gregorian-from-absolute
5046 (or (get-text-property mark 'day)
5047 (get-text-property point 'day))))))
5050 (fset 'calendar-cursor-to-date
5051 (lambda (&optional error)
5052 (calendar-gregorian-from-absolute
5053 (get-text-property point 'day))))
5054 (call-interactively cmd))
5055 (fset 'calendar-cursor-to-date oldf)))))
5058 (defun org-agenda-execute-calendar-command (cmd)
5059 "Execute a calendar command from the agenda, with the date associated to
5060 the cursor position."
5061 (require 'diary-lib)
5062 (unless (get-text-property (point) 'day)
5063 (error "Don't know which date to use for calendar command"))
5064 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5066 (date (calendar-gregorian-from-absolute
5067 (get-text-property point 'day)))
5068 (displayed-day (extract-calendar-day date))
5069 (displayed-month (extract-calendar-month date))
5070 (displayed-year (extract-calendar-year date)))
5073 (fset 'calendar-cursor-to-date
5074 (lambda (&optional error)
5075 (calendar-gregorian-from-absolute
5076 (get-text-property point 'day))))
5077 (call-interactively cmd))
5078 (fset 'calendar-cursor-to-date oldf))))
5080 (defun org-agenda-phases-of-moon ()
5081 "Display the phases of the moon for the 3 months around the cursor date."
5083 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5085 (defun org-agenda-holidays ()
5086 "Display the holidays for the 3 months around the cursor date."
5088 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5090 (defun org-agenda-sunrise-sunset (arg)
5091 "Display sunrise and sunset for the cursor date.
5092 Latitude and longitude can be specified with the variables
5093 `calendar-latitude' and `calendar-longitude'. When called with prefix
5094 argument, latitude and longitude will be prompted for."
5096 (let ((calendar-longitude (if arg nil calendar-longitude))
5097 (calendar-latitude (if arg nil calendar-latitude))
5098 (calendar-location-name
5099 (if arg "the given coordinates" calendar-location-name)))
5100 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5102 (defun org-agenda-goto-calendar ()
5103 "Open the Emacs calendar with the date at the cursor."
5105 (let* ((day (or (get-text-property (point) 'day)
5106 (error "Don't know which date to open in calendar")))
5107 (date (calendar-gregorian-from-absolute day)))
5109 (calendar-goto-date date)))
5111 (defun org-calendar-goto-agenda ()
5112 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5113 This is a command that has to be installed in `calendar-mode-map'."
5115 (org-agenda nil (calendar-absolute-from-gregorian
5116 (calendar-cursor-to-date))))
5118 (defun org-agenda-convert-date ()
5120 (let ((day (get-text-property (point) 'day))
5123 (error "Don't know which date to convert"))
5124 (setq date (calendar-gregorian-from-absolute day))
5126 "Gregorian: " (calendar-date-string date) "\n"
5127 "ISO: " (calendar-iso-date-string date) "\n"
5128 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5129 "Julian: " (calendar-julian-date-string date) "\n"
5130 "Astron. JD: " (calendar-astro-date-string date)
5131 " (Julian date number at noon UTC)\n"
5132 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5133 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5134 "French: " (calendar-french-date-string date) "\n"
5135 "Mayan: " (calendar-mayan-date-string date) "\n"
5136 "Coptic: " (calendar-coptic-date-string date) "\n"
5137 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5138 "Persian: " (calendar-persian-date-string date) "\n"
5139 "Chinese: " (calendar-chinese-date-string date) "\n"))
5140 (with-output-to-temp-buffer "*Dates*"
5142 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5146 (defun org-find-file-at-mouse (ev)
5147 "Open file link or URL at mouse."
5149 (mouse-set-point ev)
5150 (org-open-at-point 'in-emacs))
5152 (defun org-open-at-mouse (ev)
5153 "Open file link or URL at mouse."
5155 (mouse-set-point ev)
5156 (org-open-at-point))
5158 (defun org-open-at-point (&optional in-emacs)
5159 "Open link at or after point.
5160 If there is no link at point, this function will search forward up to
5161 the end of the current subtree.
5162 Normally, files will be opened by an appropriate application. If the
5163 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5165 (if (org-at-timestamp-p)
5166 (org-agenda nil (time-to-days (org-time-string-to-time
5167 (substring (match-string 1) 0 10)))
5169 (let (type path line (pos (point)))
5171 (skip-chars-backward
5172 (concat (if org-allow-space-in-links "^" "^ ")
5173 org-non-link-chars))
5174 (if (re-search-forward
5178 (progn (outline-end-of-subtree) (max pos (point)))
5179 (error (end-of-line 1) (point))))
5181 (setq type (match-string 1)
5182 path (match-string 2)))
5184 (error "No link found"))
5185 ;; Remove any trailing spaces in path
5186 (if (string-match " +\\'" path)
5187 (setq path (replace-match "" t t path)))
5191 ((string= type "file")
5192 (if (string-match ":\\([0-9]+\\)\\'" path)
5193 (setq line (string-to-number (match-string 1 path))
5194 path (substring path 0 (match-beginning 0))))
5195 (org-open-file path in-emacs line))
5197 ((string= type "news")
5198 (org-follow-gnus-link path))
5200 ((string= type "bbdb")
5201 (org-follow-bbdb-link path))
5203 ((string= type "gnus")
5204 (let (group article)
5205 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5206 (error "Error in Gnus link"))
5207 (setq group (match-string 1 path)
5208 article (match-string 3 path))
5209 (org-follow-gnus-link group article)))
5211 ((string= type "vm")
5212 (let (folder article)
5213 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5214 (error "Error in VM link"))
5215 (setq folder (match-string 1 path)
5216 article (match-string 3 path))
5217 ;; in-emacs is the prefix arg, will be interpreted as read-only
5218 (org-follow-vm-link folder article in-emacs)))
5220 ((string= type "wl")
5221 (let (folder article)
5222 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5223 (error "Error in Wanderlust link"))
5224 (setq folder (match-string 1 path)
5225 article (match-string 3 path))
5226 (org-follow-wl-link folder article)))
5228 ((string= type "rmail")
5229 (let (folder article)
5230 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5231 (error "Error in RMAIL link"))
5232 (setq folder (match-string 1 path)
5233 article (match-string 3 path))
5234 (org-follow-rmail-link folder article)))
5236 ((string= type "shell")
5238 (while (string-match "@{" cmd)
5239 (setq cmd (replace-match "<" t t cmd)))
5240 (while (string-match "@}" cmd)
5241 (setq cmd (replace-match ">" t t cmd)))
5242 (if (or (not org-confirm-shell-links)
5243 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
5248 (browse-url-at-point)))))))
5250 (defun org-follow-bbdb-link (name)
5251 "Follow a BBDB link to NAME."
5253 (let ((inhibit-redisplay t))
5255 ;; Exact match on name
5256 (bbdb-name (concat "\\`" name "\\'") nil)
5257 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5258 ;; Exact match on name
5259 (bbdb-company (concat "\\`" name "\\'") nil)
5260 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5261 ;; Partial match on name
5262 (bbdb-name name nil)
5263 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5264 ;; Partial match on company
5265 (bbdb-company name nil)
5266 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5267 ;; General match including network address and notes
5269 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
5270 (delete-window (get-buffer-window "*BBDB*"))
5271 (error "No matching BBDB record")))))
5273 (defun org-follow-gnus-link (&optional group article)
5274 "Follow a Gnus link to GROUP and ARTICLE."
5276 (funcall (cdr (assq 'gnus org-link-frame-setup)))
5277 (if group (gnus-fetch-group group))
5279 (or (gnus-summary-goto-article article nil 'force)
5280 (if (fboundp 'gnus-summary-insert-cached-articles)
5282 (gnus-summary-insert-cached-articles)
5283 (gnus-summary-goto-article article nil 'force))
5284 (message "Message could not be found.")))))
5286 (defun org-follow-vm-link (&optional folder article readonly)
5287 "Follow a VM link to FOLDER and ARTICLE."
5289 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
5290 ;; ange-ftp or efs or tramp access
5291 (let ((user (or (match-string 1 folder) (user-login-name)))
5292 (host (match-string 2 folder))
5293 (file (match-string 3 folder)))
5296 ;; use tramp to access the file
5298 (setq folder (format "[%s@%s]%s" user host file))
5299 (setq folder (format "/%s@%s:%s" user host file))))
5301 ;; use ange-ftp or efs
5302 (require (if org-xemacs-p 'efs 'ange-ftp))
5303 (setq folder (format "/%s@%s:%s" user host file))))))
5305 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
5308 (vm-select-folder-buffer)
5310 (let ((case-fold-search t))
5311 (goto-char (point-min))
5312 (if (not (re-search-forward
5313 (concat "^" "message-id: *" (regexp-quote article))))
5314 (error "Could not find the specified message in this folder"))
5317 (vm-beginning-of-message)
5320 (defun org-follow-wl-link (folder article)
5321 "Follow a Wanderlust link to FOLDER and ARTICLE."
5322 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
5323 (if article (wl-summary-jump-to-msg-by-message-id article))
5324 (wl-summary-redisplay))
5326 (defun org-follow-rmail-link (folder article)
5327 "Follow an RMAIL link to FOLDER and ARTICLE."
5328 (let (message-number)
5330 (save-window-excursion
5331 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5332 (setq message-number
5335 (goto-char (point-max))
5336 (if (re-search-backward
5337 (concat "^Message-ID:\\s-+" (regexp-quote
5340 (rmail-what-message))))))
5343 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5344 (rmail-show-message message-number)
5346 (error "Message not found"))))
5348 (defun org-open-file (path &optional in-emacs line)
5349 "Open the file at PATH.
5350 First, this expands any special file name abbreviations. Then the
5351 configuration variable `org-file-apps' is checked if it contains an
5352 entry for this file type, and if yes, the corresponding command is launched.
5353 If no application is found, Emacs simply visits the file.
5354 With optional argument IN-EMACS, Emacs will visit the file.
5355 If the file does not exist, an error is thrown."
5356 (let* ((file (convert-standard-filename (org-expand-file-name path)))
5357 (dfile (downcase file))
5359 (if (and (not (file-exists-p file))
5360 (not org-open-non-existing-files))
5361 (error "No such file: %s" file))
5362 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
5363 (setq ext (match-string 1 dfile))
5364 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
5365 (setq ext (match-string 1 dfile))))
5366 (setq apps (append org-file-apps (org-default-apps)))
5369 (setq cmd (or (cdr (assoc ext apps))
5370 (cdr (assoc t apps)))))
5372 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
5373 (setq cmd (format cmd (concat "\"" file "\"")))
5374 (save-window-excursion
5375 (shell-command (concat cmd " & &"))))
5378 (funcall (cdr (assq 'file org-link-frame-setup)) file)
5379 (if line (goto-line line)))
5382 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
5384 (defun org-default-apps ()
5385 "Return the default applications for this operating system."
5387 ((eq system-type 'darwin)
5388 org-file-apps-defaults-macosx)
5389 ((eq system-type 'windows-nt)
5390 org-file-apps-defaults-windowsnt)
5391 ((eq system-type 'linux)
5392 org-file-apps-defaults-linux)
5393 (t org-file-apps-defaults-linux)))
5395 (defun org-expand-file-name (path)
5396 "Replace special path abbreviations and expand the file name."
5397 (expand-file-name path))
5400 (defvar org-insert-link-history nil
5401 "Minibuffer history for links inserted with `org-insert-link'.")
5403 (defvar org-stored-links nil
5404 "Contains the links stored with `org-store-link'.")
5407 (defun org-store-link (arg)
5408 "\\<org-mode-map>Store an org-link to the current location.
5409 This link can later be inserted into an org-buffer with
5410 \\[org-insert-link].
5411 For some link types, a prefix arg is interpreted:
5412 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5413 For file links, arg negates `org-line-numbers-in-file-links'."
5418 ((eq major-mode 'bbdb-mode)
5419 (setq cpltxt (concat
5421 (or (bbdb-record-name (bbdb-current-record))
5422 (bbdb-record-company (bbdb-current-record))))
5423 link (org-make-link cpltxt)))
5425 ((eq major-mode 'calendar-mode)
5426 (let ((cd (calendar-cursor-to-date)))
5429 (car org-time-stamp-formats)
5431 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5434 ((or (eq major-mode 'vm-summary-mode)
5435 (eq major-mode 'vm-presentation-mode))
5436 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
5437 (vm-follow-summary-cursor)
5439 (vm-select-folder-buffer)
5440 (let* ((message (car vm-message-pointer))
5441 (folder (buffer-file-name))
5442 (subject (vm-su-subject message))
5443 (author (vm-su-full-name message))
5444 (message-id (vm-su-message-id message)))
5445 (setq folder (abbreviate-file-name folder))
5446 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
5448 (setq folder (replace-match "" t t folder)))
5449 (setq cpltxt (concat author " on: " subject))
5450 (setq link (concat cpltxt "\n "
5452 "vm:" folder "#" message-id))))))
5454 ((eq major-mode 'wl-summary-mode)
5455 (let* ((msgnum (wl-summary-message-number))
5456 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
5457 msgnum 'message-id))
5458 (wl-message-entity (elmo-msgdb-overview-get-entity
5459 msgnum (wl-summary-buffer-msgdb)))
5460 (author (wl-summary-line-from)) ; FIXME: how to get author name?
5461 (subject "???")) ; FIXME: How to get subject of email?
5462 (setq cpltxt (concat author " on: " subject))
5463 (setq link (concat cpltxt "\n "
5465 "wl:" wl-summary-buffer-folder-name
5468 ((eq major-mode 'rmail-mode)
5471 (rmail-narrow-to-non-pruned-header)
5472 (let ((folder (buffer-file-name))
5473 (message-id (mail-fetch-field "message-id"))
5474 (author (mail-fetch-field "from"))
5475 (subject (mail-fetch-field "subject")))
5476 (setq cpltxt (concat author " on: " subject))
5477 (setq link (concat cpltxt "\n "
5479 "rmail:" folder "#" message-id)))))))
5481 ((eq major-mode 'gnus-group-mode)
5482 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
5483 (gnus-group-group-name)) ; version
5484 ((fboundp 'gnus-group-name)
5487 (setq cpltxt (concat
5488 (if (org-xor arg org-usenet-links-prefer-google)
5489 "http://groups.google.com/groups?group="
5492 link (org-make-link cpltxt))))
5494 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
5495 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
5496 (gnus-summary-beginning-of-article)
5497 (let* ((group (car gnus-article-current))
5498 (article (cdr gnus-article-current))
5499 (header (gnus-summary-article-header article))
5500 (author (mail-header-from header))
5501 (message-id (mail-header-id header))
5502 (date (mail-header-date header))
5503 (subject (gnus-summary-subject-string)))
5504 (setq cpltxt (concat author " on: " subject))
5505 (if (org-xor arg org-usenet-links-prefer-google)
5509 (format "http://groups.google.com/groups?as_umsgid=%s"
5510 (org-fixup-message-id-for-http message-id))))
5511 (setq link (concat cpltxt "\n"
5514 "#" (number-to-string article)))))))
5516 ((eq major-mode 'w3-mode)
5517 (setq cpltxt (url-view-url t)
5518 link (org-make-link cpltxt)))
5519 ((eq major-mode 'w3m-mode)
5520 (setq cpltxt w3m-current-url
5521 link (org-make-link cpltxt)))
5524 ;; Just link to this file here.
5525 (setq cpltxt (concat "file:"
5526 (abbreviate-file-name (buffer-file-name))))
5527 ;; Add the line number?
5528 (if (org-xor org-line-numbers-in-file-links arg)
5532 (+ (if (bolp) 1 0) (count-lines
5533 (point-min) (point)))))))
5534 (setq link (org-make-link cpltxt)))
5537 (error "Cannot link to a buffer which is not visiting a file"))
5539 (t (setq link nil)))
5541 (if (and (interactive-p) link)
5543 (setq org-stored-links
5544 (cons (cons (or cpltxt link) link) org-stored-links))
5545 (message "Stored: %s" (or cpltxt link)))
5548 (defun org-make-link (&rest strings)
5549 "Concatenate STRINGS, format resulting string with `org-link-format'."
5550 (format org-link-format (apply 'concat strings)))
5552 (defun org-xor (a b)
5556 (defun org-get-header (header)
5557 "Find a HEADER field in the current buffer."
5559 (goto-char (point-min))
5560 (let ((case-fold-search t) s)
5563 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
5564 (setq s (match-string 1)))
5565 (while (string-match "\"" s)
5566 (setq s (replace-match "" t t s)))
5567 (if (string-match "[<(].*" s)
5568 (setq s (replace-match "" t t s))))
5569 ((eq header 'message-id)
5570 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
5571 (setq s (match-string 1))))
5572 ((eq header 'subject)
5573 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
5574 (setq s (match-string 1)))))
5575 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
5576 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
5580 (defun org-fixup-message-id-for-http (s)
5581 "Replace special characters in a message id, so it can be used in an http query."
5582 (while (string-match "<" s)
5583 (setq s (replace-match "%3C" t t s)))
5584 (while (string-match ">" s)
5585 (setq s (replace-match "%3E" t t s)))
5586 (while (string-match "@" s)
5587 (setq s (replace-match "%40" t t s)))
5590 (defun org-insert-link (&optional complete-file)
5591 "Insert a link. At the prompt, enter the link.
5593 Completion can be used to select a link previously stored with
5594 `org-store-link'. When the empty string is entered (i.e. if you just
5595 press RET at the prompt), the link defaults to the most recently
5596 stored link. As SPC triggers completion in the minibuffer, you need to
5597 use M-SPC or C-q SPC to force the insertion of a space character.
5599 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
5600 selected using completion. The path to the file will be relative to
5601 the current directory if the file is in the current directory or a
5602 subdirectory. Otherwise, the link will be the absolute path as
5603 completed in the minibuffer (i.e. normally ~/path/to/file).
5605 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
5606 is in the current directory or below."
5608 (let ((link (if complete-file
5609 (read-file-name "File: ")
5611 "Link: " org-stored-links nil nil nil
5612 org-insert-link-history
5613 (or (car (car org-stored-links))))))
5615 (if (or (not link) (equal link ""))
5616 (error "No links available"))
5618 (let ((pwd (file-name-as-directory (expand-file-name "."))))
5620 ((equal complete-file '(16))
5623 "file:" (abbreviate-file-name (expand-file-name link)))))
5624 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
5625 (expand-file-name link))
5628 "file:" (match-string 1 (expand-file-name link)))))
5629 (t (insert (org-make-link "file:" link)))))
5630 (setq linktxt (cdr (assoc link org-stored-links)))
5631 (if (not org-keep-stored-link-after-insertion)
5632 (setq org-stored-links (delq (assoc link org-stored-links)
5634 (if (not linktxt) (setq link (org-make-link link)))
5635 (let ((lines (org-split-string (or linktxt link) "\n")))
5636 (insert (car lines))
5637 (setq matched (string-match org-link-regexp (car lines)))
5638 (setq lines (cdr lines))
5642 (beginning-of-line 0)
5643 (looking-at "[ \t]+\\S-"))
5645 (setq matched (or matched
5646 (string-match org-link-regexp (car lines))))
5647 (insert (car lines))
5648 (setq lines (cdr lines))))
5650 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5652 ;;; Hooks for remember.el
5654 (defun org-remember-annotation ()
5655 "Return a link to the current location as an annotation for remember.el.
5656 If you are using Org-mode files as target for data storage with
5657 remember.el, then the annotations should include a link compatible with the
5658 conventions in Org-mode. This function returns such a link."
5659 (org-store-link nil))
5661 (defconst org-remember-help
5662 "Select a destination location for the note.
5663 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5664 RET at beg-of-buf -> Append to file as level 2 headline
5665 RET on headline -> Store as sublevel entry to current headline
5666 <left>/<right> -> Before/after current headline, same headings level")
5669 (defun org-remember-handler ()
5670 "Store stuff from remember.el into an org file.
5671 First prompts for an org file. If the user just presses return, the value
5672 of `org-default-notes-file' is used.
5673 Then the command offers the headings tree of the selected file in order to
5674 file the text at a specific location.
5675 You can either immediately press RET to get the note appended to the
5676 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5677 find a better place. Then press RET or <left> or <right> in insert the note.
5679 Key Cursor position Note gets inserted
5680 -----------------------------------------------------------------------------
5681 RET buffer-start as level 2 heading at end of file
5682 RET on headline as sublevel of the heading at cursor
5683 RET no heading at cursor position, level taken from context.
5684 Or use prefix arg to specify level manually.
5685 <left> on headline as same level, before current heading
5686 <right> on headline as same level, after current heading
5688 So the fastest way to store the note is to press RET RET to append it to
5689 the default file. This way your current train of thought is not
5690 interrupted, in accordance with the principles of remember.el. But with
5691 little extra effort, you can push it directly to the correct location.
5693 Before being stored away, the function ensures that the text has a
5694 headline, i.e. a first line that starts with a \"*\". If not, a headline
5695 is constructed from the current date and some additional data.
5697 If the variable `org-adapt-indentation' is non-nil, the entire text is
5698 also indented so that it starts in the same column as the headline
5699 \(i.e. after the stars).
5701 See also the variable `org-reverse-note-order'."
5703 (let* ((txt (buffer-substring (point-min) (point-max)))
5704 (fastp current-prefix-arg)
5705 (file (if fastp org-default-notes-file (org-get-org-file)))
5706 (visiting (find-buffer-visiting file))
5707 (org-startup-with-deadline-check nil)
5708 (org-startup-folded nil)
5709 spos level indent reversed)
5710 ;; Modify text so that it becomes a nice subtree which can be inserted
5711 ;; into an org tree.
5712 (let* ((lines (split-string txt "\n"))
5714 (lines (cdr lines)))
5715 (if (string-match "^\\*+" first)
5716 ;; Is already a headline
5717 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5719 ;; We need to add a headline: Use time and first buffer line
5720 (setq lines (cons first lines)
5721 first (concat "* " (current-time-string)
5722 " (" (remember-buffer-desc) ")")
5724 (if org-adapt-indentation
5725 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5726 (setq txt (concat first "\n"
5727 (mapconcat 'identity lines "\n"))))
5730 (find-file-noselect file))
5731 (with-current-buffer (get-file-buffer file)
5732 (setq reversed (org-notes-order-reversed-p))
5736 ;; Ask the User for a location
5737 (setq spos (if fastp 1 (org-get-location
5739 org-remember-help)))
5740 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5741 ; not handle this note
5744 ;; Put it at the start or end, as level 2
5747 (goto-char (if reversed (point-min) (point-max)))
5748 (if (not (bolp)) (newline))
5749 (org-paste-subtree (or current-prefix-arg 2) txt)))
5750 ((and (org-on-heading-p nil) (not current-prefix-arg))
5751 ;; Put it below this entry, at the beg/end of the subtree
5752 (org-back-to-heading)
5753 (setq level (outline-level))
5755 (outline-end-of-heading)
5756 (outline-end-of-subtree))
5757 (if (not (bolp)) (newline))
5758 (beginning-of-line 1)
5759 (org-paste-subtree (1+ level) txt))
5761 ;; Put it right there, with automatic level determined by
5762 ;; org-paste-subtree or from prefix arg
5763 (org-paste-subtree current-prefix-arg txt)))
5764 (when remember-save-after-remembering
5766 (if (not visiting) (kill-buffer (current-buffer)))))))))
5767 t) ;; return t to indicate that we took care of this note.
5769 (defun org-get-org-file ()
5770 "Read a filename, with default directory `org-directory'."
5771 (let ((default (or org-default-notes-file remember-data-file)))
5772 (read-file-name (format "File name [%s]: " default)
5773 (file-name-as-directory org-directory)
5776 (defun org-notes-order-reversed-p ()
5777 "Check if the current file should receive notes in reversed order."
5779 ((not org-reverse-note-order) nil)
5780 ((eq t org-reverse-note-order) t)
5781 ((not (listp org-reverse-note-order)) nil)
5783 (let ((all org-reverse-note-order)
5785 (while (setq entry (pop all))
5786 (if (string-match (car entry) (buffer-file-name))
5787 (throw 'exit (cdr entry))))
5792 ;; Watch out: Here we are talking about two different kind of tables.
5793 ;; Most of the code is for the tables created with the Org-mode table editor.
5794 ;; Sometimes, we talk about tables created and edited with the table.el
5795 ;; Emacs package. We call the former org-type tables, and the latter
5796 ;; table.el-type tables.
5799 (defun org-before-change-function (beg end)
5800 "Every change indicates that a table might need an update."
5801 (setq org-table-may-need-update t))
5803 (defconst org-table-line-regexp "^[ \t]*|"
5804 "Detects an org-type table line.")
5805 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5806 "Detects an org-type table line.")
5807 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5808 "Detects a table line marked for automatic recalculation.")
5809 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5810 "Detects a table line marked for automatic recalculation.")
5811 (defconst org-table-hline-regexp "^[ \t]*|-"
5812 "Detects an org-type table hline.")
5813 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5814 "Detects a table-type table hline.")
5815 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5816 "Detects an org-type or table-type table.")
5817 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5818 "Searching from within a table (any type) this finds the first line
5819 outside the table.")
5820 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5821 "Searching from within a table (any type) this finds the first line
5822 outside the table.")
5824 (defun org-table-create-with-table.el ()
5825 "Use the table.el package to insert a new table.
5826 If there is already a table at point, convert between Org-mode tables
5827 and table.el tables."
5831 ((org-at-table.el-p)
5832 (if (y-or-n-p "Convert table to Org-mode table? ")
5833 (org-table-convert)))
5835 (if (y-or-n-p "Convert table to table.el table? ")
5836 (org-table-convert)))
5837 (t (call-interactively 'table-insert))))
5839 (defun org-table-create (&optional size)
5840 "Query for a size and insert a table skeleton.
5841 SIZE is a string Columns x Rows like for example \"3x2\"."
5844 (setq size (read-string
5845 (concat "Table size Columns x Rows [e.g. "
5846 org-table-default-size "]: ")
5847 "" nil org-table-default-size)))
5849 (let* ((pos (point))
5850 (indent (make-string (current-column) ?\ ))
5851 (split (org-split-string size " *x *"))
5852 (rows (string-to-number (nth 1 split)))
5853 (columns (string-to-number (car split)))
5854 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5856 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5857 (point-at-bol) (point)))
5858 (beginning-of-line 1)
5860 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5861 (dotimes (i rows) (insert line))
5864 ;; Insert a hline after the first row.
5871 (defun org-table-convert-region (beg0 end0 nspace)
5872 "Convert region to a table.
5873 The region goes from BEG0 to END0, but these borders will be moved
5874 slightly, to make sure a beginning of line in the first line is included.
5875 When NSPACE is non-nil, it indicates the minimum number of spaces that
5876 separate columns (default: just one space)."
5877 (let* ((beg (min beg0 end0))
5878 (end (max beg0 end0))
5882 (beginning-of-line 1)
5883 (setq beg (move-marker (make-marker) (point)))
5885 (if (bolp) (backward-char 1) (end-of-line 1))
5886 (setq end (move-marker (make-marker) (point)))
5887 ;; Lets see if this is tab-separated material. If every nonempty line
5888 ;; contains a tab, we will assume that it is tab-separated material
5892 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5893 (if nspace (setq tabsep nil))
5896 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5897 (max 1 (prefix-numeric-value nspace)))))
5899 (while (re-search-forward re end t)
5900 (replace-match "|" t t))
5905 (defun org-table-import (file arg)
5906 "Import FILE as a table.
5907 The file is assumed to be tab-separated. Such files can be produced by most
5908 spreadsheet and database applications. If no tabs (at least one per line)
5909 are found, lines will be split on whitespace into fields."
5910 (interactive "f\nP")
5911 (or (bolp) (newline))
5914 (insert-file-contents file)
5915 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5917 (defun org-table-export ()
5918 "Export table as a tab-separated file.
5919 Such a file can be imported into a spreadsheet program like Excel."
5921 (let* ((beg (org-table-begin))
5922 (end (org-table-end))
5923 (table (buffer-substring beg end))
5924 (file (read-file-name "Export table to: "))
5926 (unless (or (not (file-exists-p file))
5927 (y-or-n-p (format "Overwrite file %s? " file)))
5929 (with-current-buffer (find-file-noselect file)
5930 (setq buf (current-buffer))
5934 (goto-char (point-min))
5935 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5936 (replace-match "" t t)
5938 (goto-char (point-min))
5939 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5940 (replace-match "" t t)
5941 (goto-char (min (1+ (point)) (point-max))))
5942 (goto-char (point-min))
5943 (while (re-search-forward "^-[-+]*$" nil t)
5945 (if (looking-at "\n")
5947 (goto-char (point-min))
5948 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5949 (replace-match "\t" t t))
5953 (defvar org-table-aligned-begin-marker (make-marker)
5954 "Marker at the beginning of the table last aligned.
5955 Used to check if cursor still is in that table, to minimize realignment.")
5956 (defvar org-table-aligned-end-marker (make-marker)
5957 "Marker at the end of the table last aligned.
5958 Used to check if cursor still is in that table, to minimize realignment.")
5959 (defvar org-table-last-alignment nil
5960 "List of flags for flushright alignment, from the last re-alignment.
5961 This is being used to correctly align a single field after TAB or RET.")
5962 ;; FIXME: The following is currently not used.
5963 (defvar org-table-last-column-widths nil
5964 "List of max width of fields in each column.
5965 This is being used to correctly align a single field after TAB or RET.")
5967 (defvar org-last-recalc-line nil)
5969 (defun org-table-align ()
5970 "Align the table at point by aligning all vertical bars."
5974 (beg (org-table-begin))
5975 (end (org-table-end))
5976 ;; Current cursor position
5977 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5978 (colpos (org-table-current-column))
5979 (winstart (window-start))
5980 text lines (new "") lengths l typenums ty fields maxfields i
5982 (indent "") cnt frac
5984 (spaces (if (org-in-invisibility-spec-p '(org-table))
5985 org-table-spaces-around-invisible-separators
5986 org-table-spaces-around-separators))
5990 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
5992 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
5995 ;; (message "Aligning table...")
5997 (setq lines (org-split-string
5998 (buffer-substring-no-properties beg end) "\n"))
5999 ;; Store the indentation of the first line
6000 (if (string-match "^ *" (car lines))
6001 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6003 (setq lines (mapcar (lambda (l)
6004 (if (string-match "^ *|-" l)
6006 (if (string-match "[ \t]+$" l)
6007 (substring l 0 (match-beginning 0))
6010 ;; Get the data fields
6011 (setq fields (mapcar
6013 (org-split-string l " *| *"))
6014 (delq nil (copy-sequence lines))))
6015 ;; How many fields in the longest line?
6017 (setq maxfields (apply 'max (mapcar 'length fields)))
6019 (kill-region beg end)
6020 (org-table-create org-table-default-size)
6021 (error "Empty table - created default table")))
6022 ;; A list of empty string to fill any short rows on output
6023 (setq emptystrings (make-list maxfields ""))
6024 ;; Get the maximum length of a field and the most common datatype
6027 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6028 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6030 (push (apply 'max 1 (mapcar 'length column)) lengths)
6031 ;; compute the fraction stepwise, ignoring empty fields
6032 (setq cnt 0 frac 0.0)
6037 (setq frac ( / (+ (* frac cnt)
6038 (if (string-match org-table-number-regexp x) 1 0))
6039 (setq cnt (1+ cnt))))))
6041 (push (>= frac org-table-number-fraction) typenums))
6042 (setq lengths (nreverse lengths)
6043 typenums (nreverse typenums))
6044 (setq org-table-last-alignment typenums
6045 org-table-last-column-widths lengths)
6046 ;; Compute the formats needed for output of the table
6047 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6048 (while (setq l (pop lengths))
6049 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6050 (setq rfmt (concat rfmt (format rfmt1 ty l))
6051 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6052 (setq rfmt (concat rfmt "\n")
6053 hfmt (concat (substring hfmt 0 -1) "|\n"))
6054 ;; Produce the new table
6056 ;; (setq l (pop lines))
6058 ;; (setq new (concat new (apply 'format rfmt
6059 ;; (append (pop fields) emptystrings))))
6060 ;; (setq new (concat new hfmt))))
6061 (setq new (mapconcat
6063 (if l (apply 'format rfmt
6064 (append (pop fields) emptystrings))
6067 ;; Replace the old one
6068 (delete-region beg end)
6069 (move-marker end nil)
6070 (move-marker org-table-aligned-begin-marker (point))
6072 (move-marker org-table-aligned-end-marker (point))
6073 ;; Try to move to the old location (approximately)
6075 (set-window-start (selected-window) winstart 'noforce)
6076 (org-table-goto-column colpos)
6077 (setq org-table-may-need-update nil)
6078 (if (org-in-invisibility-spec-p '(org-table))
6079 (org-table-add-invisible-to-vertical-lines))
6082 (defun org-table-begin (&optional table-type)
6083 "Find the beginning of the table and return its position.
6084 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6086 (if (not (re-search-backward
6087 (if table-type org-table-any-border-regexp
6088 org-table-border-regexp)
6090 (error "Can't find beginning of table")
6091 (goto-char (match-beginning 0))
6092 (beginning-of-line 2)
6095 (defun org-table-end (&optional table-type)
6096 "Find the end of the table and return its position.
6097 With argument TABLE-TYPE, go to the end of a table.el-type table."
6099 (if (not (re-search-forward
6100 (if table-type org-table-any-border-regexp
6101 org-table-border-regexp)
6103 (goto-char (point-max))
6104 (goto-char (match-beginning 0)))
6107 (defun org-table-justify-field-maybe ()
6108 "Justify the current field, text to left, number to right."
6110 (org-table-may-need-update) ; Realignment will happen anyway, don't bother
6111 ((org-at-table-hline-p)
6112 ;; This is pretty stupid, but I don't know how to deal with hlines
6113 (setq org-table-may-need-update t))
6114 ((or (not (equal (marker-buffer org-table-aligned-begin-marker)
6116 (< (point) org-table-aligned-begin-marker)
6117 (>= (point) org-table-aligned-end-marker))
6118 ;; This is not the same table, force a full re-align
6119 (setq org-table-may-need-update t))
6120 (t ;; realign the current field, based on previous full realign
6121 (let* ((pos (point)) s org-table-may-need-update
6122 (col (org-table-current-column))
6123 (num (nth (1- col) org-table-last-alignment))
6126 (skip-chars-backward "^|\n")
6127 (if (looking-at " *\\([^|\n]*?\\) *|")
6129 (setq s (match-string 1)
6131 l (max 1 (- (match-end 0) (match-beginning 0) 3)))
6132 (setq f (format (if num " %%%ds |" " %%-%ds |") l)
6134 (or (equal n o) (replace-match n)))
6135 (setq org-table-may-need-update t))
6136 (goto-char pos))))))
6138 (defun org-table-next-field ()
6139 "Go to the next field in the current table.
6140 Before doing so, re-align the table if necessary."
6142 (org-table-maybe-eval-formula)
6143 (org-table-maybe-recalculate-line)
6144 (if (and org-table-automatic-realign
6145 org-table-may-need-update)
6147 (if (org-at-table-hline-p)
6151 (re-search-forward "|" (org-table-end))
6152 (if (looking-at "[ \t]*$")
6153 (re-search-forward "|" (org-table-end)))
6154 (if (looking-at "-")
6156 (beginning-of-line 0)
6157 (org-table-insert-row 'below))
6158 (if (looking-at " ") (forward-char 1))))
6160 (org-table-insert-row 'below))))
6162 (defun org-table-previous-field ()
6163 "Go to the previous field in the table.
6164 Before doing so, re-align the table if necessary."
6166 (org-table-justify-field-maybe)
6167 (org-table-maybe-recalculate-line)
6168 (if (and org-table-automatic-realign
6169 org-table-may-need-update)
6171 (if (org-at-table-hline-p)
6173 (re-search-backward "|" (org-table-begin))
6174 (re-search-backward "|" (org-table-begin))
6175 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6176 (re-search-backward "|" (org-table-begin)))
6177 (if (looking-at "| ?")
6178 (goto-char (match-end 0))))
6180 (defun org-table-next-row ()
6181 "Go to the next row (same column) in the current table.
6182 Before doing so, re-align the table if necessary."
6184 (org-table-maybe-eval-formula)
6185 (org-table-maybe-recalculate-line)
6186 (if (or (looking-at "[ \t]*$")
6187 (save-excursion (skip-chars-backward " \t") (bolp)))
6189 (if (and org-table-automatic-realign
6190 org-table-may-need-update)
6192 (let ((col (org-table-current-column)))
6193 (beginning-of-line 2)
6194 (if (or (not (org-at-table-p))
6195 (org-at-table-hline-p))
6197 (beginning-of-line 0)
6198 (org-table-insert-row 'below)))
6199 (org-table-goto-column col)
6200 (skip-chars-backward "^|\n\r")
6201 (if (looking-at " ") (forward-char 1)))))
6203 (defun org-table-copy-down (n)
6204 "Copy a field down in the current column.
6205 If the field at the cursor is empty, copy into it the content of the nearest
6206 non-empty field above. With argument N, use the Nth non-empty field.
6207 If the current field is not empty, it is copied down to the next row, and
6208 the cursor is moved with it. Therefore, repeating this command causes the
6209 column to be filled row-by-row.
6210 If the variable `org-table-copy-increment' is non-nil and the field is an
6211 integer, it will be incremented while copying."
6213 (let* ((colpos (org-table-current-column))
6214 (field (org-table-get-field))
6215 (non-empty (string-match "[^ \t]" field))
6216 (beg (org-table-begin))
6218 (org-table-check-inside-data-field)
6221 (setq txt (org-trim field))
6222 (org-table-next-row)
6223 (org-table-blank-field))
6227 (while (progn (beginning-of-line 1)
6228 (re-search-backward org-table-dataline-regexp
6230 (org-table-goto-column colpos t)
6231 (if (and (looking-at
6232 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6233 (= (setq n (1- n)) 0))
6234 (throw 'exit (match-string 1))))))))
6237 (if (and org-table-copy-increment
6238 (string-match "^[0-9]+$" txt))
6239 (setq txt (format "%d" (+ (string-to-int txt) 1))))
6241 (org-table-maybe-recalculate-line)
6243 (error "No non-empty field found"))))
6245 (defun org-table-check-inside-data-field ()
6246 "Is point inside a table data field?
6247 I.e. not on a hline or before the first or after the last column?"
6248 (if (or (not (org-at-table-p))
6249 (= (org-table-current-column) 0)
6250 (org-at-table-hline-p)
6251 (looking-at "[ \t]*$"))
6252 (error "Not in table data field")))
6254 (defvar org-table-clip nil
6255 "Clipboard for table regions.")
6257 (defun org-table-blank-field ()
6258 "Blank the current table field or active region."
6260 (org-table-check-inside-data-field)
6261 (if (and (interactive-p) (org-region-active-p))
6262 (let (org-table-clip)
6263 (org-table-cut-region (region-beginning) (region-end)))
6264 (skip-chars-backward "^|")
6266 (if (looking-at "|[^|\n]+")
6267 (let* ((pos (match-beginning 0))
6268 (match (match-string 0))
6269 (len (length match)))
6270 (replace-match (concat "|" (make-string (1- len) ?\ )))
6271 (goto-char (+ 2 pos))
6272 (substring match 1)))))
6274 (defun org-table-get-field (&optional n replace)
6275 "Return the value of the field in column N of current row.
6276 N defaults to current field.
6277 If REPLACE is a string, replace field with this value. The return value
6278 is always the old value."
6279 (and n (org-table-goto-column n))
6280 (skip-chars-backward "^|\n")
6282 (if (looking-at "|[^|\r\n]*")
6283 (let* ((pos (match-beginning 0))
6284 (val (buffer-substring (1+ pos) (match-end 0))))
6286 (replace-match (concat "|" replace)))
6287 (goto-char (min (point-at-eol) (+ 2 pos)))
6289 (forward-char 1) ""))
6291 (defun org-table-current-column ()
6292 "Find out which column we are in.
6293 When called interactively, column is also displayed in echo area."
6295 (if (interactive-p) (org-table-check-inside-data-field))
6297 (let ((cnt 0) (pos (point)))
6298 (beginning-of-line 1)
6299 (while (search-forward "|" pos t)
6300 (setq cnt (1+ cnt)))
6301 (if (interactive-p) (message "This is table column %d" cnt))
6304 (defun org-table-goto-column (n &optional on-delim force)
6305 "Move the cursor to the Nth column in the current table line.
6306 With optional argument ON-DELIM, stop with point before the left delimiter
6308 If there are less than N fields, just go to after the last delimiter.
6309 However, when FORCE is non-nil, create new columns if necessary."
6310 (let ((pos (point-at-eol)))
6311 (beginning-of-line 1)
6313 (while (and (> (setq n (1- n)) -1)
6314 (or (search-forward "|" pos t)
6316 (progn (end-of-line 1)
6317 (skip-chars-backward "^|")
6319 ; (backward-char 2) t)))))
6320 (when (and force (not (looking-at ".*|")))
6321 (save-excursion (end-of-line 1) (insert " | ")))
6324 (if (looking-at " ") (forward-char 1))))))
6326 (defun org-at-table-p (&optional table-type)
6327 "Return t if the cursor is inside an org-type table.
6328 If TABLE-TYPE is non-nil, also check for table.el-type tables."
6329 (if org-enable-table-editor
6331 (beginning-of-line 1)
6332 (looking-at (if table-type org-table-any-line-regexp
6333 org-table-line-regexp)))
6336 (defun org-table-recognize-table.el ()
6337 "If there is a table.el table nearby, recognize it and move into it."
6338 (if org-table-tab-recognizes-table.el
6339 (if (org-at-table.el-p)
6341 (beginning-of-line 1)
6342 (if (looking-at org-table-dataline-regexp)
6344 (if (looking-at org-table1-hline-regexp)
6346 (beginning-of-line 2)
6347 (if (looking-at org-table-any-border-regexp)
6348 (beginning-of-line -1)))))
6349 (if (re-search-forward "|" (org-table-end t) t)
6352 (if (table--at-cell-p (point))
6354 (message "recognizing table.el table...")
6355 (table-recognize-table)
6356 (message "recognizing table.el table...done")))
6357 (error "This should not happen..."))
6362 (defun org-at-table.el-p ()
6363 "Return t if the cursor is inside a table.el-type table."
6365 (if (org-at-table-p 'any)
6367 (goto-char (org-table-begin 'any))
6368 (looking-at org-table1-hline-regexp))
6371 (defun org-at-table-hline-p ()
6372 "Return t if the cursor is inside a hline in a table."
6373 (if org-enable-table-editor
6375 (beginning-of-line 1)
6376 (looking-at org-table-hline-regexp))
6379 (defun org-table-insert-column ()
6380 "Insert a new column into the table."
6382 (if (not (org-at-table-p))
6383 (error "Not at a table"))
6384 (org-table-find-dataline)
6385 (let* ((col (max 1 (org-table-current-column)))
6386 (beg (org-table-begin))
6387 (end (org-table-end))
6388 ;; Current cursor position
6389 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6392 (while (< (point) end)
6393 (if (org-at-table-hline-p)
6395 (org-table-goto-column col t)
6397 (beginning-of-line 2))
6398 (move-marker end nil)
6400 (org-table-goto-column colpos)
6402 (org-table-modify-formulas 'insert col)))
6404 (defun org-table-find-dataline ()
6405 "Find a dataline in the current table, which is needed for column commands."
6406 (if (and (org-at-table-p)
6407 (not (org-at-table-hline-p)))
6409 (let ((col (current-column))
6410 (end (org-table-end)))
6411 (move-to-column col)
6412 (while (and (< (point) end)
6413 (or (not (= (current-column) col))
6414 (org-at-table-hline-p)))
6415 (beginning-of-line 2)
6416 (move-to-column col))
6417 (if (and (org-at-table-p)
6418 (not (org-at-table-hline-p)))
6421 "Please position cursor in a data line for column operations")))))
6423 (defun org-table-delete-column ()
6424 "Delete a column into the table."
6426 (if (not (org-at-table-p))
6427 (error "Not at a table"))
6428 (org-table-find-dataline)
6429 (org-table-check-inside-data-field)
6430 (let* ((col (org-table-current-column))
6431 (beg (org-table-begin))
6432 (end (org-table-end))
6433 ;; Current cursor position
6434 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6437 (while (< (point) end)
6438 (if (org-at-table-hline-p)
6440 (org-table-goto-column col t)
6441 (and (looking-at "|[^|\n]+|")
6442 (replace-match "|")))
6443 (beginning-of-line 2))
6444 (move-marker end nil)
6446 (org-table-goto-column colpos)
6448 (org-table-modify-formulas 'remove col)))
6450 (defun org-table-move-column-right ()
6451 "Move column to the right."
6453 (org-table-move-column nil))
6454 (defun org-table-move-column-left ()
6455 "Move column to the left."
6457 (org-table-move-column 'left))
6459 (defun org-table-move-column (&optional left)
6460 "Move the current column to the right. With arg LEFT, move to the left."
6462 (if (not (org-at-table-p))
6463 (error "Not at a table"))
6464 (org-table-find-dataline)
6465 (org-table-check-inside-data-field)
6466 (let* ((col (org-table-current-column))
6467 (col1 (if left (1- col) col))
6468 (beg (org-table-begin))
6469 (end (org-table-end))
6470 ;; Current cursor position
6471 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6472 (colpos (if left (1- col) (1+ col))))
6473 (if (and left (= col 1))
6474 (error "Cannot move column further left"))
6475 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6476 (error "Cannot move column further right"))
6478 (while (< (point) end)
6479 (if (org-at-table-hline-p)
6481 (org-table-goto-column col1 t)
6482 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6483 (replace-match "|\\2|\\1|")))
6484 (beginning-of-line 2))
6485 (move-marker end nil)
6487 (org-table-goto-column colpos)
6489 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6491 (defun org-table-move-row-down ()
6492 "Move table row down."
6494 (org-table-move-row nil))
6495 (defun org-table-move-row-up ()
6496 "Move table row up."
6498 (org-table-move-row 'up))
6500 (defun org-table-move-row (&optional up)
6501 "Move the current table line down. With arg UP, move it up."
6503 (let ((col (current-column))
6507 (beginning-of-line tonew)
6508 (if (not (org-at-table-p))
6511 (error "Cannot move row further")))
6513 (beginning-of-line 1)
6515 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6516 (delete-region (point) (1+ (point-at-eol)))
6517 (beginning-of-line tonew)
6519 (beginning-of-line 0)
6520 (move-to-column col)))
6522 (defun org-table-insert-row (&optional arg)
6523 "Insert a new row above the current line into the table.
6524 With prefix ARG, insert below the current line."
6526 (if (not (org-at-table-p))
6527 (error "Not at a table"))
6528 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6530 (if (string-match "^[ \t]*|-" line)
6531 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
6532 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
6533 ;; Fix the first field if necessary
6534 (setq new (concat new))
6535 (if (string-match "^[ \t]*| *[#$] *|" line)
6536 (setq new (replace-match (match-string 0 line) t t new)))
6537 (beginning-of-line (if arg 2 1))
6538 (let (org-table-may-need-update)
6539 (insert-before-markers new)
6540 (insert-before-markers "\n"))
6541 (beginning-of-line 0)
6542 (re-search-forward "| ?" (point-at-eol) t)
6543 (and org-table-may-need-update (org-table-align))))
6545 (defun org-table-insert-hline (&optional arg)
6546 "Insert a horizontal-line below the current line into the table.
6547 With prefix ARG, insert above the current line."
6549 (if (not (org-at-table-p))
6550 (error "Not at a table"))
6551 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6552 (col (current-column))
6554 (if (string-match "^[ \t]*|-" line)
6556 (mapcar (lambda (x) (if (member x '(?| ?+))
6557 (prog1 (if start ?+ ?|) (setq start t))
6561 (mapcar (lambda (x) (if (equal x ?|)
6562 (prog1 (if start ?+ ?|) (setq start t))
6565 (beginning-of-line (if arg 1 2))
6566 (apply 'insert line)
6567 (if (equal (char-before (point)) ?+)
6568 (progn (backward-delete-char 1) (insert "|")))
6570 (beginning-of-line 0)
6571 (move-to-column col)))
6573 (defun org-table-kill-row ()
6574 "Delete the current row or horizontal line from the table."
6576 (if (not (org-at-table-p))
6577 (error "Not at a table"))
6578 (let ((col (current-column)))
6579 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6580 (if (not (org-at-table-p)) (beginning-of-line 0))
6581 (move-to-column col)))
6584 (defun org-table-cut-region (beg end)
6585 "Copy region in table to the clipboard and blank all relevant fields."
6587 (org-table-copy-region beg end 'cut))
6589 (defun org-table-copy-region (beg end &optional cut)
6590 "Copy rectangular region in table to clipboard.
6591 A special clipboard is used which can only be accessed
6592 with `org-table-paste-rectangle'."
6594 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6596 (rpl (if cut " " nil)))
6598 (org-table-check-inside-data-field)
6599 (setq l01 (count-lines (point-min) (point))
6600 c01 (org-table-current-column))
6602 (org-table-check-inside-data-field)
6603 (setq l02 (count-lines (point-min) (point))
6604 c02 (org-table-current-column))
6605 (setq l1 (min l01 l02) l2 (max l01 l02)
6606 c1 (min c01 c02) c2 (max c01 c02))
6610 (if (> l1 l2) (throw 'exit t))
6612 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6613 (setq cols nil ic1 c1 ic2 c2)
6614 (while (< ic1 (1+ ic2))
6615 (push (org-table-get-field ic1 rpl) cols)
6616 (setq ic1 (1+ ic1)))
6617 (push (nreverse cols) region)
6618 (setq l1 (1+ l1)))))
6619 (setq org-table-clip (nreverse region))
6620 (if cut (org-table-align))
6623 (defun org-table-paste-rectangle ()
6624 "Paste a rectangular region into a table.
6625 The upper right corner ends up in the current field. All involved fields
6626 will be overwritten. If the rectangle does not fit into the present table,
6627 the table is enlarged as needed. The process ignores horizontal separator
6630 (unless (and org-table-clip (listp org-table-clip))
6631 (error "First cut/copy a region to paste!"))
6632 (org-table-check-inside-data-field)
6633 (let* ((clip org-table-clip)
6634 (line (count-lines (point-min) (point)))
6635 (col (org-table-current-column))
6636 (org-enable-table-editor t)
6637 (org-table-automatic-realign nil)
6639 (while (setq cols (pop clip))
6640 (while (org-at-table-hline-p) (beginning-of-line 2))
6641 (if (not (org-at-table-p))
6642 (progn (end-of-line 0) (org-table-next-field)))
6644 (while (setq field (pop cols))
6645 (org-table-goto-column c nil 'force)
6646 (org-table-get-field nil field)
6648 (beginning-of-line 2))
6650 (org-table-goto-column col)
6653 (defun org-table-convert ()
6654 "Convert from `org-mode' table to table.el and back.
6655 Obviously, this only works within limits. When an Org-mode table is
6656 converted to table.el, all horizontal separator lines get lost, because
6657 table.el uses these as cell boundaries and has no notion of horizontal lines.
6658 A table.el table can be converted to an Org-mode table only if it does not
6659 do row or column spanning. Multiline cells will become multiple cells.
6660 Beware, Org-mode does not test if the table can be successfully converted - it
6661 blindly applies a recipe that works for simple tables."
6664 (if (org-at-table.el-p)
6665 ;; convert to Org-mode table
6666 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6667 (end (move-marker (make-marker) (org-table-end t))))
6668 (table-unrecognize-region beg end)
6670 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6673 (if (org-at-table-p)
6674 ;; convert to table.el table
6675 (let ((beg (move-marker (make-marker) (org-table-begin)))
6676 (end (move-marker (make-marker) (org-table-end))))
6677 ;; first, get rid of all horizontal lines
6679 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6681 ;; insert a hline before first
6683 (org-table-insert-hline 'above)
6684 ;; insert a hline after each line
6685 (while (progn (beginning-of-line 2) (< (point) end))
6686 (org-table-insert-hline))
6688 (setq end (move-marker end (org-table-end)))
6689 ;; replace "+" at beginning and ending of hlines
6690 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6691 (replace-match "\\1+-"))
6693 (while (re-search-forward "-|[ \t]*$" end t)
6694 (replace-match "-+"))
6697 (defun org-table-wrap-region (arg)
6698 "Wrap several fields in a column like a paragraph.
6699 This is useful if you'd like to spread the contents of a field over several
6700 lines, in order to keep the table compact.
6702 If there is an active region, and both point and mark are in the same column,
6703 the text in the column is wrapped to minimum width for the given number of
6704 lines. Generally, this makes the table more compact. A prefix ARG may be
6705 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6706 formats the selected text to two lines. If the region was longer than 2
6707 lines, the remaining lines remain empty. A negative prefix argument reduces
6708 the current number of lines by that amount. The wrapped text is pasted back
6709 into the table. If you formatted it to more lines than it was before, fields
6710 further down in the table get overwritten - so you might need to make space in
6713 If there is no region, the current field is split at the cursor position and
6714 the text fragment to the right of the cursor is prepended to the field one
6717 If there is no region, but you specify a prefix ARG, the current field gets
6718 blank, and the content is appended to the field above."
6720 (org-table-check-inside-data-field)
6721 (if (org-region-active-p)
6722 ;; There is a region: fill as a paragraph
6723 (let ((beg (region-beginning))
6725 (org-table-cut-region (region-beginning) (region-end))
6726 (if (> (length (car org-table-clip)) 1)
6727 (error "Region must be limited to single column"))
6728 (setq nlines (if arg
6730 (+ (length org-table-clip) arg)
6732 (length org-table-clip)))
6733 (setq org-table-clip
6734 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6737 (org-table-paste-rectangle))
6738 ;; No region, split the current field at point
6740 ;; combine with field above
6741 (let ((s (org-table-blank-field))
6742 (col (org-table-current-column)))
6743 (beginning-of-line 0)
6744 (while (org-at-table-hline-p) (beginning-of-line 0))
6745 (org-table-goto-column col)
6746 (skip-chars-forward "^|")
6747 (skip-chars-backward " ")
6748 (insert " " (org-trim s))
6751 (when (looking-at "\\([^|]+\\)+|")
6752 (let ((s (match-string 1)))
6753 (replace-match " |")
6754 (goto-char (match-beginning 0))
6755 (org-table-next-row)
6756 (insert (org-trim s) " ")
6757 (org-table-align))))))
6760 "Remove whitespace at beginning and end of string."
6761 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6762 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6765 (defun org-wrap (string &optional width lines)
6766 "Wrap string to either a number of lines, or a width in characters.
6767 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6768 that costs. If there is a word longer than WIDTH, the text is actually
6769 wrapped to the length of that word.
6770 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6771 many lines, whatever width that takes.
6772 The return value is a list of lines, without newlines at the end."
6773 (let* ((words (org-split-string string "[ \t\n]+"))
6774 (maxword (apply 'max (mapcar 'length words)))
6777 (org-do-wrap words (max maxword width)))
6780 (setq ll (org-do-wrap words maxword))
6781 (if (<= (length ll) lines)
6784 (while (> (length ll) lines)
6786 (setq ll (org-do-wrap words w)))
6788 (t (error "Cannot wrap this")))))
6791 (defun org-do-wrap (words width)
6792 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6795 (setq line (pop words))
6796 (while (and words (< (+ (length line) (length (car words))) width))
6797 (setq line (concat line " " (pop words))))
6798 (setq lines (push line lines)))
6801 ;; FIXME: I think I can make this more efficient
6802 (defun org-split-string (string &optional separators)
6803 "Splits STRING into substrings at SEPARATORS.
6804 No empty strings are returned if there are matches at the beginning
6806 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6810 (while (and (string-match rexp string
6812 (= start (match-beginning 0))
6813 (< start (length string)))
6815 (< (match-beginning 0) (length string)))
6817 (or (eq (match-beginning 0) 0)
6818 (and (eq (match-beginning 0) (match-end 0))
6819 (eq (match-beginning 0) start))
6821 (cons (substring string start (match-beginning 0))
6823 (setq start (match-end 0)))
6824 (or (eq start (length string))
6826 (cons (substring string start)
6830 (defun org-table-add-invisible-to-vertical-lines ()
6831 "Add an `invisible' property to vertical lines of current table."
6833 (let* ((beg (org-table-begin))
6834 (end (org-table-end))
6838 (while (< (point) end)
6839 (setq end1 (point-at-eol))
6840 (if (looking-at org-table-dataline-regexp)
6841 (while (re-search-forward "|" end1 t)
6842 (add-text-properties (1- (point)) (point)
6843 '(invisible org-table)))
6844 (while (re-search-forward "[+|]" end1 t)
6845 (add-text-properties (1- (point)) (point)
6846 '(invisible org-table))))
6847 (beginning-of-line 2)))))
6849 (defun org-table-toggle-vline-visibility (&optional arg)
6850 "Toggle the visibility of table vertical lines.
6851 The effect is immediate and on all tables in the file.
6852 With prefix ARG, make lines invisible when ARG is positive, make lines
6853 visible when ARG is not positive."
6856 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
6857 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
6858 (t (if (org-in-invisibility-spec-p '(org-table))
6861 (if (eq action 'off)
6863 (org-remove-from-invisibility-spec '(org-table))
6864 (org-table-map-tables 'org-table-align)
6865 (message "Vertical table lines visible")
6866 (if (org-at-table-p)
6868 (org-add-to-invisibility-spec '(org-table))
6869 (org-table-map-tables 'org-table-align)
6870 (message "Vertical table lines invisible"))
6871 (redraw-frame (selected-frame))))
6873 (defun org-table-map-tables (function)
6874 "Apply FUNCTION to the start of all tables in the buffer."
6878 (goto-char (point-min))
6879 (while (re-search-forward org-table-any-line-regexp nil t)
6880 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6881 (beginning-of-line 1)
6882 (if (looking-at org-table-line-regexp)
6883 (save-excursion (funcall function)))
6884 (re-search-forward org-table-any-border-regexp nil 1)))))
6886 (defun org-table-sum (&optional beg end nlast)
6887 "Sum numbers in region of current table column.
6888 The result will be displayed in the echo area, and will be available
6889 as kill to be inserted with \\[yank].
6891 If there is an active region, it is interpreted as a rectangle and all
6892 numbers in that rectangle will be summed. If there is no active
6893 region and point is located in a table column, sum all numbers in that
6896 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6897 numbers are assumed to be times as well (in decimal hours) and the
6898 numbers are added as such.
6900 If NLAST is a number, only the NLAST fields will actually be summed."
6903 (let (col (timecnt 0) diff h m s org-table-clip)
6905 ((and beg end)) ; beg and end given explicitly
6906 ((org-region-active-p)
6907 (setq beg (region-beginning) end (region-end)))
6909 (setq col (org-table-current-column))
6910 (goto-char (org-table-begin))
6911 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
6912 (error "No table data"))
6913 (org-table-goto-column col)
6914 ;not needed? (skip-chars-backward "^|")
6916 (goto-char (org-table-end))
6917 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
6918 (error "No table data"))
6919 (org-table-goto-column col)
6920 ;not needed? (skip-chars-forward "^|")
6921 (setq end (point))))
6922 (let* ((items (apply 'append (org-table-copy-region beg end)))
6923 (items1 (cond ((not nlast) items)
6924 ((>= nlast (length items)) items)
6925 (t (setq items (reverse items))
6926 (setcdr (nthcdr (1- nlast) items) nil)
6928 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
6930 (res (apply '+ numbers))
6931 (sres (if (= timecnt 0)
6933 (setq diff (* 3600 res)
6934 h (floor (/ diff 3600)) diff (mod diff 3600)
6935 m (floor (/ diff 60)) diff (mod diff 60)
6937 (format "%d:%02d:%02d" h m s))))
6940 (message (substitute-command-keys
6941 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
6942 (length numbers) sres))))
6945 (defun org-table-get-number-for-summing (s)
6947 (if (string-match "^ *|? *" s)
6948 (setq s (replace-match "" nil nil s)))
6949 (if (string-match " *|? *$" s)
6950 (setq s (replace-match "" nil nil s)))
6951 (setq n (string-to-number s))
6953 ((and (string-match "0" s)
6954 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
6955 ((string-match "\\`[ \t]+\\'" s) nil)
6956 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
6957 (let ((h (string-to-number (or (match-string 1 s) "0")))
6958 (m (string-to-number (or (match-string 2 s) "0")))
6959 (s (string-to-number (or (match-string 4 s) "0"))))
6960 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
6961 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
6965 (defvar org-table-formula-history nil)
6967 (defun org-table-get-formula (&optional equation)
6968 "Read a formula from the minibuffer, offer stored formula as default."
6969 (let* ((col (org-table-current-column))
6970 (stored-list (org-table-get-stored-formulas))
6971 (stored (cdr (assoc col stored-list)))
6973 ((and stored equation (string-match "^ *= *$" equation))
6978 "Formula: " (or stored "") 'org-table-formula-history
6980 (if (not (string-match "\\S-" eq))
6981 (error "Empty formula"))
6982 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
6983 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
6985 (setcdr (assoc col stored-list) eq)
6986 (setq stored-list (cons (cons col eq) stored-list)))
6987 (if (not (equal stored eq))
6988 (org-table-store-formulas stored-list))
6991 (defun org-table-store-formulas (alist)
6992 "Store the list of formulas below the current table."
6993 (setq alist (sort alist (lambda (a b) (< (car a) (car b)))))
6995 (goto-char (org-table-end))
6996 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
6997 (delete-region (point) (match-end 0)))
6999 (mapconcat (lambda (x)
7000 (concat "$" (int-to-string (car x)) "=" (cdr x)))
7004 (defun org-table-get-stored-formulas ()
7005 "Return an alist with the stored formulas directly after current table."
7007 (let (col eq eq-alist strings string)
7009 (goto-char (org-table-end))
7010 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7011 (setq strings (org-split-string (match-string 2) " *:: *"))
7012 (while (setq string (pop strings))
7013 (if (string-match "\\$\\([0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7014 (setq col (string-to-number (match-string 1 string))
7015 eq (match-string 2 string)
7016 eq-alist (cons (cons col eq) eq-alist))))))
7019 (defun org-table-modify-formulas (action &rest columns)
7020 "Modify the formulas stored below the current table.
7021 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7022 expected, for the other action only a single column number is needed."
7023 (let ((list (org-table-get-stored-formulas))
7024 (nmax (length (org-split-string (buffer-substring (point-at-bol) (point-at-eol))
7028 ((null list)) ; No action needed if there are no stored formulas
7029 ((eq action 'remove)
7030 (setq col (car columns))
7031 (org-table-replace-in-formulas list col "INVALID")
7032 (if (assoc col list) (setq list (delq (assoc col list) list)))
7033 (loop for i from (1+ col) upto nmax by 1 do
7034 (org-table-replace-in-formulas list i (1- i))
7035 (if (assoc i list) (setcar (assoc i list) (1- i)))))
7036 ((eq action 'insert)
7037 (setq col (car columns))
7038 (loop for i from nmax downto col by 1 do
7039 (org-table-replace-in-formulas list i (1+ i))
7040 (if (assoc i list) (setcar (assoc i list) (1+ i)))))
7042 (setq col1 (car columns) col2 (nth 1 columns))
7043 (org-table-replace-in-formulas list col1 "Z")
7044 (org-table-replace-in-formulas list col2 col1)
7045 (org-table-replace-in-formulas list "Z" col2)
7046 (if (assoc col1 list) (setcar (assoc col1 list) "Z"))
7047 (if (assoc col2 list) (setcar (assoc col2 list) col1))
7048 (if (assoc "Z" list) (setcar (assoc "Z" list) col2)))
7049 (t (error "Invalid action in `org-table-modify-formulas'")))
7050 (if list (org-table-store-formulas list))))
7052 (defun org-table-replace-in-formulas (list s1 s2)
7054 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7055 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7056 re (concat (regexp-quote s1) "\\>"))
7057 (while (setq elt (pop list))
7059 (while (string-match re s)
7060 (setq s (replace-match s2 t t s)))
7063 (defvar org-table-column-names nil
7064 "Alist with column names, derived from the `!' line.")
7065 (defvar org-table-column-name-regexp nil
7066 "Regular expression matching the current column names.")
7067 (defvar org-table-local-parameters nil
7068 "Alist with parameter names, derived from the `$' line.")
7070 (defun org-table-get-specials ()
7071 "Get the column names and local parameters for this table."
7073 (let ((beg (org-table-begin)) (end (org-table-end))
7074 names name fields field cnt)
7075 (setq org-table-column-names nil
7076 org-table-local-parameters nil)
7078 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7079 (setq names (org-split-string (match-string 1) " *| *")
7081 (while (setq name (pop names))
7083 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7084 (push (cons name (int-to-string cnt)) org-table-column-names))))
7085 (setq org-table-column-names (nreverse org-table-column-names))
7086 (setq org-table-column-name-regexp
7087 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7089 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7090 (setq fields (org-split-string (match-string 1) " *| *"))
7091 (while (setq field (pop fields))
7092 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\) *= *\\(.*\\)" field)
7093 (push (cons (match-string 1 field) (match-string 2 field))
7094 org-table-local-parameters)))))))
7096 (defun org-this-word ()
7097 ;; Get the current word
7099 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7100 (end (progn (skip-chars-forward "^ \t\n") (point))))
7101 (buffer-substring-no-properties beg end))))
7103 (defun org-table-maybe-eval-formula ()
7104 "Check if the current field starts with \"=\" and evaluate the formula."
7105 ;; We already know we are in a table. Get field will only return a formula
7106 ;; when appropriate. It might return a separator line, but no problem.
7107 (when org-table-formula-evaluate-inline
7108 (let* ((field (org-trim (or (org-table-get-field) "")))
7109 (dfield (downcase field))
7111 (when (equal (string-to-char field) ?=)
7112 (if (string-match "^\\(=sum[vh]?\\)\\([0-9]+\\)$" dfield)
7113 (setq nlast (1+ (string-to-number (match-string 2 dfield)))
7114 dfield (match-string 1 dfield)))
7116 ((equal dfield "=sumh")
7117 (org-table-get-field
7119 (save-excursion (org-table-goto-column 1) (point))
7121 ((member dfield '("=sum" "=sumv"))
7122 (setq col (org-table-current-column)
7123 bolpos (point-at-bol))
7124 (org-table-get-field
7127 (goto-char (org-table-begin))
7128 (if (re-search-forward org-table-dataline-regexp bolpos t)
7130 (goto-char (match-beginning 0))
7131 (org-table-goto-column col)
7133 (error "No datalines above current")))
7135 ((and (string-match "^ *=" field)
7136 (fboundp 'calc-eval))
7137 (org-table-eval-formula nil field)))))))
7139 (defvar org-last-recalc-undo-list nil)
7140 (defcustom org-table-allow-line-recalculation t
7145 (defvar org-recalc-commands nil
7146 "List of commands triggering the recalculation of a line.
7147 Will be filled automatically during use.")
7149 (defvar org-recalc-marks
7150 '((" " . "Unmarked: no special line, no automatic recalculation")
7151 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7152 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7153 ("!" . "Column name definition line. Reference in formula as $name.")
7154 ("$" . "Parameter definition line name=value. Reference in formula as $name.")))
7156 (defun org-table-rotate-recalc-marks (&optional newchar)
7157 "Rotate the recalculation mark in the first column.
7158 If in any row, the first field is not consistent with a mark,
7159 insert a new column for the makers.
7160 When there is an active region, change all the lines in the region,
7161 after prompting for the marking character.
7162 After each change, a message will be displayed indication the meaning
7165 (unless (org-at-table-p) (error "Not at a table"))
7166 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7167 (beg (org-table-begin))
7168 (end (org-table-end))
7169 (l (org-current-line))
7170 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7171 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7175 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*| \t][^|]*|" end t))))
7176 (col (org-table-current-column))
7177 (forcenew (car (assoc newchar org-recalc-marks)))
7179 (if l1 (setq newchar (char-to-string (read-char-exclusive "Change region to what mark? Type # * ! $ or SPC: "))
7180 forcenew (car (assoc newchar org-recalc-marks))))
7181 (if (and newchar (not forcenew))
7182 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7184 (if l1 (goto-line l1))
7186 (beginning-of-line 1)
7187 (unless (looking-at org-table-dataline-regexp)
7188 (error "Not at a table data line")))
7190 (org-table-goto-column 1)
7191 (org-table-insert-column)
7192 (org-table-goto-column (1+ col)))
7193 (setq epos (point-at-eol))
7195 (beginning-of-line 1)
7196 (org-table-get-field
7197 1 (if (looking-at "^[ \t]*| *\\([#!$* ]\\) *|")
7199 (setq new (or forcenew
7200 (cadr (member (match-string 1) marks))))
7206 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7207 (and (looking-at org-table-dataline-regexp)
7208 (org-table-get-field 1 (concat " " new " "))))
7210 (if (not (= epos (point-at-eol))) (org-table-align))
7212 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7214 (defun org-table-maybe-recalculate-line ()
7215 "Recompute the current line if marked for it, and if we haven't just done it."
7217 (and org-table-allow-line-recalculation
7218 (not (and (memq last-command org-recalc-commands)
7219 (equal org-last-recalc-line (org-current-line))))
7220 (save-excursion (beginning-of-line 1)
7221 (looking-at org-table-auto-recalculate-regexp))
7222 (fboundp 'calc-eval)
7223 (org-table-recalculate) t))
7225 (defvar org-table-formula-debug nil
7226 "Non-nil means, debug table formulas.
7227 When nil, simply write \"#ERROR\" in corrupted fields.")
7230 (defsubst org-set-calc-mode (var value)
7231 (setcar (or (cdr (memq var modes)) (cons nil nil)) value))
7233 (defun org-table-eval-formula (&optional ndown equation
7234 suppress-align suppress-const
7236 "Replace the table field value at the cursor by the result of a calculation.
7238 This function makes use of Dave Gillespie's calc package, in my view the
7239 most exciting program ever written for GNU Emacs. So you need to have calc
7240 installed in order to use this function.
7242 In a table, this command replaces the value in the current field with the
7243 result of a formula. While nowhere near the computation options of a
7244 spreadsheet program, this is still very useful. There is no automatic
7245 updating of a calculated field, but the table will remember the last
7246 formula for each column. The command needs to be applied again after
7247 changing input fields.
7249 When called, the command first prompts for a formula, which is read in the
7250 minibuffer. Previously entered formulas are available through the history
7251 list, and the last used formula for each column is offered as a default.
7252 These stored formulas are adapted correctly when moving, inserting, or
7253 deleting columns with the corresponding commands.
7255 The formula can be any algebraic expression understood by the calc package.
7256 Before evaluation, variable substitution takes place: \"$\" is replaced by
7257 the field the cursor is currently in, and $1..$n reference the fields in
7258 the current row. Values from a *different* row can *not* be referenced
7259 here, so the command supports only horizontal computing. The formula can
7260 contain an optional printf format specifier after a semicolon, to reformat
7263 A few examples for formulas:
7264 $1+$2 Sum of first and second field
7265 $1+$2;%.2f Same, and format result to two digits after dec.point
7266 exp($2)+exp($1) Math functions can be used
7267 $;%.1f Reformat current cell to 1 digit after dec.point
7268 ($3-32)*5/9 Degrees F -> C conversion
7270 When called with a raw \\[universal-argument] prefix, the formula is applied to the current
7271 field, and to the same same column in all following rows, until reaching a
7272 horizontal line or the end of the table. When the command is called with a
7273 numeric prefix argument (like M-3 or C-7 or \\[universal-argument] 24), the formula is applied
7274 to the current row, and to the following n-1 rows (but not beyond a
7277 This function can also be called from Lisp programs and offers two additional
7278 Arguments: EQUATION can be the formula to apply. If this argument is given,
7279 the user will not be prompted. SUPPRESS-ALIGN is used to speed-up
7280 recursive calls by by-passing unnecessary aligns. SUPPRESS-CONST suppresses
7281 the interpretation of constants in the formula. SUPPRESS-STORE means the
7282 formula should not be stored, either because it is already stored, or because
7283 it is a modified equation that should not overwrite the stored one."
7285 (setq ndown (if (equal ndown '(4)) 10000 (prefix-numeric-value ndown)))
7287 (org-table-check-inside-data-field)
7288 (org-table-get-specials)
7290 (org-table-automatic-realign nil)
7291 (case-fold-search nil)
7293 (formula (if (and equation suppress-store)
7295 (org-table-get-formula equation)))
7296 (n0 (org-table-current-column))
7297 (modes (copy-sequence org-calc-default-modes))
7298 n form fmt x ev orig c)
7300 (if (string-match ";" formula)
7301 (let ((tmp (org-split-string formula ";")))
7302 (setq formula (car tmp) fmt (or (nth 1 tmp) ""))
7303 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
7304 (setq c (string-to-char (match-string 1 fmt))
7305 n (string-to-number (or (match-string 1 fmt) "")))
7306 (if (= c ?p) (org-set-calc-mode 'calc-internal-prec n)
7307 (org-set-calc-mode 'calc-float-format
7308 (list (cdr (assoc c '((?n. float) (?f. fix)
7309 (?s. sci) (?e. eng))))
7311 (setq fmt (replace-match "" t t fmt)))
7312 (when (string-match "[DR]" fmt)
7313 (org-set-calc-mode 'calc-angle-mode
7314 (if (equal (match-string 0 fmt) "D")
7316 (setq fmt (replace-match "" t t fmt)))
7317 (when (string-match "F" fmt)
7318 (org-set-calc-mode 'calc-prefer-frac t)
7319 (setq fmt (replace-match "" t t fmt)))
7320 (when (string-match "S" fmt)
7321 (org-set-calc-mode 'calc-symbolic-mode t)
7322 (setq fmt (replace-match "" t t fmt)))
7323 (unless (string-match "\\S-" fmt)
7325 (if (and (not suppress-const) org-table-formula-use-constants)
7326 (setq formula (org-table-formula-substitute-names formula)))
7327 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7329 (setq fields (org-split-string
7331 (point-at-bol) (point-at-eol)) " *| *"))
7332 (if org-table-formula-numbers-only
7333 (setq fields (mapcar
7334 (lambda (x) (number-to-string (string-to-number x)))
7336 (setq ndown (1- ndown))
7337 (setq form (copy-sequence formula))
7338 (while (string-match "\\$\\([0-9]+\\)?" form)
7339 (setq n (if (match-beginning 1)
7340 (string-to-int (match-string 1 form))
7342 x (nth (1- n) fields))
7343 (unless x (error "Invalid field specifier \"%s\""
7344 (match-string 0 form)))
7345 (if (equal x "") (setq x "0"))
7346 (setq form (replace-match (concat "(" x ")") t t form)))
7347 (setq ev (calc-eval (cons form modes)
7348 (if org-table-formula-numbers-only 'num)))
7350 (when org-table-formula-debug
7351 (with-output-to-temp-buffer "*Help*"
7352 (princ (format "Substitution history of formula
7355 $1-> %s\n" orig formula form))
7357 (princ (format " %s^\nError: %s"
7358 (make-string (car ev) ?\-) (nth 1 ev)))
7359 (princ (format "Result: %s" ev))))
7360 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7361 (unless (and (interactive-p) (not ndown))
7362 (unless (let (inhibit-redisplay)
7363 (y-or-n-p "Debugging Formula. Continue to next? "))
7366 (delete-window (get-buffer-window "*Help*"))
7369 (setq fmt nil ev "#ERROR"))
7370 (org-table-blank-field)
7372 (insert (format fmt (string-to-number ev)))
7374 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7375 (call-interactively 'org-return)
7377 (or suppress-align (org-table-align))))
7379 (defun org-table-recalculate (&optional all noalign)
7380 "Recalculate the current table line by applying all stored formulas."
7382 (or (memq this-command org-recalc-commands)
7383 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7384 (unless (org-at-table-p) (error "Not at a table"))
7385 (org-table-get-specials)
7386 (let* ((eqlist (sort (org-table-get-stored-formulas)
7387 (lambda (a b) (< (car a) (car b)))))
7388 (inhibit-redisplay t)
7389 (line-re org-table-dataline-regexp)
7390 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7391 (thiscol (org-table-current-column))
7392 beg end entry eql (cnt 0))
7393 ;; Insert constants in all formulas
7396 (setcdr x (org-table-formula-substitute-names (cdr x)))
7401 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7402 (goto-char (setq beg (org-table-begin)))
7403 (if (re-search-forward org-table-recalculate-regexp end t)
7404 (setq line-re org-table-recalculate-regexp)
7405 (if (and (re-search-forward org-table-dataline-regexp end t)
7406 (re-search-forward org-table-hline-regexp end t)
7407 (re-search-forward org-table-dataline-regexp end t))
7408 (setq beg (match-beginning 0))
7409 nil))) ;; just leave beg where it is
7410 (setq beg (point-at-bol)
7411 end (move-marker (make-marker) (1+ (point-at-eol)))))
7413 (and all (message "Re-applying formulas to full table..."))
7414 (while (re-search-forward line-re end t)
7415 (unless (string-match "^ *[!$] *$" (org-table-get-field 1))
7416 ;; Unprotected line, recalculate
7417 (and all (message "Re-applying formulas to full table...(line %d)"
7418 (setq cnt (1+ cnt))))
7419 (setq org-last-recalc-line (org-current-line))
7421 (while (setq entry (pop eql))
7422 (goto-line org-last-recalc-line)
7423 (org-table-goto-column (car entry) nil 'force)
7424 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7425 (goto-line thisline)
7426 (org-table-goto-column thiscol)
7427 (or noalign (org-table-align)
7428 (and all (message "Re-applying formulas to %d lines...done" cnt)))))
7430 (defun org-table-formula-substitute-names (f)
7431 "Replace $const with values in string F."
7432 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7433 ;; First, check for column names
7434 (while (setq start (string-match org-table-column-name-regexp f start))
7435 (setq start (1+ start))
7436 (setq a (assoc (match-string 1 f) org-table-column-names))
7437 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7438 ;; Expand ranges to vectors
7439 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7440 (setq n1 (string-to-number (match-string 1 f))
7441 n2 (string-to-number (match-string 2 f))
7442 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7443 s (concat "[($" (number-to-string (1- nn1)) ")"))
7444 (loop for i from nn1 upto nn2 do
7445 (setq s (concat s ",($" (int-to-string i) ")")))
7446 (setq s (concat s "]"))
7447 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7448 (setq f (replace-match s t t f)))
7449 ;; Parameters and constants
7451 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7452 (setq start (1+ start))
7453 (if (setq a (save-match-data
7454 (org-table-get-constant (match-string 1 f))))
7455 (setq f (replace-match (concat "(" a ")") t t f))))
7456 (if org-table-formula-debug
7457 (put-text-property 0 (length f) :orig-formula f1 f))
7460 (defun org-table-get-constant (const)
7461 "Find the value for a parameter or constant in a formula.
7462 Parameters get priority."
7463 (or (cdr (assoc const org-table-local-parameters))
7464 (cdr (assoc const org-table-formula-constants))
7465 (and (fboundp 'constants-get) (constants-get const))
7468 ;;; The orgtbl minor mode
7470 ;; Define a minor mode which can be used in other modes in order to
7471 ;; integrate the org-mode table editor.
7473 ;; This is really a hack, because the org-mode table editor uses several
7474 ;; keys which normally belong to the major mode, for example the TAB and
7475 ;; RET keys. Here is how it works: The minor mode defines all the keys
7476 ;; necessary to operate the table editor, but wraps the commands into a
7477 ;; function which tests if the cursor is currently inside a table. If that
7478 ;; is the case, the table editor command is executed. However, when any of
7479 ;; those keys is used outside a table, the function uses `key-binding' to
7480 ;; look up if the key has an associated command in another currently active
7481 ;; keymap (minor modes, major mode, global), and executes that command.
7482 ;; There might be problems if any of the keys used by the table editor is
7483 ;; otherwise used as a prefix key.
7485 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7486 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7487 ;; addresses this by checking explicitly for both bindings.
7489 ;; The optimized version (see variable `orgtbl-optimized') takes over
7490 ;; all keys which are bound to `self-insert-command' in the *global map*.
7491 ;; Some modes bind other commands to simple characters, for example
7492 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7493 ;; active, this binding is ignored inside tables and replaced with a
7494 ;; modified self-insert.
7496 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
7497 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
7498 In the optimized version, the table editor takes over all simple keys that
7499 normally just insert a character. In tables, the characters are inserted
7500 in a way to minimize disturbing the table structure (i.e. in overwrite mode
7501 for empty fields). Outside tables, the correct binding of the keys is
7504 The default for this option is t if the optimized version is also used in
7505 Org-mode. See the variable `org-enable-table-editor' for details. Changing
7506 this variable requires a restart of Emacs to become effective."
7510 (defvar orgtbl-mode nil
7511 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7512 table editor in arbitrary modes.")
7513 (make-variable-buffer-local 'orgtbl-mode)
7515 (defvar orgtbl-mode-map (make-sparse-keymap)
7516 "Keymap for `orgtbl-mode'.")
7519 (defun turn-on-orgtbl ()
7520 "Unconditionally turn on `orgtbl-mode'."
7524 (defun orgtbl-mode (&optional arg)
7525 "The `org-mode' table editor as a minor mode for use in other modes."
7527 (if (eq major-mode 'org-mode)
7528 ;; Exit without error, in case some hook functions calls this
7529 ;; by accident in org-mode.
7530 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7532 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7535 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7536 ;; Make sure we are first in minor-mode-map-alist
7537 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7538 (and c (setq minor-mode-map-alist
7539 (cons c (delq c minor-mode-map-alist)))))
7540 (set (make-local-variable (quote org-table-may-need-update)) t)
7541 (make-local-hook (quote before-change-functions))
7542 (add-hook 'before-change-functions 'org-before-change-function
7544 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
7545 auto-fill-inhibit-regexp)
7546 (set (make-local-variable 'auto-fill-inhibit-regexp)
7547 (if auto-fill-inhibit-regexp
7548 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7550 (easy-menu-add orgtbl-mode-menu)
7551 (run-hooks 'orgtbl-mode-hook))
7552 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7553 (remove-hook 'before-change-functions 'org-before-change-function t)
7554 (easy-menu-remove orgtbl-mode-menu)
7555 (force-mode-line-update 'all))))
7557 ;; Install it as a minor mode.
7558 (put 'orgtbl-mode :included t)
7559 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7560 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7562 (defun orgtbl-make-binding (fun n &rest keys)
7563 "Create a function for binding in the table minor mode.
7564 FUN is the command to call inside a table. N is used to create a unique
7565 command name. KEYS are keys that should be checked in for a command
7566 to execute outside of tables."
7569 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7571 (concat "In tables, run `" (symbol-name fun) "'.\n"
7572 "Outside of tables, run the binding of `"
7573 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7578 (list 'call-interactively (list 'quote fun))
7579 (list 'let '(orgtbl-mode)
7580 (list 'call-interactively
7583 (list 'key-binding k))
7585 '('orgtbl-error))))))))
7587 (defun orgtbl-error ()
7588 "Error when there is no default binding for a table key."
7590 (error "This key has no function outside tables"))
7592 (defun orgtbl-setup ()
7593 "Setup orgtbl keymaps."
7597 '([(meta shift left)] org-table-delete-column)
7598 '([(meta left)] org-table-move-column-left)
7599 '([(meta right)] org-table-move-column-right)
7600 '([(meta shift right)] org-table-insert-column)
7601 '([(meta shift up)] org-table-kill-row)
7602 '([(meta shift down)] org-table-insert-row)
7603 '([(meta up)] org-table-move-row-up)
7604 '([(meta down)] org-table-move-row-down)
7605 '("\C-c\C-w" org-table-cut-region)
7606 '("\C-c\M-w" org-table-copy-region)
7607 '("\C-c\C-y" org-table-paste-rectangle)
7608 '("\C-c-" org-table-insert-hline)
7609 '([(shift tab)] org-table-previous-field)
7610 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7611 '("\C-m" org-table-next-row)
7612 (list (org-key 'S-return) 'org-table-copy-down)
7613 '([(meta return)] org-table-wrap-region)
7614 '("\C-c\C-q" org-table-wrap-region)
7615 '("\C-c?" org-table-current-column)
7616 '("\C-c " org-table-blank-field)
7617 '("\C-c+" org-table-sum)
7618 '("\C-c|" org-table-toggle-vline-visibility)
7619 '("\C-c=" org-table-eval-formula)
7620 '("\C-c*" org-table-recalculate)
7621 '([(control ?#)] org-table-rotate-recalc-marks)))
7623 (while (setq elt (pop bindings))
7624 (setq nfunc (1+ nfunc))
7627 cmd (orgtbl-make-binding fun nfunc key))
7628 (define-key orgtbl-mode-map key cmd))
7629 ;; Special treatment needed for TAB and RET
7630 (define-key orgtbl-mode-map [(return)]
7631 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
7632 (define-key orgtbl-mode-map "\C-m"
7633 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
7634 (define-key orgtbl-mode-map [(tab)]
7635 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
7636 (define-key orgtbl-mode-map "\C-i"
7637 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
7638 (when orgtbl-optimized
7639 ;; If the user wants maximum table support, we need to hijack
7640 ;; some standard editing functions
7641 (substitute-key-definition 'self-insert-command 'orgtbl-self-insert-command
7642 orgtbl-mode-map global-map)
7643 (substitute-key-definition 'delete-char 'orgtbl-delete-char
7644 orgtbl-mode-map global-map)
7645 (substitute-key-definition 'delete-backward-char 'orgtbl-delete-backward-char
7646 orgtbl-mode-map global-map)
7647 (define-key org-mode-map "|" 'self-insert-command))
7648 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
7650 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
7651 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
7652 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
7653 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
7655 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
7656 ["Copy Field from Above"
7657 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
7660 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
7661 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
7662 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
7663 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
7665 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
7666 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
7667 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
7668 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
7670 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
7672 ["Copy Rectangle" org-copy-special :active (org-at-table-p) :keys "C-c M-w"]
7673 ["Cut Rectangle" org-cut-special :active (org-at-table-p) :keys "C-c C-w"]
7674 ["Paste Rectangle" org-paste-special :active (org-at-table-p) :keys "C-c C-y"]
7675 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p) :keys "C-c C-q"])
7677 ["Eval Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
7678 ["Eval Formula Down " (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
7679 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
7680 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
7681 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
7682 ["Sum Column/Rectangle" org-table-sum
7683 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
7684 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
7686 (setq org-table-formula-debug (not org-table-formula-debug))
7687 :style toggle :selected org-table-formula-debug]
7691 (defun orgtbl-tab ()
7692 "Justification and field motion for `orgtbl-mode'."
7694 (org-table-justify-field-maybe)
7695 (org-table-next-field))
7697 (defun orgtbl-ret ()
7698 "Justification and field motion for `orgtbl-mode'."
7700 (org-table-justify-field-maybe)
7701 (org-table-next-row))
7703 (defun orgtbl-self-insert-command (N)
7704 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
7705 If the cursor is in a table looking at whitespace, the whitespace is
7706 overwritten, and the table is not marked as requiring realignment."
7708 (if (and (org-at-table-p)
7710 (looking-at "[^|\n]* +|"))
7711 (let (org-table-may-need-update)
7712 (goto-char (1- (match-end 0)))
7713 (delete-backward-char 1)
7714 (goto-char (match-beginning 0))
7715 (self-insert-command N))
7716 (setq org-table-may-need-update t)
7718 (call-interactively (key-binding (vector last-input-event))))))
7720 (defun orgtbl-delete-backward-char (N)
7721 "Like `delete-backward-char', insert whitespace at field end in tables.
7722 When deleting backwards, in tables this function will insert whitespace in
7723 front of the next \"|\" separator, to keep the table aligned. The table will
7724 still be marked for re-alignment, because a narrow field may lead to a
7725 reduced column width."
7727 (if (and (org-at-table-p)
7729 (string-match "|" (buffer-substring (point-at-bol) (point)))
7730 (looking-at ".*?|"))
7731 (let ((pos (point)))
7732 (backward-delete-char N)
7733 (skip-chars-forward "^|")
7735 (goto-char (1- pos)))
7736 (delete-backward-char N)))
7738 (defun orgtbl-delete-char (N)
7739 "Like `delete-char', but insert whitespace at field end in tables.
7740 When deleting characters, in tables this function will insert whitespace in
7741 front of the next \"|\" separator, to keep the table aligned. The table
7742 will still be marked for re-alignment, because a narrow field may lead to
7743 a reduced column width."
7745 (if (and (org-at-table-p)
7747 (not (= (char-after) ?|))
7749 (if (looking-at ".*?|")
7750 (let ((pos (point)))
7751 (replace-match (concat
7752 (substring (match-string 0) 1 -1)
7759 (defconst org-level-max 20)
7761 (defun org-export-find-first-heading-line (list)
7762 "Remove all lines from LIST which are before the first headline."
7763 (let ((orig-list list)
7764 (re (concat "^" outline-regexp)))
7766 (not (string-match re (car list))))
7768 (or list orig-list)))
7770 (defun org-skip-comments (lines)
7771 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
7772 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
7773 (re2 "^\\(\\*+\\)[ \t\n\r]")
7775 (while (setq line (pop lines))
7777 ((and (string-match re1 line)
7778 (setq level (- (match-end 1) (match-beginning 1))))
7779 ;; Beginning of a COMMENT subtree. Skip it.
7780 (while (and (setq line (pop lines))
7781 (or (not (string-match re2 line))
7782 (> (- (match-end 1) (match-beginning 1)) level))))
7783 (setq lines (cons line lines)))
7784 ((string-match "^#" line)
7785 ;; an ordinary comment line
7787 (t (setq rtn (cons line rtn)))))
7792 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
7793 "Characters for underlining headings in ASCII export.")
7795 (defconst org-html-entities
7835 ("Aring") ("AA"."Å")
7924 ("varepsilon"."ε")
7937 ("sigmaf") ("varsigma"."ς")
7945 ("thetasym") ("vartheta"."ϑ")
7948 ("bull") ("bullet"."•")
7949 ("hellip") ("dots"."…")
7959 ("larr") ("leftarrow"."←") ("gets"."←")
7960 ("uarr") ("uparrow"."↑")
7961 ("rarr") ("to"."→") ("rightarrow"."→")
7962 ("darr")("downarrow"."↓")
7963 ("harr") ("leftrightarrow"."↔")
7964 ("crarr") ("hookleftarrow"."↵") ; has round hook, not quite CR
7965 ("lArr") ("Leftarrow"."⇐")
7966 ("uArr") ("Uparrow"."⇑")
7967 ("rArr") ("Rightarrow"."⇒")
7968 ("dArr") ("Downarrow"."⇓")
7969 ("hArr") ("Leftrightarrow"."⇔")
7971 ("part") ("partial"."∂")
7972 ("exist") ("exists"."∃")
7973 ("empty") ("emptyset"."∅")
7975 ("isin") ("in"."∈")
7981 ("lowast") ("ast"."∗")
7983 ("prop") ("proptp"."∝")
7984 ("infin") ("infty"."∞")
7985 ("ang") ("angle"."∠")
7986 ("and") ("vee"."∧")
7987 ("or") ("wedge"."∨")
7993 ("cong") ("simeq"."≅")
7994 ("asymp")("approx"."≈")
7995 ("ne") ("neq"."≠")
7999 ("sub") ("subset"."⊂")
8000 ("sup") ("supset"."⊃")
8007 ("sdot") ("cdot"."⋅")
8014 ("loz") ("Diamond"."◊")
8015 ("spades") ("spadesuit"."♠")
8016 ("clubs") ("clubsuit"."♣")
8017 ("hearts") ("diamondsuit"."♥")
8018 ("diams") ("diamondsuit"."♦")
8085 "Entities for TeX->HTML translation.
8086 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
8087 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
8088 In that case, \"\\ent\" will be translated to \"&other;\".
8089 The list contains HTML entities for Latin-1, Greek and other symbols.
8090 It is supplemented by a number of commonly used TeX macros with appropriate
8091 translations. There is currently no way for users to extend this.")
8093 (defvar org-last-level nil) ; dynamically scoped variable
8095 (defun org-export-as-ascii (arg)
8096 "Export the outline as a pretty ASCII file.
8097 If there is an active region, export only the region.
8098 The prefix ARG specifies how many levels of the outline should become
8099 underlined headlines. The default is 3."
8101 (setq-default org-todo-line-regexp org-todo-line-regexp)
8104 (if (org-region-active-p) (region-beginning) (point-min))
8105 (if (org-region-active-p) (region-end) (point-max))))
8106 (lines (org-export-find-first-heading-line
8107 (org-skip-comments (org-split-string region "[\r\n]"))))
8108 (org-startup-with-deadline-check nil)
8111 (case-fold-search nil)
8112 (filename (concat (file-name-sans-extension (buffer-file-name))
8114 (buffer (find-file-noselect filename))
8115 (levels-open (make-vector org-level-max nil))
8116 (date (format-time-string "%Y/%m/%d" (current-time)))
8117 (time (format-time-string "%X" (current-time)))
8118 (author user-full-name)
8119 (title (buffer-name))
8121 (email user-mail-address)
8122 (language org-export-default-language)
8127 (setq org-last-level 1)
8128 (org-init-section-numbers)
8130 (find-file-noselect filename)
8132 ;; Search for the export key lines
8133 (org-parse-key-lines)
8135 (setq lang-words (or (assoc language org-export-language-setup)
8136 (assoc "en" org-export-language-setup)))
8137 (if org-export-ascii-show-new-buffer
8138 (switch-to-buffer-other-window buffer)
8139 (set-buffer buffer))
8142 (if options (org-parse-export-options options))
8143 (setq umax (if arg (prefix-numeric-value arg)
8144 org-export-headline-levels))
8147 (if title (org-insert-centered title ?=))
8149 (if (or author email)
8150 (insert (concat (nth 1 lang-words) ": " (or author "")
8151 (if email (concat " <" email ">") "")
8154 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
8155 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
8159 (if org-export-with-toc
8161 (insert (nth 3 lang-words) "\n"
8162 (make-string (length (nth 3 lang-words)) ?=) "\n")
8163 (mapcar '(lambda (line)
8164 (if (string-match org-todo-line-regexp
8166 ;; This is a headline
8168 (setq level (- (match-end 1) (match-beginning 1))
8169 txt (match-string 3 line)
8171 (or (and (match-beginning 2)
8172 (not (equal (match-string 2 line)
8176 (org-search-todo-below
8177 line lines level))))
8178 (setq txt (org-html-expand-for-ascii txt))
8180 (if org-export-with-section-numbers
8181 (setq txt (concat (org-section-number level)
8186 (make-string (* (1- level) 4) ?\ )
8187 (format (if todo "%s (*)\n" "%s\n") txt))
8188 (setq org-last-level level))
8192 (org-init-section-numbers)
8193 (while (setq line (pop lines))
8194 ;; Remove the quoted HTML tags.
8195 (setq line (org-html-expand-for-ascii line))
8197 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8199 (setq level (- (match-end 1) (match-beginning 1))
8200 txt (match-string 2 line))
8201 (org-ascii-level-start level txt umax))
8202 (t (insert line "\n"))))
8205 (goto-char (point-min))))
8207 (defun org-search-todo-below (line lines level)
8208 "Search the subtree below LINE for any TODO entries."
8209 (let ((rest (cdr (memq line lines)))
8210 (re org-todo-line-regexp)
8213 (while (setq line (pop rest))
8214 (if (string-match re line)
8216 (setq lv (- (match-end 1) (match-beginning 1))
8217 todo (and (match-beginning 2)
8218 (not (equal (match-string 2 line)
8221 (if (<= lv level) (throw 'exit nil))
8222 (if todo (throw 'exit t))))))))
8224 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
8225 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
8226 (defun org-html-expand-for-ascii (line)
8227 "Handle quoted HTML for ASCII export."
8228 (if org-export-html-expand
8229 (while (string-match "@<[^<>\n]*>" line)
8230 ;; We just remove the tags for now.
8231 (setq line (replace-match "" nil nil line))))
8234 (defun org-insert-centered (s &optional underline)
8235 "Insert the string S centered and underline it with character UNDERLINE."
8236 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
8237 (insert (make-string ind ?\ ) s "\n")
8239 (insert (make-string ind ?\ )
8240 (make-string (length s) underline)
8243 (defun org-ascii-level-start (level title umax)
8244 "Insert a new level in ASCII export."
8247 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
8248 (if (or (not (equal (char-before) ?\n))
8249 (not (equal (char-before (1- (point))) ?\n)))
8251 (setq char (nth (- umax level) (reverse org-ascii-underline)))
8252 (if org-export-with-section-numbers
8253 (setq title (concat (org-section-number level) " " title)))
8254 (insert title "\n" (make-string (string-width title) char) "\n"))))
8256 (defun org-export-copy-visible ()
8257 "Copy the visible part of the buffer to another buffer, for printing.
8258 Also removes the first line of the buffer if it specifies a mode,
8259 and all options lines."
8261 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
8263 (buffer (find-file-noselect filename))
8265 (org-make-options-regexp
8266 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
8268 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
8269 (if org-noutline-p "\\(\n\\|$\\)" "")))
8271 (with-current-buffer buffer
8275 (setq s (goto-char (point-min)))
8276 (while (not (= (point) (point-max)))
8277 (goto-char (org-find-invisible))
8278 (append-to-buffer buffer s (point))
8279 (setq s (goto-char (org-find-visible)))))
8280 (switch-to-buffer-other-window buffer)
8282 (goto-char (point-min))
8283 (if (looking-at ".*-\\*- mode:.*\n")
8285 (while (re-search-forward ore nil t)
8287 (goto-char (point-min))))
8289 (defun org-find-visible ()
8290 (if (featurep 'noutline)
8292 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8293 (get-char-property s 'invisible)))
8295 (skip-chars-forward "^\n")
8297 (defun org-find-invisible ()
8298 (if (featurep 'noutline)
8300 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8301 (not (get-char-property s 'invisible))))
8303 (skip-chars-forward "^\r")
8308 (defun org-get-current-options ()
8309 "Return a string with current options as keyword options.
8310 Does include HTML export options as well as TODO and CATEGORY stuff."
8316 #+TEXT: Some descriptive text to be emitted. Several lines OK.
8317 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
8324 (buffer-name) (user-full-name) user-mail-address org-export-default-language
8325 org-export-headline-levels
8326 org-export-with-section-numbers
8328 org-export-preserve-breaks
8329 org-export-html-expand
8330 org-export-with-fixed-width
8331 org-export-with-tables
8332 org-export-with-sub-superscripts
8333 org-export-with-emphasize
8334 org-export-with-TeX-macros
8335 (file-name-nondirectory (buffer-file-name))
8336 (if (equal org-todo-interpretation 'sequence)
8337 (mapconcat 'identity org-todo-keywords " ")
8338 "TODO FEEDBACK VERIFY DONE")
8339 (if (equal org-todo-interpretation 'type)
8340 (mapconcat 'identity org-todo-keywords " ")
8341 "Me Jason Marie DONE")
8342 (cdr (assoc org-startup-folded
8343 '((nil . "nofold")(t . "fold")(content . "content"))))
8344 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
8345 org-archive-location
8348 (defun org-insert-export-options-template ()
8349 "Insert into the buffer a template with information for exporting."
8351 (if (not (bolp)) (newline))
8352 (let ((s (org-get-current-options)))
8353 (and (string-match "#\\+CATEGORY" s)
8354 (setq s (substring s 0 (match-beginning 0))))
8357 (defun org-toggle-fixed-width-section (arg)
8358 "Toggle the fixed-width indicator at the beginning of lines in the region.
8359 If there is no active region, only acts on the current line.
8360 If the first non-white character in the first line of the region is a
8361 vertical bar \"|\", then the command removes the bar from all lines in
8362 the region. If the first character is not a bar, the command adds a
8363 bar to all lines, in the column given by the beginning of the region.
8365 If there is a numerical prefix ARG, create ARG new lines starting with \"|\"."
8368 (regionp (org-region-active-p))
8369 (beg (if regionp (region-beginning) (point)))
8370 (end (if regionp (region-end)))
8371 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
8372 (re "[ \t]*\\(:\\)")
8376 (setq cc (current-column))
8377 (beginning-of-line 1)
8378 (setq off (looking-at re))
8380 (setq nlines (1- nlines))
8381 (beginning-of-line 1)
8384 (move-to-column cc t)
8387 ((and off (looking-at re))
8388 (replace-match "" t t nil 1))
8389 ((not off) (move-to-column cc t) (insert ":")))
8390 (forward-line 1)))))
8392 (defun org-export-as-html-and-open (arg)
8393 "Export the outline as HTML and immediately open it with a browser.
8394 If there is an active region, export only the region.
8395 The prefix ARG specifies how many levels of the outline should become
8396 headlines. The default is 3. Lower levels will become bulleted lists."
8398 (org-export-as-html arg 'hidden)
8399 (org-open-file (buffer-file-name)))
8401 (defun org-export-as-html-batch ()
8402 "Call `org-export-as-html', may be used in batch processing as
8404 --load=$HOME/lib/emacs/org.el
8405 --eval \"(setq org-export-headline-levels 2)\"
8406 --visit=MyFile --funcall org-export-as-html-batch"
8407 (org-export-as-html org-export-headline-levels 'hidden))
8409 (defun org-export-as-html (arg &optional hidden)
8410 "Export the outline as a pretty HTML file.
8411 If there is an active region, export only the region.
8412 The prefix ARG specifies how many levels of the outline should become
8413 headlines. The default is 3. Lower levels will become bulleted lists."
8415 (setq-default org-todo-line-regexp org-todo-line-regexp)
8416 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
8417 (setq-default org-done-string org-done-string)
8418 (let* ((region-p (org-region-active-p))
8421 (if region-p (region-beginning) (point-min))
8422 (if region-p (region-end) (point-max))))
8424 (org-skip-comments (org-split-string region "[\r\n]")))
8425 (lines (org-export-find-first-heading-line all_lines))
8426 (level 0) (line "") (origline "") txt todo
8428 (filename (concat (file-name-sans-extension (buffer-file-name))
8430 (buffer (find-file-noselect filename))
8431 (levels-open (make-vector org-level-max nil))
8432 (date (format-time-string "%Y/%m/%d" (current-time)))
8433 (time (format-time-string "%X" (current-time)))
8434 (author user-full-name)
8435 (title (buffer-name))
8437 (email user-mail-address)
8438 (language org-export-default-language)
8444 table-buffer table-orig-buffer
8446 (message "Exporting...")
8448 (setq org-last-level 1)
8449 (org-init-section-numbers)
8451 ;; Search for the export key lines
8452 (org-parse-key-lines)
8453 (setq lang-words (or (assoc language org-export-language-setup)
8454 (assoc "en" org-export-language-setup)))
8456 ;; Switch to the output buffer
8457 (if (or hidden (not org-export-html-show-new-buffer))
8459 (switch-to-buffer-other-window buffer))
8462 (let ((case-fold-search nil))
8463 (if options (org-parse-export-options options))
8464 (setq umax (if arg (prefix-numeric-value arg)
8465 org-export-headline-levels))
8469 "<html lang=\"%s\"><head>
8471 <meta http-equiv=\"Content-Type\" content=\"text/html\">
8472 <meta name=generator content=\"Org-mode\">
8473 <meta name=generated content=\"%s %s\">
8474 <meta name=author content=\"%s\">
8477 language (org-html-expand title) date time author))
8478 (if title (insert (concat "<H1 align=\"center\">"
8479 (org-html-expand title) "</H1>\n")))
8480 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
8481 (if email (insert (concat "<a href=\"mailto:" email "\"><"
8482 email "></a>\n")))
8483 (if (or author email) (insert "<br>\n"))
8484 (if (and date time) (insert (concat (nth 2 lang-words) ": "
8485 date " " time "<br>\n")))
8486 (if text (insert (concat "<p>\n" (org-html-expand text))))
8487 (if org-export-with-toc
8489 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
8491 (mapcar '(lambda (line)
8492 (if (string-match org-todo-line-regexp line)
8493 ;; This is a headline
8495 (setq level (- (match-end 1) (match-beginning 1))
8496 txt (save-match-data
8498 (match-string 3 line)))
8500 (or (and (match-beginning 2)
8501 (not (equal (match-string 2 line)
8505 (org-search-todo-below
8506 line lines level))))
8507 (if org-export-with-section-numbers
8508 (setq txt (concat (org-section-number level)
8512 (setq head-count (+ head-count 1))
8513 (if (> level org-last-level)
8515 (setq cnt (- level org-last-level))
8516 (while (>= (setq cnt (1- cnt)) 0)
8519 (if (< level org-last-level)
8521 (setq cnt (- org-last-level level))
8522 (while (>= (setq cnt (1- cnt)) 0)
8528 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
8529 "<li><a href=\"#sec-%d\">%s</a></li>\n")
8531 (setq org-last-level level))
8534 (while (> org-last-level 0)
8535 (setq org-last-level (1- org-last-level))
8539 (org-init-section-numbers)
8540 (while (setq line (pop lines) origline line)
8541 ;; Protect the links
8543 (while (string-match org-link-maybe-angles-regexp line start)
8544 (setq start (match-end 0))
8545 (setq line (replace-match
8546 (concat "\000" (match-string 1 line) "\000")
8549 ;; replace "<" and ">" by "<" and ">"
8550 ;; handle @<..> HTML tags (replace "@>..<" by "<..>")
8551 (setq line (org-html-expand line))
8554 (if (and org-export-with-fixed-width
8555 (string-match "^[ \t]*:\\(.*\\)" line))
8557 (let ((l (match-string 1 line)))
8558 (while (string-match " " l)
8559 (setq l (replace-match " " t t l)))
8560 (insert "\n<span style='font-family:Courier'>"
8563 (not (string-match "^[ \t]+\\(:.*\\)"
8567 (while (string-match org-protected-link-regexp line start)
8568 (setq start (- (match-end 0) 2))
8569 (setq type (match-string 1 line))
8571 ((member type '("http" "https" "ftp" "mailto" "news"))
8573 (setq line (replace-match
8574 ; "<a href=\"\\1:\\2\"><\\1:\\2></a>"
8575 "<a href=\"\\1:\\2\">\\1:\\2</a>"
8577 ((string= type "file")
8579 (let* ((filename (match-string 2 line))
8580 (abs-p (file-name-absolute-p filename))
8581 (thefile (if abs-p (expand-file-name filename) filename))
8582 (thefile (save-match-data
8583 (if (string-match ":[0-9]+$" thefile)
8584 (replace-match "" t t thefile)
8588 (string-match (org-image-file-name-regexp) thefile))))
8589 (setq line (replace-match
8590 (if (and org-export-html-inline-images
8592 (concat "<img src=\"" thefile "\"/>")
8593 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
8596 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
8597 (setq line (replace-match
8598 "<i><\\1:\\2></i>" nil nil line)))))
8601 (if (and (string-match org-todo-line-regexp line)
8602 (match-beginning 2))
8603 (if (equal (match-string 2 line) org-done-string)
8604 (setq line (replace-match
8605 "<span style='color:green'>\\2</span>"
8607 (setq line (replace-match "<span style='color:red'>\\2</span>"
8611 (if (string-match org-deadline-line-regexp line)
8613 (if (save-match-data
8614 (string-match "<a href"
8615 (substring line 0 (match-beginning 0))))
8616 nil ; Don't do the replacement - it is inside a link
8617 (setq line (replace-match "<span style='color:red'>\\&</span>"
8621 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8622 ;; This is a headline
8623 (setq level (- (match-end 1) (match-beginning 1))
8624 txt (match-string 2 line))
8625 (if (<= level umax) (setq head-count (+ head-count 1)))
8626 (org-html-level-start level txt umax
8627 (and org-export-with-toc (<= level umax))
8630 ((and org-export-with-tables
8631 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
8632 (if (not table-open)
8634 (setq table-open t table-buffer nil table-orig-buffer nil))
8636 (setq table-buffer (cons line table-buffer)
8637 table-orig-buffer (cons origline table-orig-buffer))
8638 (when (or (not lines)
8639 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
8641 (setq table-open nil
8642 table-buffer (nreverse table-buffer)
8643 table-orig-buffer (nreverse table-orig-buffer))
8644 (insert (org-format-table-html table-buffer table-orig-buffer))))
8647 ;; Lines starting with "-", and empty lines make new paragraph.
8648 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
8649 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
8651 (if org-export-html-with-timestamp
8652 (insert org-export-html-html-helper-timestamp))
8653 (insert "</body>\n</html>\n")
8656 (goto-char (point-min)))))
8658 (defun org-format-table-html (lines olines)
8659 "Find out which HTML converter to use and return the HTML code."
8660 (if (string-match "^[ \t]*|" (car lines))
8661 ;; A normal org table
8662 (org-format-org-table-html lines)
8663 ;; Table made by table.el - test for spanning
8664 (let* ((hlines (delq nil (mapcar
8666 (if (string-match "^[ \t]*\\+-" x) x
8669 (first (car hlines))
8670 (ll (and (string-match "\\S-+" first)
8671 (match-string 0 first)))
8672 (re (concat "^[ \t]*" (regexp-quote ll)))
8673 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
8675 (if (and (not spanning)
8676 (not org-export-prefer-native-exporter-for-tables))
8677 ;; We can use my own converter with HTML conversions
8678 (org-format-table-table-html lines)
8679 ;; Need to use the code generator in table.el, with the original text.
8680 (org-format-table-table-html-using-table-generate-source olines)))))
8682 (defun org-format-org-table-html (lines)
8683 "Format a table into HTML."
8684 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
8685 (setq lines (nreverse lines))
8686 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
8687 (setq lines (nreverse lines))
8688 (let ((head (and org-export-highlight-first-table-line
8690 (lambda (x) (string-match "^[ \t]*|-" x))
8693 (setq html (concat org-export-html-table-tag "\n"))
8694 (while (setq line (pop lines))
8696 (if (string-match "^[ \t]*|-" line)
8698 (setq head nil) ;; head ends here, first time around
8700 (throw 'next-line t)))
8701 ;; Break the line into fields
8702 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
8706 (mapconcat (lambda (x)
8708 (concat "<th>" x "</th>")
8709 (concat "<td valign=\"top\">" x "</td>")))
8712 (setq html (concat html "</table>\n"))
8715 (defun org-fake-empty-table-line (line)
8716 "Replace everything except \"|\" with spaces."
8717 (let ((i (length line))
8718 (newstr (copy-sequence line)))
8721 (if (not (eq (aref newstr i) ?|))
8722 (aset newstr i ?\ )))
8725 (defun org-format-table-table-html (lines)
8726 "Format a table generated by table.el into HTML.
8727 This conversion does *not* use `table-generate-source' from table.el.
8728 This has the advantage that Org-mode's HTML conversions can be used.
8729 But it has the disadvantage, that no cell- or row-spanning is allowed."
8730 (let (line field-buffer
8731 (head org-export-highlight-first-table-line)
8733 (setq html (concat org-export-html-table-tag "\n"))
8734 (while (setq line (pop lines))
8735 (setq empty " ")
8737 (if (string-match "^[ \t]*\\+-" line)
8746 (if (equal x "") (setq x empty))
8748 (concat "<th valign=\"top\">" x
8750 (concat "<td valign=\"top\">" x
8755 (setq field-buffer nil)))
8757 (throw 'next-line t)))
8758 ;; Break the line into fields and store the fields
8759 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
8761 (setq field-buffer (mapcar
8763 (concat x "<br>" (pop fields)))
8765 (setq field-buffer fields))))
8766 (setq html (concat html "</table>\n"))
8769 (defun org-format-table-table-html-using-table-generate-source (lines)
8770 "Format a table into HTML, using `table-generate-source' from table.el.
8771 This has the advantage that cell- or row-spanning is allowed.
8772 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
8774 (with-current-buffer (get-buffer-create " org-tmp1 ")
8776 (insert (mapconcat 'identity lines "\n"))
8777 (goto-char (point-min))
8778 (if (not (re-search-forward "|[^+]" nil t))
8779 (error "Error processing table"))
8780 (table-recognize-table)
8781 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
8782 (table-generate-source 'html " org-tmp2 ")
8783 (set-buffer " org-tmp2 ")
8784 (buffer-substring (point-min) (point-max))))
8786 (defun org-html-expand (string)
8787 "Prepare STRING for HTML export. Applies all active conversions."
8788 ;; First check if there is a link in the line - if yes, apply conversions
8789 ;; only before the start of the link.
8790 (let* ((m (string-match org-link-regexp string))
8791 (s (if m (substring string 0 m) string))
8792 (r (if m (substring string m) "")))
8793 ;; convert < to < and > to >
8794 (while (string-match "<" s)
8795 (setq s (replace-match "<" t t s)))
8796 (while (string-match ">" s)
8797 (setq s (replace-match ">" t t s)))
8798 (if org-export-html-expand
8799 (while (string-match "@<\\([^&]*\\)>" s)
8800 (setq s (replace-match "<\\1>" nil nil s))))
8801 (if org-export-with-emphasize
8802 (setq s (org-export-html-convert-emphasize s)))
8803 (if org-export-with-sub-superscripts
8804 (setq s (org-export-html-convert-sub-super s)))
8805 (if org-export-with-TeX-macros
8806 (let ((start 0) wd ass)
8807 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
8808 (setq wd (match-string 1 s))
8809 (if (setq ass (assoc wd org-html-entities))
8810 (setq s (replace-match (or (cdr ass)
8811 (concat "&" (car ass) ";"))
8813 (setq start (+ start (length wd)))))))
8816 (defun org-create-multibrace-regexp (left right n)
8817 "Create a regular expression which will match a balanced sexp.
8818 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
8819 as single character strings.
8820 The regexp returned will match the entire expression including the
8821 delimiters. It will also define a single group which contains the
8822 match except for the outermost delimiters. The maximum depth of
8823 stacked delimiters is N. Escaping delimiters is not possible."
8824 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
8827 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
8830 re (concat re or next)
8831 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
8832 (concat left "\\(" re "\\)" right)))
8834 (defvar org-match-substring-regexp
8836 "\\([^\\]\\)\\([_^]\\)\\("
8837 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
8839 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
8841 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
8842 "The regular expression matching a sub- or superscript.")
8844 (defun org-export-html-convert-sub-super (string)
8845 "Convert sub- and superscripts in STRING to HTML."
8847 (while (string-match org-match-substring-regexp string)
8848 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
8849 (setq c (or (match-string 8 string)
8850 (match-string 6 string)
8851 (match-string 5 string)))
8852 (setq string (replace-match
8853 (concat (match-string 1 string)
8854 "<" key ">" c "</" key ">")
8856 (while (string-match "\\\\\\([_^]\\)" string)
8857 (setq string (replace-match (match-string 1 string) t t string))))
8860 (defun org-export-html-convert-emphasize (string)
8861 (while (string-match
8862 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
8864 (setq string (replace-match
8865 (concat "<b>" (match-string 3 string) "</b>")
8867 (while (string-match
8868 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
8870 (setq string (replace-match
8871 (concat "<i>" (match-string 3 string) "</i>")
8873 (while (string-match
8874 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
8876 (setq string (replace-match
8877 (concat "<u>" (match-string 3 string) "</u>")
8881 (defun org-parse-key-lines ()
8882 "Find the special key lines with the information for exporters."
8885 (let ((re (org-make-options-regexp
8886 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
8888 (while (re-search-forward re nil t)
8889 (setq key (match-string 1))
8890 (cond ((string-equal key "TITLE")
8891 (setq title (match-string 2)))
8892 ((string-equal key "AUTHOR")
8893 (setq author (match-string 2)))
8894 ((string-equal key "EMAIL")
8895 (setq email (match-string 2)))
8896 ((string-equal key "LANGUAGE")
8897 (setq language (match-string 2)))
8898 ((string-equal key "TEXT")
8899 (setq text (concat text "\n" (match-string 2))))
8900 ((string-equal key "OPTIONS")
8901 (setq options (match-string 2))))))))
8903 (defun org-parse-export-options (s)
8904 "Parse the export options line."
8905 (let ((op '(("H" . org-export-headline-levels)
8906 ("num" . org-export-with-section-numbers)
8907 ("toc" . org-export-with-toc)
8908 ("\\n" . org-export-preserve-breaks)
8909 ("@" . org-export-html-expand)
8910 (":" . org-export-with-fixed-width)
8911 ("|" . org-export-with-tables)
8912 ("^" . org-export-with-sub-superscripts)
8913 ("*" . org-export-with-emphasize)
8914 ("TeX" . org-export-with-TeX-macros)))
8916 (while (setq o (pop op))
8917 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
8919 (set (make-local-variable (cdr o))
8920 (car (read-from-string (match-string 1 s))))))))
8922 (defun org-html-level-start (level title umax with-toc head-count)
8923 "Insert a new level in HTML export."
8924 (let ((l (1+ (max level umax))))
8925 (while (<= l org-level-max)
8926 (if (aref levels-open (1- l))
8928 (org-html-level-close l)
8929 (aset levels-open (1- l) nil)))
8933 (if (aref levels-open (1- level))
8934 (insert "<li>" title "<p>\n")
8935 (aset levels-open (1- level) t)
8936 (insert "<ul><li>" title "<p>\n")))
8937 (if org-export-with-section-numbers
8938 (setq title (concat (org-section-number level) " " title)))
8939 (setq level (+ level 1))
8941 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
8942 level head-count title level))
8943 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
8945 (defun org-html-level-close (&rest args)
8946 "Terminate one level in HTML export."
8950 ;; Variable holding the vector with section numbers
8951 (defvar org-section-numbers (make-vector org-level-max 0))
8953 (defun org-init-section-numbers ()
8954 "Initialize the vector for the section numbers."
8956 (numbers (nreverse (org-split-string "" "\\.")))
8957 (depth (1- (length org-section-numbers)))
8958 (i depth) number-string)
8961 (aset org-section-numbers i 0)
8962 (setq number-string (or (car numbers) "0"))
8963 (if (string-match "\\`[A-Z]\\'" number-string)
8964 (aset org-section-numbers i
8965 (- (string-to-char number-string) ?A -1))
8966 (aset org-section-numbers i (string-to-int number-string)))
8970 (defun org-section-number (&optional level)
8971 "Return a string with the current section number.
8972 When LEVEL is non-nil, increase section numbers on that level."
8973 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
8976 (aset org-section-numbers
8977 level (1+ (aref org-section-numbers level))))
8978 (setq idx (1+ level))
8979 (while (<= idx depth)
8981 (aset org-section-numbers idx 0))
8982 (setq idx (1+ idx))))
8984 (while (<= idx depth)
8985 (setq n (aref org-section-numbers idx))
8986 (setq string (concat string (if (not (string= string "")) "." "")
8988 (setq idx (1+ idx)))
8990 (if (string-match "\\`\\([@0]\\.\\)+" string)
8991 (setq string (replace-match "" nil nil string)))
8992 (if (string-match "\\(\\.0\\)+\\'" string)
8993 (setq string (replace-match "" nil nil string))))
8999 ;; - Bindings in Org-mode map are currently
9000 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
9001 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
9002 ;; e (?) useful from outline-mode
9003 ;; i k @ expendable from outline-mode
9004 ;; 0123456789 ! %^& ()_{} " `' free
9006 (define-key org-mode-map "\C-i" 'org-cycle)
9007 (define-key org-mode-map [(meta tab)] 'org-complete)
9008 (define-key org-mode-map "\M-\C-i" 'org-complete)
9009 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
9010 (define-key org-mode-map [(meta left)] 'org-metaleft)
9011 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
9012 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
9013 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
9014 (define-key org-mode-map [(meta right)] 'org-metaright)
9015 (define-key org-mode-map [(meta up)] 'org-metaup)
9016 (define-key org-mode-map [(meta down)] 'org-metadown)
9017 ;(define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-subtree)
9018 ;(define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-subtree)
9019 ;(define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-subtree)
9020 (define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-special)
9021 (define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-special)
9022 (define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-special)
9023 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
9024 (define-key org-mode-map "\C-c\C-j" 'org-goto)
9025 (define-key org-mode-map "\C-c\C-t" 'org-todo)
9026 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
9027 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
9028 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
9029 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
9030 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
9031 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
9032 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
9033 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
9034 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
9035 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
9036 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
9037 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
9038 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
9039 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
9040 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
9041 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
9042 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
9043 (define-key org-mode-map "\C-c[" 'org-add-file)
9044 (define-key org-mode-map "\C-c]" 'org-remove-file)
9045 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
9046 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
9047 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
9048 (define-key org-mode-map (org-key 'S-left) 'org-timestamp-down-day)
9049 (define-key org-mode-map (org-key 'S-right) 'org-timestamp-up-day)
9050 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
9051 ;; The following line is e.g. necessary for German keyboards under Suse Linux
9052 (unless org-xemacs-p
9053 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
9054 (define-key org-mode-map [(shift tab)] 'org-shifttab)
9055 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
9056 (define-key org-mode-map "\C-m" 'org-return)
9057 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
9058 (define-key org-mode-map [(meta return)] 'org-meta-return)
9059 (define-key org-mode-map "\C-c?" 'org-table-current-column)
9060 (define-key org-mode-map "\C-c " 'org-table-blank-field)
9061 (define-key org-mode-map "\C-c+" 'org-table-sum)
9062 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
9063 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
9064 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
9065 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
9066 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
9067 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
9068 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
9069 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
9070 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
9071 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
9072 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
9073 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
9074 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
9075 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
9076 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
9077 (define-key org-mode-map "\C-c\C-x\C-h" 'org-export-as-html-and-open)
9079 (defsubst org-table-p () (org-at-table-p))
9081 (defun org-self-insert-command (N)
9082 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9083 If the cursor is in a table looking at whitespace, the whitespace is
9084 overwritten, and the table is not marked as requiring realignment."
9086 (if (and (org-table-p)
9088 (looking-at "[^|\n]* +|"))
9089 (let (org-table-may-need-update)
9090 (goto-char (1- (match-end 0)))
9091 (delete-backward-char 1)
9092 (goto-char (match-beginning 0))
9093 (self-insert-command N))
9094 (setq org-table-may-need-update t)
9095 (self-insert-command N)))
9098 ;; The following two functions might still be optimized to trigger
9099 ;; re-alignment less frequently.
9101 (defun org-delete-backward-char (N)
9102 "Like `delete-backward-char', insert whitespace at field end in tables.
9103 When deleting backwards, in tables this function will insert whitespace in
9104 front of the next \"|\" separator, to keep the table aligned. The table will
9105 still be marked for re-alignment, because a narrow field may lead to a
9106 reduced column width."
9108 (if (and (org-table-p)
9110 (string-match "|" (buffer-substring (point-at-bol) (point)))
9111 (looking-at ".*?|"))
9112 (let ((pos (point)))
9113 (backward-delete-char N)
9114 (skip-chars-forward "^|")
9116 (goto-char (1- pos)))
9117 (backward-delete-char N)))
9119 (defun org-delete-char (N)
9120 "Like `delete-char', but insert whitespace at field end in tables.
9121 When deleting characters, in tables this function will insert whitespace in
9122 front of the next \"|\" separator, to keep the table aligned. The table
9123 will still be marked for re-alignment, because a narrow field may lead to
9124 a reduced column width."
9126 (if (and (org-table-p)
9128 (not (= (char-after) ?|))
9130 (if (looking-at ".*?|")
9131 (let ((pos (point)))
9132 (replace-match (concat
9133 (substring (match-string 0) 1 -1)
9138 ;; How to do this: Measure non-white length of current string
9139 ;; If equal to column width, we should realign.
9141 (when (eq org-enable-table-editor 'optimized)
9142 ;; If the user wants maximum table support, we need to hijack
9143 ;; some standard editing functions
9144 (substitute-key-definition 'self-insert-command 'org-self-insert-command
9145 org-mode-map global-map)
9146 (substitute-key-definition 'delete-char 'org-delete-char
9147 org-mode-map global-map)
9148 (substitute-key-definition 'delete-backward-char 'org-delete-backward-char
9149 org-mode-map global-map)
9150 (define-key org-mode-map "|" 'self-insert-command))
9152 (defun org-shiftcursor-error ()
9153 "Throw an error because Shift-Cursor command was applied in wrong context."
9154 (error "This command is only active in tables and on headlines"))
9156 (defun org-shifttab ()
9157 "Call `(org-cycle t)' or `org-table-previous-field'."
9160 ((org-at-table-p) (org-table-previous-field))
9161 (t (org-cycle '(4)))))
9163 (defun org-shiftmetaleft ()
9164 "Call `org-promote-subtree' or `org-table-delete-column'."
9167 ((org-at-table-p) (org-table-delete-column))
9168 ((org-on-heading-p) (org-promote-subtree))
9169 (t (org-shiftcursor-error))))
9171 (defun org-shiftmetaright ()
9172 "Call `org-demote-subtree' or `org-table-insert-column'."
9175 ((org-at-table-p) (org-table-insert-column))
9176 ((org-on-heading-p) (org-demote-subtree))
9177 (t (org-shiftcursor-error))))
9179 (defun org-shiftmetaup (&optional arg)
9180 "Call `org-move-subtree-up' or `org-table-kill-row'."
9183 ((org-at-table-p) (org-table-kill-row))
9184 ((org-on-heading-p) (org-move-subtree-up arg))
9185 (t (org-shiftcursor-error))))
9186 (defun org-shiftmetadown (&optional arg)
9187 "Call `org-move-subtree-down' or `org-table-insert-row'."
9190 ((org-at-table-p) (org-table-insert-row arg))
9191 ((org-on-heading-p) (org-move-subtree-down arg))
9192 (t (org-shiftcursor-error))))
9194 (defun org-metaleft (&optional arg)
9195 "Call `org-do-promote' or `org-table-move-column' to left."
9198 ((org-at-table-p) (org-table-move-column 'left))
9199 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
9200 (t (backward-word (prefix-numeric-value arg)))))
9202 (defun org-metaright (&optional arg)
9203 "Call `org-do-demote' or `org-table-move-column' to right."
9206 ((org-at-table-p) (org-table-move-column nil))
9207 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
9208 (t (forward-word (prefix-numeric-value arg)))))
9210 (defun org-metaup (&optional arg)
9211 "Call `org-move-subtree-up' or `org-table-move-row' up."
9214 ((org-at-table-p) (org-table-move-row 'up))
9215 ((org-on-heading-p) (org-move-subtree-up arg))
9216 (t (org-shiftcursor-error))))
9218 (defun org-metadown (&optional arg)
9219 "Call `org-move-subtree-down' or `org-table-move-row' down."
9222 ((org-at-table-p) (org-table-move-row nil))
9223 ((org-on-heading-p) (org-move-subtree-down arg))
9224 (t (org-shiftcursor-error))))
9226 (defun org-shiftup (&optional arg)
9227 "Call `org-timestamp-up' or `org-priority-up'."
9230 ((org-at-timestamp-p) (org-timestamp-up arg))
9231 (t (org-priority-up))))
9233 (defun org-shiftdown (&optional arg)
9234 "Call `org-timestamp-down' or `org-priority-down'."
9237 ((org-at-timestamp-p) (org-timestamp-down arg))
9238 (t (org-priority-down))))
9240 (defun org-copy-special ()
9241 "Call either `org-table-copy' or `org-copy-subtree'."
9244 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
9246 (defun org-cut-special ()
9247 "Call either `org-table-copy' or `org-cut-subtree'."
9250 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
9252 (defun org-paste-special (arg)
9253 "Call either `org-table-paste-rectangle' or `org-paste-subtree'."
9255 (if (org-at-table-p)
9256 (org-table-paste-rectangle)
9257 (org-paste-subtree arg)))
9259 (defun org-ctrl-c-ctrl-c (&optional arg)
9260 "Call realign table, or recognize a table.el table, or update keywords.
9261 When the cursor is inside a table created by the table.el package,
9262 activate that table. Otherwise, if the cursor is at a normal table
9263 created with org.el, re-align that table. This command works even if
9264 the automatic table editor has been turned off.
9265 If the cursor is in one of the special #+KEYWORD lines, this triggers
9266 scanning the buffer for these lines and updating the information."
9268 (let ((org-enable-table-editor t))
9270 ((org-at-table.el-p)
9272 (beginning-of-line 1)
9273 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
9274 (table-recognize-table))
9276 (org-table-maybe-eval-formula)
9278 (org-table-recalculate t)
9279 (org-table-maybe-recalculate-line))
9281 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
9283 ((equal (match-string 1) "TBLFM")
9284 ;; Recalculate the table before this line
9286 (beginning-of-line 1)
9287 (skip-chars-backward " \r\n\t")
9288 (if (org-at-table-p) (org-table-recalculate t))))
9290 (let ((org-inhibit-startup t)) (org-mode)))))
9291 ((org-region-active-p)
9292 (org-table-convert-region (region-beginning) (region-end) arg))
9293 ((and (region-beginning) (region-end))
9294 (if (y-or-n-p "Convert inactive region to table? ")
9295 (org-table-convert-region (region-beginning) (region-end) arg)
9297 (t (error "No table at point, and no region to make one")))))
9299 (defun org-return ()
9300 "Call `org-table-next-row' or `newline'."
9304 (org-table-justify-field-maybe)
9305 (org-table-next-row))
9308 (defun org-meta-return (&optional arg)
9309 "Call `org-insert-heading' or `org-table-wrap-region'."
9313 (org-table-wrap-region arg))
9314 (t (org-insert-heading))))
9318 ;; Define the Org-mode menus
9319 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
9321 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
9322 ["Next Field" org-cycle (org-at-table-p)]
9323 ["Previous Field" org-shifttab (org-at-table-p)]
9324 ["Next Row" org-return (org-at-table-p)]
9326 ["Blank Field" org-table-blank-field (org-at-table-p)]
9327 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
9330 ["Move Column Left" org-metaleft (org-at-table-p)]
9331 ["Move Column Right" org-metaright (org-at-table-p)]
9332 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
9333 ["Insert Column" org-shiftmetaright (org-at-table-p)])
9335 ["Move Row Up" org-metaup (org-at-table-p)]
9336 ["Move Row Down" org-metadown (org-at-table-p)]
9337 ["Delete Row" org-shiftmetaup (org-at-table-p)]
9338 ["Insert Row" org-shiftmetadown (org-at-table-p)]
9340 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
9342 ["Copy Rectangle" org-copy-special (org-at-table-p)]
9343 ["Cut Rectangle" org-cut-special (org-at-table-p)]
9344 ["Paste Rectangle" org-paste-special (org-at-table-p)]
9345 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
9348 ["Eval Formula" org-table-eval-formula (org-at-table-p)]
9349 ["Eval Formula Down" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9350 ["Recalculate line" org-table-recalculate (org-at-table-p)]
9351 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
9352 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
9353 ["Sum Column/Rectangle" org-table-sum
9354 (or (org-at-table-p) (org-region-active-p))]
9355 ["Which Column?" org-table-current-column (org-at-table-p)])
9357 (setq org-table-formula-debug (not org-table-formula-debug))
9358 :style toggle :selected org-table-formula-debug]
9360 ["Invisible Vlines" org-table-toggle-vline-visibility
9361 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
9363 ["Create" org-table-create (and (not (org-at-table-p))
9364 org-enable-table-editor)]
9365 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
9366 ["Import from File" org-table-import (not (org-at-table-p))]
9367 ["Export to File" org-table-export (org-at-table-p)]
9369 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
9371 (easy-menu-define org-org-menu org-mode-map "Org menu"
9373 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
9374 ["Sparse Tree" org-occur t]
9375 ["Show All" show-all t]
9377 ["New Heading" org-insert-heading t]
9378 ("Navigate Headings"
9379 ["Up" outline-up-heading t]
9380 ["Next" outline-next-visible-heading t]
9381 ["Previous" outline-previous-visible-heading t]
9382 ["Next Same Level" outline-forward-same-level t]
9383 ["Previous Same Level" outline-backward-same-level t]
9385 ["Jump" org-goto t])
9387 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
9388 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
9390 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
9391 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
9392 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
9394 ["Promote Heading" org-metaleft (not (org-at-table-p))]
9395 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
9396 ["Demote Heading" org-metaright (not (org-at-table-p))]
9397 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
9399 ["Archive Subtree" org-archive-subtree t])
9402 ["TODO/DONE/-" org-todo t]
9403 ["Show TODO Tree" org-show-todo-tree t]
9405 ["Set Priority" org-priority t]
9406 ["Priority Up" org-shiftup t]
9407 ["Priority Down" org-shiftdown t])
9408 ("Dates and Scheduling"
9409 ["Timestamp" org-time-stamp t]
9411 ["1 Day Later" org-timestamp-up-day t]
9412 ["1 Day Earlier" org-timestamp-down-day t]
9413 ["1 ... Later" org-shiftup t]
9414 ["1 ... Earlier" org-shiftdown t])
9415 ["Compute Time Range" org-evaluate-time-range t]
9416 ["Schedule Item" org-schedule t]
9417 ["Deadline" org-deadline t]
9419 ["Goto Calendar" org-goto-calendar t]
9420 ["Date from Calendar" org-date-from-calendar t])
9423 ["Show TODO Tree this File" org-show-todo-tree t]
9424 ["Check Deadlines this File" org-check-deadlines t]
9425 ["Timeline Current File" org-timeline t]
9427 ["Agenda" org-agenda t])
9428 ("File List for Agenda")
9431 ["Store Link (Global)" org-store-link t]
9432 ["Insert Link" org-insert-link t]
9433 ["Follow Link" org-open-at-point t])
9436 ["ASCII" org-export-as-ascii t]
9437 ["Extract Visible Text" org-export-copy-visible t]
9438 ["HTML" org-export-as-html t]
9439 ["HTML and Open" org-export-as-html-and-open t]
9440 ; ["OPML" org-export-as-opml nil]
9442 ["Option Template" org-insert-export-options-template t]
9443 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
9446 ["Show Version" org-version t]
9447 ["Info Documentation" org-info t])
9449 ["Browse Org Group" org-customize t]
9451 ["Build Full Customize Menu" org-create-customize-menu
9452 (fboundp 'customize-menu-create)])
9455 (defun org-info (&optional node)
9456 "Read documentation for Org-mode in the info system.
9457 With optional NODE, go directly to that node."
9460 (Info-goto-node (format "(org)%s" (or node ""))))
9462 (defun org-install-agenda-files-menu ()
9464 '("Org") "File List for Agenda"
9467 ["Edit File List" (customize-variable 'org-agenda-files) t]
9468 ["Add Current File to List" org-add-file t]
9469 ["Remove Current File from List" org-remove-file t]
9471 (mapcar 'org-file-menu-entry org-agenda-files))))
9475 (defun org-customize ()
9476 "Call the customize function with `org' as argument."
9478 (customize-browse 'org))
9480 (defun org-create-customize-menu ()
9481 "Create a full customization menu for Org-mode, insert it into the menu."
9483 (if (fboundp 'customize-menu-create)
9486 '("Org") "Customize"
9487 `(["Browse Org group" org-customize t]
9489 ,(customize-menu-create 'org)
9490 ["Set" Custom-set t]
9491 ["Save" Custom-save t]
9492 ["Reset to Current" Custom-reset-current t]
9493 ["Reset to Saved" Custom-reset-saved t]
9494 ["Reset to Standard Settings" Custom-reset-standard t]))
9495 (message "\"Org\"-menu now contains full customization menu"))
9496 (error "Cannot expand menu (outdated version of cus-edit.el)")))
9498 ;;; Miscellaneous stuff
9500 (defun org-move-line-down (arg)
9501 "Move the current line down. With prefix argument, move it past ARG lines."
9503 (let ((col (current-column))
9505 (beginning-of-line 1) (setq beg (point))
9506 (beginning-of-line 2) (setq end (point))
9507 (beginning-of-line (+ 1 arg))
9508 (setq pos (move-marker (make-marker) (point)))
9509 (insert (delete-and-extract-region beg end))
9511 (move-to-column col)))
9513 (defun org-move-line-up (arg)
9514 "Move the current line up. With prefix argument, move it past ARG lines."
9516 (let ((col (current-column))
9518 (beginning-of-line 1) (setq beg (point))
9519 (beginning-of-line 2) (setq end (point))
9520 (beginning-of-line (- arg))
9521 (setq pos (move-marker (make-marker) (point)))
9522 (insert (delete-and-extract-region beg end))
9524 (move-to-column col)))
9526 ;; Functions needed for Emacs/XEmacs region compatibility
9528 (defun org-region-active-p ()
9529 "Is `transient-mark-mode' on and the region active?
9530 Works on both Emacs and XEmacs."
9531 (if org-ignore-region
9534 (and zmacs-regions (region-active-p))
9535 (and transient-mark-mode mark-active))))
9537 (defun org-add-to-invisibility-spec (arg)
9538 "Add elements to `buffer-invisibility-spec'.
9539 See documentation for `buffer-invisibility-spec' for the kind of elements
9542 ((fboundp 'add-to-invisibility-spec)
9543 (add-to-invisibility-spec arg))
9544 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
9545 (setq buffer-invisibility-spec (list arg)))
9547 (setq buffer-invisibility-spec
9548 (cons arg buffer-invisibility-spec)))))
9550 (defun org-remove-from-invisibility-spec (arg)
9551 "Remove elements from `buffer-invisibility-spec'."
9552 (if (fboundp 'remove-from-invisibility-spec)
9553 (remove-from-invisibility-spec arg)
9554 (if (consp buffer-invisibility-spec)
9555 (setq buffer-invisibility-spec
9556 (delete arg buffer-invisibility-spec)))))
9558 (defun org-in-invisibility-spec-p (arg)
9559 "Is ARG a member of `buffer-invisibility-spec'?."
9560 (if (consp buffer-invisibility-spec)
9561 (member arg buffer-invisibility-spec)
9564 (defun org-image-file-name-regexp ()
9565 "Return regexp matching the file names of images."
9566 (if (fboundp 'image-file-name-regexp)
9567 (image-file-name-regexp)
9568 (let ((image-file-name-extensions
9569 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
9570 "xbm" "xpm" "pbm" "pgm" "ppm")))
9572 (regexp-opt (nconc (mapcar 'upcase
9573 image-file-name-extensions)
9574 image-file-name-extensions)
9578 ;; Functions needed for compatibility with old outline.el
9580 ;; The following functions capture almost the entire compatibility code
9581 ;; between the different versions of outline-mode. The only other place
9582 ;; where this is important are the font-lock-keywords. Search for
9583 ;; `org-noutline-p' to find it.
9585 ;; C-a should go to the beginning of a *visible* line, also in the
9586 ;; new outline.el. I guess this should be patched into Emacs?
9587 (defun org-beginning-of-line ()
9588 "Go to the beginning of the current line. If that is invisible, continue
9589 to a visible line beginning. This makes the function of C-a more intuitive."
9591 (beginning-of-line 1)
9595 (if (org-invisible-p)
9596 (while (and (not (bobp)) (org-invisible-p))
9598 (beginning-of-line 1))
9600 (when org-noutline-p
9601 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
9603 (defun org-invisible-p ()
9604 "Check if point is at a character currently not visible."
9606 ;; Early versions of noutline don't have `outline-invisible-p'.
9607 (if (fboundp 'outline-invisible-p)
9608 (outline-invisible-p)
9609 (get-char-property (point) 'invisible))
9611 (skip-chars-backward "^\r\n")
9612 (equal (char-before) ?\r))))
9614 (defun org-back-to-heading (&optional invisible-ok)
9615 "Move to previous heading line, or beginning of this line if it's a heading.
9616 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
9618 (outline-back-to-heading invisible-ok)
9619 (if (looking-at outline-regexp)
9621 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
9625 (progn (goto-char (match-end 1))
9626 (looking-at outline-regexp)))
9627 (error "Before first heading")))))
9629 (defun org-on-heading-p (&optional invisible-ok)
9630 "Return t if point is on a (visible) heading line.
9631 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
9633 (outline-on-heading-p 'invisible-ok)
9635 (skip-chars-backward "^\n\r")
9636 (and (looking-at outline-regexp)
9639 (equal (char-before) ?\n))))))
9641 (defun org-up-heading-all (arg)
9642 "Move to the heading line of which the present line is a subheading.
9643 This function considers both visible and invisible heading lines.
9644 With argument, move up ARG levels."
9646 (if (fboundp 'outline-up-heading-all)
9647 (outline-up-heading-all arg) ; emacs 21 version of outline.el
9648 (outline-up-heading arg t)) ; emacs 22 version of outline.el
9649 (org-back-to-heading t)
9650 (looking-at outline-regexp)
9651 (if (<= (- (match-end 0) (match-beginning 0)) arg)
9652 (error "Cannot move up %d levels" arg)
9654 (concat "[\n\r]" (regexp-quote
9655 (make-string (- (match-end 0) (match-beginning 0) arg)
9660 (defun org-show-hidden-entry ()
9661 "Show an entry where even the heading is hidden."
9663 (if (not org-noutline-p)
9665 (org-back-to-heading t)
9666 (org-flag-heading nil)))
9669 (defun org-check-occur-regexp (regexp)
9670 "If REGEXP starts with \"^\", modify it to check for \\r as well.
9671 Of course, only for the old outline mode."
9674 (if (string-match "^\\^" regexp)
9675 (concat "[\n\r]" (substring regexp 1))
9678 (defun org-flag-heading (flag &optional entry)
9679 "Flag the current heading. FLAG non-nil means make invisible.
9680 When ENTRY is non-nil, show the entire entry."
9682 (org-back-to-heading t)
9683 (if (not org-noutline-p)
9684 ;; Make the current headline visible
9685 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
9686 ;; Check if we should show the entire entry
9690 (save-excursion ;; FIXME: Is this the fix for points in the -|
9691 ;; middle of text? |
9692 (and (outline-next-heading) ;; |
9693 (org-flag-heading nil)))) ; show the next heading _|
9694 (outline-flag-region (max 1 (1- (point)))
9695 (save-excursion (outline-end-of-heading) (point))
9698 (if flag ?\r ?\n))))))
9700 (defun org-show-subtree ()
9701 "Show everything after this heading at deeper levels."
9702 (outline-flag-region
9705 (outline-end-of-subtree) (outline-next-heading) (point))
9706 (if org-noutline-p nil ?\n)))
9708 (defun org-show-entry ()
9709 "Show the body directly following this heading.
9710 Show the heading too, if it is currently invisible."
9713 (org-back-to-heading t)
9714 (outline-flag-region
9717 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
9718 (or (match-beginning 1) (point-max)))
9719 (if org-noutline-p nil ?\n))))
9722 (defun org-make-options-regexp (kwds)
9723 "Make a regular expression for keyword lines."
9725 (if org-noutline-p "^" "[\n\r]")
9727 (mapconcat 'regexp-quote kwds "\\|")
9729 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
9731 ;; Advise the bookmark-jump function to make jump position visible
9732 ;; Wrapped into eval-after-load to avoid loading advice unnecessarily
9733 (eval-after-load "bookmark"
9734 '(defadvice bookmark-jump (after org-make-visible activate)
9735 "Make the position visible."
9736 (and (eq major-mode 'org-mode)
9738 (org-show-hierarchy-above))))
9744 (run-hooks 'org-load-hook)
9746 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
9747 ;;; org.el ends here