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
35 ;; top of outline-mode - ideal to keep the content of large files well
36 ;; structured. It supports ToDo items, deadlines and time stamps, which
37 ;; magically appear in the diary listing of the Emacs calendar. Tables are
38 ;; easily created with a built-in table editor. Plain text URL-like links
39 ;; connect to websites, emails (VM,RMAIL,WANDERLUST), Usenet messages (Gnus),
40 ;; BBDB entries, and any files related to the projects. For printing and
41 ;; sharing of notes, an Org-mode file (or a part of it) can be exported as
42 ;; a structured ASCII file, or as HTML.
46 ;; The instruction below assume that you have downloaded Org-mode from the
47 ;; web. If Org-mode is part of the Emacs distribution or an XEmacs package,
48 ;; you only need to add to .emacs the last three lines of Lisp code listed
49 ;; below, i.e. the `auto-mode-alist' modification and the global key bindings.
51 ;; Byte-compile org.el and put it on your load path. Then copy the
52 ;; following lines into .emacs. The last two lines define *global*
53 ;; keys for the commands `org-store-link' and `org-agenda' - please
54 ;; choose suitable keys yourself.
56 ;; (autoload 'org-mode "org" "Org mode" t)
57 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
58 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
59 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
60 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
61 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
62 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
63 ;; (define-key global-map "\C-cl" 'org-store-link)
64 ;; (define-key global-map "\C-ca" 'org-agenda)
66 ;; This will put all files with extension ".org" into Org-mode. As an
67 ;; 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.
77 ;; The distribution also contains a PDF version of it. At the homepage
78 ;; of Org-mode, you can read the same text online as HTML.
83 ;; - "|" no longer allowed as part of a link, to allow links in tables.
84 ;; - The prefix of items in the agenda buffer can be configured.
88 ;; - Some folding incinsistencies removed.
89 ;; - BBDB links to company-only entries.
90 ;; - Bug fixes and global cleanup.
93 ;; - M-S-RET inserts a new TODO heading.
94 ;; - New startup option `content'.
95 ;; - Better visual response when TODO items in agenda change status.
96 ;; - Window positioning after visibility state changes optimized and made
97 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
100 ;; - Agenda entries from the diary are linked to the diary file, so
101 ;; adding and editing diary entries can be done directly from the agenda.
102 ;; - Many calendar/diary commands available directly from agenda.
103 ;; - Field copying in tables with S-RET does increment.
104 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
105 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
108 ;; - Table editor optimized to need fewer realignments, and to keep
109 ;; table shape when typing in fields.
110 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
111 ;; into arbitrary major modes.
112 ;; - Fixed bug with realignment in XEmacs.
113 ;; - Startup options can be set with special #+STARTUP line.
114 ;; - Heading following a match in org-occur can be suppressed.
117 ;; - Copyright transfer to the FSF.
118 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
119 ;; - Timeline now always contains today, and `.' jumps to it.
121 ;; - cut and paste of rectangular regions in tables
122 ;; - command to convert org-mode table to table.el table and back
123 ;; - command to treat several cells like a paragraph and fill it
124 ;; - command to convert a buffer region to a table
125 ;; - import/export tables as tab-separated files (exchange with Excel)
127 ;; - Sorting mechanism for agenda items rewritten from scratch.
128 ;; - Sorting fully configurable.
129 ;; - Entries specifying a time are sorted together.
130 ;; - Completion also covers option keywords after `#-'.
134 ;; - New reference card, thanks to Philip Rooke for creating it.
135 ;; - Single file agenda renamed to "Timeline". It no longer shows
136 ;; warnings about upcoming deadlines/overdue scheduled items.
137 ;; That functionality is now limited to the (multifile) agenda.
138 ;; - When reading a date, the calendar can be manipulated with keys.
139 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested)
140 ;; - Minor bug fixes and documentation improvements.
144 (eval-when-compile (require 'cl) (require 'calendar))
149 ;;; Customization variables
151 (defvar org-version "3.08"
152 "The version number of the file org.el.")
153 (defun org-version ()
155 (message "Org-mode version %s" org-version))
157 ;; The following two constants are for compatibility with different
158 ;; Emacs versions (Emacs versus XEmacs) and with different versions of
159 ;; outline.el. All the compatibility code in org.el is based on these two
161 (defconst org-xemacs-p (featurep 'xemacs)
162 "Are we running xemacs?")
163 (defconst org-noutline-p (featurep 'noutline)
164 "Are we using the new outline mode?")
167 "Outline-based notes management and organizer "
173 (defgroup org-startup nil
174 "Options concerning startup of Org-mode."
178 (defcustom org-startup-folded t
179 "Non-nil means, entering Org-mode will switch to OVERVIEW.
180 This can also be configured on a per-file basis by adding one of
181 the following lines anywhere in the buffer:
188 (const :tag "nofold: show all" nil)
189 (const :tag "fold: overview" t)
190 (const :tag "content: all headlines" content)))
192 (defcustom org-startup-truncated t
193 "Non-nil means, entering Org-mode will set `truncate-lines'.
194 This is useful since some lines containing links can be very long and
195 uninteresting. Also tables look terrible when wrapped."
199 (defcustom org-startup-with-deadline-check nil
200 "Non-nil means, entering Org-mode will run the deadline check.
201 This means, if you start editing an org file, you will get an
202 immediate reminder of any due deadlines.
203 This can also be configured on a per-file basis by adding one of
204 the following lines anywhere in the buffer:
207 #+STARTUP: nodlcheck"
211 (defcustom org-insert-mode-line-in-empty-file nil
212 "Non-nil means insert the first line setting Org-mode in empty files.
213 When the function `org-mode' is called interactively in an empty file, this
214 normally means that the file name does not automatically trigger Org-mode.
215 To ensure that the file will always be in Org-mode in the future, a
216 line enforcing Org-mode will be inserted into the buffer, if this option
221 (defgroup org-keywords nil
222 "Options concerning TODO items in Org-mode."
226 (defcustom org-todo-keywords '("TODO" "DONE")
227 "List of TODO entry keywords.
228 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
229 considered to mean that the entry is \"done\". All the other mean that
230 action is required, and will make the entry show up in todo lists, diaries
232 The command \\[org-todo] cycles an entry through these states, and an
233 additional state where no keyword is present. For details about this
234 cycling, see also the variable `org-todo-interpretation'
235 Changes become only effective after restarting Emacs."
237 :type '(repeat (string :tag "Keyword")))
239 (defcustom org-todo-interpretation 'sequence
240 "Controls how TODO keywords are interpreted.
241 \\<org-mode-map>Possible values are `sequence' and `type'.
242 This variable is only relevant if `org-todo-keywords' contains more than two
243 states. There are two ways how these keywords can be used:
245 - As a sequence in the process of working on a TODO item, for example
246 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
247 org-todo-interpretation 'sequence)
249 - As different types of TODO items, for example
250 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
251 org-todo-interpretation 'type)
253 When the states are interpreted as a sequence, \\[org-todo] always cycles
254 to the next state, in order to walk through all different states. So with
255 \\[org-todo], you turn an empty entry into the state TODO. When you started
256 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
257 later to VERIFY and finally to DONE.
259 When the states are interpreted as types, \\[org-todo] still cycles through
260 when it is called several times in direct succession, in order to initially
261 select the type. However, if not called immediately after a previous
262 \\[org-todo], it switches from each type directly to DONE. So with the
263 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
264 RELAXED. If you later return to this entry and press \\[org-todo] again,
265 RELAXED will not be changed REMIND, but directly to DONE.
267 You can create a large number of types. To initially select a
268 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
269 type with completion. Of course, you can also type the keyword
270 directly into the buffer. M-TAB completes TODO keywords at the
271 beginning of a headline."
273 :type '(choice (const sequence)
276 (defcustom org-default-priority ?B
277 "The default priority of TODO items.
278 This is the priority an item get if no explicit priority is given."
282 (defcustom org-lowest-priority ?C
283 "The lowest priority of TODO items. A character like ?A, ?B etc."
287 (defcustom org-deadline-string "DEADLINE:"
288 "String to mark deadline entries.
289 A deadline is this string, followed by a time stamp. Should be a word,
290 terminated by a colon. You can insert a schedule keyword and
291 a timestamp with \\[org-deadline].
292 Changes become only effective after restarting Emacs."
296 (defcustom org-scheduled-string "SCHEDULED:"
297 "String to mark scheduled TODO entries.
298 A schedule is this string, followed by a time stamp. Should be a word,
299 terminated by a colon. You can insert a schedule keyword and
300 a timestamp with \\[org-schedule].
301 Changes become only effective after restarting Emacs."
305 (defcustom org-comment-string "COMMENT"
306 "Entries starting with this keyword will never be exported.
307 An entry can be toggled between COMMENT and normal with
308 \\[org-toggle-comment].
309 Changes become only effective after restarting Emacs."
313 (defcustom org-after-todo-state-change-hook nil
314 "Hook which is run after the state of a TODO item was changed.
315 The new state (a string with a todo keyword, or nil) is available in the
316 Lisp variable `state'."
320 ;; Variables for pre-computed regular expressions, all buffer local
321 (defvar org-todo-kwd-priority-p nil
322 "Do TODO items have priorities?")
323 (make-variable-buffer-local 'org-todo-kwd-priority-p)
324 (defvar org-todo-kwd-max-priority nil
325 "Maximum priority of TODO items.")
326 (make-variable-buffer-local 'org-todo-kwd-max-priority)
327 (defvar org-ds-keyword-length 12
328 "Maximum length of the Deadline and SCHEDULED keywords.")
329 (make-variable-buffer-local 'org-ds-keyword-length)
330 (defvar org-done-string nil
331 "The last string in `org-todo-keywords', indicating an item is DONE.")
332 (make-variable-buffer-local 'org-done-string)
333 (defvar org-todo-regexp nil
334 "Matches any of the TODO state keywords.")
335 (make-variable-buffer-local 'org-todo-regexp)
336 (defvar org-not-done-regexp nil
337 "Matches any of the TODO state keywords except the last one.")
338 (make-variable-buffer-local 'org-not-done-regexp)
339 (defvar org-todo-line-regexp nil
340 "Matches a headline and puts TODO state into group 2 if present.")
341 (make-variable-buffer-local 'org-todo-line-regexp)
342 (defvar org-nl-done-regexp nil
343 "Matches newline followed by a headline with the DONE keyword.")
344 (make-variable-buffer-local 'org-nl-done-regexp)
345 (defvar org-looking-at-done-regexp nil
346 "Matches the DONE keyword a point.")
347 (make-variable-buffer-local 'org-looking-at-done-regexp)
348 (defvar org-deadline-regexp nil
349 "Matches the DEADLINE keyword.")
350 (make-variable-buffer-local 'org-deadline-regexp)
351 (defvar org-deadline-time-regexp nil
352 "Matches the DEADLINE keyword together with a time stamp.")
353 (make-variable-buffer-local 'org-deadline-time-regexp)
354 (defvar org-deadline-line-regexp nil
355 "Matches the DEADLINE keyword and the rest of the line.")
356 (make-variable-buffer-local 'org-deadline-line-regexp)
357 (defvar org-scheduled-regexp nil
358 "Matches the SCHEDULED keyword.")
359 (make-variable-buffer-local 'org-scheduled-regexp)
360 (defvar org-scheduled-time-regexp nil
361 "Matches the SCHEDULED keyword together with a time stamp.")
362 (make-variable-buffer-local 'org-scheduled-time-regexp)
364 (defvar org-category nil
365 "Variable used by org files to set a category for agenda display.
366 Such files should use a file variable to set it, for example
368 -*- mode: org; org-category: \"ELisp\"
370 If the file does not specify a category, the file's base name
373 (defun org-set-regexps-and-options ()
374 "Precompute regular expressions for current buffer."
375 (when (eq major-mode 'org-mode)
376 (let ((re (org-make-options-regexp
377 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO" "STARTUP")))
379 kwds int key value cat)
383 (goto-char (point-min))
384 (while (re-search-forward re nil t)
385 (setq key (match-string 1) value (match-string 2))
387 ((equal key "CATEGORY")
388 (if (string-match "[ \t]+$" value)
389 (setq value (replace-match "" t t value)))
390 (setq cat (intern value)))
391 ((equal key "SEQ_TODO")
393 kwds (append kwds (org-split-string value splitre))))
394 ((equal key "PRI_TODO")
396 kwds (append kwds (org-split-string value splitre))))
397 ((equal key "TYP_TODO")
399 kwds (append kwds (org-split-string value splitre))))
400 ((equal key "STARTUP")
401 (let ((opts (org-split-string value splitre))
402 (set '(("fold" org-startup-folded t)
403 ("nofold" org-startup-folded nil)
404 ("content" org-startup-folded content)
405 ("dlcheck" org-startup-with-deadline-check t)
406 ("nodlcheck" org-startup-with-deadline-check nil)))
408 (while (setq l (assoc (pop opts) set))
409 (setq var (nth 1 l) val (nth 2 l))
410 (set (make-local-variable var) val)))))
412 (and cat (set (make-local-variable 'org-category) cat))
413 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
414 (and int (set (make-local-variable 'org-todo-interpretation) int)))
415 ;; Compute the regular expressions and other local variables
416 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
417 org-todo-kwd-max-priority (1- (length org-todo-keywords))
418 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
419 (length org-scheduled-string)))
421 (nth (1- (length org-todo-keywords)) org-todo-keywords)
423 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
427 (mapconcat 'regexp-quote
428 (nreverse (cdr (reverse org-todo-keywords)))
432 (concat "^\\(\\*+\\)[ \t]*\\("
433 (mapconcat 'regexp-quote org-todo-keywords "\\|")
436 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
437 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
438 org-deadline-regexp (concat "\\<" org-deadline-string)
439 org-deadline-time-regexp
440 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
441 org-deadline-line-regexp
442 (concat "\\<\\(" org-deadline-string "\\).*")
444 (concat "\\<" org-scheduled-string)
445 org-scheduled-time-regexp
446 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
447 (org-set-font-lock-defaults)))
449 (defgroup org-time nil
450 "Options concerning time stamps and deadlines in Org-mode."
454 (defcustom org-deadline-warning-days 30
455 "No. of days before expiration during which a deadline becomes active.
456 This variable governs the display in the org file."
460 (defcustom org-popup-calendar-for-date-prompt t
461 "Non-nil means, pop up a calendar when prompting for a date.
462 In the calendar, the date can be selected with mouse-1. However, the
463 minibuffer will also be active, and you can simply enter the date as well.
464 When nil, only the minibuffer will be available."
468 (defcustom org-calendar-follow-timestamp-change t
469 "Non-nil means, make the calendar window follow timestamp changes.
470 When a timestamp is modified and the calendar window is visible, it will be
471 moved to the new date."
475 (defgroup org-agenda nil
476 "Options concerning agenda display Org-mode."
480 (defcustom org-agenda-files nil
481 "A list of org files for agenda/diary display.
482 Entries are added to this list with \\[org-add-file] and removed with
483 \\[org-remove-file]. You can also use customize to edit the list."
485 :type '(repeat file))
487 (defcustom org-select-timeline-window t
488 "Non-nil means, after creating a timeline, move cursor into Timeline window.
489 When nil, cursor will remain in the current window."
493 (defcustom org-select-agenda-window t
494 "Non-nil means, after creating an agenda, move cursor into Agenda window.
495 When nil, cursor will remain in the current window."
499 (defcustom org-fit-agenda-window t
500 "Non-nil means, change window size of agenda to fit content."
504 (defcustom org-agenda-show-all-dates t
505 "Non-nil means, `org-agenda' shows every day in the selected range.
506 When nil, only the days which actually have entries are shown."
510 ;; FIXME: First day of month works only for current month because it would
511 ;; require a variable ndays treatment.
512 (defcustom org-agenda-start-on-weekday 1
513 "Non-nil means, start the overview always on the specified weekday.
514 0 Denotes Sunday, 1 denotes Monday etc.
515 When nil, always start on the current day."
517 :type '(choice (const :tag "Today" nil)
518 (const :tag "First day of month" t)
519 (number :tag "Weekday No.")))
521 (defcustom org-agenda-ndays 7
522 "Number of days to include in overview display."
526 (defcustom org-agenda-include-all-todo t
527 "Non-nil means, the agenda will always contain all TODO entries.
528 When nil, date-less entries will only be shown if `org-agenda' is called
529 with a prefix argument.
530 When non-nil, the TODO entries will be listed at the top of the agenda, before
531 the entries for specific days."
535 (defcustom org-agenda-include-diary nil
536 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
540 (defcustom org-calendar-to-agenda-key [?c]
541 "The key to be installed in `calendar-mode-map' for switching to the agenda.
542 The command `org-calendar-goto-agenda' will be bound to this key. The
543 default is the character `c' because then`c' can be used to switch back and
544 force between agenda and calendar."
548 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
549 "Sorting structure for the agenda items of a single day.
550 This is a list of symbols which will be used in sequence to determine
551 if an entry should be listed before another entry. The following
552 symbols are recognized.
554 time-up Put entries with time-of-day indications first, early first
555 time-down Put entries with time-of-day indications first, late first
556 category-keep Keep the default order of categories, corresponding to the
557 sequence in `org-agenda-files'.
558 category-up Sort alphabetically by category, A-Z.
559 category-down Sort alphabetically by category, Z-A.
560 priority-up Sort numerically by priority, high priority last.
561 priority-down Sort numerically by priority, high priority first.
563 The different possibilities will be tried in sequence, and testing stops
564 if one comparison returns a \"not-equal\". For example, the default
565 '(time-up category-keep priority-down)
566 means: Pull out all entries having a specified time of day and sort them,
567 in order to make a time schedule for the current day the first thing in the
568 agenda listing for the day. Of the entries without a time indication, keep
569 the grouped in categories, don't sort the categories, but keep them in
570 the sequence given in `org-agenda-files'. Within each category sort by
573 Leaving out the `category-keep' would mean that items will be sorted across
574 categories by priority."
580 (const category-keep)
582 (const category-down)
584 (const priority-down))))
586 (defcustom org-agenda-prefix-format " %-12:c% s"
587 "Format specification for the prefix of items in the agenda buffer.
588 This format works similar to a printf format, with the following meaning:
590 %c the category of the item, \"Diary\" for entries from the diary, or
591 as given by the CATEGORY keyword or derived from the file name.
592 %t the time-of-day specification if one applies to the entry, in the
594 %s Scheduling/Deadline information, a short string
596 In addition to the normal printf field modifiers like field width and
597 padding instructions, in this format you can also add an additional
598 punctuation or whitespace character just before the final format letter.
599 This character will be appended to the field value if the value is not
600 empty. For example, the format \"%-12:c\" leads to \"Diary: \" if
601 the category is \"Diary\". If the category were be empty, no additional
602 colon would be interted.
604 Including `%t' in the format string leads to a double time specification
605 because the headline/diary item will contain the time specification as
606 well. However, using `%t' in the format will result in a canonical 24
607 hour time specification at a consistent position in the prefix, while the
608 time specification in the headline/diary item may be at any position and in
611 (setq org-agenda-prefix-format \" %-12:c% t% s\")"
615 (defcustom org-timeline-prefix-format " % s"
616 "Like `org-agenda-prefix-format', but for the timeline of a single file."
620 (defvar org-prefix-format-compiled nil
621 "The compiled version of `org-???-prefix-format'.")
623 (defcustom org-sort-agenda-notime-is-late t
624 "Non-nil means, items without time are considered late.
625 This is only relevant for sorting. When t, items which have no explicit
626 time like 15:30 will be considered as 24:01, i.e. later than any items which
627 do have a time. When nil, the default time is before 0:00."
631 (defgroup org-structure nil
632 "Options concerning structure editing in Org-mode."
636 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
637 "Hook that is run after `org-cycle' has changed the buffer visibility.
638 The function(s) in this hook must accept a single argument which indicates
639 the new state that was set by the most recent `org-cycle' command. The
640 argument is a symbol. After a global state change, it can have the values
641 `overview', `content', or `all'. After a local state change, it can have
642 the values `folded', `children', or `subtree'."
643 :group 'org-structure
646 (defcustom org-occur-hook '(org-first-headline-recenter)
647 "Hook that is run after `org-occur' has constructed a sparse tree.
648 This can be used to recenter the window to show as much of the structure
650 :group 'org-structure
653 (defcustom org-adapt-indentation t
654 "Non-nil means, adapt indentation when promoting and demoting.
655 When this is set and the *entire* text in an entry is indented, the
656 indentation is increased by one space in a demotion command, and
657 decreased by one in a promotion command. If any line in the entry
658 body starts at column 0, indentation is not changed at all."
659 :group 'org-structure
662 (defcustom org-cycle-emulate-tab t
663 "Where should `org-cycle' emulate TAB.
665 white Only in completely white lines
666 t Everywhere except in headlines"
667 :group 'org-structure
668 :type '(choice (const :tag "Never" nil)
669 (const :tag "Only in completely white lines" white)
670 (const :tag "Everywhere except in headlines" t)
673 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
674 "Formats for `format-time-string' which are used for time stamps.
675 It is not recommended to change this constant.")
677 (defcustom org-show-following-heading t
678 "Non-nil means, show heading following match in `org-occur'.
679 When doing an `org-occur' it is useful to show the headline which
680 follows the match, even if they do not match the regexp. This makes it
681 easier to edit directly inside the sparse tree. However, if you use
682 org-occur mainly as an overview, the following headlines are
683 unnecessary clutter."
684 :group 'org-structure
688 (defgroup org-link nil
689 "Options concerning links in Org-mode."
693 (defcustom org-allow-space-in-links t
694 "Non-nil means, file names in links may contain space characters.
695 When nil, it becomes possible to put several links into a line.
696 Note that in tables, a link never extends accross fields, so in a table
697 it is always possible to put several links into a line.
698 Changing this varable requires a re-launch of Emacs of become effective."
702 (defcustom org-line-numbers-in-file-links t
703 "Non-nil means, file links from `org-store-link' contain line numbers.
704 The line number will be added to the file name with :NNN and interpreted
705 by the command `org-open-at-point'.
706 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
707 negates this setting for the duration of the command."
711 (defcustom org-keep-stored-link-after-insertion nil
712 "Non-nil means, keep link in list for entire session.
714 The command `org-store-link' adds a link pointing to the current
715 location to an internal list. These links accumulate during a session.
716 The command `org-insert-link' can be used to insert links into any
717 Org-mode file (offering completion for all stored links). When this
718 option is nil, every link which has been inserted once using \\[org-insert-link]
719 will be removed from the list, to make completing the unused links
724 (defcustom org-link-frame-setup
725 '((vm . vm-visit-folder-other-frame)
726 (gnus . gnus-other-frame)
727 (file . find-file-other-window))
728 "Setup the frame configuration for following links.
729 When following a link with Emacs, it may often be useful to display
730 this link in another window or frame. This variable can be used to
731 set this up for the different types of links.
734 `vm-visit-folder-other-frame'
740 `find-file-other-window'
741 `find-file-other-frame'
742 For the calendar, use the variable `calendar-setup'.
743 For BBDB, it is currently only possible to display the matches in
749 (const vm-visit-folder)
750 (const vm-visit-folder-other-window)
751 (const vm-visit-folder-other-frame)))
755 (const gnus-other-frame)))
759 (const find-file-other-window)
760 (const find-file-other-frame)))))
762 (defcustom org-usenet-links-prefer-google nil
763 "Non-nil means, `org-store-link' will create web links to google groups.
764 When nil, Gnus will be used for such links.
765 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
766 negates this setting for the duration of the command."
770 (defcustom org-open-non-existing-files nil
771 "Non-nil means, `org-open-file' will open non-existing file.
772 When nil, an error will be generated."
776 (defcustom org-confirm-shell-links t
777 "Non-nil means, ask for confirmation before executing shell links.
778 The default is true, to keep new users from shooting into their own foot."
782 (defconst org-file-apps-defaults-linux
796 ("mpeg" . "plaympeg %s")
797 ("mp3" . "plaympeg %s")
799 ("pdf" . "acroread %s")
800 ("doc" . "soffice %s")
801 ("ppt" . "soffice %s")
802 ("pps" . "soffice %s")
803 ("html" . "netscape -remote openURL(%s,new-window)")
804 ("htm" . "netscape -remote openURL(%s,new-window)")
805 ("xs" . "soffice %s"))
806 "Default file applications on a UNIX/LINUX system.
807 See `org-file-apps'.")
809 (defconst org-file-apps-defaults-macosx
817 "Default file applications on a MacOS X system.
818 The system \"open\" is known as a default, but we use X11 applications
819 for some files for which the OS does not have a good default.
820 See `org-file-apps'.")
822 (defconst org-file-apps-defaults-windowsnt
823 '((t . (w32-shell-execute "open" file)))
824 "Default file applications on a Windows NT system.
825 The system \"open\" is used for most files.
826 See `org-file-apps'.")
828 (defcustom org-file-apps
836 "External applications for opening `file:path' items in a document.
837 Org-mode uses system defaults for different file types, but
838 you can use this variable to set the application for a given file
839 extension. The entries in this list are cons cells with a file extension
840 and the corresponding command. Possible values for the command are:
841 `emacs' The file will be visited by the current Emacs process.
842 `default' Use the default application for this file type.
843 string A command to be executed by a shell; %s will be replaced
844 by the path to the file.
845 sexp A Lisp form which will be evaluated. The file path will
846 be available in the Lisp variable `file'.
847 For more examples, see the system specific constants
848 `org-file-apps-defaults-macosx'
849 `org-file-apps-defaults-windowsnt'
850 `org-file-apps-defaults-linux'."
853 (cons (string :tag "Extension")
855 (const :tag "Visit with Emacs" 'emacs)
856 (const :tag "Use system default" 'default)
857 (string :tag "Command")
858 (sexp :tag "Lisp form")))))
861 (defgroup org-remember nil
862 "Options concerning interaction with remember.el."
866 (defcustom org-directory "~/org"
867 "Directory with org files.
868 This directory will be used as default to prompt for org files.
869 Used by the hooks for remember.el."
873 (defcustom org-default-notes-file "~/.notes"
874 "Default target for storing notes.
875 Used by the hooks for remember.el. This can be a string, or nil to mean
876 the value of `remember-data-file'."
879 (const :tag "Default from remember-data-file" nil)
882 (defcustom org-reverse-note-order nil
883 "Non-nil means, store new notes at the beginning of a file or entry.
884 When nil, new notes will be filed to the end of a file or entry."
887 (const :tag "Reverse always" t)
888 (const :tag "Reverse never" nil)
889 (repeat :tag "By file name regexp"
890 (cons regexp boolean))))
892 (defgroup org-table nil
893 "Options concerning tables in Org-mode."
897 (defcustom org-enable-table-editor 'optimized
898 "Non-nil means, lines starting with \"|\" are handled by the table editor.
899 When nil, such lines will be treated like ordinary lines.
901 When equal to the symbol `optimized', the table editor will be optimized to
903 - Use automatic overwrite mode in front of whitespace in table fields.
904 This make the structure of the table stay in tact as long as the edited
905 field does not exceed the column width.
906 - Minimize the number of realigns. Normally, the table is aligned each time
907 TAB or RET are pressed to move to another field. With optimization this
908 happens only if changes to a field might have changed the column width.
909 Optimization requires replacing the functions `self-insert-command',
910 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
911 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
912 very good at guessing when a re-align will be necessary, but you can always
913 force one with `C-c C-c'.
915 If you would like to use the optimized version in Org-mode, but the
916 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
918 This variable can be used to turn on and off the table editor during a session,
919 but in order to toggle optimization, a restart is required."
922 (const :tag "off" nil)
924 (const :tag "on, optimized" optimized)))
926 (defcustom org-table-default-size "5x2"
927 "The default size for newly created tables, Columns x Rows."
931 (defcustom org-table-automatic-realign t
932 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
933 When nil, aligning is only done with \\[org-table-align], or after column
938 (defcustom org-table-spaces-around-separators '(1 . 1)
939 "The number of spaces to be placed before and after separators."
941 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
943 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
944 "The number of spaces to be placed before and after separators.
945 This option applies when the column separators have been made invisible."
947 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
949 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
950 "Regular expression for recognizing numbers in table columns.
951 If a table column contains mostly numbers, it will be aligned to the
952 right. If not, it will be aligned to the left.
954 The default value of this option is a regular expression which allows
955 anything which looks remotely like a number as used in scientific
956 context. For example, all of the following will be considered a
958 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
960 Other options offered by the customize interface are more restrictive."
963 (const :tag "Positive Integers"
965 (const :tag "Integers"
967 (const :tag "Floating Point Numbers"
968 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
969 (const :tag "Floating Point Number or Integer"
970 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
971 (const :tag "Exponential, Floating point, Integer"
972 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
973 (const :tag "Very General Number-Like"
974 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
975 (string :tag "Regexp:")))
977 (defcustom org-table-number-fraction 0.5
978 "Fraction of numbers in a column required to make the column align right.
979 In a column all non-white fields are considered. If at least this
980 fraction of fields is matched by `org-table-number-fraction',
981 alignment to the right border applies."
985 (defcustom org-export-highlight-first-table-line t
986 "Non-nil means, highlight the first table line.
987 In HTML export, this means use <th> instead of <td>.
988 In tables created with table.el, this applies to the first table line.
989 In Org-mode tables, all lines before the first horizontal separator
990 line will be formatted with <th> tags."
994 (defcustom org-table-copy-increment t
995 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
999 (defcustom org-table-tab-recognizes-table.el t
1000 "Non-nil means, TAB will automatically notice a table.el table.
1001 When it sees such a table, it moves point into it and - if necessary -
1002 calls `table-recognize-table'."
1006 (defcustom org-export-prefer-native-exporter-for-tables nil
1007 "Non-nil means, always export tables created with table.el natively.
1008 Natively means, use the HTML code generator in table.el.
1009 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1010 the table does not use row- or column-spanning). This has the
1011 advantage, that the automatic HTML conversions for math symbols and
1012 sub/superscripts can be applied. Org-mode's HTML generator is also
1017 (defcustom org-enable-fixed-width-editor t
1018 "Non-nil means, lines starting with \":\" are treated as fixed-width.
1019 This currently only means, they are never auto-wrapped.
1020 When nil, such lines will be treated like ordinary lines."
1024 (defgroup org-export nil
1025 "Options for exporting org-listings."
1029 (defcustom org-export-language-setup
1030 '(("en" "Author" "Date" "Table of Contents")
1031 ("da" "Ophavsmand" "Dato" "Indhold")
1032 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1033 ("es" "Autor" "Fecha" "\xccndice")
1034 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1035 ("it" "Autore" "Data" "Indice")
1036 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1037 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1038 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1039 "Terms used in export text, translated to different languages.
1040 Use the variable `org-export-default-language' to set the language,
1041 or use the +OPTION lines for a per-file setting."
1045 (string :tag "HTML language tag")
1046 (string :tag "Author")
1047 (string :tag "Date")
1048 (string :tag "Table of Contents"))))
1050 (defcustom org-export-default-language "en"
1051 "The default language of HTML export, as a string.
1052 This should have an association in `org-export-language-setup'"
1056 (defcustom org-export-headline-levels 3
1057 "The last level which is still exported as a headline.
1058 Inferior levels will produce itemize lists when exported.
1059 Note that a numeric prefix argument to an exporter function overrides
1062 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1066 (defcustom org-export-with-section-numbers t
1067 "Non-nil means, add section numbers to headlines when exporting.
1069 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1073 (defcustom org-export-with-toc t
1074 "Non-nil means, create a table of contents in exported files.
1075 The TOC contains headlines with levels up to`org-export-headline-levels'.
1077 Headlines which contain any TODO items will be marked with \"(*)\" in
1078 ASCII export, and with red color in HTML output.
1080 In HTML output, the TOC will be clickable.
1082 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1086 (defcustom org-export-preserve-breaks nil
1087 "Non-nil means, preserve all line breaks when exporting.
1088 Normally, in HTML output paragraphs will be reformatted. In ASCII
1089 export, line breaks will always be preserved, regardless of this variable.
1091 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1095 (defcustom org-export-html-inline-images t
1096 "Non-nil means, inline images into exported HTML pages.
1097 The link will still be to the original location of the image file.
1098 So if you are moving the page, lets say to your public HTML site,
1099 you will have to move the image and maybe change the link."
1103 (defcustom org-export-html-expand t
1104 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1105 When nil, these tags will be exported as plain text and therefore
1106 not be interpreted by a browser.
1108 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1112 (defcustom org-export-with-fixed-width t
1113 "Non-nil means, lines starting with \":\" will be in fixed width font.
1114 This can be used to have pre-formatted text, fragments of code etc. For
1116 : ;; Some Lisp examples
1119 will be looking just like this in also HTML. In ASCII export, this option
1122 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1126 (defcustom org-export-with-tables t
1127 "If non-nil, lines starting with \"|\" define a table.
1130 | Name | Address | Birthday |
1131 |-------------+----------+-----------|
1132 | Arthur Dent | England | 29.2.2100 |
1134 In ASCII export, this option has no effect.
1136 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1140 (defcustom org-export-html-table-tag
1141 "<table border=1 cellspacing=0 cellpadding=6>"
1142 "The HTML tag used to start a table.
1143 This must be a <table> tag, but you may change the options like
1144 borders and spacing."
1148 (defcustom org-export-with-emphasize t
1149 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1150 If the export target supports emphasizing text, the word will be
1151 typeset in bold, italic, or underlined, respectively. Works only for
1152 single words, but you can say: I *really* *mean* *this*.
1153 In ASCII export, this option has no effect.
1155 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1159 (defcustom org-match-sexp-depth 3
1160 "Number of stacked braces for sub/superscript matching.
1161 This has to be set before loading org.el to be effective."
1165 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1166 (defcustom org-export-with-sub-superscripts t
1167 "Non-nil means, interpret \"_\" and \"^\" for export.
1168 When this option is turned on, you can use TeX-like syntax for sub- and
1169 superscripts. Several characters after \"_\" or \"^\" will be
1170 considered as a single item - so grouping with {} is normally not
1171 needed. For example, the following things will be parsed as single
1172 sub- or superscripts.
1174 10^24 or 10^tau several digits will be considered 1 item
1175 10^-12 or 10^-tau a leading sign with digits or a word
1176 x^2-y^3 will be read as x^2 - y^3, because items are
1177 terminated by almost any nonword/nondigit char.
1178 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1180 Still, ambiguity is possible - so when in doubt use {} to enclose the
1182 In ASCII export, this option has no effect.
1184 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1188 (defcustom org-export-with-TeX-macros t
1189 "Non-nil means, interpret simple TeX-like macros when exporting.
1190 For example, HTML export converts \\alpha to α and \\AA to Å.
1191 No only real TeX macros will work here, but the standard HTML entities
1192 for math can be used as macro names as well. For a list of supported
1193 names in HTML export, see the constant `org-html-entities'.
1194 In ASCII export, this option has no effect.
1196 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1200 (defcustom org-export-html-with-timestamp nil
1201 "If non-nil, write `org-export-html-html-helper-timestamp'
1202 into the exported html text. Otherwise, the buffer will just be saved
1207 (defcustom org-export-html-html-helper-timestamp
1208 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1209 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1213 (defcustom org-export-ascii-show-new-buffer t
1214 "Non-nil means, popup buffer containing the exported ASCII text.
1215 Otherwise the buffer will just be saved to a file and stay hidden."
1219 (defcustom org-export-html-show-new-buffer nil
1220 "Non-nil means, popup buffer containing the exported html text.
1221 Otherwise, the buffer will just be saved to a file and stay hidden."
1226 (defgroup org-faces nil
1227 "Faces for highlighting in Org-mode."
1231 (defface org-level-1-face ;; font-lock-function-name-face
1232 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1233 (((class color) (background light)) (:foreground "Blue"))
1234 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1235 (t (:inverse-video t :bold t)))
1236 "Face used for level 1 headlines."
1239 (defface org-level-2-face ;; font-lock-variable-name-face
1240 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1241 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1242 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1243 (t (:bold t :italic t)))
1244 "Face used for level 2 headlines."
1247 (defface org-level-3-face ;; font-lock-keyword-face
1248 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1249 (((class color) (background light)) (:foreground "Purple"))
1250 (((class color) (background dark)) (:foreground "Cyan"))
1252 "Face used for level 3 headlines."
1255 (defface org-level-4-face ;; font-lock-comment-face
1256 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1257 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1258 (((class color) (background light)) (:foreground "Firebrick"))
1259 (((class color) (background dark)) (:foreground "chocolate1"))
1260 (t (:bold t :italic t)))
1261 "Face used for level 4 headlines."
1264 (defface org-level-5-face ;; font-lock-type-face
1265 '((((type tty) (class color)) (:foreground "green"))
1266 (((class color) (background light)) (:foreground "ForestGreen"))
1267 (((class color) (background dark)) (:foreground "PaleGreen"))
1268 (t (:bold t :underline t)))
1269 "Face used for level 5 headlines."
1272 (defface org-level-6-face ;; font-lock-constant-face
1273 '((((type tty) (class color)) (:foreground "magenta"))
1274 (((class color) (background light)) (:foreground "CadetBlue"))
1275 (((class color) (background dark)) (:foreground "Aquamarine"))
1276 (t (:bold t :underline t)))
1277 "Face used for level 6 headlines."
1280 (defface org-level-7-face ;; font-lock-builtin-face
1281 '((((type tty) (class color)) (:foreground "blue" :weight light))
1282 (((class color) (background light)) (:foreground "Orchid"))
1283 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1285 "Face used for level 7 headlines."
1288 (defface org-level-8-face ;; font-lock-string-face
1289 '((((type tty) (class color)) (:foreground "green"))
1290 (((class color) (background light)) (:foreground "RosyBrown"))
1291 (((class color) (background dark)) (:foreground "LightSalmon"))
1293 "Face used for level 8 headlines."
1296 (defface org-warning-face ;; font-lock-warning-face
1297 '((((type tty) (class color)) (:foreground "red"))
1298 (((class color) (background light)) (:foreground "Red" :bold t))
1299 (((class color) (background dark)) (:foreground "Red1" :bold t))
1300 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1301 (t (:inverse-video t :bold t)))
1302 "Face for deadlines and TODO keywords."
1305 (defcustom org-fontify-done-headline nil
1306 "Non-nil means, change the face of a headline if it is marked DONE.
1307 Normally, only the TODO/DONE keyword indicates the state of a headline.
1308 When this is non-nil, the headline after the keyword is set to the
1309 `org-headline-done-face' as an additional indication."
1313 (defface org-headline-done-face ;; font-lock-string-face
1314 '((((type tty) (class color)) (:foreground "green"))
1315 (((class color) (background light)) (:foreground "RosyBrown"))
1316 (((class color) (background dark)) (:foreground "LightSalmon"))
1318 "Face used to indicate that a headline is DONE. See also the variable
1319 `org-fontify-done-headline'."
1322 ;; Inheritance does not yet work for xemacs. So we just copy...
1324 (defface org-deadline-announce-face
1325 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1326 (((class color) (background light)) (:foreground "Blue"))
1327 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1328 (t (:inverse-video t :bold t)))
1329 "Face for upcoming deadlines."
1332 (defface org-scheduled-today-face
1333 '((((type tty) (class color)) (:foreground "green"))
1334 (((class color) (background light)) (:foreground "DarkGreen"))
1335 (((class color) (background dark)) (:foreground "PaleGreen"))
1336 (t (:bold t :underline t)))
1337 "Face for items scheduled for a certain day."
1340 (defface org-scheduled-previously-face
1341 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1342 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1343 (((class color) (background light)) (:foreground "Firebrick"))
1344 (((class color) (background dark)) (:foreground "chocolate1"))
1345 (t (:bold t :italic t)))
1346 "Face for items scheduled previously, and not yet done."
1349 (defface org-link-face
1350 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1351 (((class color) (background light)) (:foreground "Purple"))
1352 (((class color) (background dark)) (:foreground "Cyan"))
1357 (defface org-done-face ;; font-lock-type-face
1358 '((((type tty) (class color)) (:foreground "green"))
1359 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1360 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1361 (t (:bold t :underline t)))
1362 "Face used for DONE."
1365 (defface org-table-face ;; font-lock-function-name-face
1366 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1367 (((class color) (background light)) (:foreground "Blue"))
1368 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1369 (t (:inverse-video t :bold t)))
1370 "Face used for tables."
1373 (defvar org-level-faces
1384 (defvar org-n-levels (length org-level-faces))
1386 ;; Tell the compiler about dynamically scoped variables,
1387 ;; and variables from other packages
1389 (defvar zmacs-regions)
1390 (defvar original-date)
1391 (defvar org-transient-mark-mode)
1392 (defvar org-old-auto-fill-inhibit-regexp)
1393 (defvar orgtbl-mode-menu)
1394 (defvar org-html-entities)
1395 (defvar org-goto-start-pos)
1396 (defvar org-cursor-color)
1397 (defvar org-time-was-given)
1398 (defvar org-ts-what)
1399 (defvar mark-active)
1401 (defvar levels-open)
1412 (defvar starting-day)
1413 (defvar include-all-loc)
1414 (defvar vm-message-pointer)
1415 (defvar vm-folder-directory)
1416 (defvar wl-summary-buffer-elmo-folder)
1417 (defvar wl-summary-buffer-folder-name)
1418 (defvar gnus-group-name)
1419 (defvar gnus-article-current)
1420 (defvar w3m-current-url)
1421 (defvar org-selected-point)
1422 (defvar calendar-mode-map)
1423 (defvar remember-save-after-remembering)
1424 (defvar remember-data-file))
1429 (defvar org-mode-map (copy-keymap outline-mode-map)
1430 "Keymap for Org-mode.")
1432 (defvar org-struct-menu)
1433 (defvar org-org-menu)
1435 ;; We use a before-change function to check if a table might need
1437 (defvar org-table-may-need-update t
1438 "Indicates of a table might need an update.
1439 This variable is set by `org-before-change-function'. `org-table-align'
1440 sets it back to nil.")
1442 (defvar org-mode-hook nil)
1443 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1447 (defun org-mode (&optional arg)
1448 "Outline-based notes management and organizer, alias
1449 \"Carstens outline-mode for keeping track of everything.\"
1451 Org-mode develops organizational tasks around a NOTES file which
1452 contains information about projects as plain text. Org-mode is
1453 implemented on top of outline-mode, which is ideal to keep the content
1454 of large files well structured. It supports ToDo items, deadlines and
1455 time stamps, which magically appear in the diary listing of the Emacs
1456 calendar. Tables are easily created with a built-in table editor.
1457 Plain text URL-like links connect to websites, emails (VM), Usenet
1458 messages (Gnus), BBDB entries, and any files related to the project.
1459 For printing and sharing of notes, an Org-mode file (or a part of it)
1460 can be exported as a well-structured ASCII or HTML file.
1462 The following commands are available:
1467 (setq major-mode 'org-mode)
1468 (setq mode-name "Org")
1469 (use-local-map org-mode-map)
1470 (easy-menu-add org-org-menu)
1471 (org-install-agenda-files-menu)
1472 (setq outline-regexp "\\*+")
1473 (if org-startup-truncated (setq truncate-lines t))
1474 (org-set-regexps-and-options)
1475 (set (make-local-variable 'font-lock-unfontify-region-function)
1476 'org-unfontify-region)
1477 ;; Activate before-change-function
1478 (set (make-local-variable 'org-table-may-need-update) t)
1479 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1480 (add-hook 'before-change-functions 'org-before-change-function nil
1482 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1483 (set (make-local-variable 'auto-fill-inhibit-regexp)
1485 (if (or org-enable-table-editor org-enable-fixed-width-editor)
1488 (if org-enable-table-editor "|" "")
1489 (if org-enable-fixed-width-editor ":" "")
1491 ;; Hook, and startup actions
1493 (and org-insert-mode-line-in-empty-file
1495 (= (point-min) (point-max))))
1497 (goto-char (point-min))
1498 (insert " -*- mode: org -*-\n\n")))
1499 (run-hooks 'org-mode-hook) ;FIXME: Should be run-mode-hooks.
1500 (unless org-inhibit-startup
1501 (if org-startup-with-deadline-check
1502 (call-interactively 'org-check-deadlines)
1504 ((eq org-startup-folded t)
1506 ((eq org-startup-folded 'content)
1507 (let ((this-command 'org-cycle) (last-command 'org-cycle))
1508 (org-cycle '(4)) (org-cycle '(4))))))))
1512 (defvar org-mouse-map (make-sparse-keymap))
1513 (define-key org-mouse-map
1514 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
1515 (define-key org-mouse-map
1516 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1518 (require 'font-lock)
1520 (defconst org-non-link-chars "\t\n\r|")
1521 (defconst org-link-regexp
1522 (if org-allow-space-in-links
1524 "\\(https?\\|ftp\\|mailto|\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
1526 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
1528 "Regular expression for matching links.")
1529 (defconst org-ts-lengths
1530 (cons (length (format-time-string (car org-time-stamp-formats)))
1531 (length (format-time-string (cdr org-time-stamp-formats))))
1532 "This holds the lengths of the two different time formats.")
1533 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1534 "Regular expression for fast time stamp matching.")
1535 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1536 "Regular expression matching time strings for analysis.")
1537 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1538 "Regular expression matching time stamps, with groups.")
1539 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1540 "Regular expression matching a time stamp range.")
1541 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1542 org-ts-regexp "\\)?")
1543 "Regular expression matching a time stamp or time stamp range.")
1545 (defun org-activate-links (limit)
1546 "Run through the buffer and add overlays to links."
1547 (if (re-search-forward org-link-regexp limit t)
1549 (add-text-properties (match-beginning 0) (match-end 0)
1550 (list 'mouse-face 'highlight
1551 'keymap org-mouse-map))
1554 (defun org-activate-dates (limit)
1555 "Run through the buffer and add overlays to dates."
1556 (if (re-search-forward org-tsr-regexp limit t)
1558 (add-text-properties (match-beginning 0) (match-end 0)
1559 (list 'mouse-face 'highlight
1560 'keymap org-mouse-map))
1564 (defun org-font-lock-level ()
1566 (org-back-to-heading t)
1567 (- (match-end 0) (match-beginning 0))))
1569 (defvar org-font-lock-keywords nil)
1571 (defun org-set-font-lock-defaults ()
1572 (let ((org-font-lock-extra-keywords
1574 '(org-activate-links (0 'org-link-face))
1575 '(org-activate-dates (0 'org-link-face))
1576 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
1577 '(1 'org-warning-face t))
1578 (list (concat "\\[#[A-Z]\\]") '(0 'org-warning-face t))
1579 (list (concat "\\<" org-deadline-string) '(0 'org-warning-face t))
1580 (list (concat "\\<" org-scheduled-string) '(0 'org-warning-face t))
1581 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
1583 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
1585 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
1587 '("\\<FIXME\\>" (0 'org-warning-face t))
1588 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
1589 '(1 'org-warning-face t))
1590 '("^#.*" (0 'font-lock-comment-face t))
1591 (if org-fontify-done-headline
1592 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
1593 '(1 'org-done-face t) '(2 'org-headline-done-face t))
1594 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
1595 '(1 'org-done-face t)))
1596 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
1597 (1 'org-table-face t))
1598 '("^[ \t]*\\(:.*\\)" (1 'org-table-face t)))))
1599 (set (make-local-variable 'org-font-lock-keywords)
1601 (if org-noutline-p ; FIXME: I am not sure if eval will work
1602 ; on XEmacs if noutline is ever ported
1603 '((eval . (list "^\\(\\*+\\).*"
1605 (% (- (match-end 1) (match-beginning 1) 1)
1609 '(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
1610 (1 (nth (% (- (match-end 2) (match-beginning 2) 1)
1614 org-font-lock-extra-keywords))
1615 (set (make-local-variable 'font-lock-defaults)
1616 '(org-font-lock-keywords t nil nil backward-paragraph))
1617 (kill-local-variable 'font-lock-keywords) nil))
1619 (defun org-unfontify-region (beg end &optional maybe_loudly)
1620 "Remove fontification and activation overlays from links."
1621 (font-lock-default-unfontify-region beg end)
1622 (let* ((buffer-undo-list t)
1623 (inhibit-read-only t) (inhibit-point-motion-hooks t)
1624 (inhibit-modification-hooks t)
1625 deactivate-mark buffer-file-name buffer-file-truename)
1626 (remove-text-properties beg end '(mouse-face nil keymap nil))))
1628 ;;; Visibility cycling
1630 (defvar org-cycle-global-status nil)
1631 (defvar org-cycle-subtree-status nil)
1632 (defun org-cycle (&optional arg)
1633 "Visibility cycling for Org-mode.
1635 - When this function is called with a prefix argument, rotate the entire
1636 buffer through 3 states (global cycling)
1637 1. OVERVIEW: Show only top-level headlines.
1638 2. CONTENTS: Show all headlines of all levels, but no body text.
1639 3. SHOW ALL: Show everything.
1641 - When point is at the beginning of a headline, rotate the subtree started
1642 by this line through 3 different states (local cycling)
1643 1. FOLDED: Only the main headline is shown.
1644 2. CHILDREN: The main headline and the direct children are shown. From
1645 this state, you can move to one of the children and
1647 3. SUBTREE: Show the entire subtree, including body text.
1649 - When there is a numeric prefix, go ARG levels up and do a `show-subtree',
1650 keeping cursor position.
1652 - When point is not at the beginning of a headline, execute
1653 `indent-relative', like TAB normally does. See the option
1654 `org-cycle-emulate-tab' for details.
1656 - Special case: if point is the the beginning of the buffer and there is
1657 no headline in line 1, this function will act as if called with prefix arg."
1660 (if (or (and (bobp) (not (looking-at outline-regexp)))
1662 ;; special case: use global cycling
1667 ((org-at-table-p 'any)
1668 ;; Enter the table or move to the next field in the table
1669 (or (org-table-recognize-table.el)
1671 (org-table-justify-field-maybe)
1672 (org-table-next-field))))
1674 ((eq arg t) ;; Global cycling
1677 ((and (eq last-command this-command)
1678 (eq org-cycle-global-status 'overview))
1679 ;; We just created the overview - now do table of contents
1680 ;; This can be slow in very large buffers, so indicate action
1681 (message "CONTENTS...")
1683 ;; Visit all headings and show their offspring
1684 (goto-char (point-max))
1686 (while (and (progn (condition-case nil
1687 (outline-previous-visible-heading 1)
1688 (error (goto-char (point-min))))
1690 (looking-at outline-regexp))
1692 (if (bobp) (throw 'exit nil))))
1693 (message "CONTENTS...done"))
1694 (setq org-cycle-global-status 'contents)
1695 (run-hook-with-args 'org-cycle-hook 'contents))
1697 ((and (eq last-command this-command)
1698 (eq org-cycle-global-status 'contents))
1699 ;; We just showed the table of contents - now show everything
1701 (message "SHOW ALL")
1702 (setq org-cycle-global-status 'all)
1703 (run-hook-with-args 'org-cycle-hook 'all))
1706 ;; Default action: go to overview
1708 (message "OVERVIEW")
1709 (setq org-cycle-global-status 'overview)
1710 (run-hook-with-args 'org-cycle-hook 'overview))))
1713 ;; Show-subtree, ARG levels up from here.
1715 (org-back-to-heading)
1716 (outline-up-heading arg)
1717 (org-show-subtree)))
1719 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
1720 ;; At a heading: rotate between three different views
1721 (org-back-to-heading)
1722 (let ((goal-column 0) eoh eol eos)
1723 ;; First, some boundaries
1725 (org-back-to-heading)
1727 (beginning-of-line 2)
1728 (while (and (not (eobp)) ;; this is like `next-line'
1729 (get-char-property (1- (point)) 'invisible))
1730 (beginning-of-line 2)) (setq eol (point)))
1731 (outline-end-of-heading) (setq eoh (point))
1732 (outline-end-of-subtree) (setq eos (point))
1733 (outline-next-heading))
1734 ;; Find out what to do next and set `this-command'
1737 ;; Nothing is hidden behind this heading
1738 (message "EMPTY ENTRY")
1739 (setq org-cycle-subtree-status nil))
1741 ;; Entire subtree is hidden in one line: open it
1744 (message "CHILDREN")
1745 (setq org-cycle-subtree-status 'children)
1746 (run-hook-with-args 'org-cycle-hook 'children))
1747 ((and (eq last-command this-command)
1748 (eq org-cycle-subtree-status 'children))
1749 ;; We just showed the children, now show everything.
1752 (setq org-cycle-subtree-status 'subtree)
1753 (run-hook-with-args 'org-cycle-hook 'subtree))
1755 ;; Default action: hide the subtree.
1758 (setq org-cycle-subtree-status 'folded)
1759 (run-hook-with-args 'org-cycle-hook 'folded)))))
1762 (buffer-read-only (org-back-to-heading))
1763 ((if (and (eq org-cycle-emulate-tab 'white)
1764 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
1766 (eq org-cycle-emulate-tab t))
1767 (if (and (looking-at "[ \n\r\t]")
1768 (string-match "^[ \t]*$" (buffer-substring
1769 (point-at-bol) (point))))
1771 (beginning-of-line 1)
1772 (and (looking-at "[ \t]+") (replace-match ""))))
1776 (org-back-to-heading)
1779 (defun org-optimize-window-after-visibility-change (state)
1780 "Adjust the window after a change in outline visibility.
1781 This function is the default value of the hook `org-cycle-hook'."
1783 ((eq state 'overview) (org-first-headline-recenter 1))
1784 ((eq state 'content) nil)
1785 ((eq state 'all) nil)
1786 ((eq state 'folded) nil)
1787 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
1788 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
1790 (defun org-subtree-end-visible-p ()
1791 "Is the end of the current subtree visible?"
1792 (pos-visible-in-window-p
1793 (save-excursion (outline-end-of-subtree) (point))))
1795 (defun org-first-headline-recenter (&optional N)
1796 "Move cursor to the first headline and recenter the headline.
1797 Optional argument N means, put the headline into the Nth line of the window."
1798 (goto-char (point-min))
1799 (when (re-search-forward (concat "^" outline-regexp) nil t)
1801 (recenter (prefix-numeric-value N))))
1803 (defvar org-goto-window-configuration nil)
1804 (defvar org-goto-marker nil)
1805 (defvar org-goto-map (make-sparse-keymap))
1806 (let ((cmds '(isearch-forward isearch-backward)) cmd)
1807 (while (setq cmd (pop cmds))
1808 (substitute-key-definition cmd cmd org-goto-map global-map)))
1809 (define-key org-goto-map [(return)] 'org-goto-ret)
1810 (define-key org-goto-map [(left)] 'org-goto-left)
1811 (define-key org-goto-map [(right)] 'org-goto-right)
1812 (define-key org-goto-map [(?q)] 'org-goto-quit)
1813 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
1814 (define-key org-goto-map [(tab)] 'org-cycle)
1815 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
1816 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
1817 (define-key org-goto-map "n" 'outline-next-visible-heading)
1818 (define-key org-goto-map "p" 'outline-previous-visible-heading)
1819 (define-key org-goto-map "f" 'outline-forward-same-level)
1820 (define-key org-goto-map "b" 'outline-backward-same-level)
1821 (define-key org-goto-map "u" 'outline-up-heading)
1822 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
1823 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
1824 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
1825 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
1826 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
1827 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
1828 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
1830 (defconst org-goto-help
1831 "Select a location to jump to, press RET
1832 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
1835 "Go to a different location of the document, keeping current visibility.
1837 When you want to go to a different location in a document, the fastest way
1838 is often to fold the entire buffer and then dive into the tree. This
1839 method has the disadvantage, that the previous location will be folded,
1840 which may not be what you want.
1842 This command works around this by showing a copy of the current buffer in
1843 overview mode. You can dive into the tree in that copy, to find the
1844 location you want to reach. When pressing RET, the command returns to the
1845 original buffer in which the visibility is still unchanged. It then jumps
1846 to the new location, making it and the headline hierarchy above it visible."
1848 (let* ((org-goto-start-pos (point))
1850 (org-get-location (current-buffer) org-goto-help)))
1853 (goto-char selected-point)
1854 (if (org-invisible-p) (org-show-hierarchy-above)))
1857 (defun org-get-location (buf help)
1858 "Let the user select a location in the Org-mode buffer BUF.
1859 This function uses a recursive edit. It returns the selected position
1861 (let (org-selected-point)
1863 (save-window-excursion
1864 (delete-other-windows)
1865 (switch-to-buffer (get-buffer-create "*org-goto*"))
1866 (with-output-to-temp-buffer "*Help*"
1868 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
1869 (setq buffer-read-only nil)
1872 (let ((org-startup-truncated t)
1873 (org-startup-folded t)
1874 (org-startup-with-deadline-check nil))
1876 (setq buffer-read-only t)
1877 (if (boundp 'org-goto-start-pos)
1878 (goto-char org-goto-start-pos)
1879 (goto-char (point-min)))
1880 (org-beginning-of-line)
1881 (message "Select location and press RET")
1882 ;; now we make sure that during selection, ony very few keys work
1883 ;; and that it is impossible to switch to another window.
1884 (let ((gm (current-global-map))
1885 (overriding-local-map org-goto-map))
1888 (use-global-map org-goto-map)
1890 (use-global-map gm)))))
1891 (kill-buffer "*org-goto*")
1892 org-selected-point))
1894 ;; FIXME: It may not be a good idea to temper with the prefix argument...
1895 (defun org-goto-ret (&optional arg)
1896 "Finish org-goto by going to the new location."
1898 (setq org-selected-point (point)
1899 current-prefix-arg arg)
1902 (defun org-goto-left ()
1903 "Finish org-goto by going to the new location."
1905 (if (org-on-heading-p)
1907 (beginning-of-line 1)
1908 (setq org-selected-point (point)
1909 current-prefix-arg (- (match-end 0) (match-beginning 0)))
1911 (error "Not on a heading")))
1913 (defun org-goto-right ()
1914 "Finish org-goto by going to the new location."
1916 (if (org-on-heading-p)
1918 (outline-end-of-subtree)
1919 (or (eobp) (forward-char 1))
1920 (setq org-selected-point (point)
1921 current-prefix-arg (- (match-end 0) (match-beginning 0)))
1923 (error "Not on a heading")))
1925 (defun org-goto-quit ()
1926 "Finish org-goto without cursor motion."
1928 (setq org-selected-point nil)
1931 ;;; Promotion, Demotion, Inserting new headlines
1933 (defvar org-ignore-region nil
1934 "To temporarily disable the active region.")
1936 (defun org-insert-heading ()
1937 "Insert a new heading with same depth at point."
1939 (let* ((head (save-excursion
1941 (org-back-to-heading)
1942 (error (outline-next-heading)))
1943 (prog1 (match-string 0)
1944 (funcall outline-level)))))
1945 (unless (bolp) (newline))
1948 (save-excursion (newline-and-indent)))
1949 (unless (equal (char-before) ?\ )
1951 (run-hooks 'org-insert-heading-hook)))
1953 (defun org-insert-todo-heading (arg)
1954 "Insert a new heading with the same level and TODO state as current heading.
1955 If the heading has no TODO state, or if the state is DONE, use the first
1956 state (TODO by default). Also with prefix arg, force first state."
1958 (org-insert-heading)
1960 (org-back-to-heading)
1961 (outline-previous-heading)
1962 (looking-at org-todo-line-regexp))
1964 (not (match-beginning 2))
1965 (equal (match-string 2) org-done-string))
1966 (insert (car org-todo-keywords) " ")
1967 (insert (match-string 2) " ")))
1969 (defun org-promote-subtree ()
1970 "Promote the entire subtree.
1971 See also `org-promote'."
1974 (org-map-tree 'org-promote)))
1976 (defun org-demote-subtree ()
1977 "Demote the entire subtree. See `org-demote'.
1978 See also `org-promote'."
1981 (org-map-tree 'org-demote)))
1983 (defun org-do-promote ()
1984 "Promote the current heading higher up the tree.
1985 If the region is active in `transient-mark-mode', promote all headings
1989 (if (org-region-active-p)
1990 (org-map-region 'org-promote (region-beginning) (region-end))
1992 (org-fix-position-after-promote))
1994 (defun org-do-demote ()
1995 "Demote the current heading lower down the tree.
1996 If the region is active in `transient-mark-mode', demote all headings
2000 (if (org-region-active-p)
2001 (org-map-region 'org-demote (region-beginning) (region-end))
2003 (org-fix-position-after-promote))
2005 (defun org-fix-position-after-promote ()
2006 "Make sure that after pro/demotion cursor position is right."
2007 (and (equal (char-after) ?\ )
2008 (equal (char-before) ?*)
2011 (defun org-promote ()
2012 "Promote the current heading higher up the tree.
2013 If the region is active in `transient-mark-mode', promote all headings
2015 (org-back-to-heading t)
2016 (let* ((level (save-match-data (funcall outline-level)))
2017 (up-head (make-string (1- level) ?*)))
2018 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover."))
2019 (replace-match up-head nil t)
2020 (if org-adapt-indentation
2021 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2023 (defun org-demote ()
2024 "Demote the current heading lower down the tree.
2025 If the region is active in `transient-mark-mode', demote all headings
2027 (org-back-to-heading t)
2028 (let* ((level (save-match-data (funcall outline-level)))
2029 (down-head (make-string (1+ level) ?*)))
2030 (replace-match down-head nil t)
2031 (if org-adapt-indentation
2032 (org-fixup-indentation "^ " " " "^\\S-"))))
2034 (defun org-map-tree (fun)
2035 "Call FUN for every heading underneath the current one."
2036 (org-back-to-heading)
2037 (let ((level (outline-level)))
2041 (outline-next-heading)
2042 (> (funcall outline-level) level))
2046 (defun org-map-region (fun beg end)
2047 "Call FUN for every heading between BEG and END."
2048 (let ((org-ignore-region t))
2050 (setq end (copy-marker end))
2052 ;; (if (fboundp 'deactivate-mark) (deactivate-mark))
2053 ;; (if (fboundp 'zmacs-deactivate-region) (zmacs-deactivate-region))
2054 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2058 (outline-next-heading)
2063 (defun org-fixup-indentation (from to prohibit)
2064 "Change the indentation in the current entry by re-replacing FROM with TO.
2065 However, if the regexp PROHIBIT matches at all, don't do anything.
2066 This is being used to change indentation along with the length of the
2067 heading marker. But if there are any lines which are not indented, nothing
2070 (let ((end (save-excursion (outline-next-heading)
2072 (unless (save-excursion (re-search-forward prohibit end t))
2073 (while (re-search-forward from end t)
2075 (beginning-of-line 2)))
2076 (move-marker end nil))))
2078 ;;; Vertical tree motion, cutting and pasting of subtrees
2080 (defun org-move-subtree-up (&optional arg)
2081 "Move the current subtree up past ARG headlines of the same level."
2083 (org-move-subtree-down (- (prefix-numeric-value arg))))
2085 (defun org-move-subtree-down (&optional arg)
2086 "Move the current subtree down past ARG headlines of the same level."
2088 (setq arg (prefix-numeric-value arg))
2089 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2090 'outline-get-last-sibling))
2091 (ins-point (make-marker))
2095 (org-back-to-heading)
2098 (save-excursion (outline-end-of-heading)
2099 (setq folded (org-invisible-p)))
2100 (outline-end-of-subtree))
2101 (outline-next-heading)
2103 ;; Find insertion point, with error handling
2106 (or (and (funcall movfunc) (looking-at outline-regexp))
2107 (progn (goto-char beg)
2108 (error "Cannot move past superior level or buffer limit")))
2109 (setq cnt (1- cnt)))
2111 ;; Moving forward - still need to move over subtree
2112 (progn (outline-end-of-subtree)
2113 (outline-next-heading)
2114 (if (not (or (looking-at (concat "^" outline-regexp))
2117 (move-marker ins-point (point))
2118 (setq txt (buffer-substring beg end))
2119 (delete-region beg end)
2121 (goto-char ins-point)
2122 (if folded (hide-subtree))
2123 (move-marker ins-point nil)))
2125 (defvar org-subtree-clip ""
2126 "Clipboard for cut and paste of subtrees.
2127 This is actually only a copy of the kill, because we use the normal kill
2128 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2130 (defvar org-subtree-clip-folded nil
2131 "Was the last copied subtree folded?
2132 This is used to fold the tree back after pasting.")
2134 (defun org-cut-subtree ()
2135 "Cut the current subtree into the clipboard.
2136 This is a short-hand for marking the subtree and then cutting it."
2138 (org-copy-subtree 'cut))
2140 (defun org-copy-subtree (&optional cut)
2141 "Cut the current subtree into the clipboard.
2142 This is a short-hand for marking the subtree and then copying it.
2143 If CUT is non nil, actually cut the subtree."
2145 (let (beg end folded)
2146 (org-back-to-heading)
2149 (save-excursion (outline-end-of-heading)
2150 (setq folded (org-invisible-p)))
2151 (outline-end-of-subtree))
2152 (if (equal (char-after) ?\n) (forward-char 1))
2156 (setq org-subtree-clip-folded folded)
2157 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2158 (setq org-subtree-clip (current-kill 0))
2159 (message "%s: Subtree with %d characters"
2160 (if cut "Cut" "Copied")
2161 (length org-subtree-clip)))))
2163 (defun org-paste-subtree (&optional level tree)
2164 "Paste the clipboard as a subtree, with modification of headline level.
2165 The entire subtree is promoted or demoted in order to match a new headline
2166 level. By default, the new level is derived from the visible headings
2167 before and after the insertion point, and taken to be the inferior headline
2168 level of the two. So if the previous visible heading is level 3 and the
2169 next is level 4 (or vice versa), level 4 will be used for insertion.
2170 This makes sure that the subtree remains an independent subtree and does
2171 not swallow low level entries.
2173 You can also force a different level, either by using a numeric prefix
2174 argument, or by inserting the heading marker by hand. For example, if the
2175 cursor is after \"*****\", then the tree will be shifted to level 5.
2177 If you want to insert the tree as is, just use \\[yank].
2179 If optional TREE is given, use this text instead of the kill ring."
2181 (unless (org-kill-is-subtree-p tree)
2183 (substitute-command-keys
2184 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2185 (let* ((txt (or tree (current-kill 0)))
2186 (^re (concat "^\\(" outline-regexp "\\)"))
2187 (re (concat "\\(" outline-regexp "\\)"))
2188 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2190 (old-level (if (string-match ^re txt)
2191 (- (match-end 0) (match-beginning 0))
2193 (force-level (cond (level (prefix-numeric-value level))
2195 ^re_ (buffer-substring (point-at-bol) (point)))
2196 (- (match-end 0) (match-beginning 0)))
2198 (previous-level (save-excursion
2199 (outline-previous-visible-heading 1)
2201 (- (match-end 0) (match-beginning 0))
2203 (next-level (save-excursion
2204 (outline-next-visible-heading 1)
2206 (- (match-end 0) (match-beginning 0))
2208 (new-level (or force-level (max previous-level next-level)))
2209 (shift (if (or (= old-level -1)
2211 (= old-level new-level))
2213 (- new-level old-level)))
2215 (delta (if (> shift 0) -1 1))
2216 (func (if (> shift 0) 'org-demote 'org-promote))
2218 ;; Remove the forces level indicator
2220 (delete-region (point-at-bol) (point)))
2221 ;; Make sure we start at the beginning of an empty line
2222 (if (not (bolp)) (insert "\n"))
2223 (if (not (looking-at "[ \t]*$"))
2224 (progn (insert "\n") (backward-char 1)))
2230 ;; Shift if necessary
2232 (message "Pasted at level %d, without shift" new-level)
2234 (narrow-to-region beg end)
2235 (while (not (= shift 0))
2236 (org-map-region func (point-min) (point-max))
2237 (setq shift (+ delta shift)))
2238 (goto-char (point-min))
2239 (message "Pasted at level %d, with shift by %d levels"
2241 (if (and (eq org-subtree-clip (current-kill 0))
2242 org-subtree-clip-folded)
2243 ;; The tree was folded before it was killed/copied
2246 (defun org-kill-is-subtree-p (&optional txt)
2247 "Check if the current kill is an outline subtree, or a set of trees.
2248 Returns nil if kill does not start with a headline, or if the first
2249 headline level is not the largest headline level in the tree.
2250 So this will actually accept several entries of equal levels as well,
2251 which is OK for `org-paste-subtree'.
2252 If optional TXT is given, check this string instead of the current kill."
2253 (let* ((kill (or txt (current-kill 0) ""))
2254 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2255 (- (match-end 0) (match-beginning 0))))
2256 (re (concat "^" outline-regexp))
2258 (if (not start-level)
2259 nil ;; does not even start with a heading
2261 (while (setq start (string-match re kill (1+ start)))
2262 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2268 (defun org-complete (&optional arg)
2269 "Perform completion on word at point.
2270 At the beginning of a headline, this completes TODO keywords as given in
2271 `org-todo-keywords'.
2272 If the current word is preceded by a backslash, completes the TeX symbols
2273 that are supported for HTML support.
2274 If the current word is preceded by \"#+\", completes special words for
2275 setting file options.
2276 At all other locations, this simply calls `ispell-complete-word'."
2279 (let* ((end (point))
2280 (beg (save-excursion
2281 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2282 (skip-chars-backward "a-zA-Z0-9_:")
2284 (texp (equal (char-before beg) ?\\))
2285 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2288 (pattern (buffer-substring-no-properties beg end))
2289 (completion-ignore-case opt)
2295 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2296 (cons (match-string 2 x) (match-string 1 x)))
2297 (org-split-string (org-get-current-options) "\n")))
2301 ((string-match "\\`\\*+[ \t]*\\'"
2302 (buffer-substring (point-at-bol) beg))
2304 (mapcar 'list org-todo-keywords))
2305 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2306 (completion (try-completion pattern table)))
2307 (cond ((eq completion t)
2308 (if (equal type :opt)
2309 (insert (substring (cdr (assoc (upcase pattern) table))
2310 (length pattern)))))
2312 (message "Can't find completion for \"%s\"" pattern)
2314 ((not (string= pattern completion))
2315 (delete-region beg end)
2316 (if (string-match " +$" completion)
2317 (setq completion (replace-match "" t t completion)))
2319 (if (get-buffer-window "*Completions*")
2320 (delete-window (get-buffer-window "*Completions*")))
2321 (if (and (eq type :todo)
2322 (assoc completion table))
2324 (if (and (equal type :opt) (assoc completion table))
2325 (message (substitute-command-keys
2326 "Press \\[org-complete] again to insert example settings"))))
2328 (message "Making completion list...")
2329 (let ((list (sort (all-completions pattern table) 'string<)))
2330 (with-output-to-temp-buffer "*Completions*"
2331 (display-completion-list list)))
2332 (message "Making completion list...%s" "done"))))))
2334 ;;; Comments, TODO and DEADLINE
2336 (defun org-toggle-comment ()
2337 "Change the COMMENT state of an entry."
2340 (org-back-to-heading)
2341 (if (looking-at (concat outline-regexp
2342 "\\( +\\<" org-comment-string "\\>\\)"))
2343 (replace-match "" t t nil 1)
2344 (if (looking-at outline-regexp)
2346 (goto-char (match-end 0))
2347 (insert " " org-comment-string))))))
2349 (defvar org-last-todo-state-is-todo nil
2350 "This is non-nil when the last TODO state change led to a TODO state.
2351 If the last change removed the TODO tag or switched to DONE, then
2354 (defun org-todo (&optional arg)
2355 "Change the TODO state of an item.
2356 The state of an item is given by a keyword at the start of the heading,
2358 *** TODO Write paper
2361 The different keywords are specified in the variable `org-todo-keywords'. By
2362 default the available states are \"TODO\" and \"DONE\".
2363 So for this example: when the item starts with TODO, it is changed to DONE.
2364 When it starts with DONE, the DONE is removed. And when neither TODO nor
2365 DONE are present, add TODO at the beginning of the heading.
2367 With prefix arg, use completion to determined the new state. With numeric
2368 prefix arg, switch to that state."
2371 (org-back-to-heading)
2372 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2373 (or (looking-at (concat " +" org-todo-regexp " *"))
2375 (let* ((this (match-string 1))
2376 (completion-ignore-case t)
2377 (member (member this org-todo-keywords))
2381 ;; Read a state with completion
2382 (completing-read "State: " (mapcar (lambda(x) (list x))
2386 ;; user requests a specific state
2387 (nth (1- (prefix-numeric-value arg))
2389 ((null member) (car org-todo-keywords))
2390 ((null tail) nil) ;; -> first entry
2391 ((eq org-todo-interpretation 'sequence)
2393 ((memq org-todo-interpretation '(type priority))
2394 (if (eq this-command last-command)
2396 (if (> (length tail) 0) org-done-string nil)))
2398 (next (if state (concat " " state " ") " ")))
2399 (replace-match next t t)
2400 (setq org-last-todo-state-is-todo
2401 (not (equal state org-done-string)))
2402 (run-hooks 'org-after-todo-state-change-hook)))
2403 ;; Fixup cursor location if close to the keyword
2404 (if (and (outline-on-heading-p)
2406 (save-excursion (beginning-of-line 1)
2407 (looking-at org-todo-line-regexp))
2408 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2410 (goto-char (or (match-end 2) (match-end 1)))
2413 (defun org-show-todo-tree (arg)
2414 "Make a compact tree which shows all headlines marked with TODO.
2415 The tree will show the lines where the regexp matches, and all higher
2416 headlines above the match."
2418 (let ((case-fold-search nil)
2419 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2420 (message "%d TODO entries found"
2421 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2423 (defun org-deadline ()
2424 "Insert the DEADLINE: string to make a deadline.
2425 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2426 to modify it to the correct date."
2429 org-deadline-string " "
2430 (format-time-string (car org-time-stamp-formats)
2431 (org-read-date nil 'to-time)))
2432 (message (substitute-command-keys
2433 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2435 (defun org-schedule ()
2436 "Insert the SCHEDULED: string to schedule a TODO item.
2437 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2438 to modify it to the correct date."
2441 org-scheduled-string " "
2442 (format-time-string (car org-time-stamp-formats)
2443 (org-read-date nil 'to-time)))
2444 (message (substitute-command-keys
2445 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2448 (defun org-occur (regexp &optional callback)
2449 "Make a compact tree which shows all matches of REGEXP.
2450 The tree will show the lines where the regexp matches, and all higher
2451 headlines above the match. It will also show the heading after the match,
2452 to make sure editing the matching entry is easy.
2453 if CALLBACK is non-nil, it is a function which is called to confirm
2454 that the match should indeed be shown."
2455 (interactive "sRegexp: ")
2456 (setq regexp (org-check-occur-regexp regexp))
2459 (goto-char (point-min))
2461 (while (re-search-forward regexp nil t)
2462 (when (or (not callback)
2465 (org-show-hierarchy-above))))
2466 (run-hooks 'org-occur-hook)
2468 (message "%d match(es) for regexp %s" cnt regexp))
2471 (defun org-show-hierarchy-above ()
2472 "Make sure point and the headings hierarchy above is visible."
2473 (if (org-on-heading-p t)
2474 (org-flag-heading nil) ; only show the heading
2475 (org-show-hidden-entry)) ; show entire entry
2477 (and org-show-following-heading
2478 (outline-next-heading)
2479 (org-flag-heading nil))) ; show the next heading
2480 (save-excursion ; show all higher headings
2481 (while (condition-case nil
2482 (progn (org-up-heading-all 1) t)
2484 (org-flag-heading nil))))
2488 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
2489 "Regular expression matching the priority indicator.")
2491 (defvar org-remove-priority-next-time nil)
2493 (defun org-priority-up ()
2494 "Increase the priority of the current item."
2498 (defun org-priority-down ()
2499 "Decrease the priority of the current item."
2501 (org-priority 'down))
2503 (defun org-priority (&optional action)
2504 "Change the priority of an item by ARG.
2505 ACTION can be set, up, or down."
2507 (setq action (or action 'set))
2508 (let (current new news have remove)
2510 (org-back-to-heading)
2511 (if (looking-at org-priority-regexp)
2512 (setq current (string-to-char (match-string 2))
2514 (setq current org-default-priority))
2517 (message (format "Priority A-%c, SPC to remove: " org-lowest-priority))
2518 (setq new (read-char-exclusive))
2519 (cond ((equal new ?\ ) (setq remove t))
2520 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
2521 (error "Priority must be between `%c' and `%c'"
2522 ?A org-lowest-priority))))
2524 (setq new (1- current)))
2526 (setq new (1+ current)))
2527 (t (error "Invalid action")))
2528 (setq new (min (max ?A (upcase new)) org-lowest-priority))
2529 (setq news (format "%c" new))
2532 (replace-match "" t t nil 1)
2533 (replace-match news t t nil 2))
2535 (error "No priority cookie found in line")
2536 (looking-at org-todo-line-regexp)
2539 (goto-char (match-end 2))
2540 (insert " [#" news "]"))
2541 (goto-char (match-beginning 3))
2542 (insert "[#" news "] ")))))
2544 (message "Priority removed")
2545 (message "Priority of current item set to %s" news))))
2548 (defun org-get-priority (s)
2549 "Find priority cookie and return priority."
2551 (if (not (string-match org-priority-regexp s))
2552 (* 1000 (- org-lowest-priority org-default-priority))
2553 (* 1000 (- org-lowest-priority
2554 (string-to-char (match-string 2 s)))))))
2558 (defvar org-last-changed-timestamp nil)
2560 (defun org-time-stamp (arg)
2561 "Prompt for a date/time and insert a time stamp.
2562 If the user specifies a time like HH:MM, or if this command is called
2563 with a prefix argument, the time stamp will contain date and time.
2564 Otherwise, only the date will be included. All parts of a date not
2565 specified by the user will be filled in from the current date/time.
2566 So if you press just return without typing anything, the time stamp
2567 will represent the current date/time. If there is already a timestamp
2568 at the cursor, it will be modified."
2570 (let ((fmt (if arg (cdr org-time-stamp-formats)
2571 (car org-time-stamp-formats)))
2572 (org-time-was-given nil)
2575 ((and (org-at-timestamp-p)
2576 (eq last-command 'org-time-stamp)
2577 (eq this-command 'org-time-stamp))
2579 (setq time (let ((this-command this-command))
2580 (org-read-date arg 'totime)))
2581 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
2582 (insert (format-time-string fmt time)))
2583 ((org-at-timestamp-p)
2584 (setq time (let ((this-command this-command))
2585 (org-read-date arg 'totime)))
2586 (and (org-at-timestamp-p) (replace-match
2587 (setq org-last-changed-timestamp
2588 (format-time-string fmt time))
2590 (message "Timestamp updated"))
2592 (setq time (let ((this-command this-command))
2593 (org-read-date arg 'totime)))
2594 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
2595 (insert (format-time-string fmt time))))))
2597 ;;; FIXME: Make the function take "Fri" as "next friday"
2598 (defun org-read-date (&optional with-time to-time)
2599 "Read a date and make things smooth for the user.
2600 The prompt will suggest to enter an ISO date, but you can also enter anything
2601 which will at least partially be understood by `parse-time-string'.
2602 Unrecognized parts of the date will default to the current day, month ,year,
2603 hour and minute. For example,
2604 3-2-5 --> 2003-02-05
2605 feb 15 --> currentyear-02-15
2606 sep 12 9 --> 2009-09-12
2607 12:45 --> today 12:45
2608 22 sept 0:34 --> currentyear-09-22 0:34
2609 12 --> currentyear-currentmonth-12
2611 The function understands only English month and weekday abbreviations,
2612 but this can be configured with the variables `parse-time-months' and
2613 `parse-time-weekdays'.
2615 While prompting, a calendar is popped up - you can also select the
2616 date with the mouse (button 1). The calendar shows a period of three
2617 month. To scroll it to other months, use the keys `>' and `<'.
2618 If you don't like the calendar, turn it off with
2619 \(setq org-popup-calendar-for-date-prompt nil).
2621 With optional argument TO-TIME, the date will immediately be converted
2622 to an internal time.
2623 With an optional argument WITH-TIME, the prompt will suggest to also
2624 insert a time. Note that when WITH-TIME is not set, you can still
2625 enter a time, and this function will inform the calling routine about
2626 this change. The calling routine may then choose to change the format
2627 used to insert the time stamp into the buffer to include the time."
2628 (let* ((default-time
2629 ;; Default time is either today, or, when entering a range,
2633 (concat org-ts-regexp "--\\=")
2637 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
2638 (parse-time-string (match-string 1))))
2640 (timestr (format-time-string
2641 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
2642 (prompt (format "YYYY-MM-DD [%s]: " timestr))
2644 second minute hour day month year tl)
2646 (if org-popup-calendar-for-date-prompt
2647 ;; Also show a calendar for date selection
2648 ;; Copied (with modifications) from planner.el by John Wiegley
2650 (save-window-excursion
2652 (calendar-forward-day (- (time-to-days default-time)
2653 (calendar-absolute-from-gregorian
2654 (calendar-current-date))))
2655 (let* ((old-map (current-local-map))
2656 (map (copy-keymap calendar-mode-map))
2657 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
2658 (define-key map (kbd "RET") 'org-calendar-select)
2659 (define-key map (if org-xemacs-p [button1] [mouse-1])
2660 'org-calendar-select)
2661 (define-key minibuffer-local-map [(meta shift left)]
2662 (lambda () (interactive)
2663 (org-eval-in-calendar '(calendar-backward-month 1))))
2664 (define-key minibuffer-local-map [(meta shift right)]
2665 (lambda () (interactive)
2666 (org-eval-in-calendar '(calendar-forward-month 1))))
2667 (define-key minibuffer-local-map [(shift up)]
2668 (lambda () (interactive)
2669 (org-eval-in-calendar '(calendar-backward-week 1))))
2670 (define-key minibuffer-local-map [(shift down)]
2671 (lambda () (interactive)
2672 (org-eval-in-calendar '(calendar-forward-week 1))))
2673 (define-key minibuffer-local-map [(shift left)]
2674 (lambda () (interactive)
2675 (org-eval-in-calendar '(calendar-backward-day 1))))
2676 (define-key minibuffer-local-map [(shift right)]
2677 (lambda () (interactive)
2678 (org-eval-in-calendar '(calendar-forward-day 1))))
2679 (define-key minibuffer-local-map ">"
2680 (lambda () (interactive)
2681 (org-eval-in-calendar '(scroll-calendar-left 1))))
2682 (define-key minibuffer-local-map "<"
2683 (lambda () (interactive)
2684 (org-eval-in-calendar '(scroll-calendar-right 1))))
2688 (setq ans (read-string prompt "" nil nil))
2689 (setq ans (or ans1 ans2 ans)))
2690 (use-local-map old-map)))))
2691 ;; Naked prompt only
2692 (setq ans (read-string prompt "" nil timestr)))
2695 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
2697 (setq year (if (match-end 2)
2698 (string-to-number (match-string 2 ans))
2699 (string-to-number (format-time-string "%Y")))
2700 month (string-to-number (match-string 3 ans))
2701 day (string-to-number (match-string 4 ans)))
2702 (if (< year 100) (setq year (+ 2000 year)))
2703 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
2705 (setq tl (parse-time-string ans)
2706 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
2707 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
2708 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
2709 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
2710 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
2711 second (or (nth 0 tl) 0))
2712 (if (and (boundp 'org-time-was-given)
2714 (setq org-time-was-given t))
2715 (if (< year 100) (setq year (+ 2000 year)))
2717 (encode-time second minute hour day month year)
2718 (if (or (nth 1 tl) (nth 2 tl))
2719 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
2720 (format "%04d-%02d-%02d" year month day)))))
2722 (defun org-eval-in-calendar (form)
2723 "Eval FORM in the calendar window and return to current window.
2724 Also, store the cursor date in variable ans2."
2725 (let ((sw (selected-window)))
2726 (select-window (get-buffer-window "*Calendar*"))
2728 (when (calendar-cursor-to-date)
2729 (let* ((date (calendar-cursor-to-date))
2730 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
2731 (setq ans2 (format-time-string "%Y-%m-%d" time))))
2732 (select-window sw)))
2734 (defun org-calendar-select ()
2735 "Return to `org-read-date' with the date currently selected.
2736 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
2738 (when (calendar-cursor-to-date)
2739 (let* ((date (calendar-cursor-to-date))
2740 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
2741 (setq ans1 (format-time-string "%Y-%m-%d" time)))
2742 (if (active-minibuffer-window) (exit-minibuffer))))
2744 (defun org-check-deadlines (ndays)
2745 "Check if there are any deadlines due or past due.
2746 A deadline is considered due if it happens within `org-deadline-warning-days'
2747 days from today's date. If the deadline appears in an entry marked DONE,
2748 it is not shown. The prefix arg NDAYS can be used to test that many
2749 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
2751 (let* ((org-warn-days
2753 ((equal ndays '(4)) 100000)
2754 (ndays (prefix-numeric-value ndays))
2755 (t org-deadline-warning-days)))
2756 (case-fold-search nil)
2757 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
2760 (and (let ((d1 (time-to-days (current-time)))
2762 (org-time-string-to-time (match-string 1)))))
2763 (< (- d2 d1) org-warn-days))
2764 (not (org-entry-is-done-p))))))
2765 (message "%d deadlines past-due or due within %d days"
2766 (org-occur regexp callback)
2769 (defun org-evaluate-time-range (&optional to-buffer)
2770 "Evaluate a time range by computing the difference between start and end.
2771 Normally the result is just printed in the echo area, but with prefix arg
2772 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
2773 If the time range is actually in a table, the result is inserted into the
2775 For time difference computation, a year is assumed to be exactly 365
2776 days in order to avoid rounding problems."
2779 (unless (org-at-date-range-p)
2780 (goto-char (point-at-bol))
2781 (re-search-forward org-tr-regexp (point-at-eol) t))
2782 (if (not (org-at-date-range-p))
2783 (error "Not at a time-stamp range, and none found in current line.")))
2784 (let* ((ts1 (match-string 1))
2785 (ts2 (match-string 2))
2786 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
2787 (match-end (match-end 0))
2788 (time1 (org-time-string-to-time ts1))
2789 (time2 (org-time-string-to-time ts2))
2790 (t1 (time-to-seconds time1))
2791 (t2 (time-to-seconds time2))
2792 (diff (abs (- t2 t1)))
2793 (negative (< (- t2 t1) 0))
2794 ;; (ys (floor (* 365 24 60 60)))
2797 (fy "%dy %dd %02d:%02d")
2799 (fd "%dd %02d:%02d")
2803 ;; FIXME: Should I re-introduce years, make year refer to same date?
2804 ;; This would be the only useful way to have years, actually.
2806 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
2808 d (floor (/ diff ds)) diff (mod diff ds)
2809 h (floor (/ diff hs)) diff (mod diff hs)
2810 m (floor (/ diff 60)))
2811 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
2813 d (floor (+ (/ diff ds) 0.5))
2816 (message (org-make-tdiff-string y d h m))
2817 (when (org-at-table-p)
2818 (goto-char match-end)
2820 (and (looking-at " *|") (goto-char (match-end 0))))
2822 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
2824 (if negative (insert " -"))
2825 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
2826 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
2827 (insert " " (format fh h m))))
2828 (if align (org-table-align))
2829 (message "Time difference inserted"))))
2831 (defun org-make-tdiff-string (y d h m)
2834 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
2836 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
2838 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
2840 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
2842 (apply 'format fmt (nreverse l))))
2844 (defun org-time-string-to-time (s)
2845 (apply 'encode-time (org-parse-time-string s)))
2847 (defun org-parse-time-string (s)
2848 "Parse the standard Org-mode time string.
2849 This should be a lot faster than the normal `parse-time-string'."
2850 (if (string-match org-ts-regexp1 s)
2852 (string-to-number (or (match-string 8 s) "0"))
2853 (string-to-number (or (match-string 7 s) "0"))
2854 (string-to-number (match-string 4 s))
2855 (string-to-number (match-string 3 s))
2856 (string-to-number (match-string 2 s))
2860 (defun org-timestamp-up (&optional arg)
2861 "Increase the date item at the cursor by one.
2862 If the cursor is on the year, change the year. If it is on the month or
2863 the day, change that.
2864 With prefix ARG, change by that many units."
2866 (org-timestamp-change (prefix-numeric-value arg)))
2868 (defun org-timestamp-down (&optional arg)
2869 "Decrease the date item at the cursor by one.
2870 If the cursor is on the year, change the year. If it is on the month or
2871 the day, change that.
2872 With prefix ARG, change by that many units."
2874 (org-timestamp-change (- (prefix-numeric-value arg))))
2876 (defun org-timestamp-up-day (&optional arg)
2877 "Increase the date in the time stamp by one day.
2878 With prefix ARG, change that many days."
2880 (org-timestamp-change (prefix-numeric-value arg) 'day))
2882 (defun org-timestamp-down-day (&optional arg)
2883 "Decrease the date in the time stamp by one day.
2884 With prefix ARG, change that many days."
2886 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
2888 (defsubst org-pos-in-match-range (pos n)
2889 (and (match-beginning n)
2890 (<= (match-beginning n) pos)
2891 (>= (match-end n) pos)))
2893 (defun org-at-timestamp-p ()
2894 "Determine if the cursor is or at a timestamp."
2896 (let* ((tsr org-ts-regexp2)
2898 (ans (or (looking-at tsr)
2900 (skip-chars-backward "^<\n\r\t")
2901 (if (> (point) 1) (backward-char 1))
2902 (and (looking-at tsr)
2903 (> (- (match-end 0) pos) -1))))))
2904 (and (boundp 'org-ts-what)
2907 ((org-pos-in-match-range pos 2) 'year)
2908 ((org-pos-in-match-range pos 3) 'month)
2909 ((org-pos-in-match-range pos 7) 'hour)
2910 ((org-pos-in-match-range pos 8) 'minute)
2911 ((or (org-pos-in-match-range pos 4)
2912 (org-pos-in-match-range pos 5)) 'day)
2916 (defun org-timestamp-change (n &optional what)
2917 "Change the date in the time stamp at point.
2918 The date will be changed by N times WHAT. WHAT can be `day', `month',
2919 `year', `minute', `second'. If WHAT is not given, the cursor position
2920 in the timestamp determines what will be changed."
2921 (let ((fmt (car org-time-stamp-formats))
2925 (if (not (org-at-timestamp-p))
2926 (error "Not at a timestamp"))
2927 (setq org-ts-what (or what org-ts-what))
2928 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
2929 (- (match-end 0) (match-beginning 0))))
2931 (cdr org-time-stamp-formats)
2932 (car org-time-stamp-formats)))
2933 (setq ts (match-string 0))
2935 (setq time0 (org-parse-time-string ts))
2939 (list (or (car time0) 0))
2940 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
2941 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
2942 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
2943 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
2944 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
2946 (if (eq what 'calendar)
2950 (set-buffer "*Calendar*")
2951 (calendar-cursor-to-date)))))
2952 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
2953 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
2954 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
2955 (setcar time0 (or (car time0) 0))
2956 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
2957 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
2958 (setq time (apply 'encode-time time0))))
2959 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
2961 ;; Try to recenter the calendar window, if any
2962 (if (and org-calendar-follow-timestamp-change
2963 (get-buffer-window "*Calendar*" t)
2964 (memq org-ts-what '(day month year)))
2965 (org-recenter-calendar (time-to-days time)))))
2967 (defun org-recenter-calendar (date)
2968 "If the calendar is visible, recenter it to DATE."
2969 (let* ((win (selected-window))
2970 (cwin (get-buffer-window "*Calendar*" t)))
2972 (select-window cwin)
2973 (calendar-goto-date (if (listp date) date
2974 (calendar-gregorian-from-absolute date)))
2975 (select-window win))))
2977 (defun org-goto-calendar (&optional arg)
2978 "Go to the Emacs calendar at the current date.
2979 If there is a time stamp in the current line, go to that date.
2980 A prefix ARG can be used force the current date."
2982 (let ((tsr org-ts-regexp) diff)
2983 (if (or (org-at-timestamp-p)
2985 (beginning-of-line 1)
2986 (looking-at (concat ".*" tsr))))
2987 (let ((d1 (time-to-days (current-time)))
2989 (org-time-string-to-time (match-string 1)))))
2990 (setq diff (- d2 d1))))
2992 (calendar-goto-today)
2993 (if (and diff (not arg)) (calendar-forward-day diff))))
2995 (defun org-date-from-calendar ()
2996 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
2997 If there is already a time stamp at the cursor position, update it."
2999 (org-timestamp-change 0 'calendar))
3001 ;;; Agenda, and Diary Integration
3005 (defvar org-agenda-mode-map (make-sparse-keymap)
3006 "Keymap for `org-agenda-mode'.")
3008 (defvar org-agenda-menu)
3009 (defvar org-agenda-follow-mode nil)
3010 (defvar org-agenda-buffer-name "*Org Agenda*")
3011 (defvar org-agenda-redo-command nil)
3014 (defun org-agenda-mode ()
3015 "Mode for time-sorted view on action items in Org-mode files.
3017 The following commands are available:
3019 \\{org-agenda-mode-map}"
3021 (kill-all-local-variables)
3022 (setq major-mode 'org-agenda-mode)
3023 (setq mode-name "Org-Agenda")
3024 (use-local-map org-agenda-mode-map)
3025 (easy-menu-add org-agenda-menu)
3026 (if org-startup-truncated (setq truncate-lines t))
3027 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
3028 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
3029 (setq org-agenda-follow-mode nil)
3031 '("Agenda") "Agenda Files"
3034 ["Edit File List" (customize-variable 'org-agenda-files) t]
3036 (mapcar 'org-file-menu-entry org-agenda-files)))
3037 (org-agenda-set-mode-name)
3038 (run-hooks 'org-agenda-mode-hook))
3040 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
3041 (define-key org-agenda-mode-map [(return)] 'org-agenda-switch-to)
3042 (define-key org-agenda-mode-map " " 'org-agenda-show)
3043 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
3044 (define-key org-agenda-mode-map "o" 'delete-other-windows)
3045 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
3046 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
3047 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
3048 (define-key org-agenda-mode-map "w" 'org-agenda-toggle-week-view)
3049 (define-key org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
3050 (define-key org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
3052 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
3053 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3054 (while l (define-key org-agenda-mode-map
3055 (int-to-string (pop l)) 'digit-argument)))
3057 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
3058 (define-key org-agenda-mode-map "d" 'org-agenda-toggle-diary)
3059 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
3060 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
3061 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
3062 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
3063 (define-key org-agenda-mode-map "n" 'next-line)
3064 (define-key org-agenda-mode-map "p" 'previous-line)
3065 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
3066 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
3067 (define-key org-agenda-mode-map "," 'org-agenda-priority)
3068 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
3069 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
3070 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
3071 (eval-after-load "calendar"
3072 '(define-key calendar-mode-map org-calendar-to-agenda-key
3073 'org-calendar-goto-agenda))
3074 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
3075 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
3076 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3077 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3078 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3079 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3080 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3081 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3082 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3083 (define-key org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
3084 (define-key org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
3085 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3086 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3088 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3089 "Local keymap for agenda entries from Org-mode.")
3091 (define-key org-agenda-keymap
3092 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3093 (define-key org-agenda-keymap
3094 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3096 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3100 ["Show" org-agenda-show t]
3101 ["Go To (other window)" org-agenda-goto t]
3102 ["Go To (one window)" org-agenda-switch-to t]
3103 ["Follow Mode" org-agenda-follow-mode
3104 :style toggle :selected org-agenda-follow-mode :active t]
3106 ["Cycle TODO" org-agenda-todo t]
3108 ["Reschedule +1 day" org-agenda-date-later t]
3109 ["Reschedule -1 day" org-agenda-date-earlier t]
3111 ["Reschedule to ..." org-agenda-date-prompt t])
3113 ["Set Priority" org-agenda-priority t]
3114 ["Increase Priority" org-agenda-priority-up t]
3115 ["Decrease Priority" org-agenda-priority-down t]
3116 ["Show Priority" org-agenda-show-priority t])
3118 ["Rebuild" org-agenda-redo t]
3119 ["Goto Today" org-agenda-goto-today t]
3120 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3121 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3123 ["Week/Day View" org-agenda-toggle-week-view
3124 (local-variable-p 'starting-day)]
3125 ["Include Diary" org-agenda-toggle-diary
3126 :style toggle :selected org-agenda-include-diary :active t]
3128 ["New Diary Entry" org-agenda-diary-entry t]
3129 ("Calendar Commands"
3130 ["Goto Calendar" org-agenda-goto-calendar t]
3131 ["Phases of the Moon" org-agenda-phases-of-moon t]
3132 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3133 ["Holidays" org-agenda-holidays t]
3134 ["Convert" org-agenda-convert-date t])
3136 ["Quit" org-agenda-quit t]
3137 ["Exit and Release Buffers" org-agenda-exit t]
3140 (defvar org-agenda-markers nil
3141 "List of all currently active markers created by `org-agenda'.")
3142 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3143 "Creation time of the last agenda marker.")
3145 (defun org-agenda-new-marker (&optional pos)
3146 "Return a new agenda marker.
3147 Org-mode keeps a list of these markers and resets them when they are
3149 (let ((m (copy-marker (or pos (point)))))
3150 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3151 (push m org-agenda-markers)
3154 (defun org-agenda-maybe-reset-markers (&optional force)
3155 "Reset markers created by `org-agenda'. But only if they are old enough."
3157 (> (- (time-to-seconds (current-time))
3158 org-agenda-last-marker-time)
3160 (while org-agenda-markers
3161 (move-marker (pop org-agenda-markers) nil))))
3163 (defvar org-agenda-new-buffers nil
3164 "Buffers created to visit agenda files.")
3166 (defun org-get-agenda-file-buffer (file)
3167 "Get a buffer visiting FILE. If the buffer needs to be created, add
3168 it to the list of buffers which might be released later."
3169 (let ((buf (find-buffer-visiting file)))
3171 buf ; just return it
3172 ;; Make a new buffer and remember it
3173 (setq buf (find-file-noselect file))
3174 (if buf (push buf org-agenda-new-buffers))
3177 (defun org-release-buffers (blist)
3178 "Release all buffers in list, asking the user for confirmation when needed.
3179 When a buffer is unmodified, it is just killed. When modified, it is saved
3180 \(if the user agrees) and then killed."
3182 (while (setq buf (pop blist))
3183 (setq file (buffer-file-name buf))
3184 (when (and (buffer-modified-p buf)
3186 (y-or-n-p (format "Save file %s? " file)))
3187 (with-current-buffer buf (save-buffer)))
3188 (kill-buffer buf))))
3190 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
3192 (defun org-timeline (&optional include-all)
3193 "Show a time-sorted view of the entries in the current org file.
3194 Only entries with a time stamp of today or later will be listed. With
3195 one \\[universal-argument] prefix argument, past entries will also be listed.
3196 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
3197 under the current date.
3198 If the buffer contains an active region, only check the region for
3202 (org-agenda-maybe-reset-markers 'force)
3203 (org-compile-prefix-format org-timeline-prefix-format)
3204 (let* ((dopast include-all)
3205 (dotodo (equal include-all '(16)))
3206 (entry (buffer-file-name))
3207 (org-agenda-files (list (buffer-file-name)))
3208 (date (calendar-current-date))
3209 (win (selected-window))
3211 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3212 (end (if (org-region-active-p) (region-end) (point-max)))
3213 (day-numbers (org-get-all-dates beg end 'no-ranges
3214 t)) ; always include today
3215 (today (time-to-days (current-time)))
3216 (org-respect-restriction t)
3219 (setq org-agenda-redo-command
3221 (list 'switch-to-buffer-other-window (current-buffer))
3222 (list 'org-timeline include-all)))
3224 ;; Remove past dates from the list of dates.
3225 (setq day-numbers (delq nil (mapcar (lambda(x)
3226 (if (>= x today) x nil))
3228 (switch-to-buffer-other-window
3229 (get-buffer-create org-agenda-buffer-name))
3230 (setq buffer-read-only nil)
3232 (org-agenda-mode) (setq buffer-read-only nil)
3233 (while (setq d (pop day-numbers))
3234 (if (and (>= d today)
3239 (insert (make-string 79 ?-) "\n")))
3240 (setq date (calendar-gregorian-from-absolute d))
3243 (setq rtn (org-agenda-get-day-entries
3244 entry date :todo :timestamp))
3245 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3246 (if (or rtn (equal d today))
3248 (insert (calendar-day-name date) " "
3249 (number-to-string (extract-calendar-day date)) " "
3250 (calendar-month-name (extract-calendar-month date)) " "
3251 (number-to-string (extract-calendar-year date)) "\n")
3252 (put-text-property s (1- (point)) 'face
3255 (put-text-property s (1- (point)) 'org-today t))
3256 (insert (org-finalize-agenda-entries rtn) "\n")
3257 (put-text-property s (1- (point)) 'day d))))
3258 (goto-char (point-min))
3259 (setq buffer-read-only t)
3260 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3262 (when (not org-select-timeline-window)
3267 (defun org-agenda (&optional include-all start-day ndays)
3268 "Produce a weekly view from all files in variable `org-agenda-files'.
3269 The view will be for the current week, but from the overview buffer you
3270 will be able to go to other weeks.
3271 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
3272 also be shown, under the current date.
3273 START-DAY defaults to TODAY, or to the most recent match for the weekday
3274 given in `org-agenda-start-on-weekday'.
3275 NDAYS defaults to `org-agenda-ndays'."
3277 (org-agenda-maybe-reset-markers 'force)
3278 (org-compile-prefix-format org-agenda-prefix-format)
3280 (let* ((org-agenda-start-on-weekday
3281 (if (or (equal ndays 1)
3282 (and (null ndays) (equal 1 org-agenda-ndays)))
3283 nil org-agenda-start-on-weekday))
3284 (files (copy-sequence org-agenda-files))
3285 (win (selected-window))
3286 (today (time-to-days (current-time)))
3287 (sd (or start-day today))
3288 (start (if (or (null org-agenda-start-on-weekday)
3289 (< org-agenda-ndays 7))
3291 (let* ((nt (calendar-day-of-week
3292 (calendar-gregorian-from-absolute sd)))
3293 (n1 org-agenda-start-on-weekday)
3295 (- sd (+ (if (< d 0) 7 0) d)))))
3296 (day-numbers (list start))
3297 s e rtn rtnall file date d start-pos end-pos)
3298 (setq org-agenda-redo-command
3299 (list 'org-agenda include-all start-day ndays))
3300 ;; Make the list of days
3301 (setq ndays (or ndays org-agenda-ndays))
3303 (push (1+ (car day-numbers)) day-numbers)
3304 (setq ndays (1- ndays)))
3305 (setq day-numbers (nreverse day-numbers))
3306 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3308 (delete-other-windows)
3309 (switch-to-buffer-other-window
3310 (get-buffer-create org-agenda-buffer-name))))
3311 (setq buffer-read-only nil)
3313 (org-agenda-mode) (setq buffer-read-only nil)
3314 (set (make-local-variable 'starting-day) (car day-numbers))
3315 (set (make-local-variable 'include-all-loc) include-all)
3316 (when (and (or include-all org-agenda-include-all-todo)
3317 (member today day-numbers))
3318 (setq files org-agenda-files
3320 (while (setq file (pop files))
3322 (org-check-agenda-file file)
3323 (setq date (calendar-gregorian-from-absolute today)
3324 rtn (org-agenda-get-day-entries
3326 (setq rtnall (append rtnall rtn))))
3327 (if rtnall (insert (org-finalize-agenda-entries rtnall) "\n")))
3328 (while (setq d (pop day-numbers))
3329 (setq date (calendar-gregorian-from-absolute d)
3332 (and (not start-pos) (= d sd)))
3333 (setq start-pos (point))
3334 (if (and start-pos (not end-pos))
3335 (setq end-pos (point))))
3336 (setq files org-agenda-files
3338 (while (setq file (pop files))
3340 (org-check-agenda-file file)
3341 (setq rtn (org-agenda-get-day-entries file date))
3342 (setq rtnall (append rtnall rtn))))
3343 (if org-agenda-include-diary
3345 (require 'diary-lib)
3346 (setq rtn (org-get-entries-from-diary date))
3347 (setq rtnall (append rtnall rtn))))
3348 (if (or rtnall org-agenda-show-all-dates)
3350 (insert (format "%-9s %2d %-9s %4d\n"
3351 (calendar-day-name date)
3352 (extract-calendar-day date)
3353 (calendar-month-name (extract-calendar-month date))
3354 (extract-calendar-year date)))
3355 (put-text-property s (1- (point)) 'face
3357 (if rtnall (insert (org-finalize-agenda-entries rtnall) "\n"))
3358 (put-text-property s (1- (point)) 'day d))))
3359 (goto-char (point-min))
3360 (setq buffer-read-only t)
3361 (if org-fit-agenda-window
3362 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3363 (/ (frame-height) 2)))
3364 (unless (and (pos-visible-in-window-p (point-min))
3365 (pos-visible-in-window-p (point-max)))
3366 (goto-char (1- (point-max)))
3368 (if (not (pos-visible-in-window-p (or start-pos 1)))
3370 (goto-char (or start-pos 1))
3372 (goto-char (or start-pos 1))
3373 (if (not org-select-agenda-window) (select-window win))
3376 (defun org-check-agenda-file (file)
3377 "Make sure FILE exists. If not, ask user what to do."
3378 ;; FIXME: this does not correctly change the menus
3379 ;; Could probably be fixed by explicitly going to the buffer.
3380 (when (not (file-exists-p file))
3381 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3383 (let ((r (downcase (read-char-exclusive))))
3386 (org-remove-file file)
3387 (throw 'nextfile t))
3388 (t (error "Abort"))))))
3390 (defun org-agenda-quit ()
3391 "Exit agenda by removing the window or the buffer."
3393 (let ((buf (current-buffer)))
3394 (if (not (one-window-p)) (delete-window))
3396 (org-agenda-maybe-reset-markers 'force)))
3398 (defun org-agenda-exit ()
3399 "Exit agenda by removing the window or the buffer.
3400 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3401 Org-mode buffers visited directly by the user will not be touched."
3403 (org-release-buffers org-agenda-new-buffers)
3404 (setq org-agenda-new-buffers nil)
3407 (defun org-agenda-redo ()
3410 (eval org-agenda-redo-command))
3412 (defun org-agenda-goto-today ()
3415 (if (boundp 'starting-day)
3416 (let ((cmd (car org-agenda-redo-command))
3417 (iall (nth 1 org-agenda-redo-command))
3418 (nday (nth 3 org-agenda-redo-command)))
3419 (eval (list cmd iall nil nday)))
3420 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3423 (defun org-agenda-later (arg)
3424 "Go forward in time by `org-agenda-ndays' days.
3425 With prefix ARG, go forward that many times `org-agenda-ndays'."
3427 (unless (boundp 'starting-day)
3428 (error "Not allowed"))
3429 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3430 (+ starting-day (* arg org-agenda-ndays))))
3432 (defun org-agenda-earlier (arg)
3433 "Go back in time by `org-agenda-ndays' days.
3434 With prefix ARG, go back that many times `org-agenda-ndays'."
3436 (unless (boundp 'starting-day)
3437 (error "Not allowed"))
3438 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3439 (- starting-day (* arg org-agenda-ndays))))
3441 (defun org-agenda-toggle-week-view ()
3442 "Toggle weekly/daily view for aagenda."
3444 (unless (boundp 'starting-day)
3445 (error "Not allowed"))
3446 (setq org-agenda-ndays
3447 (if (equal org-agenda-ndays 1) 7 1))
3448 (org-agenda include-all-loc
3449 (or (get-text-property (point) 'day)
3451 (org-agenda-set-mode-name)
3452 (message "Switched to %s view"
3453 (if (equal org-agenda-ndays 1) "day" "week")))
3455 (defun org-agenda-next-date-line (&optional arg)
3456 "Jump to the next line indicating a date in agenda buffer."
3458 (beginning-of-line 1)
3459 (if (looking-at "^\\S-") (forward-char 1))
3460 (if (not (re-search-forward "^\\S-" nil t arg))
3463 (error "No next date after this line in this buffer.")))
3464 (goto-char (match-beginning 0)))
3466 (defun org-agenda-previous-date-line (&optional arg)
3467 "Jump to the next line indicating a date in agenda buffer."
3469 (beginning-of-line 1)
3470 (if (not (re-search-backward "^\\S-" nil t arg))
3471 (error "No previous date before this line in this buffer.")))
3473 ;; Initialize the highlight
3474 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
3475 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
3478 (defun org-highlight (begin end &optional buffer)
3479 "Highlight a region with overlay."
3480 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
3481 org-hl begin end (or buffer (current-buffer))))
3483 (defun org-unhighlight ()
3484 "Detach overlay INDEX."
3485 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
3488 (defun org-agenda-follow-mode ()
3489 "Toggle follow mode in an agenda buffer."
3491 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
3492 (org-agenda-set-mode-name)
3493 (message "Follow mode is %s"
3494 (if org-agenda-follow-mode "on" "off")))
3496 (defun org-agenda-toggle-diary ()
3497 "Toggle follow mode in an agenda buffer."
3499 (setq org-agenda-include-diary (not org-agenda-include-diary))
3501 (org-agenda-set-mode-name)
3502 (message "Diary inclusion turned %s"
3503 (if org-agenda-include-diary "on" "off")))
3505 (defun org-agenda-set-mode-name ()
3506 "Set the mode name to indicate all the small mode settings."
3508 (concat "Org-Agenda"
3509 (if (equal org-agenda-ndays 1) " Day" "")
3510 (if (equal org-agenda-ndays 7) " Week" "")
3511 (if org-agenda-follow-mode " Follow" "")
3512 (if org-agenda-include-diary " Diary" "")))
3513 (force-mode-line-update))
3515 (defun org-agenda-post-command-hook ()
3516 (and (eolp) (not (bolp)) (backward-char 1))
3517 (if (and org-agenda-follow-mode
3518 (get-text-property (point) 'org-marker))
3521 (defvar org-disable-diary nil) ;Dynamically-scoped param.
3523 (defun org-get-entries-from-diary (date)
3524 "Get the (Emacs Calendar) diary entries for DATE."
3525 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
3526 (diary-display-hook '(fancy-diary-display))
3527 (list-diary-entries-hook
3528 (cons 'org-diary-default-entry list-diary-entries-hook))
3530 (org-disable-diary t))
3532 (save-window-excursion
3533 (list-diary-entries date 1)))
3534 (if (not (get-buffer fancy-diary-buffer))
3536 (with-current-buffer fancy-diary-buffer
3537 (setq buffer-read-only nil)
3538 (if (= (point-max) 1)
3541 ;; Omit the date and other unnecessary stuff
3542 (org-agenda-cleanup-fancy-diary)
3543 ;; Add prefix to each line and extend the text properties
3544 (if (= (point-max) 1)
3546 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
3547 (set-buffer-modified-p nil)
3548 (kill-buffer fancy-diary-buffer)))
3550 (setq entries (org-split-string entries "\n"))
3554 (setq x (org-format-agenda-item "" x "Diary"))
3555 ;; Extend the text properties to the beginning of the line
3556 (add-text-properties
3558 (text-properties-at (1- (length x)) x)
3563 (defun org-agenda-cleanup-fancy-diary ()
3564 "Remove unwanted stuff in buffer created by fancy-diary-display.
3565 This gets rid of the date, the underline under the date, and
3566 the dummy entry installed by `org-mode' to ensure non-empty diary for each
3567 date. Itt also removes lines that contain only whitespace."
3568 (goto-char (point-min))
3569 (if (looking-at ".*?:[ \t]*")
3572 (re-search-forward "\n=+$" nil t)
3574 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
3575 (re-search-forward "\n=+$" nil t)
3576 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
3577 (goto-char (point-min))
3578 (while (re-search-forward "^ +\n" nil t)
3580 (goto-char (point-min))
3581 (if (re-search-forward "^Org-mode dummy\n?" nil t)
3582 (replace-match "")))
3584 ;; Advise the add-to-diary-list function to allow org to jump to
3585 ;; diary entries. Wrapped into eval-after-load to avoid loading
3586 ;; advice unnecessarily
3587 (eval-after-load "diary-lib"
3588 '(defadvice add-to-diary-list (before org-mark-diary-entry activate)
3589 "Make the position visible."
3590 (if (and org-disable-diary ;; called from org-agenda
3593 (add-text-properties
3595 (list 'mouse-face 'highlight
3596 'keymap org-agenda-keymap
3599 "mouse-2 or RET jump to diary file %s"
3600 (abbreviate-file-name (buffer-file-name)))
3601 'org-agenda-diary-link t
3602 'org-marker (org-agenda-new-marker (point-at-bol)))
3605 (defun org-diary-default-entry ()
3606 "Add a dummy entry to the diary.
3607 Needed to avoid empty dates which mess up holiday display."
3608 ;; Catch the error if dealing with the new add-to-diary-alist
3610 (add-to-diary-list original-date "Org-mode dummy" "")
3612 (add-to-diary-list original-date "Org-mode dummy" "" nil))))
3614 (defun org-add-file (&optional file)
3615 "Add current file to the list of files in variable `org-agenda-files'.
3616 These are the files which are being checked for agenda entries.
3617 Optional argument FILE means, use this file instead of the current.
3618 It is possible (but not recommended) to add this function to the
3622 (let* ((file (or file (buffer-file-name)
3624 (error "Buffer is not visiting a file")
3625 (throw 'exit nil))))
3626 (true-file (file-truename file))
3627 (afile (abbreviate-file-name file))
3628 (present (delq nil (mapcar
3630 (equal true-file (file-truename x)))
3631 org-agenda-files))))
3634 (setq org-agenda-files
3635 (cons afile org-agenda-files))
3636 ;; Make sure custom.el does not end up with Org-mode
3637 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
3638 (customize-save-variable 'org-agenda-files org-agenda-files))
3639 (org-install-agenda-files-menu)
3640 (message "Added file: %s" afile))
3641 (message "File was already in list: %s" afile)))))
3643 (defun org-remove-file (&optional file)
3644 "Remove current file from the list of files in variable `org-agenda-files'.
3645 These are the files which are being checked for agenda entries.
3646 Optional argument FILE means, use this file instead of the current."
3648 (let* ((file (or file (buffer-file-name)))
3649 (true-file (file-truename file))
3650 (afile (abbreviate-file-name file))
3651 (files (delq nil (mapcar
3653 (if (equal true-file
3656 org-agenda-files))))
3657 (if (not (= (length files) (length org-agenda-files)))
3659 (setq org-agenda-files files)
3660 (customize-save-variable 'org-agenda-files org-agenda-files)
3661 (org-install-agenda-files-menu)
3662 (message "Removed file: %s" afile))
3663 (message "File was not in list: %s" afile))))
3665 (defun org-file-menu-entry (file)
3666 (vector file (list 'find-file file) t))
3668 (defun org-get-all-dates (beg end &optional no-ranges force-today)
3669 "Return a list of all relevant day numbers from BEG to END buffer positions.
3670 If NO-RANGES is non-nil, include only the start and end dates of a range,
3671 not every single day in the range. If FORCE-TODAY is non-nil, make
3672 sure that TODAY is included in the list."
3673 (let (dates date day day1 day2 ts1 ts2)
3675 (setq dates (list (time-to-days (current-time)))))
3678 (while (re-search-forward org-ts-regexp end t)
3679 (setq day (time-to-days (org-time-string-to-time
3680 (substring (match-string 1) 0 10))))
3681 (or (memq day dates) (push day dates)))
3684 (while (re-search-forward org-tr-regexp end t)
3685 (setq ts1 (substring (match-string 1) 0 10)
3686 ts2 (substring (match-string 2) 0 10)
3687 day1 (time-to-days (org-time-string-to-time ts1))
3688 day2 (time-to-days (org-time-string-to-time ts2)))
3689 (while (< (setq day1 (1+ day1)) day2)
3690 (or (memq day1 dates) (push day1 dates)))))
3694 (defun org-diary (&rest args)
3695 "Return diary information from org-files.
3696 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
3697 It accesses org files and extracts information from those files to be
3698 listed in the diary. The function accepts arguments specifying what
3699 items should be listed. The following arguments are allowed:
3701 :timestamp List the headlines of items containing a date stamp or
3702 date range matching the selected date. Deadlines will
3703 also be listed, on the expiration day.
3705 :deadline List any deadlines past due, or due within
3706 `org-deadline-warning-days'. The listing occurs only
3707 in the diary for *today*, not at any other date. If
3708 an entry is marked DONE, it is no longer listed.
3710 :scheduled List all items which are scheduled for the given date.
3711 The diary for *today* also contains items which were
3712 scheduled earlier and are not yet marked DONE.
3714 :todo List all TODO items from the org-file. This may be a
3715 long list - so this is not turned on by default.
3716 Like deadlines, these entries only show up in the
3717 diary for *today*, not at any other date.
3719 The call in the diary file should look like this:
3721 &%%(org-diary) ~/path/to/some/orgfile.org
3723 Use a separate line for each org file to check. Or, if you omit the file name,
3724 all files listed in `org-agenda-files' will be checked automatically:
3728 If you don't give any arguments (as in the example above), the default
3729 arguments (:deadline :scheduled :timestamp) are used. So the example above may
3732 &%%(org-diary :deadline :timestamp :scheduled)
3734 The function expects the lisp variables `entry' and `date' to be provided
3735 by the caller, because this is how the calendar works. Don't use this
3736 function from a program - use `org-agenda-get-day-entries' instead."
3737 (org-agenda-maybe-reset-markers)
3738 (org-compile-agenda-prefix-format org-agenda-prefix-format)
3739 (setq args (or args '(:deadline :scheduled :timestamp)))
3740 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
3744 ;; If this is called during org-agenda, don't return any entries to
3745 ;; the calendar. Org Agenda will list these entries itself.
3746 (if org-disable-diary (setq files nil))
3747 (while (setq file (pop files))
3748 (setq rtn (apply 'org-agenda-get-day-entries file date args))
3749 (setq results (append results rtn)))
3750 (concat (org-finalize-agenda-entries results) "\n")))
3752 (defun org-agenda-get-day-entries (file date &rest args)
3753 "Does the work for `org-diary' and `org-agenda'.
3754 FILE is the path to a file to be checked for entries. DATE is date like
3755 the one returned by `calendar-current-date'. ARGS are symbols indicating
3756 which kind of entries should be extracted. For details about these, see
3757 the documentation of `org-diary'."
3758 (setq args (or args '(:deadline :scheduled :timestamp)))
3759 (let* ((org-startup-with-deadline-check nil)
3760 (org-startup-folded nil)
3761 (buffer (if (file-exists-p file)
3762 (org-get-agenda-file-buffer file)
3763 (error "No such file %s" file)))
3766 ;; If file does not exist, make sure an error message ends up in diary
3767 (format "ORG-AGENDA-ERROR: No such org-file %s" file)
3768 (with-current-buffer buffer
3769 (unless (eq major-mode 'org-mode)
3770 (error "Agenda file %s is not in `org-mode'" file))
3771 (let ((case-fold-search nil))
3774 (if org-respect-restriction
3775 (if (org-region-active-p)
3776 ;; Respect a region to restrict search
3777 (narrow-to-region (region-beginning) (region-end)))
3778 ;; If we work for the calendar or many files,
3779 ;; get rid of any restriction
3781 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
3782 (while (setq arg (pop args))
3784 ((and (eq arg :todo)
3785 (equal date (calendar-current-date)))
3786 (setq rtn (org-agenda-get-todos))
3787 (setq results (append results rtn)))
3788 ((eq arg :timestamp)
3789 (setq rtn (org-agenda-get-blocks))
3790 (setq results (append results rtn))
3791 (setq rtn (org-agenda-get-timestamps))
3792 (setq results (append results rtn)))
3793 ((eq arg :scheduled)
3794 (setq rtn (org-agenda-get-scheduled))
3795 (setq results (append results rtn)))
3796 ((and (eq arg :deadline)
3797 (equal date (calendar-current-date)))
3798 (setq rtn (org-agenda-get-deadlines))
3799 (setq results (append results rtn))))))))))
3802 (defun org-entry-is-done-p ()
3803 "Is the current entry marked DONE?"
3805 (and (re-search-backward "[\r\n]\\*" nil t)
3806 (looking-at org-nl-done-regexp))))
3808 (defun org-at-date-range-p ()
3809 "Is the cursor inside a date range?"
3813 (let ((pos (point)))
3814 (skip-chars-backward "^<\r\n")
3815 (skip-chars-backward "<")
3816 (and (looking-at org-tr-regexp)
3817 (>= (match-end 0) pos)
3819 (skip-chars-backward "^<\r\n")
3820 (skip-chars-backward "<")
3821 (and (looking-at org-tr-regexp)
3822 (>= (match-end 0) pos)
3826 (defun org-agenda-get-todos ()
3827 "Return the TODO information for agenda display."
3828 (let* ((props (list 'face nil
3829 'done-face 'org-done-face
3830 'mouse-face 'highlight
3831 'keymap org-agenda-keymap
3833 (format "mouse-2 or RET jump to org file %s"
3834 (abbreviate-file-name (buffer-file-name)))))
3835 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
3839 (goto-char (point-min))
3840 (while (re-search-forward regexp nil t)
3841 (goto-char (match-beginning 1))
3842 (setq marker (org-agenda-new-marker (point-at-bol))
3843 txt (org-format-agenda-item "" (match-string 1))
3845 (+ (org-get-priority txt)
3846 (if org-todo-kwd-priority-p
3847 (- org-todo-kwd-max-priority -2
3849 (member (match-string 2) org-todo-keywords)))
3851 (add-text-properties
3852 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
3857 (goto-char (match-end 1)))
3860 (defconst org-agenda-no-heading-message
3861 "No heading for this item in buffer or region")
3863 (defun org-agenda-get-timestamps ()
3864 "Return the date stamp information for agenda display."
3865 (let* ((props (list 'face nil
3866 'mouse-face 'highlight
3867 'keymap org-agenda-keymap
3869 (format "mouse-2 or RET jump to org file %s"
3870 (abbreviate-file-name (buffer-file-name)))))
3871 (regexp (regexp-quote
3874 (car org-time-stamp-formats)
3875 (apply 'encode-time ; DATE bound by calendar
3876 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
3878 marker hdmarker deadlinep scheduledp donep tmp priority
3880 (goto-char (point-min))
3881 (while (re-search-forward regexp nil t)
3882 (if (not (save-match-data (org-at-date-range-p)))
3884 (setq marker (org-agenda-new-marker (match-beginning 0))
3885 tmp (buffer-substring (max (point-min)
3886 (- (match-beginning 0)
3887 org-ds-keyword-length))
3888 (match-beginning 0))
3889 deadlinep (string-match org-deadline-regexp tmp)
3890 scheduledp (string-match org-scheduled-regexp tmp)
3891 donep (org-entry-is-done-p))
3893 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
3895 (goto-char (match-end 1))
3896 (setq hdmarker (org-agenda-new-marker))
3897 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
3898 (setq txt (org-format-agenda-item
3900 (if deadlinep "Deadline: " "")
3901 (if scheduledp "Scheduled: " ""))
3903 (setq txt org-agenda-no-heading-message))
3904 (setq priority (org-get-priority txt))
3905 (add-text-properties
3906 0 (length txt) (append (list 'org-marker marker
3907 'org-hd-marker hdmarker) props)
3910 (add-text-properties
3913 (if donep 'org-done-face 'org-warning-face)
3914 'undone-face 'org-warning-face
3915 'done-face 'org-done-face
3916 'priority (+ 100 priority))
3919 (add-text-properties
3921 (list 'face 'org-scheduled-today-face
3922 'undone-face 'org-scheduled-today-face
3923 'done-face 'org-done-face
3924 priority (+ 99 priority))
3926 (add-text-properties
3928 (list 'priority priority) txt)))
3930 (outline-next-heading))))
3933 (defun org-agenda-get-deadlines ()
3934 "Return the deadline information for agenda display."
3935 (let* ((wdays org-deadline-warning-days)
3936 (props (list 'mouse-face 'highlight
3937 'keymap org-agenda-keymap
3939 (format "mouse-2 or RET jump to org file %s"
3940 (abbreviate-file-name (buffer-file-name)))))
3941 (regexp org-deadline-time-regexp)
3942 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
3943 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
3946 (goto-char (point-min))
3947 (while (re-search-forward regexp nil t)
3948 (setq pos (1- (match-beginning 1))
3950 (org-time-string-to-time (match-string 1)))
3952 ;; When to show a deadline in the calendar:
3953 ;; If the expiration is within wdays warning time.
3954 ;; Past-due deadlines are only shown on the current date
3955 (if (and (< diff wdays) todayp (not (= diff 0)))
3957 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
3959 (goto-char (match-end 0))
3960 (setq pos1 (match-end 1))
3961 (setq head (buffer-substring-no-properties
3963 (progn (skip-chars-forward "^\r\n")
3965 (if (string-match org-looking-at-done-regexp head)
3967 (setq txt (org-format-agenda-item
3968 (format "In %3d d.: " diff) head))))
3969 (setq txt org-agenda-no-heading-message))
3971 (add-text-properties
3974 (list 'org-marker (org-agenda-new-marker pos)
3975 'org-hd-marker (org-agenda-new-marker pos1)
3976 'priority (+ (- 10 diff) (org-get-priority txt))
3977 'face (cond ((<= diff 0) 'org-warning-face)
3978 ((<= diff 5) 'org-scheduled-previously-face)
3981 ((<= diff 0) 'org-warning-face)
3982 ((<= diff 5) 'org-scheduled-previously-face)
3984 'done-face 'org-done-face)
3990 (defun org-agenda-get-scheduled ()
3991 "Return the scheduled information for agenda display."
3992 (let* ((props (list 'face 'org-scheduled-previously-face
3993 'undone-face 'org-scheduled-previously-face
3994 'done-face 'org-done-face
3995 'mouse-face 'highlight
3996 'keymap org-agenda-keymap
3998 (format "mouse-2 or RET jump to org file %s"
3999 (abbreviate-file-name (buffer-file-name)))))
4000 (regexp org-scheduled-time-regexp)
4001 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4002 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4005 (goto-char (point-min))
4006 (while (re-search-forward regexp nil t)
4007 (setq pos (1- (match-beginning 1))
4009 (org-time-string-to-time (match-string 1)))
4011 ;; When to show a scheduled item in the calendar:
4012 ;; If it is on or past the date.
4013 (if (and (< diff 0) todayp)
4015 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4017 (goto-char (match-end 0))
4018 (setq pos1 (match-end 1))
4019 (setq head (buffer-substring-no-properties
4021 (progn (skip-chars-forward "^\r\n") (point))))
4022 (if (string-match org-looking-at-done-regexp head)
4024 (setq txt (org-format-agenda-item
4025 (format "Sched.%2dx: " (- 1 diff)) head))))
4026 (setq txt org-agenda-no-heading-message))
4028 (add-text-properties
4030 (append (list 'org-marker (org-agenda-new-marker pos)
4031 'org-hd-marker (org-agenda-new-marker pos1)
4032 'priority (+ (- 5 diff) (org-get-priority txt)))
4037 (defun org-agenda-get-blocks ()
4038 "Return the date-range information for agenda display."
4039 (let* ((props (list 'face nil
4040 'mouse-face 'highlight
4041 'keymap org-agenda-keymap
4043 (format "mouse-2 or RET jump to org file %s"
4044 (abbreviate-file-name (buffer-file-name)))))
4045 (regexp org-tr-regexp)
4046 (d0 (calendar-absolute-from-gregorian date))
4047 marker hdmarker ee txt d1 d2 s1 s2)
4048 (goto-char (point-min))
4049 (while (re-search-forward regexp nil t)
4050 (setq s1 (match-string 1)
4052 d1 (time-to-days (org-time-string-to-time s1))
4053 d2 (time-to-days (org-time-string-to-time s2)))
4054 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4055 ;; Only allow days between the limits, because the normal
4056 ;; date stamps will catch the limits.
4058 (setq marker (org-agenda-new-marker (point)))
4059 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4061 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4062 (goto-char (match-end 1))
4063 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4064 (setq txt (org-format-agenda-item
4066 (1+ (- d0 d1)) (1+ (- d2 d1)))
4068 (setq txt org-agenda-no-heading-message))
4069 (add-text-properties
4070 0 (length txt) (append (list 'org-marker marker
4071 'org-hd-marker hdmarker
4072 'priority (org-get-priority txt))
4076 (outline-next-heading))
4077 ;; Sort the entries by expiration date.
4080 (defun org-format-agenda-item (prefix txt &optional category)
4081 "Format TXT to be inserted into the agenda buffer.
4082 In particular, this indents the line and adds a category."
4083 (let* ((category (or category
4085 (file-name-sans-extension
4086 (file-name-nondirectory (buffer-file-name)))))
4088 (time-of-day (org-get-time-of-day txt))
4089 (t1 (if time-of-day (concat "0" (int-to-string time-of-day)) "0000"))
4090 (time (if time-of-day
4091 (concat (substring t1 -4 -2)
4092 ":" (substring t1 -2))
4095 (if (symbolp category) (setq category (symbol-name category)))
4096 (setq rtn (concat (eval org-prefix-format-compiled) txt))
4097 (add-text-properties
4098 0 (length rtn) (list 'category (downcase category)
4099 'prefix-length (- (length rtn) (length txt))
4100 'time-of-day time-of-day)
4104 (defun org-compile-prefix-format (format)
4105 "Compile the prefix format into a Lisp form that can be evaluated.
4106 The resulting form is returned and stored in the variable
4107 `org-prefix-format-compiled'."
4108 (let ((start 0) varform vars (s format) c)
4109 (while (string-match "%\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4111 (setq var (cdr (assoc (match-string 3 s)
4112 '(("c" . category) ("t" . time) ("s" . extra))))
4113 c (match-string 2 s)
4114 start (1+ (match-beginning 0)))
4115 (if (= (length c) 1)
4116 (setq varform `(if (equal "" ,var) "" (concat ,var ,c)))
4118 (setq s (replace-match "%\\1s" t nil s))
4119 (push varform vars))
4120 (setq vars (nreverse vars))
4121 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4123 (defun org-get-time-of-day (s)
4124 "Check string S for a time of day.
4125 If found, return it as a military time number between 0 and 2400.
4126 If not found, return nil."
4130 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\>" s)
4132 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\>" s))
4133 (+ (* 100 (+ (string-to-number (match-string 1 s))
4134 (if (and (match-beginning 4)
4135 (equal (downcase (match-string 4 s)) "pm"))
4137 (if (match-beginning 3)
4138 (string-to-number (match-string 3 s))
4141 (defun org-finalize-agenda-entries (list)
4142 "Sort and concatenate the agenda items."
4143 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4145 (defsubst org-cmp-priority (a b)
4146 "Compare the priorities of string a and b."
4147 (let ((pa (or (get-text-property 1 'priority a) 0))
4148 (pb (or (get-text-property 1 'priority b) 0)))
4149 (cond ((> pa pb) +1)
4153 (defsubst org-cmp-category (a b)
4154 "Compare the string values of categories of strings a and b."
4155 (let ((ca (or (get-text-property 1 'category a) ""))
4156 (cb (or (get-text-property 1 'category b) "")))
4157 (cond ((string-lessp ca cb) -1)
4158 ((string-lessp cb ca) +1)
4161 (defsubst org-cmp-time (a b)
4162 "Compare the time-of-day values of strings a and b."
4163 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4164 (ta (or (get-text-property 1 'time-of-day a) def))
4165 (tb (or (get-text-property 1 'time-of-day b) def)))
4166 (cond ((< ta tb) -1)
4170 (defun org-entries-lessp (a b)
4171 "Predicate for sorting agenda entries."
4172 (let* ((time-up (org-cmp-time a b))
4173 (time-down (if time-up (- time-up) nil))
4174 (priority-up (org-cmp-priority a b))
4175 (priority-down (if priority-up (- priority-up) nil))
4176 (category-up (org-cmp-category a b))
4177 (category-down (if category-up (- category-up) nil))
4178 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4180 (eval (cons 'or org-agenda-sorting-strategy))
4181 '((-1 . t) (1 . nil) (nil . nil))))))
4183 (defun org-agenda-show-priority ()
4184 "Show the priority of the current item.
4185 This priority is composed of the main priority given with the [#A] cookies,
4186 and by additional input from the age of a schedules or deadline entry."
4188 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4189 (message "Priority is %d" (if pri pri -1000))))
4191 (defun org-agenda-goto (&optional highlight)
4192 "Go to the Org-mode file which contains the item at point."
4194 (let* ((marker (or (get-text-property (point) 'org-marker)
4195 (org-agenda-error)))
4196 (buffer (marker-buffer marker))
4197 (pos (marker-position marker)))
4198 (switch-to-buffer-other-window buffer)
4201 (when (eq major-mode 'org-mode)
4202 (org-show-hidden-entry)
4204 (and (outline-next-heading)
4205 (org-flag-heading nil)))) ; show the next heading
4206 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4208 (defun org-agenda-switch-to ()
4209 "Go to the Org-mode file which contains the item at point."
4211 (let* ((marker (or (get-text-property (point) 'org-marker)
4212 (org-agenda-error)))
4213 (buffer (marker-buffer marker))
4214 (pos (marker-position marker)))
4215 (switch-to-buffer buffer)
4216 (delete-other-windows)
4219 (when (eq major-mode 'org-mode)
4220 (org-show-hidden-entry)
4222 (and (outline-next-heading)
4223 (org-flag-heading nil)))))) ; show the next heading
4225 (defun org-agenda-goto-mouse (ev)
4226 "Go to the Org-mode file which contains the item at the mouse click."
4228 (mouse-set-point ev)
4231 (defun org-agenda-show ()
4232 "Display the Org-mode file which contains the item at point."
4234 (let ((win (selected-window)))
4236 (select-window win)))
4238 (defun org-agenda-recenter (arg)
4239 "Display the Org-mode file which contains the item at point and recenter."
4241 (let ((win (selected-window)))
4244 (select-window win)))
4246 (defun org-agenda-show-mouse (ev)
4247 "Display the Org-mode file which contains the item at the mouse click."
4249 (mouse-set-point ev)
4252 (defun org-agenda-check-no-diary ()
4253 "Check if the entry is a diary link and abort if yes."
4254 (if (get-text-property (point) 'org-agenda-diary-link)
4255 (org-agenda-error)))
4257 (defun org-agenda-error ()
4258 (error "Command not allowed in this line."))
4260 (defvar org-last-heading-marker (make-marker)
4261 "Marker pointing to the headline that last changed its TODO state
4262 by a remote command from the agenda.")
4264 (defun org-agenda-todo ()
4265 "Cycle TODO state of line at point, also in Org-mode file.
4266 This changes the line at point, all other lines in the agenda referring to
4267 the same tree node, and the headline of the tree node in the Org-mode file."
4269 (org-agenda-check-no-diary)
4270 (let* ((col (current-column))
4271 (marker (or (get-text-property (point) 'org-marker)
4272 (org-agenda-error)))
4273 (buffer (marker-buffer marker))
4274 (pos (marker-position marker))
4275 (hdmarker (get-text-property (point) 'org-hd-marker))
4276 (buffer-read-only nil)
4278 (with-current-buffer buffer
4281 (org-show-hidden-entry)
4283 (and (outline-next-heading)
4284 (org-flag-heading nil))) ; show the next heading
4287 (setq newhead (org-get-heading))
4289 (org-back-to-heading)
4290 (move-marker org-last-heading-marker (point))))
4291 (beginning-of-line 1)
4293 (org-agenda-change-all-lines newhead hdmarker 'fixface))
4294 (move-to-column col)))
4296 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
4297 "Change all lines in the agenda buffer which match hdmarker.
4298 The new content of the line will be NEWHEAD. HDMARKER is checked with
4299 `equal' against all `org-hd-marker' text properties in the file."
4300 (let* (props m pl undone-face done-face)
4302 (goto-char (point-max))
4303 (beginning-of-line 1)
4305 (when (and (setq m (get-text-property (point) 'org-hd-marker))
4307 (setq props (text-properties-at (point))
4308 pl (get-text-property (point) 'prefix-length)
4309 undone-face (get-text-property (point) 'undone-face)
4310 done-face (get-text-property (point) 'done-face))
4312 (if (looking-at ".*")
4314 (replace-match newhead t t)
4315 (beginning-of-line 1)
4316 (add-text-properties (point-at-bol) (point-at-eol) props)
4318 (add-text-properties
4319 (point-at-bol) (point-at-eol)
4321 (if org-last-todo-state-is-todo
4322 undone-face done-face))))
4323 (beginning-of-line 1))
4324 (error "Line update did not work")))
4325 (beginning-of-line 0)))))
4327 (defun org-agenda-priority-up ()
4328 "Increase the priority of line at point, also in Org-mode file."
4330 (org-agenda-priority 'up))
4332 (defun org-agenda-priority-down ()
4333 "Decrease the priority of line at point, also in Org-mode file."
4335 (org-agenda-priority 'down))
4337 (defun org-agenda-priority (&optional force-direction)
4338 "Set the priority of line at point, also in Org-mode file.
4339 This changes the line at point, all other lines in the agenda referring to
4340 the same tree node, and the headline of the tree node in the Org-mode file."
4342 (org-agenda-check-no-diary)
4343 (let* ((marker (or (get-text-property (point) 'org-marker)
4344 (org-agenda-error)))
4345 (buffer (marker-buffer marker))
4346 (pos (marker-position marker))
4347 (hdmarker (get-text-property (point) 'org-hd-marker))
4348 (buffer-read-only nil)
4350 (with-current-buffer buffer
4353 (org-show-hidden-entry)
4355 (and (outline-next-heading)
4356 (org-flag-heading nil))) ; show the next heading
4357 (funcall 'org-priority force-direction)
4358 (setq newhead (org-get-heading)))
4359 (org-agenda-change-all-lines newhead hdmarker)
4360 (beginning-of-line 1)))
4362 (defun org-agenda-date-later (arg &optional what)
4363 "Change the date of this item to one day later."
4365 (org-agenda-check-no-diary)
4366 (let* ((marker (or (get-text-property (point) 'org-marker)
4367 (org-agenda-error)))
4368 (buffer (marker-buffer marker))
4369 (pos (marker-position marker)))
4370 (with-current-buffer buffer
4373 (if (not (org-at-timestamp-p))
4374 (error "Cannot find time stamp"))
4375 (org-timestamp-change arg (or what 'day))
4376 (message "Time stamp changed to %s" org-last-changed-timestamp))))
4378 (defun org-agenda-date-earlier (arg &optional what)
4379 "Change the date of this item to one day earlier."
4381 (org-agenda-date-later (- arg) what))
4383 (defun org-agenda-date-prompt (arg)
4384 "Change the date of this item. Date is prompted for, with default today.
4385 The prefix ARG is passed to the `org-time-stamp' command and can therefore
4386 be used to request time specification in the time stamp."
4388 (org-agenda-check-no-diary)
4389 (let* ((marker (or (get-text-property (point) 'org-marker)
4390 (org-agenda-error)))
4391 (buffer (marker-buffer marker))
4392 (pos (marker-position marker)))
4393 (with-current-buffer buffer
4396 (if (not (org-at-timestamp-p))
4397 (error "Cannot find time stamp"))
4398 (org-time-stamp arg)
4399 (message "Time stamp changed to %s" org-last-changed-timestamp))))
4401 (defun org-get-heading ()
4402 "Return the heading of the current entry, without the stars."
4404 (if (and (re-search-backward "[\r\n]\\*" nil t)
4405 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
4409 (defun org-agenda-diary-entry ()
4410 "Make a diary entry, like the `i' command from the calendar.
4411 All the standard commands work: block, weekly etc"
4413 (require 'diary-lib)
4415 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
4416 (read-char-exclusive)))
4417 (cmd (cdr (assoc char
4418 '((?d . insert-diary-entry)
4419 (?w . insert-weekly-diary-entry)
4420 (?m . insert-monthly-diary-entry)
4421 (?y . insert-yearly-diary-entry)
4422 (?a . insert-anniversary-diary-entry)
4423 (?b . insert-block-diary-entry)
4424 (?c . insert-cyclic-diary-entry)))))
4425 (oldf (symbol-function 'calendar-cursor-to-date))
4427 (mark (or (mark t) (point))))
4429 (error "No command associated with <%c>" char))
4430 (unless (and (get-text-property point 'day)
4431 (or (not (equal ?b char))
4432 (get-text-property mark 'day)))
4433 (error "Don't know which date to use for diary entry"))
4434 ;; We implement this by hacking the `calendar-cursor-to-date' function
4435 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
4436 (let ((calendar-mark-ring
4437 (list (calendar-gregorian-from-absolute
4438 (or (get-text-property mark 'day)
4439 (get-text-property point 'day))))))
4442 (fset 'calendar-cursor-to-date
4443 (lambda (&optional error)
4444 (calendar-gregorian-from-absolute
4445 (get-text-property point 'day))))
4446 (call-interactively cmd))
4447 (fset 'calendar-cursor-to-date oldf)))))
4450 (defun org-agenda-execute-calendar-command (cmd)
4451 "Execute a calendar command from the agenda, with the date associated to
4452 the cursor position."
4453 (require 'diary-lib)
4454 (unless (get-text-property (point) 'day)
4455 (error "Don't know which date to use for calendar command"))
4456 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
4458 (date (calendar-gregorian-from-absolute
4459 (get-text-property point 'day)))
4460 (displayed-day (extract-calendar-day date))
4461 (displayed-month (extract-calendar-month date))
4462 (displayed-year (extract-calendar-year date)))
4465 (fset 'calendar-cursor-to-date
4466 (lambda (&optional error)
4467 (calendar-gregorian-from-absolute
4468 (get-text-property point 'day))))
4469 (call-interactively cmd))
4470 (fset 'calendar-cursor-to-date oldf))))
4472 (defun org-agenda-phases-of-moon ()
4473 "Display the phases of the moon for the 3 months around the cursor date."
4475 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
4477 (defun org-agenda-holidays ()
4478 "Display the holidays for the 3 months around the cursor date."
4480 (org-agenda-execute-calendar-command 'list-calendar-holidays))
4482 (defun org-agenda-sunrise-sunset (arg)
4483 "Display sunrise and sunset for the cursor date.
4484 Latitude and longitude can be specified with the variables
4485 `calendar-latitude' and `calendar-longitude'. When called with prefix
4486 argument, latitude and longitude will be prompted for."
4488 (let ((calendar-longitude (if arg nil calendar-longitude))
4489 (calendar-latitude (if arg nil calendar-latitude))
4490 (calendar-location-name
4491 (if arg "the given coordinates" calendar-location-name)))
4492 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
4494 (defun org-agenda-goto-calendar ()
4495 "Open the Emacs calendar with the date at the cursor."
4497 (let* ((day (or (get-text-property (point) 'day)
4498 (error "Don't know which date to open in calendar")))
4499 (date (calendar-gregorian-from-absolute day)))
4501 (calendar-goto-date date)))
4503 (defun org-calendar-goto-agenda ()
4504 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
4505 This is a command that has to be installed in `calendar-mode-map'."
4507 (org-agenda nil (calendar-absolute-from-gregorian
4508 (calendar-cursor-to-date))))
4510 (defun org-agenda-convert-date ()
4512 (let ((day (get-text-property (point) 'day))
4515 (error "Don't know which date to convert"))
4516 (setq date (calendar-gregorian-from-absolute day))
4518 "Gregorian: " (calendar-date-string date) "\n"
4519 "ISO: " (calendar-iso-date-string date) "\n"
4520 "Day of Yr: " (calendar-day-of-year-string date) "\n"
4521 "Julian: " (calendar-julian-date-string date) "\n"
4522 "Astronomic: " (calendar-astro-date-string date)
4523 " (Julian date number at noon UTC)\n"
4524 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
4525 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
4526 "French: " (calendar-french-date-string date) "\n"
4527 "Mayan: " (calendar-mayan-date-string date) "\n"
4528 "Coptic: " (calendar-coptic-date-string date) "\n"
4529 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
4530 "Persian: " (calendar-persian-date-string date) "\n"
4531 "Chinese: " (calendar-chinese-date-string date) "\n"))
4532 (with-output-to-temp-buffer "*Dates*"
4534 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
4538 (defun org-find-file-at-mouse (ev)
4539 "Open file link or URL at mouse."
4541 (mouse-set-point ev)
4542 (org-open-at-point 'in-emacs))
4544 (defun org-open-at-mouse (ev)
4545 "Open file link or URL at mouse."
4547 (mouse-set-point ev)
4548 (org-open-at-point))
4550 (defun org-open-at-point (&optional in-emacs)
4551 "Open link at or after point.
4552 If there is no link at point, this function will search forward up to
4553 the end of the current subtree.
4554 Normally, files will be opened by an appropriate application. If the
4555 optional argument IN-EMACS is non-nil, Emacs will visit the file."
4557 (if (org-at-timestamp-p)
4558 (org-agenda nil (time-to-days (org-time-string-to-time
4559 (substring (match-string 1) 0 10)))
4561 (let (type path line (pos (point)))
4563 (skip-chars-backward
4564 (if org-allow-space-in-links "^\t\n\r" "^ \t\n\r"))
4565 (if (re-search-forward
4569 (progn (outline-end-of-subtree) (max pos (point)))
4570 (error (end-of-line 1) (point))))
4572 (setq type (match-string 1)
4573 path (match-string 2)))
4575 (error "No link found."))
4576 ;; Remove any trailing spaces in path
4577 (if (string-match " +\\'" path)
4578 (setq path (replace-match "" t t path)))
4582 ((string= type "file")
4583 (if (string-match ":\\([0-9]+\\)\\'" path)
4584 (setq line (string-to-number (match-string 1 path))
4585 path (substring path 0 (match-beginning 0))))
4586 (org-open-file path in-emacs line))
4588 ((string= type "news")
4589 (org-follow-gnus-link path))
4591 ((string= type "bbdb")
4592 (org-follow-bbdb-link path))
4594 ((string= type "gnus")
4595 (let (group article)
4596 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
4597 (error "Error in Gnus link"))
4598 (setq group (match-string 1 path)
4599 article (match-string 3 path))
4600 (org-follow-gnus-link group article)))
4602 ((string= type "vm")
4603 (let (folder article)
4604 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
4605 (error "Error in VM link"))
4606 (setq folder (match-string 1 path)
4607 article (match-string 3 path))
4608 ;; in-emacs is the prefix arg, will be interpreted as read-only
4609 (org-follow-vm-link folder article in-emacs)))
4611 ((string= type "wl")
4612 (let (folder article)
4613 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
4614 (error "Error in Wanderlust link"))
4615 (setq folder (match-string 1 path)
4616 article (match-string 3 path))
4617 (org-follow-wl-link folder article)))
4619 ((string= type "rmail")
4620 (let (folder article)
4621 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
4622 (error "Error in RMAIL link"))
4623 (setq folder (match-string 1 path)
4624 article (match-string 3 path))
4625 (org-follow-rmail-link folder article)))
4627 ((string= type "shell")
4629 (if (or (not org-confirm-shell-links)
4630 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
4635 (browse-url-at-point)))))))
4637 (defun org-follow-bbdb-link (name)
4638 "Follow a BBDB link to NAME."
4640 (let ((inhibit-redisplay t))
4642 ;; Exact match on name
4643 (bbdb-name (concat "\\`" name "\\'") nil)
4644 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
4645 ;; Exact match on name
4646 (bbdb-company (concat "\\`" name "\\'") nil)
4647 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
4648 ;; Partial match on name
4649 (bbdb-name name nil)
4650 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
4651 ;; Partial match on company
4652 (bbdb-company name nil)
4653 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
4654 ;; General match including network address and notes
4656 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
4657 (delete-window (get-buffer-window "*BBDB*"))
4658 (error "No matching BBDB record")))))
4660 (defun org-follow-gnus-link (&optional group article)
4661 "Follow a Gnus link to GROUP and ARTICLE."
4663 (funcall (cdr (assq 'gnus org-link-frame-setup)))
4664 (if group (gnus-fetch-group group))
4666 (or (gnus-summary-goto-article article nil 'force)
4667 (if (fboundp 'gnus-summary-insert-cached-articles)
4669 (gnus-summary-insert-cached-articles)
4670 (gnus-summary-goto-article article nil 'force))
4671 (message "Message could not be found.")))))
4673 (defun org-follow-vm-link (&optional folder article readonly)
4674 "Follow a VM link to FOLDER and ARTICLE."
4676 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
4677 ;; ange-ftp or efs or tramp access
4678 (let ((user (or (match-string 1 folder) (user-login-name)))
4679 (host (match-string 2 folder))
4680 (file (match-string 3 folder)))
4683 ;; use tramp to access the file
4685 (setq folder (format "[%s@%s]%s" user host file))
4686 (setq folder (format "/%s@%s:%s" user host file))))
4688 ;; use ange-ftp or efs
4689 (require (if org-xemacs-p 'efs 'ange-ftp))
4690 (setq folder (format "/%s@%s:%s" user host file))))))
4692 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
4695 (vm-select-folder-buffer)
4697 (let ((case-fold-search t))
4698 (goto-char (point-min))
4699 (if (not (re-search-forward
4700 (concat "^" "message-id: *" (regexp-quote article))))
4701 (error "Could not find the specified message in this folder"))
4704 (vm-beginning-of-message)
4707 (defun org-follow-wl-link (folder article)
4708 "Follow a Wanderlust link to FOLDER and ARTICLE."
4709 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
4710 (if article (wl-summary-jump-to-msg-by-message-id article))
4711 (wl-summary-redisplay))
4713 (defun org-follow-rmail-link (folder article)
4714 "Follow an RMAIL link to FOLDER and ARTICLE."
4715 (let (message-number)
4717 (save-window-excursion
4718 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
4719 (setq message-number
4722 (goto-char (point-max))
4723 (if (re-search-backward
4724 (concat "^Message-ID:\\s-+" (regexp-quote
4727 (rmail-what-message))))))
4730 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
4731 (rmail-show-message message-number)
4733 (error "Message not found"))))
4735 (defun org-open-file (path &optional in-emacs line)
4736 "Open the file at PATH.
4737 First, this expands any special file name abbreviations. Then the
4738 configuration variable `org-file-apps' is checked if it contains an
4739 entry for this file type, and if yes, the corresponding command is launched.
4740 If no application is found, Emacs simply visits the file.
4741 With optional argument IN-EMACS, Emacs will visit the file.
4742 If the file does not exist, an error is thrown."
4743 (let* ((file (convert-standard-filename (org-expand-file-name path)))
4744 (dfile (downcase file))
4746 (if (and (not (file-exists-p file))
4747 (not org-open-non-existing-files))
4748 (error "No such file: %s" file))
4749 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
4750 (setq ext (match-string 1 dfile))
4751 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
4752 (setq ext (match-string 1 dfile))))
4753 (setq apps (append org-file-apps (org-default-apps)))
4756 (setq cmd (or (cdr (assoc ext apps))
4757 (cdr (assoc t apps)))))
4759 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
4760 (setq cmd (format cmd file))
4761 (save-window-excursion
4762 (shell-command (concat cmd " & &"))))
4765 (funcall (cdr (assq 'file org-link-frame-setup)) file)
4766 (if line (goto-line line)))
4769 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
4771 (defun org-default-apps ()
4772 "Return the default applications for this operating system."
4774 ((eq system-type 'darwin)
4775 org-file-apps-defaults-macosx)
4776 ((eq system-type 'windows-nt)
4777 org-file-apps-defaults-windowsnt)
4778 ((eq system-type 'linux)
4779 org-file-apps-defaults-linux)
4780 (t org-file-apps-defaults-linux)))
4782 (defun org-expand-file-name (path)
4783 "Replace special path abbreviations and expand the file name."
4784 (expand-file-name path))
4787 (defvar org-insert-link-history nil
4788 "Minibuffer history for links inserted with `org-insert-link'.")
4790 (defvar org-stored-links nil
4791 "Contains the links stored with `org-store-link'.")
4794 (defun org-store-link (arg)
4795 "\\<org-mode-map>Store an org-link to the current location.
4796 This link can later be inserted into an org-buffer with
4797 \\[org-insert-link].
4798 For some link types, a prefix arg is interpreted:
4799 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
4800 For file links, arg negates `org-line-numbers-in-file-links'."
4805 ((eq major-mode 'bbdb-mode)
4806 (setq link (concat "bbdb:"
4807 (or (bbdb-record-name (bbdb-current-record))
4808 (bbdb-record-company (bbdb-current-record))))))
4810 ((eq major-mode 'calendar-mode)
4811 (let ((cd (calendar-cursor-to-date)))
4814 (car org-time-stamp-formats)
4816 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
4819 ((or (eq major-mode 'vm-summary-mode)
4820 (eq major-mode 'vm-presentation-mode))
4821 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
4822 (vm-follow-summary-cursor)
4824 (vm-select-folder-buffer)
4825 (let* ((message (car vm-message-pointer))
4826 (folder (buffer-file-name))
4827 (subject (vm-su-subject message))
4828 (author (vm-su-full-name message))
4829 (message-id (vm-su-message-id message)))
4830 (setq folder (abbreviate-file-name folder))
4831 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
4833 (setq folder (replace-match "" t t folder)))
4834 (setq cpltxt (concat author " on: " subject))
4835 (setq link (concat cpltxt "\n " "vm:" folder
4838 ((eq major-mode 'wl-summary-mode)
4839 (let* ((msgnum (wl-summary-message-number))
4840 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
4841 msgnum 'message-id))
4842 (wl-message-entity (elmo-msgdb-overview-get-entity
4843 msgnum (wl-summary-buffer-msgdb)))
4844 (author (wl-summary-line-from)) ; FIXME: how to get author name?
4845 (subject "???")) ; FIXME: How to get subject of email?
4846 (setq cpltxt (concat author " on: " subject))
4847 (setq link (concat cpltxt "\n " "wl:" wl-summary-buffer-folder-name
4850 ((eq major-mode 'rmail-mode)
4853 (rmail-narrow-to-non-pruned-header)
4854 (let ((folder (buffer-file-name))
4855 (message-id (mail-fetch-field "message-id"))
4856 (author (mail-fetch-field "from"))
4857 (subject (mail-fetch-field "subject")))
4858 (setq cpltxt (concat author " on: " subject))
4859 (setq link (concat cpltxt "\n " "rmail:" folder
4860 "#" message-id))))))
4862 ((eq major-mode 'gnus-group-mode)
4863 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
4864 (gnus-group-group-name)) ; version
4865 ((fboundp 'gnus-group-name)
4868 (setq link (concat (if (org-xor arg org-usenet-links-prefer-google)
4869 "http://groups.google.com/groups?group="
4873 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
4874 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
4875 (gnus-summary-beginning-of-article)
4876 (let* ((group (car gnus-article-current))
4877 (article (cdr gnus-article-current))
4878 (header (gnus-summary-article-header article))
4879 (author (mail-header-from header))
4880 (message-id (mail-header-id header))
4881 (date (mail-header-date header))
4882 (subject (gnus-summary-subject-string)))
4883 (setq cpltxt (concat author " on: " subject))
4884 (if (org-xor arg org-usenet-links-prefer-google)
4888 (format "http://groups.google.com/groups?as_umsgid=%s"
4889 (org-fixup-message-id-for-http message-id))))
4890 (setq link (concat cpltxt "\n" "gnus:" group
4891 "#" (number-to-string article))))))
4893 ((eq major-mode 'w3-mode)
4894 (setq link (url-view-url t)))
4895 ((eq major-mode 'w3m-mode)
4896 (setq link w3m-current-url))
4899 ;; Just link to this file here.
4900 (setq link (concat "file:"
4901 (abbreviate-file-name (buffer-file-name))))
4902 ;; Add the line number?
4903 (if (org-xor org-line-numbers-in-file-links arg)
4907 (+ (if (bolp) 1 0) (count-lines
4908 (point-min) (point))))))))
4910 (error "Cannot link to a buffer which is not visiting a file"))
4911 (t (setq link nil)))
4913 (if (and (interactive-p) link)
4915 (setq org-stored-links
4916 (cons (cons (or cpltxt link) link) org-stored-links))
4917 (message "Stored: %s" (or cpltxt link)))
4920 (defun org-xor (a b)
4926 (defun org-get-header (header)
4927 "Find a header field in the current buffer."
4929 (goto-char (point-min))
4930 (let ((case-fold-search t) s)
4933 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
4934 (setq s (match-string 1)))
4935 (while (string-match "\"" s)
4936 (setq s (replace-match "" t t s)))
4937 (if (string-match "[<(].*" s)
4938 (setq s (replace-match "" t t s))))
4939 ((eq header 'message-id)
4940 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
4941 (setq s (match-string 1))))
4942 ((eq header 'subject)
4943 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
4944 (setq s (match-string 1)))))
4945 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
4946 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
4950 (defun org-fixup-message-id-for-http (s)
4951 "Replace special characters in a message id, so it can be used in an http query."
4952 (while (string-match "<" s)
4953 (setq s (replace-match "%3C" t t s)))
4954 (while (string-match ">" s)
4955 (setq s (replace-match "%3E" t t s)))
4956 (while (string-match "@" s)
4957 (setq s (replace-match "%40" t t s)))
4960 (defun org-insert-link (&optional complete-file)
4961 "Insert a link. At the prompt, enter the link.
4963 Completion can be used to select a link previously stored with
4964 `org-store-link'. When the empty string is entered (i.e. if you just
4965 press RET at the prompt), the link defaults to the most recently
4968 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
4969 selected using completion. The path to the file will be relative to
4970 the current directory if the file is in the current directory or a
4971 subdirectory. Otherwise, the link will be the absolute path as
4972 completed in the minibuffer (i.e. normally ~/path/to/file).
4974 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
4975 is in the current directory or below."
4977 (let ((link (if complete-file
4978 (read-file-name "File: ")
4980 "Link: " org-stored-links nil nil nil
4981 org-insert-link-history
4982 (or (car (car org-stored-links))))))
4984 (if (or (not link) (equal link ""))
4985 (error "No links available"))
4987 (let ((pwd (file-name-as-directory (expand-file-name "."))))
4989 ((equal complete-file '(16))
4990 (insert "file:" (abbreviate-file-name (expand-file-name link))))
4991 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
4992 (expand-file-name link))
4993 (insert "file:" (match-string 1 (expand-file-name link))))
4994 (t (insert "file:" link))))
4995 (setq linktxt (cdr (assoc link org-stored-links)))
4996 (if (not org-keep-stored-link-after-insertion)
4997 (setq org-stored-links (delq (assoc link org-stored-links)
4999 (let ((lines (org-split-string (or linktxt link) "\n")))
5000 (insert (car lines))
5001 (setq matched (string-match org-link-regexp (car lines)))
5002 (setq lines (cdr lines))
5006 (beginning-of-line 0)
5007 (looking-at "[ \t]+\\S-"))
5009 (setq matched (or matched
5010 (string-match org-link-regexp (car lines))))
5011 (insert (car lines))
5012 (setq lines (cdr lines))))
5014 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5016 ;;; Hooks for remember.el
5018 (defun org-remember-annotation ()
5019 "Return a link to the current location as an annotation for remember.el.
5020 If you are using Org-mode files as target for data storage with
5021 remember.el, then the annotations should include a link compatible with the
5022 conventions in Org-mode. This function returns such a link."
5023 (org-store-link nil))
5025 (defconst org-remember-help
5026 "Select a destination location for the note.
5027 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5028 RET at beg-of-buf -> Append to file as level 2 headline
5029 RET on headline -> Store as sublevel entry to current headline
5030 <left>/<right> -> before/after current headline, same headings level")
5033 (defun org-remember-handler ()
5034 "Store stuff from remember.el into an org file.
5035 First prompts for an org file. If the user just presses return, the value
5036 of `org-default-notes-file' is used.
5037 Then the command offers the headings tree of the selected file in order to
5038 file the text at a specific location.
5039 You can either immediately press RET to get the note appended to the
5040 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5041 find a better place. Then press RET or <left> or <right> in insert the note.
5043 Key Cursor position Note gets inserted
5044 -----------------------------------------------------------------------------
5045 RET buffer-start as level 2 heading at end of file
5046 RET on headline as sublevel of the heading at cursor
5047 RET no heading at cursor position, level taken from context.
5048 Or use prefix arg to specify level manually.
5049 <left> on headline as same level, before current heading
5050 <right> on headline as same level, after current heading
5052 So the fastest way to store the note is to press RET RET to append it to
5053 the default file. This way your current train of thought is not
5054 interrupted, in accordance with the principles of remember.el. But with
5055 little extra effort, you can push it directly to the correct location.
5057 Before being stored away, the function ensures that the text has a
5058 headline, i.e. a first line that starts with a \"*\". If not, a headline
5059 is constructed from the current date and some additional data.
5061 If the variable `org-adapt-indentation' is non-nil, the entire text is
5062 also indented so that it starts in the same column as the headline
5063 \(i.e. after the stars).
5065 See also the variable `org-reverse-note-order'."
5067 (let* ((txt (buffer-substring (point-min) (point-max)))
5068 (fastp current-prefix-arg)
5069 (file (if fastp org-default-notes-file (org-get-org-file)))
5070 (visiting (find-buffer-visiting file))
5071 (org-startup-with-deadline-check nil)
5072 (org-startup-folded nil)
5073 spos level indent reversed)
5074 ;; Modify text so that it becomes a nice subtree which can be inserted
5075 ;; into an org tree.
5076 (let* ((lines (split-string txt "\n"))
5078 (lines (cdr lines)))
5079 (if (string-match "^\\*+" first)
5080 ;; Is already a headline
5081 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5083 ;; We need to add a headline: Use time and first buffer line
5084 (setq lines (cons first lines)
5085 first (concat "* " (current-time-string)
5086 " (" (remember-buffer-desc) ")")
5088 (if org-adapt-indentation
5089 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5090 (setq txt (concat first "\n"
5091 (mapconcat 'identity lines "\n"))))
5094 (find-file-noselect file))
5095 (with-current-buffer (get-file-buffer file)
5096 (setq reversed (org-notes-order-reversed-p))
5100 ;; Ask the User for a location
5101 (setq spos (if fastp 1 (org-get-location
5103 org-remember-help)))
5104 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5105 ; not handle this note
5108 ;; Put it at the start or end, as level 2
5111 (goto-char (if reversed (point-min) (point-max)))
5112 (if (not (bolp)) (newline))
5113 (org-paste-subtree (or current-prefix-arg 2) txt)))
5114 ((and (org-on-heading-p nil) (not current-prefix-arg))
5115 ;; Put it below this entry, at the beg/end of the subtree
5116 (org-back-to-heading)
5117 (setq level (outline-level))
5119 (outline-end-of-heading)
5120 (outline-end-of-subtree))
5121 (if (not (bolp)) (newline))
5122 (beginning-of-line 1)
5123 (org-paste-subtree (1+ level) txt))
5125 ;; Put it right there, with automatic level determined by
5126 ;; org-paste-subtree or from prefix arg
5127 (org-paste-subtree current-prefix-arg txt)))
5128 (when remember-save-after-remembering
5130 (if (not visiting) (kill-buffer (current-buffer)))))))))
5131 t) ;; return t to indicate that we took care of this note.
5133 (defun org-get-org-file ()
5134 "Read a filename, with default directory `org-directory'."
5135 (let ((default (or org-default-notes-file remember-data-file)))
5136 (read-file-name (format "File name [%s]: " default)
5137 (file-name-as-directory org-directory)
5140 (defun org-notes-order-reversed-p ()
5141 "Check if the current file should receive notes in reversed order."
5143 ((not org-reverse-note-order) nil)
5144 ((eq t org-reverse-note-order) t)
5145 ((not (listp org-reverse-note-order)) nil)
5147 (let ((all org-reverse-note-order)
5149 (while (setq entry (pop all))
5150 (if (string-match (car entry) (buffer-file-name))
5151 (throw 'exit (cdr entry))))
5156 ;; Watch out: Here we are talking about two different kind of tables.
5157 ;; Most of the code is for the tables created with the Org-mode table editor.
5158 ;; Sometimes, we talk about tables created and edited with the table.el
5159 ;; Emacs package. We call the former org-type tables, and the latter
5160 ;; table.el-type tables.
5163 (defun org-before-change-function (beg end)
5164 "Every change indicates that a table might need an update."
5165 (setq org-table-may-need-update t))
5167 (defconst org-table-line-regexp "^[ \t]*|"
5168 "Detects an org-type table line.")
5169 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5170 "Detects an org-type table line.")
5171 (defconst org-table-hline-regexp "^[ \t]*|-"
5172 "Detects an org-type table hline.")
5173 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5174 "Detects a table-type table hline.")
5175 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5176 "Detects an org-type or table-type table.")
5177 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5178 "Searching from within a table (any type) this finds the first line
5179 outside the table.")
5180 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5181 "Searching from within a table (any type) this finds the first line
5182 outside the table.")
5184 (defun org-table-create-with-table.el ()
5185 "Use the table.el package to insert a new table.
5186 If there is already a table at point, convert between Org-mode tables
5187 and table.el tables."
5191 ((org-at-table.el-p)
5192 (if (y-or-n-p "Convert table to Org-mode table? ")
5193 (org-table-convert)))
5195 (if (y-or-n-p "Convert table to table.el table? ")
5196 (org-table-convert)))
5197 (t (call-interactively 'table-insert))))
5199 (defun org-table-create (&optional size)
5200 "Query for a size and insert a table skeleton.
5201 SIZE is a string Columns x Rows like for example \"3x2\"."
5204 (setq size (read-string
5205 (concat "Table size Columns x Rows [e.g. "
5206 org-table-default-size "]: ")
5207 "" nil org-table-default-size)))
5209 (let* ((pos (point))
5210 (indent (make-string (current-column) ?\ ))
5211 (split (org-split-string size " *x *"))
5212 (rows (string-to-number (nth 1 split)))
5213 (columns (string-to-number (car split)))
5214 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5216 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5217 (point-at-bol) (point)))
5218 (beginning-of-line 1)
5220 (mapcar (lambda (x) (insert line)) (make-list rows t))
5223 ;; Insert a hline after the first row.
5230 (defun org-table-convert-region (beg0 end0 nspace)
5231 "Convert region to a table.
5232 The region goes from BEG0 to END0, but these borders will be moved
5233 slightly, to make sure a beginning of line in the first line is included.
5234 When NSPACE is non-nil, it indicates the minimum number of spaces that
5235 separate columns (default: just one space)"
5236 (let* ((beg (min beg0 end0))
5237 (end (max beg0 end0))
5241 (beginning-of-line 1)
5242 (setq beg (move-marker (make-marker) (point)))
5244 (if (bolp) (backward-char 1) (end-of-line 1))
5245 (setq end (move-marker (make-marker) (point)))
5246 ;; Lets see if this is tab-separated material. If every nonempty line
5247 ;; contains a tab, we will assume that it is tab-separated material
5251 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5252 (if nspace (setq tabsep nil))
5255 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5256 (max 1 (prefix-numeric-value nspace)))))
5258 (while (re-search-forward re end t)
5259 (replace-match "|" t t))
5264 (defun org-table-import (file arg)
5265 "Import FILE as a table.
5266 The file is assumed to be tab-separated. Such files can be produced by most
5267 spreadsheet and database applications. If no tabs (at least one per line)
5268 are found, lines will be split on whitespace into fields."
5269 (interactive "f\nP")
5270 (or (bolp) (newline))
5273 (insert-file-contents file)
5274 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5276 (defun org-table-export ()
5277 "Export table as a tab-separated file.
5278 Such a file can be imported into a spreadsheet program like Excel."
5280 (let* ((beg (org-table-begin))
5281 (end (org-table-end))
5282 (table (buffer-substring beg end))
5283 (file (read-file-name "Export table to: "))
5285 (unless (or (not (file-exists-p file))
5286 (y-or-n-p (format "Overwrite file %s? " file)))
5290 (setq buf (current-buffer))
5294 (goto-char (point-min))
5295 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5296 (replace-match "" t t)
5298 (goto-char (point-min))
5299 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5300 (replace-match "" t t)
5301 (goto-char (min (1+ (point)) (point-max))))
5302 (goto-char (point-min))
5303 (while (re-search-forward "^-[-+]*$" nil t)
5305 (if (looking-at "\n")
5307 (goto-char (point-min))
5308 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5309 (replace-match "\t" t t))
5313 (defvar org-table-aligned-begin-marker (make-marker)
5314 "Marker at the beginning of the table last aligned.
5315 Used to check if cursor still is in that table, to minimize realignment.")
5316 (defvar org-table-aligned-end-marker (make-marker)
5317 "Marker at the end of the table last aligned.
5318 Used to check if cursor still is in that table, to minimize realignment.")
5319 (defvar org-table-last-alignment nil
5320 "List of flags for flushright alignment, from the last re-alignment.
5321 This is being used to correctly align a single field after TAB or RET.")
5322 ;; FIXME: The following is currently not used.
5323 (defvar org-table-last-column-widths nil
5324 "List of max width of fields in each column.
5325 This is being used to correctly align a single field after TAB or RET.")
5328 (defun org-table-align ()
5329 "Align the table at point by aligning all vertical bars."
5333 (beg (org-table-begin))
5334 (end (org-table-end))
5335 ;; Current cursor position
5336 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5337 (colpos (org-table-current-column))
5338 (winstart (window-start))
5339 text lines (new "") lengths l typenums ty fields maxfields i
5341 (indent "") cnt frac
5343 (spaces (if (org-in-invisibility-spec-p '(org-table))
5344 org-table-spaces-around-invisible-separators
5345 org-table-spaces-around-separators))
5349 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
5351 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
5354 ;; (message "Aligning table...")
5356 (setq lines (org-split-string
5357 (buffer-substring-no-properties beg end) "\n"))
5358 ;; Store the indentation of the first line
5359 (if (string-match "^ *" (car lines))
5360 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
5362 (setq lines (mapcar (lambda (l) (if (string-match "^ *|-" l) nil l))
5364 ;; Get the data fields
5365 (setq fields (mapcar
5367 (org-split-string l " *| *"))
5368 (delq nil (copy-sequence lines))))
5369 ;; How many fields in the longest line?
5371 (setq maxfields (apply 'max (mapcar 'length fields)))
5373 (kill-region beg end)
5374 (org-table-create org-table-default-size)
5375 (error "Empty table - created default table")))
5376 ;; A list of empty string to fill any short rows on output
5377 (setq emptystrings (make-list maxfields ""))
5378 ;; Get the maximum length of a field and the most common datatype
5381 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
5382 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
5384 (push (apply 'max 1 (mapcar 'length column)) lengths)
5385 ;; compute the fraction stepwise, ignoring empty fields
5386 (setq cnt 0 frac 0.0)
5391 (setq frac ( / (+ (* frac cnt)
5392 (if (string-match org-table-number-regexp x) 1 0))
5393 (setq cnt (1+ cnt))))))
5395 (push (>= frac org-table-number-fraction) typenums))
5396 (setq lengths (nreverse lengths)
5397 typenums (nreverse typenums))
5398 (setq org-table-last-alignment typenums
5399 org-table-last-column-widths lengths)
5400 ;; Compute the formats needed for output of the table
5401 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
5402 (while (setq l (pop lengths))
5403 (setq ty (if (pop typenums) "" "-")) ; number types flushright
5404 (setq rfmt (concat rfmt (format rfmt1 ty l))
5405 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
5406 (setq rfmt (concat rfmt "\n")
5407 hfmt (concat (substring hfmt 0 -1) "|\n"))
5408 ;; Produce the new table
5410 (setq l (pop lines))
5412 (setq new (concat new (apply 'format rfmt
5413 (append (pop fields) emptystrings))))
5414 (setq new (concat new hfmt))))
5415 ;; Replace the old one
5416 (delete-region beg end)
5417 (move-marker end nil)
5418 (move-marker org-table-aligned-begin-marker (point))
5420 (move-marker org-table-aligned-end-marker (point))
5421 ;; Try to move to the old location (approximately)
5423 (set-window-start (selected-window) winstart 'noforce)
5424 (org-table-goto-column colpos)
5425 (setq org-table-may-need-update nil)
5426 (if (org-in-invisibility-spec-p '(org-table))
5427 (org-table-add-invisible-to-vertical-lines))
5430 (defun org-table-begin (&optional table-type)
5431 "Find the beginning of the table and return its position.
5432 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
5434 (if (not (re-search-backward
5435 (if table-type org-table-any-border-regexp
5436 org-table-border-regexp)
5438 (error "Can't find beginning of table")
5439 (goto-char (match-beginning 0))
5440 (beginning-of-line 2)
5443 (defun org-table-end (&optional table-type)
5444 "Find the end of the table and return its position.
5445 With argument TABLE-TYPE, go to the end of a table.el-type table."
5447 (if (not (re-search-forward
5448 (if table-type org-table-any-border-regexp
5449 org-table-border-regexp)
5451 (goto-char (point-max))
5452 (goto-char (match-beginning 0)))
5455 (defun org-table-justify-field-maybe ()
5456 "Justify the current field, text to left, number to right."
5458 (org-table-may-need-update) ; Realignment will happen anyway, don't bother
5459 ((org-at-table-hline-p)
5460 ;; This is pretty stupid, but I don't know how to deal with hlines
5461 (setq org-table-may-need-update t))
5462 ((or (not (equal (marker-buffer org-table-aligned-begin-marker)
5464 (< (point) org-table-aligned-begin-marker)
5465 (>= (point) org-table-aligned-end-marker))
5466 ;; This is not the same table, force a full re-align
5467 (setq org-table-may-need-update t))
5468 (t ;; realign the current field, based on previous full realign
5469 (let* ((pos (point)) s org-table-may-need-update
5470 (col (org-table-current-column))
5471 (num (nth (1- col) org-table-last-alignment))
5474 (skip-chars-backward "^|\n")
5475 (if (looking-at " *\\([^|\n]*?\\) *|")
5477 (setq s (match-string 1)
5478 l (max 1 (- (match-end 0) (match-beginning 0) 3)))
5479 (setq f (format (if num " %%%ds |" " %%-%ds |") l))
5480 (replace-match (format f s t t)))
5481 (setq org-table-may-need-update t))
5482 (goto-char pos))))))
5484 (defun org-table-next-field ()
5485 "Go to the next field in the current table.
5486 Before doing so, re-align the table if necessary."
5488 (if (and org-table-automatic-realign
5489 org-table-may-need-update)
5491 (if (org-at-table-hline-p)
5495 (re-search-forward "|" (org-table-end))
5496 (if (looking-at "[ \t]*$")
5497 (re-search-forward "|" (org-table-end)))
5498 (if (looking-at "-")
5500 (beginning-of-line 0)
5501 (org-table-insert-row 'below))
5502 (if (looking-at " ") (forward-char 1))))
5504 (org-table-insert-row 'below))))
5506 (defun org-table-previous-field ()
5507 "Go to the previous field in the table.
5508 Before doing so, re-align the table if necessary."
5510 (if (and org-table-automatic-realign
5511 org-table-may-need-update)
5513 (if (org-at-table-hline-p)
5515 (re-search-backward "|" (org-table-begin))
5516 (re-search-backward "|" (org-table-begin))
5517 (while (looking-at "|\\(-\\|[ \t]*$\\)")
5518 (re-search-backward "|" (org-table-begin)))
5519 (if (looking-at "| ?")
5520 (goto-char (match-end 0))))
5522 (defun org-table-next-row ()
5523 "Go to the next row (same column) in the current table.
5524 Before doing so, re-align the table if necessary."
5526 (if (or (looking-at "[ \t]*$")
5527 (save-excursion (skip-chars-backward " \t") (bolp)))
5529 (if (and org-table-automatic-realign
5530 org-table-may-need-update)
5532 (let ((col (org-table-current-column)))
5533 (beginning-of-line 2)
5534 (if (or (not (org-at-table-p))
5535 (org-at-table-hline-p))
5537 (beginning-of-line 0)
5538 (org-table-insert-row 'below)))
5539 (org-table-goto-column col)
5540 (skip-chars-backward "^|\n\r")
5541 (if (looking-at " ") (forward-char 1)))))
5543 (defun org-table-copy-down (n)
5544 "Copy a field down in the current column.
5545 If the field at the cursor is empty, copy into it the content of the nearest
5546 non-empty field above. With argument N, use the Nth non-empty field.
5547 If the current field is not empty, it is copied down to the next row, and
5548 the cursor is moved with it. Therefore, repeating this command causes the
5549 column to be filled row-by-row.
5550 If the variable `org-table-copy-increment' is non-nil and the field is an
5551 integer, it will be incremented while copying."
5553 (let* ((colpos (org-table-current-column))
5554 (field (org-table-get-field))
5555 (non-empty (string-match "[^ \t]" field))
5556 (beg (org-table-begin))
5558 (org-table-check-inside-data-field)
5559 (if non-empty (progn (org-table-next-row) (org-table-blank-field)))
5563 (while (progn (beginning-of-line 1)
5564 (re-search-backward org-table-dataline-regexp
5566 (org-table-goto-column colpos t)
5567 (if (and (looking-at
5568 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
5569 (= (setq n (1- n)) 0))
5570 (throw 'exit (match-string 1)))))))
5572 (if (and org-table-copy-increment
5573 (string-match "^[0-9]+$" txt))
5574 (setq txt (format "%d" (+ (string-to-int txt) 1))))
5577 (error "No non-empty field found"))))
5579 (defun org-table-check-inside-data-field ()
5580 "Is point inside a table data field?
5581 I.e. not on a hline or before the first or after the last column?"
5582 (if (or (not (org-at-table-p))
5583 (= (org-table-current-column) 0)
5584 (org-at-table-hline-p)
5585 (looking-at "[ \t]*$"))
5586 (error "Not in table data field")))
5588 (defvar org-table-clip nil
5589 "Clipboard for table regions.")
5591 (defun org-table-blank-field ()
5592 "Blank the current table field or active region."
5594 (org-table-check-inside-data-field)
5595 (if (and (interactive-p) (org-region-active-p))
5596 (let (org-table-clip)
5597 (org-table-cut-region))
5598 (skip-chars-backward "^|")
5600 (if (looking-at "|[^|]+")
5601 (let* ((pos (match-beginning 0))
5602 (match (match-string 0))
5603 (len (length match)))
5604 (replace-match (concat "|" (make-string (1- len) ?\ )))
5605 (goto-char (+ 2 pos))
5606 (substring match 1)))))
5608 (defun org-table-get-field (&optional n replace)
5609 "Return the value of the field in column N of current row.
5610 N defaults to current field.
5611 If REPLACE is a string, replace field with this value. The return value
5612 is always the old value."
5613 (and n (org-table-goto-column n))
5614 (skip-chars-backward "^|")
5616 (if (looking-at "|[^|\r\n]*")
5617 (let* ((pos (match-beginning 0))
5618 (val (buffer-substring (1+ pos) (match-end 0))))
5620 (replace-match (concat "|" replace)))
5621 (goto-char (+ 2 pos))
5624 (defun org-table-current-column ()
5625 "Find out which column we are in.
5626 When called interactively, column is also displayed in echo area."
5628 (if (interactive-p) (org-table-check-inside-data-field))
5630 (let ((cnt 0) (pos (point)))
5631 (beginning-of-line 1)
5632 (while (search-forward "|" pos t)
5633 (setq cnt (1+ cnt)))
5634 (if (interactive-p) (message "This is table column %d" cnt))
5637 (defun org-table-goto-column (n &optional on-delim force)
5638 "Move the cursor to the Nth column in the current table line.
5639 With optional argument ON-DELIM, stop with point before the left delimiter
5641 If there are less than N fields, just go to after the last delimiter.
5642 However, when FORCE is non-nil, create new columns if necessary."
5643 (let ((pos (point-at-eol)))
5644 (beginning-of-line 1)
5646 (while (and (> (setq n (1- n)) -1)
5647 (or (search-forward "|" pos t)
5649 (progn (end-of-line 1)
5650 (skip-chars-backward "^|")
5652 (backward-char 2) t)))))
5653 (when (and force (not (looking-at ".*|")))
5654 (save-excursion (end-of-line 1) (insert "|")))
5657 (if (looking-at " ") (forward-char 1))))))
5659 (defun org-at-table-p (&optional table-type)
5660 "Return t if the cursor is inside an org-type table."
5661 (if org-enable-table-editor
5663 (beginning-of-line 1)
5664 (looking-at (if table-type org-table-any-line-regexp
5665 org-table-line-regexp)))
5668 (defun org-table-recognize-table.el ()
5669 "If there is a table.el table nearby, recognize it and move into it."
5670 (if org-table-tab-recognizes-table.el
5671 (if (org-at-table.el-p)
5673 (beginning-of-line 1)
5674 (if (looking-at org-table-dataline-regexp)
5676 (if (looking-at org-table1-hline-regexp)
5678 (beginning-of-line 2)
5679 (if (looking-at org-table-any-border-regexp)
5680 (beginning-of-line -1)))))
5681 (if (re-search-forward "|" (org-table-end t) t)
5684 (if (table--at-cell-p (point))
5686 (message "recognizing table.el table...")
5687 (table-recognize-table)
5688 (message "recognizing table.el table...done")))
5689 (error "This should not happen..."))
5694 (defun org-at-table.el-p ()
5695 "Return t if the cursor is inside a table.el-type table."
5697 (if (org-at-table-p 'any)
5699 (goto-char (org-table-begin 'any))
5700 (looking-at org-table1-hline-regexp))
5703 (defun org-at-table-hline-p ()
5704 "Return t if the cursor is inside a hline in a table."
5705 (if org-enable-table-editor
5707 (beginning-of-line 1)
5708 (looking-at org-table-hline-regexp))
5711 (defun org-table-insert-column ()
5712 "Insert a new column into the table."
5714 (if (not (org-at-table-p))
5715 (error "Not at a table"))
5716 (org-table-find-dataline)
5717 (let* ((col (max 1 (org-table-current-column)))
5718 (beg (org-table-begin))
5719 (end (org-table-end))
5720 ;; Current cursor position
5721 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5724 (while (< (point) end)
5725 (if (org-at-table-hline-p)
5727 (org-table-goto-column col t)
5729 (beginning-of-line 2))
5730 (move-marker end nil)
5732 (org-table-goto-column colpos))
5735 (defun org-table-find-dataline ()
5736 "Find a dataline in the current table, which is needed for column commands."
5737 (if (and (org-at-table-p)
5738 (not (org-at-table-hline-p)))
5740 (let ((col (current-column))
5741 (end (org-table-end)))
5742 (move-to-column col)
5743 (while (and (< (point) end)
5744 (or (not (= (current-column) col))
5745 (org-at-table-hline-p)))
5746 (beginning-of-line 2)
5747 (move-to-column col))
5748 (if (and (org-at-table-p)
5749 (not (org-at-table-hline-p)))
5752 "Please position cursor in a data line for column operations")))))
5754 (defun org-table-delete-column ()
5755 "Delete a column into the table."
5757 (if (not (org-at-table-p))
5758 (error "Not at a table"))
5759 (org-table-find-dataline)
5760 (org-table-check-inside-data-field)
5761 (let* ((col (org-table-current-column))
5762 (beg (org-table-begin))
5763 (end (org-table-end))
5764 ;; Current cursor position
5765 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5768 (while (< (point) end)
5769 (if (org-at-table-hline-p)
5771 (org-table-goto-column col t)
5772 (and (looking-at "|[^|\n]+|")
5773 (replace-match "|")))
5774 (beginning-of-line 2))
5775 (move-marker end nil)
5777 (org-table-goto-column colpos))
5780 (defun org-table-move-column-right ()
5781 "Move column to the right."
5783 (org-table-move-column nil))
5784 (defun org-table-move-column-left ()
5785 "Move column to the left."
5787 (org-table-move-column 'left))
5789 (defun org-table-move-column (&optional left)
5790 "Move the current column to the right. With arg LEFT, move to the left."
5792 (if (not (org-at-table-p))
5793 (error "Not at a table"))
5794 (org-table-find-dataline)
5795 (org-table-check-inside-data-field)
5796 (let* ((col (org-table-current-column))
5797 (col1 (if left (1- col) col))
5798 (beg (org-table-begin))
5799 (end (org-table-end))
5800 ;; Current cursor position
5801 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5802 (colpos (if left (1- col) (1+ col))))
5803 (if (and left (= col 1))
5804 (error "Cannot move column further left"))
5805 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
5806 (error "Cannot move column further right"))
5808 (while (< (point) end)
5809 (if (org-at-table-hline-p)
5811 (org-table-goto-column col1 t)
5812 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
5813 (replace-match "|\\2|\\1|")))
5814 (beginning-of-line 2))
5815 (move-marker end nil)
5817 (org-table-goto-column colpos))
5820 (defun org-table-move-row-down ()
5821 "Move table row down."
5823 (org-table-move-row nil))
5824 (defun org-table-move-row-up ()
5825 "Move table row up."
5827 (org-table-move-row 'up))
5829 (defun org-table-move-row (&optional up)
5830 "Move the current table line down. With arg UP, move it up."
5832 (let ((col (current-column))
5836 (beginning-of-line tonew)
5837 (if (not (org-at-table-p))
5840 (error "Cannot move row further.")))
5842 (beginning-of-line 1)
5844 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
5845 (delete-region (point) (1+ (point-at-eol)))
5846 (beginning-of-line tonew)
5848 (beginning-of-line 0)
5849 (move-to-column col)))
5851 (defun org-table-insert-row (&optional arg)
5852 "Insert a new row above the current line into the table.
5853 With prefix ARG, insert below the current line."
5855 (if (not (org-at-table-p))
5856 (error "Not at a table"))
5857 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
5858 (if (string-match "^[ \t]*|-" line)
5859 (setq line (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
5860 (setq line (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
5861 (beginning-of-line (if arg 2 1))
5862 (let (org-table-may-need-update)
5863 (apply 'insert-before-markers line)
5864 (insert-before-markers "\n"))
5865 (beginning-of-line 0)
5866 (re-search-forward "| ?" (point-at-eol) t)
5867 (and org-table-may-need-update (org-table-align))))
5869 (defun org-table-insert-hline (&optional arg)
5870 "Insert a horizontal-line below the current line into the table.
5871 With prefix ARG, insert above the current line."
5873 (if (not (org-at-table-p))
5874 (error "Not at a table"))
5875 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
5876 (col (current-column))
5878 (if (string-match "^[ \t]*|-" line)
5880 (mapcar (lambda (x) (if (member x '(?| ?+))
5881 (prog1 (if start ?+ ?|) (setq start t))
5885 (mapcar (lambda (x) (if (equal x ?|)
5886 (prog1 (if start ?+ ?|) (setq start t))
5889 (beginning-of-line (if arg 1 2))
5890 (apply 'insert line)
5891 (if (equal (char-before (point)) ?+)
5892 (progn (backward-delete-char 1) (insert "|")))
5894 (beginning-of-line 0)
5895 (move-to-column col)))
5897 (defun org-table-kill-row ()
5898 "Delete the current row or horizontal line from the table."
5900 (if (not (org-at-table-p))
5901 (error "Not at a table"))
5902 (let ((col (current-column)))
5903 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
5904 (if (not (org-at-table-p)) (beginning-of-line 0))
5905 (move-to-column col)))
5908 (defun org-table-cut-region ()
5909 "Copy region in table to the clipboard and blank all relevant fields."
5911 (org-table-copy-region 'cut))
5913 (defun org-table-copy-region (&optional cut)
5914 "Copy rectangular region in table to clipboard.
5915 A special clipboard is used which can only be accessed
5916 with `org-table-paste-rectangle'"
5918 (unless (org-region-active-p) (error "No active region"))
5919 (let* ((beg (region-beginning))
5921 l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
5923 (rpl (if cut " " nil)))
5925 (org-table-check-inside-data-field)
5926 (setq l01 (count-lines (point-min) (point))
5927 c01 (org-table-current-column))
5929 (org-table-check-inside-data-field)
5930 (setq l02 (count-lines (point-min) (point))
5931 c02 (org-table-current-column))
5932 (setq l1 (min l01 l02) l2 (max l01 l02)
5933 c1 (min c01 c02) c2 (max c01 c02))
5937 (if (> l1 l2) (throw 'exit t))
5939 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
5940 (setq cols nil ic1 c1 ic2 c2)
5941 (while (< ic1 (1+ ic2))
5942 (push (org-table-get-field ic1 rpl) cols)
5943 (setq ic1 (1+ ic1)))
5944 (push (nreverse cols) region)
5945 (setq l1 (1+ l1)))))
5946 (setq org-table-clip (nreverse region))
5947 (if cut (org-table-align))))
5949 (defun org-table-paste-rectangle ()
5950 "Paste a rectangular region into a table.
5951 The upper right corner ends up in the current field. All involved fields
5952 will be overwritten. If the rectangle does not fit into the present table,
5953 the table is enlarged as needed. The process ignores horizontal separator
5956 (unless (and org-table-clip (listp org-table-clip))
5957 (error "First cut/copy a region to paste!"))
5958 (org-table-check-inside-data-field)
5959 (let* ((clip org-table-clip)
5960 (line (count-lines (point-min) (point)))
5961 (col (org-table-current-column))
5962 (org-enable-table-editor t)
5963 (org-table-automatic-realign nil)
5965 (while (setq cols (pop clip))
5966 (while (org-at-table-hline-p) (beginning-of-line 2))
5967 (if (not (org-at-table-p))
5968 (progn (end-of-line 0) (org-table-next-field)))
5970 (while (setq field (pop cols))
5971 (org-table-goto-column c nil 'force)
5972 (org-table-get-field nil field)
5974 (beginning-of-line 2))
5976 (org-table-goto-column col)
5979 (defun org-table-convert ()
5980 "Convert from `org-mode' table to table.el and back.
5981 Obviously, this only works within limits. When an Org-mode table is
5982 converted to table.el, all horizontal separator lines get lost, because
5983 table.el uses these as cell boundaries and has no notion of horizontal lines.
5984 A table.el table can be converted to an Org-mode table only if it does not
5985 do row or column spanning. Multiline cells will become multiple cells.
5986 Beware, Org-mode does not test if the table can be successfully converted - it
5987 blindly applies a recipe that works for simple tables."
5990 (if (org-at-table.el-p)
5991 ;; convert to Org-mode table
5992 (let ((beg (move-marker (make-marker) (org-table-begin t)))
5993 (end (move-marker (make-marker) (org-table-end t))))
5994 (table-unrecognize-region beg end)
5996 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
5999 (if (org-at-table-p)
6000 ;; convert to table.el table
6001 (let ((beg (move-marker (make-marker) (org-table-begin)))
6002 (end (move-marker (make-marker) (org-table-end))))
6003 ;; first, get rid of all horizontal lines
6005 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6007 ;; insert a hline before first
6009 (org-table-insert-hline 'above)
6010 ;; insert a hline after each line
6011 (while (progn (beginning-of-line 2) (< (point) end))
6012 (org-table-insert-hline))
6014 (setq end (move-marker end (org-table-end)))
6015 ;; replace "+" at beginning and ending of hlines
6016 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6017 (replace-match "\\1+-"))
6019 (while (re-search-forward "-|[ \t]*$" end t)
6020 (replace-match "-+"))
6023 (defun org-table-wrap-region (arg)
6024 "Wrap several fields in a column like a paragraph.
6025 This is useful if you'd like to spread the contents of a field over several
6026 lines, in order to keep the table compact.
6028 If there is an active region, and both point and mark are in the same column,
6029 the text in the column is wrapped to minimum width for the given number of
6030 lines. Generally, this makes the table more compact. A prefix ARG may be
6031 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6032 formats the selected text to two lines. If the region was longer than 2
6033 lines, the remaining lines remain empty. A negative prefix argument reduces
6034 the current number of lines by that amount. The wrapped text is pasted back
6035 into the table. If you formatted it to more lines than it was before, fields
6036 further down in the table get overwritten - so you might need to make space in
6039 If there is no region, the current field is split at the cursor position and
6040 the text fragment to the right of the cursor is prepended to the field one
6043 If there is no region, but you specify a prefix ARG, the current field gets
6044 blank, and the content is appended to the field above."
6046 (org-table-check-inside-data-field)
6047 (if (org-region-active-p)
6048 ;; There is a region: fill as a paragraph
6049 (let ((beg (region-beginning))
6051 (org-table-cut-region)
6052 (if (> (length (car org-table-clip)) 1)
6053 (error "Region must be limited to single column"))
6054 (setq nlines (if arg
6056 (+ (length org-table-clip) arg)
6058 (length org-table-clip)))
6059 (setq org-table-clip
6060 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6063 (org-table-paste-rectangle))
6064 ;; No region, split the current field at point
6066 ;; combine with field above
6067 (let ((s (org-table-blank-field))
6068 (col (org-table-current-column)))
6069 (beginning-of-line 0)
6070 (while (org-at-table-hline-p) (beginning-of-line 0))
6071 (org-table-goto-column col)
6072 (skip-chars-forward "^|")
6073 (skip-chars-backward " ")
6074 (insert " " (org-trim s))
6077 (when (looking-at "\\([^|]+\\)+|")
6078 (let ((s (match-string 1)))
6079 (replace-match " |")
6080 (goto-char (match-beginning 0))
6081 (org-table-next-row)
6082 (insert (org-trim s) " ")
6083 (org-table-align))))))
6086 "Remove whitespace at beginning and end of string."
6087 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6088 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s))))
6090 (defun org-wrap (string &optional width lines)
6091 "Wrap string to either a number of lines, or a width in characters.
6092 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6093 that costs. If there is a word longer than WIDTH, the text is actually
6094 wrapped to the length of that word.
6095 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6096 many lines, whatever width that takes.
6097 The return value is a list of lines, without newlines at the end."
6098 (let* ((words (org-split-string string "[ \t\n]+"))
6099 (maxword (apply 'max (mapcar 'length words)))
6102 (org-do-wrap words (max maxword width)))
6105 (setq ll (org-do-wrap words maxword))
6106 (if (<= (length ll) lines)
6109 (while (> (length ll) lines)
6111 (setq ll (org-do-wrap words w)))
6113 (t (error "Cannot wrap this")))))
6116 (defun org-do-wrap (words width)
6117 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6120 (setq line (pop words))
6121 (while (and words (< (+ (length line) (length (car words))) width))
6122 (setq line (concat line " " (pop words))))
6123 (setq lines (push line lines)))
6126 ;; FIXME: I think I can make this more efficient
6127 (defun org-split-string (string &optional separators)
6128 "Splits STRING into substrings at SEPARATORS.
6129 No empty strings are returned if there are matches at the beginning
6131 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6135 (while (and (string-match rexp string
6137 (= start (match-beginning 0))
6138 (< start (length string)))
6140 (< (match-beginning 0) (length string)))
6142 (or (eq (match-beginning 0) 0)
6143 (and (eq (match-beginning 0) (match-end 0))
6144 (eq (match-beginning 0) start))
6146 (cons (substring string start (match-beginning 0))
6148 (setq start (match-end 0)))
6149 (or (eq start (length string))
6151 (cons (substring string start)
6155 (defun org-table-add-invisible-to-vertical-lines ()
6156 "Add an `invisible' property to vertical lines of current table."
6158 (let* ((beg (org-table-begin))
6159 (end (org-table-end))
6163 (while (< (point) end)
6164 (setq end1 (point-at-eol))
6165 (if (looking-at org-table-dataline-regexp)
6166 (while (re-search-forward "|" end1 t)
6167 (add-text-properties (1- (point)) (point)
6168 '(invisible org-table)))
6169 (while (re-search-forward "[+|]" end1 t)
6170 (add-text-properties (1- (point)) (point)
6171 '(invisible org-table))))
6172 (beginning-of-line 2)))))
6174 (defun org-table-toggle-vline-visibility (&optional arg)
6175 "Toggle the visibility of table vertical lines.
6176 The effect is immediate and on all tables in the file.
6177 With prefix ARG, make lines invisible when ARG is positive, make lines
6178 visible when ARG is not positive"
6181 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
6182 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
6183 (t (if (org-in-invisibility-spec-p '(org-table))
6186 (if (eq action 'off)
6188 (org-remove-from-invisibility-spec '(org-table))
6189 (org-table-map-tables 'org-table-align)
6190 (message "Vertical table lines visible")
6191 (if (org-at-table-p)
6193 (org-add-to-invisibility-spec '(org-table))
6194 (org-table-map-tables 'org-table-align)
6195 (message "Vertical table lines invisible"))
6196 (redraw-frame (selected-frame))))
6198 (defun org-table-map-tables (function)
6199 "Apply FUNCTION to the start of all tables in the buffer."
6203 (goto-char (point-min))
6204 (while (re-search-forward org-table-any-line-regexp nil t)
6205 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6206 (beginning-of-line 1)
6207 (if (looking-at org-table-line-regexp)
6208 (save-excursion (funcall function)))
6209 (re-search-forward org-table-any-border-regexp nil 1)))))
6211 (defun org-table-sum ()
6212 "Sum numbers in region of current table column.
6213 The result will be displayed in the echo area, and will be available
6214 as kill to be inserted with \\[yank].
6216 If there is an active region, it is interpreted as a rectangle and all
6217 numbers in that rectangle will be summed. If there is no active
6218 region and point is located in a table column, sum all numbers in that
6221 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6222 numbers are assumed to be times as well (in decimal hours) and the
6223 numbers are added as such."
6226 (let (beg end col (timecnt 0) diff h m s)
6227 (if (org-region-active-p)
6228 (setq beg (region-beginning) end (region-end))
6229 (setq col (org-table-current-column))
6230 (goto-char (org-table-begin))
6231 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
6232 (error "No table data"))
6233 (org-table-goto-column col)
6234 (skip-chars-backward "^|")
6236 (goto-char (org-table-end))
6237 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
6238 (error "No table data"))
6239 (org-table-goto-column col)
6240 (skip-chars-forward "^|")
6242 (let* ((l1 (progn (goto-char beg)
6243 (+ (if (bolp) 1 0) (count-lines (point-min) (point)))))
6244 (l2 (progn (goto-char end)
6245 (+ (if (bolp) 1 0) (count-lines (point-min) (point)))))
6246 (items (if (= l1 l2)
6247 (split-string (buffer-substring beg end))
6249 (mapconcat 'identity (extract-rectangle beg end) " "))))
6250 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
6252 (res (apply '+ numbers))
6253 (sres (if (= timecnt 0)
6255 (setq diff (* 3600 res)
6256 h (floor (/ diff 3600)) diff (mod diff 3600)
6257 m (floor (/ diff 60)) diff (mod diff 60)
6259 (format "%d:%02d:%02d" h m s))))
6261 (message (substitute-command-keys
6262 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
6263 (length numbers) sres)))))))
6265 (defun org-table-get-number-for-summing (s)
6267 (if (string-match "^ *|? *" s)
6268 (setq s (replace-match "" nil nil s)))
6269 (if (string-match " *|? *$" s)
6270 (setq s (replace-match "" nil nil s)))
6271 (setq n (string-to-number s))
6273 ((and (string-match "0" s)
6274 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
6275 ((string-match "\\`[ \t]+\\'" s) nil)
6276 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
6277 (let ((h (string-to-number (or (match-string 1 s) "0")))
6278 (m (string-to-number (or (match-string 2 s) "0")))
6279 (s (string-to-number (or (match-string 4 s) "0"))))
6280 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
6281 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
6285 (defvar org-table-current-formula nil)
6286 (defvar org-table-formula-history nil)
6287 (defun org-table-get-formula (current)
6288 (if (and current (not (equal "" org-table-current-formula)))
6289 org-table-current-formula
6290 (setq org-table-current-formula
6292 "Formula [last]: " "" 'org-table-formula-history
6293 org-table-current-formula))))
6295 (defun org-this-word ()
6296 ;; Get the current word
6298 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
6299 (end (progn (skip-chars-forward "^ \t\n") (point))))
6300 (buffer-substring-no-properties beg end))))
6302 (defun org-table-eval-formula (&optional ndown)
6303 "Replace the table field value at the cursor by the result of a calculation.
6305 This function makes use of Dave Gillespie's calc package, arguably the most
6306 exciting program ever written for GNU Emacs. So you need to have calc
6307 installed in order to use this function.
6309 In a table, this command replaces the value in the current field with the
6310 result of a formula. While nowhere near the computation options of a
6311 spreadsheet program, this is still very useful. Note that there is no
6312 automatic updating of a calculated field, nor will the field remember the
6313 formula. The command needs to be applied again after changing input
6316 When called, the command first prompts for a formula, which is read in the
6317 minibuffer. Previously entered formulae are available through the history
6318 list, and the last used formula is the default, reachable by simply
6321 The formula can be any algebraic expression understood by the calc package.
6322 Before evaluation, variable substitution takes place: \"$\" is replaced by
6323 the field the cursor is currently in, and $1..$n reference the fields in
6324 the current row. Values from a *different* row can *not* be referenced
6325 here, so the command supports only horizontal computing. The formula can
6326 contain an optional printf format specifier after a semicolon, to reformat
6329 A few examples for formulae:
6330 $1+$2 Sum of first and second field
6331 $1+$2;%.2f Same, and format result to two digits after dec.point
6332 exp($2)+exp($1) Math functions can be used
6333 $;%.1f Reformat current cell to 1 digit after dec.point
6334 ($3-32)*5/9 degrees F -> C conversion
6336 When called with a raw \\[universal-argument] prefix, the formula is applied to the current
6337 field, and to the same same column in all following rows, until reaching a
6338 horizontal line or the end of the table. When the command is called with a
6339 numeric prefix argument (like M-3 or C-7 or \\[universal-argument] 24), the formula is applied
6340 to the current row, and to the following n-1 rows (but not beyond a
6343 (setq ndown (if (equal ndown '(4)) 10000 (prefix-numeric-value ndown)))
6345 (org-table-check-inside-data-field)
6347 (org-table-automatic-realign nil)
6349 (formula (org-table-get-formula nil))
6350 (n0 (org-table-current-column))
6352 (if (string-match ";" formula)
6353 (let ((tmp (org-split-string formula ";")))
6354 (setq formula (car tmp) fmt (nth 1 tmp))))
6356 (setq fields (org-split-string
6357 (concat " " (buffer-substring
6358 (point-at-bol) (point-at-eol))) "|"))
6359 (setq ndown (1- ndown))
6360 (setq form (copy-sequence formula))
6361 (while (string-match "\\$\\([0-9]+\\)?" form)
6362 (setq n (if (match-beginning 1)
6363 (string-to-int (match-string 1 form))
6366 (unless x (error "Invalid field specifier \"%s\""
6367 (match-string 0 form)))
6368 (if (equal (string-to-number x) 0) (setq x "0"))
6369 (setq form (replace-match x t t form)))
6370 (setq ev (calc-eval (list form) 'num))
6372 (error "Invalid expression: %s (%s at %d)" form (nth 1 ev) (car ev)))
6373 (org-table-blank-field)
6375 (insert (format fmt (string-to-number ev)))
6377 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
6378 (call-interactively 'org-return)
6382 ;;; The orgtbl minor mode
6384 ;; Define a minor mode which can be used in other modes in order to
6385 ;; integrate the org-mode table editor.
6387 ;; This is really a hack, because the org-mode table editor uses several
6388 ;; keys which normally belong to the major mode, for example the TAB and
6389 ;; RET keys. Here is how it works: The minor mode defines all the keys
6390 ;; necessary to operate the table editor, but wraps the commands into a
6391 ;; function which tests if the cursor is currently inside a table. If that
6392 ;; is the case, the table editor command is executed. However, when any of
6393 ;; those keys is used outside a table, the function uses `key-binding' to
6394 ;; look up if the key has an associated command in another currently active
6395 ;; keymap (minor modes, major mode, global), and executes that command.
6396 ;; There might be problems if any of the keys used by the table editor is
6397 ;; otherwise used as a prefix key.
6399 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6400 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6401 ;; addresses this by checking explicitly for both bindings.
6403 ;; The optimized version (see variable `orgtbl-optimized') takes over
6404 ;; all keys which are bound to `self-insert-command' in the *global map*.
6405 ;; Some modes bind other commands to simple characters, for example
6406 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
6407 ;; active, this binding is ignored inside tables and replaced with a
6408 ;; modified self-insert.
6410 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
6411 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
6412 In the optimized version, the table editor takes over all simple keys that
6413 normally just insert a character. In tables, the characters are inserted
6414 in a way to minimize disturbing the table structure (i.e. in overwrite mode
6415 for empty fields). Outside tables, the correct binding of the keys is
6418 The default for this option is t if the optimized version is also used in
6419 Org-mode. See the variable `org-enable-table-editor' for details. Changing
6420 this variable requires a restart of Emacs to become effective."
6424 (defvar orgtbl-mode nil
6425 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
6426 table editor in arbitrary modes.")
6427 (make-variable-buffer-local 'orgtbl-mode)
6429 (defvar orgtbl-mode-map (make-sparse-keymap)
6430 "Keymap for `orgtbl-mode'.")
6433 (defun turn-on-orgtbl ()
6434 "Unconditionally turn on `orgtbl-mode'."
6438 (defun orgtbl-mode (&optional arg)
6439 "The `org-mode' table editor as a minor mode for use in other modes."
6442 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
6445 (set (make-local-variable (quote org-table-may-need-update)) t)
6446 (make-local-hook (quote before-change-functions))
6447 (add-hook 'before-change-functions 'org-before-change-function
6449 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
6450 auto-fill-inhibit-regexp)
6451 (set (make-local-variable 'auto-fill-inhibit-regexp)
6452 (if auto-fill-inhibit-regexp
6453 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
6455 (easy-menu-add orgtbl-mode-menu)
6456 (run-hooks (quote orgtbl-mode-hook)))
6457 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
6458 (remove-hook 'before-change-functions 'org-before-change-function t)
6459 (easy-menu-remove orgtbl-mode-menu)
6460 (force-mode-line-update 'all)))
6462 ;; Install it as a minor mode.
6463 (put 'orgtbl-mode :included t)
6464 (put 'orgtbl-mode :menu-tag "Org Table Mode")
6465 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
6467 (defun orgtbl-make-binding (fun &rest keys)
6468 "Create a function for binding in the table minor mode."
6469 (list 'lambda '(arg) '(interactive "p")
6472 (list 'call-interactively (list 'quote fun))
6473 (list 'let '(orgtbl-mode)
6474 (list 'call-interactively
6477 (list 'key-binding k))
6479 '('orgtbl-error)))))))
6481 (defun orgtbl-error ()
6482 "Error when there is no default binding for a table key."
6484 (error "This key is has no function outside tables"))
6486 ;; Keybindings for the minor mode
6488 '(([(meta shift left)] org-table-delete-column)
6489 ([(meta left)] org-table-move-column-left)
6490 ([(meta right)] org-table-move-column-right)
6491 ([(meta shift right)] org-table-insert-column)
6492 ([(meta shift up)] org-table-kill-row)
6493 ([(meta shift down)] org-table-insert-row)
6494 ([(meta up)] org-table-move-row-up)
6495 ([(meta down)] org-table-move-row-down)
6496 ("\C-c\C-w" org-table-cut-region)
6497 ("\C-c\M-w" org-table-copy-region)
6498 ("\C-c\C-y" org-table-paste-rectangle)
6499 ("\C-c-" org-table-insert-hline)
6500 ([(shift tab)] org-table-previous-field)
6501 ("\C-c\C-c" org-table-align)
6502 ([(return)] org-table-next-row)
6503 ([(shift return)] org-table-copy-down)
6504 ([(meta return)] org-table-wrap-region)
6505 ("\C-c\C-q" org-table-wrap-region)
6506 ("\C-c?" org-table-current-column)
6507 ("\C-c " org-table-blank-field)
6508 ("\C-c+" org-table-sum)
6509 ("\C-c|" org-table-toggle-vline-visibility)
6510 ("\C-c=" org-table-eval-formula)))
6512 (while (setq elt (pop bindings))
6515 cmd (orgtbl-make-binding fun key))
6516 (define-key orgtbl-mode-map key cmd)))
6518 ;; Special treatment needed for TAB and RET
6519 ;(define-key orgtbl-mode-map [(return)]
6520 ; (orgtbl-make-binding 'org-table-next-row [(return)] "\C-m"))
6521 ;(define-key orgtbl-mode-map "\C-m"
6522 ; (orgtbl-make-binding 'org-table-next-row "\C-m" [(return)]))
6523 ;(define-key orgtbl-mode-map [(tab)]
6524 ; (orgtbl-make-binding 'org-table-next-field [(tab)] "\C-i"))
6525 ;(define-key orgtbl-mode-map "\C-i"
6526 ; (orgtbl-make-binding 'org-table-next-field "\C-i" [(tab)]))
6528 (define-key orgtbl-mode-map [(return)]
6529 (orgtbl-make-binding 'orgtbl-ret [(return)] "\C-m"))
6530 (define-key orgtbl-mode-map "\C-m"
6531 (orgtbl-make-binding 'orgtbl-ret "\C-m" [(return)]))
6532 (define-key orgtbl-mode-map [(tab)]
6533 (orgtbl-make-binding 'orgtbl-tab [(tab)] "\C-i"))
6534 (define-key orgtbl-mode-map "\C-i"
6535 (orgtbl-make-binding 'orgtbl-tab "\C-i" [(tab)]))
6537 (when orgtbl-optimized
6538 ;; If the user wants maximum table support, we need to hijack
6539 ;; some standard editing functions
6540 (substitute-key-definition 'self-insert-command 'orgtbl-self-insert-command
6541 orgtbl-mode-map global-map)
6542 (substitute-key-definition 'delete-char 'orgtbl-delete-char
6543 orgtbl-mode-map global-map)
6544 (substitute-key-definition 'delete-backward-char 'orgtbl-delete-backward-char
6545 orgtbl-mode-map global-map)
6546 (define-key org-mode-map "|" 'self-insert-command))
6548 (defun orgtbl-tab ()
6549 "Justification and field motion for `orgtbl-mode'."
6551 (org-table-justify-field-maybe)
6552 (org-table-next-field))
6554 (defun orgtbl-ret ()
6555 "Justification and field motion for `orgtbl-mode'."
6557 (org-table-justify-field-maybe)
6558 (org-table-next-row))
6560 (defun orgtbl-self-insert-command (N)
6561 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
6562 If the cursor is in a table looking at whitespace, the whitespace is
6563 overwritten, and the table is not marked as requiring realignment."
6565 (if (and (org-at-table-p)
6567 (looking-at "[^|\n]* +|"))
6568 (let (org-table-may-need-update)
6569 (goto-char (1- (match-end 0)))
6570 (delete-backward-char 1)
6571 (goto-char (match-beginning 0))
6572 (self-insert-command N))
6573 (setq org-table-may-need-update t)
6575 (call-interactively (key-binding (vector last-input-event))))))
6577 (defun orgtbl-delete-backward-char (N)
6578 "Like `delete-backward-char', insert whitespace at field end in tables.
6579 When deleting backwards, in tables this function will insert whitespace in
6580 front of the next \"|\" separator, to keep the table aligned. The table will
6581 still be marked for re-alignment, because a narrow field may lead to a
6582 reduced column width."
6584 (if (and (org-at-table-p)
6586 (looking-at ".*?|"))
6587 (let ((pos (point)))
6588 (backward-delete-char N)
6589 (skip-chars-forward "^|")
6591 (goto-char (1- pos)))
6592 (message "%s" last-input-event) (sit-for 1)
6593 (delete-backward-char N)))
6595 (defun orgtbl-delete-char (N)
6596 "Like `delete-char', but insert whitespace at field end in tables.
6597 When deleting characters, in tables this function will insert whitespace in
6598 front of the next \"|\" separator, to keep the table aligned. The table
6599 will still be marked for re-alignment, because a narrow field may lead to
6600 a reduced column width."
6602 (if (and (org-at-table-p)
6604 (if (looking-at ".*?|")
6605 (let ((pos (point)))
6606 (replace-match (concat
6607 (substring (match-string 0) 1 -1)
6612 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
6614 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
6615 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
6616 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
6617 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
6619 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
6620 ["Copy Field from Above"
6621 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
6624 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
6625 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
6626 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
6627 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
6629 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
6630 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
6631 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
6632 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
6634 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
6636 ["Copy Rectangle" org-copy-special :active (org-at-table-p) :keys "C-c M-w"]
6637 ["Cut Rectangle" org-cut-special :active (org-at-table-p) :keys "C-c C-w"]
6638 ["Paste Rectangle" org-paste-special :active (org-at-table-p) :keys "C-c C-y"]
6639 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p) :keys "C-c C-q"])
6641 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
6642 ["Sum Column/Rectangle" org-table-sum
6643 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
6644 ["Eval Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
6649 (defconst org-level-max 20)
6651 (defun org-export-find-first-heading-line (list)
6652 "Remove all lines from LIST which are before the first headline."
6653 (let ((orig-list list)
6654 (re (concat "^" outline-regexp)))
6656 (not (string-match re (car list))))
6658 (or list orig-list)))
6660 (defun org-skip-comments (lines)
6661 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
6662 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
6663 (re2 "^\\(\\*+\\)[ \t\n\r]")
6665 (while (setq line (pop lines))
6667 ((and (string-match re1 line)
6668 (setq level (- (match-end 1) (match-beginning 1))))
6669 ;; Beginning of a COMMENT subtree. Skip it.
6670 (while (and (setq line (pop lines))
6671 (or (not (string-match re2 line))
6672 (> (- (match-end 1) (match-beginning 1)) level))))
6673 (setq lines (cons line lines)))
6674 ((string-match "^#" line)
6675 ;; an ordinary comment line
6677 (t (setq rtn (cons line rtn)))))
6682 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
6683 "Characters for underlining headings in ASCII export.")
6685 (defconst org-html-entities
6725 ("Aring") ("AA"."Å")
6814 ("varepsilon"."ε")
6827 ("sigmaf") ("varsigma"."ς")
6835 ("thetasym") ("vartheta"."ϑ")
6838 ("bull") ("bullet"."•")
6839 ("hellip") ("dots"."…")
6849 ("larr") ("leftarrow"."←") ("gets"."←")
6850 ("uarr") ("uparrow"."↑")
6851 ("rarr") ("to"."→") ("rightarrow"."→")
6852 ("darr")("downarrow"."↓")
6853 ("harr") ("leftrightarrow"."↔")
6854 ("crarr") ("hookleftarrow"."↵") ; has round hook, not quite CR
6855 ("lArr") ("Leftarrow"."⇐")
6856 ("uArr") ("Uparrow"."⇑")
6857 ("rArr") ("Rightarrow"."⇒")
6858 ("dArr") ("Downarrow"."⇓")
6859 ("hArr") ("Leftrightarrow"."⇔")
6861 ("part") ("partial"."∂")
6862 ("exist") ("exists"."∃")
6863 ("empty") ("emptyset"."∅")
6865 ("isin") ("in"."∈")
6871 ("lowast") ("ast"."∗")
6873 ("prop") ("proptp"."∝")
6874 ("infin") ("infty"."∞")
6875 ("ang") ("angle"."∠")
6876 ("and") ("vee"."∧")
6877 ("or") ("wedge"."∨")
6883 ("cong") ("simeq"."≅")
6884 ("asymp")("approx"."≈")
6885 ("ne") ("neq"."≠")
6889 ("sub") ("subset"."⊂")
6890 ("sup") ("supset"."⊃")
6897 ("sdot") ("cdot"."⋅")
6904 ("loz") ("Diamond"."◊")
6905 ("spades") ("spadesuit"."♠")
6906 ("clubs") ("clubsuit"."♣")
6907 ("hearts") ("diamondsuit"."♥")
6908 ("diams") ("diamondsuit"."♦")
6975 "Entities for TeX->HTML translation.
6976 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
6977 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
6978 In that case, \"\\ent\" will be translated to \"&other;\".
6979 The list contains HTML entities for Latin-1, Greek and other symbols.
6980 It is supplemented by a number of commonly used TeX macros with appropriate
6983 (defvar org-last-level nil) ; dynamically scoped variable
6985 (defun org-export-as-ascii (arg)
6986 "Export the outline as a pretty ASCII file.
6987 If there is an active region, export only the region.
6988 The prefix ARG specifies how many levels of the outline should become
6989 underlined headlines. The default is 3."
6991 (setq-default org-todo-line-regexp org-todo-line-regexp)
6994 (if (org-region-active-p) (region-beginning) (point-min))
6995 (if (org-region-active-p) (region-end) (point-max))))
6996 (lines (org-export-find-first-heading-line
6997 (org-skip-comments (org-split-string region "[\r\n]"))))
6998 (org-startup-with-deadline-check nil)
7001 (case-fold-search nil)
7002 (filename (concat (file-name-sans-extension (buffer-file-name))
7004 (buffer (find-file-noselect filename))
7005 (levels-open (make-vector org-level-max nil))
7006 (date (format-time-string "%Y/%m/%d" (current-time)))
7007 (time (format-time-string "%X" (current-time)))
7008 (author user-full-name)
7009 (title (buffer-name))
7011 (email user-mail-address)
7012 (language org-export-default-language)
7017 (setq org-last-level 1)
7018 (org-init-section-numbers)
7020 (find-file-noselect filename)
7022 ;; Search for the export key lines
7023 (org-parse-key-lines)
7025 (setq lang-words (or (assoc language org-export-language-setup)
7026 (assoc "en" org-export-language-setup)))
7027 (if org-export-ascii-show-new-buffer
7028 (switch-to-buffer-other-window buffer)
7029 (set-buffer buffer))
7032 (if options (org-parse-export-options options))
7033 (setq umax (if arg (prefix-numeric-value arg)
7034 org-export-headline-levels))
7037 (if title (org-insert-centered title ?=))
7039 (if (or author email)
7040 (insert (concat (nth 1 lang-words) ": " (or author "")
7041 (if email (concat " <" email ">") "")
7044 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
7045 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
7049 (if org-export-with-toc
7051 (insert (nth 3 lang-words) "\n"
7052 (make-string (length (nth 3 lang-words)) ?=) "\n")
7053 (mapcar '(lambda (line)
7054 (if (string-match org-todo-line-regexp
7056 ;; This is a headline
7058 (setq level (- (match-end 1) (match-beginning 1))
7059 txt (match-string 3 line)
7061 (or (and (match-beginning 2)
7062 (not (equal (match-string 2 line)
7066 (org-search-todo-below
7067 line lines level))))
7068 (setq txt (org-html-expand-for-ascii txt))
7070 (if org-export-with-section-numbers
7071 (setq txt (concat (org-section-number level)
7076 (make-string (* (1- level) 4) ?\ )
7077 (format (if todo "%s (*)\n" "%s\n") txt))
7078 (setq org-last-level level))
7082 (org-init-section-numbers)
7083 (while (setq line (pop lines))
7084 ;; Remove the quoted HTML tags.
7085 (setq line (org-html-expand-for-ascii line))
7087 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
7089 (setq level (- (match-end 1) (match-beginning 1))
7090 txt (match-string 2 line))
7091 (org-ascii-level-start level txt umax))
7092 (t (insert line "\n"))))
7095 (goto-char (point-min))))
7097 (defun org-search-todo-below (line lines level)
7098 "Search the subtree below LINE for any TODO entries."
7099 (let ((rest (cdr (memq line lines)))
7100 (re org-todo-line-regexp)
7103 (while (setq line (pop rest))
7104 (if (string-match re line)
7106 (setq lv (- (match-end 1) (match-beginning 1))
7107 todo (and (match-beginning 2)
7108 (not (equal (match-string 2 line)
7111 (if (<= lv level) (throw 'exit nil))
7112 (if todo (throw 'exit t))))))))
7114 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
7115 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
7116 (defun org-html-expand-for-ascii (line)
7117 "Handle quoted HTML for ASCII export."
7118 (if org-export-html-expand
7119 (while (string-match "@<[^<>\n]*>" line)
7120 ;; We just remove the tags for now.
7121 (setq line (replace-match "" nil nil line))))
7124 (defun org-insert-centered (s &optional underline)
7125 "Insert the string S centered and underline it with character UNDERLINE."
7126 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
7127 (insert (make-string ind ?\ ) s "\n")
7129 (insert (make-string ind ?\ )
7130 (make-string (length s) underline)
7133 (defun org-ascii-level-start (level title umax)
7134 "Insert a new level in ASCII export."
7137 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
7138 (if (or (not (equal (char-before) ?\n))
7139 (not (equal (char-before (1- (point))) ?\n)))
7141 (setq char (nth (- umax level) (reverse org-ascii-underline)))
7142 (if org-export-with-section-numbers
7143 (setq title (concat (org-section-number level) " " title)))
7144 (insert title "\n" (make-string (string-width title) char) "\n"))))
7146 (defun org-export-copy-visible ()
7147 "Copy the visible part of the buffer to another buffer, for printing.
7148 Also removes the first line of the buffer if it specifies a mode,
7149 and all options lines."
7151 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
7153 (buffer (find-file-noselect filename))
7155 (org-make-options-regexp
7156 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO" "STARTUP"
7157 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
7158 (if org-noutline-p "\\(\n\\|$\\)" "")))
7160 (with-current-buffer buffer
7164 (setq s (goto-char (point-min)))
7165 (while (not (= (point) (point-max)))
7166 (goto-char (org-find-invisible))
7167 (append-to-buffer buffer s (point))
7168 (setq s (goto-char (org-find-visible)))))
7169 (switch-to-buffer-other-window buffer)
7171 (goto-char (point-min))
7172 (if (looking-at ".*-\\*- mode:.*\n")
7174 (while (re-search-forward ore nil t)
7176 (goto-char (point-min))))
7178 (defun org-find-visible ()
7179 (if (featurep 'noutline)
7181 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
7182 (get-char-property s 'invisible)))
7184 (skip-chars-forward "^\n")
7186 (defun org-find-invisible ()
7187 (if (featurep 'noutline)
7189 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
7190 (not (get-char-property s 'invisible))))
7192 (skip-chars-forward "^\r")
7197 (defun org-get-current-options ()
7198 "Return a string with current options as keyword options.
7199 Does include HTML export options as well as TODO and CATEGORY stuff."
7205 #+TEXT: Some descriptive text to be emitted. Several lines OK.
7206 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
7212 (buffer-name) (user-full-name) user-mail-address org-export-default-language
7213 org-export-headline-levels
7214 org-export-with-section-numbers
7216 org-export-preserve-breaks
7217 org-export-html-expand
7218 org-export-with-fixed-width
7219 org-export-with-tables
7220 org-export-with-sub-superscripts
7221 org-export-with-emphasize
7222 org-export-with-TeX-macros
7223 (file-name-nondirectory (buffer-file-name))
7224 (if (equal org-todo-interpretation 'sequence)
7225 (mapconcat 'identity org-todo-keywords " ")
7226 "TODO FEEDBACK VERIFY DONE")
7227 (if (equal org-todo-interpretation 'type)
7228 (mapconcat 'identity org-todo-keywords " ")
7229 "Me Jason Marie DONE")
7230 (cdr (assoc org-startup-folded
7231 '((nil . "nofold")(t . "fold")(content . "content"))))
7232 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
7235 (defun org-insert-export-options-template ()
7236 "Insert into the buffer a template with information for exporting."
7238 (if (not (bolp)) (newline))
7239 (let ((s (org-get-current-options)))
7240 (and (string-match "#\\+CATEGORY" s)
7241 (setq s (substring s 0 (match-beginning 0))))
7244 (defun org-toggle-fixed-width-section (arg)
7245 "Toggle the fixed-width indicator at the beginning of lines in the region.
7246 If there is no active region, only acts on the current line.
7247 If the first non-white character in the first line of the region is a
7248 vertical bar \"|\", then the command removes the bar from all lines in
7249 the region. If the first character is not a bar, the command adds a
7250 bar to all lines, in the column given by the beginning of the region.
7252 If there is a numerical prefix ARG, create ARG new lines starting with \"|\"."
7255 (regionp (org-region-active-p))
7256 (beg (if regionp (region-beginning) (point)))
7257 (end (if regionp (region-end)))
7258 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
7259 (re "[ \t]*\\(:\\)")
7263 (setq cc (current-column))
7264 (beginning-of-line 1)
7265 (setq off (looking-at re))
7267 (setq nlines (1- nlines))
7268 (beginning-of-line 1)
7271 (move-to-column cc t)
7274 ((and off (looking-at re))
7275 (replace-match "" t t nil 1))
7276 ((not off) (move-to-column cc t) (insert ":")))
7277 (forward-line 1)))))
7279 (defun org-export-as-html-and-open (arg)
7280 "Export the outline as HTML and immediately open it with a browser.
7281 If there is an active region, export only the region.
7282 The prefix ARG specifies how many levels of the outline should become
7283 headlines. The default is 3. Lower levels will become bulleted lists."
7285 (org-export-as-html arg 'hidden)
7286 (org-open-file (buffer-file-name)))
7288 (defun org-export-as-html-batch ()
7289 "Call `org-export-as-html', may be used in batch processing as
7291 --load=$HOME/lib/emacs/org.el
7292 --eval \"(setq org-export-headline-levels 2)\"
7293 --visit=MyFile --funcall org-export-as-html-batch"
7294 (org-export-as-html org-export-headline-levels 'hidden))
7296 (defun org-export-as-html (arg &optional hidden)
7297 "Export the outline as a pretty HTML file.
7298 If there is an active region, export only the region.
7299 The prefix ARG specifies how many levels of the outline should become
7300 headlines. The default is 3. Lower levels will become bulleted lists."
7302 (setq-default org-todo-line-regexp org-todo-line-regexp)
7303 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
7304 (setq-default org-done-string org-done-string)
7305 (let* ((region-p (org-region-active-p))
7308 (if region-p (region-beginning) (point-min))
7309 (if region-p (region-end) (point-max))))
7311 (org-skip-comments (org-split-string region "[\r\n]")))
7312 (lines (org-export-find-first-heading-line all_lines))
7313 (level 0) (line "") (origline "") txt todo
7315 (filename (concat (file-name-sans-extension (buffer-file-name))
7317 (buffer (find-file-noselect filename))
7318 (levels-open (make-vector org-level-max nil))
7319 (date (format-time-string "%Y/%m/%d" (current-time)))
7320 (time (format-time-string "%X" (current-time)))
7321 (author user-full-name)
7322 (title (buffer-name))
7324 (email user-mail-address)
7325 (language org-export-default-language)
7330 table-buffer table-orig-buffer
7332 (message "Exporting...")
7334 (setq org-last-level 1)
7335 (org-init-section-numbers)
7337 ;; Search for the export key lines
7338 (org-parse-key-lines)
7339 (setq lang-words (or (assoc language org-export-language-setup)
7340 (assoc "en" org-export-language-setup)))
7342 ;; Switch to the output buffer
7343 (if (or hidden (not org-export-html-show-new-buffer))
7345 (switch-to-buffer-other-window buffer))
7348 (let ((case-fold-search nil))
7349 (if options (org-parse-export-options options))
7350 (setq umax (if arg (prefix-numeric-value arg)
7351 org-export-headline-levels))
7355 "<html lang=\"%s\"><head>
7357 <meta http-equiv=\"Content-Type\" content=\"text/html\">
7358 <meta name=generator content=\"Org-mode\">
7359 <meta name=generated content=\"%s %s\">
7360 <meta name=author content=\"%s\">
7363 language (org-html-expand title) date time author))
7364 (if title (insert (concat "<H1 align=\"center\">"
7365 (org-html-expand title) "</H1>\n")))
7366 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
7367 (if email (insert (concat "<a href=\"mailto:" email "\"><"
7368 email "></a>\n")))
7369 (if (or author email) (insert "<br>\n"))
7370 (if (and date time) (insert (concat (nth 2 lang-words) ": "
7371 date " " time "<br>\n")))
7372 (if text (insert (concat "<p>\n" (org-html-expand text))))
7373 (if org-export-with-toc
7375 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
7377 (mapcar '(lambda (line)
7378 (if (string-match org-todo-line-regexp line)
7379 ;; This is a headline
7381 (setq level (- (match-end 1) (match-beginning 1))
7382 txt (save-match-data
7384 (match-string 3 line)))
7386 (or (and (match-beginning 2)
7387 (not (equal (match-string 2 line)
7391 (org-search-todo-below
7392 line lines level))))
7393 (if org-export-with-section-numbers
7394 (setq txt (concat (org-section-number level)
7398 (setq head-count (+ head-count 1))
7399 (if (> level org-last-level)
7401 (setq cnt (- level org-last-level))
7402 (while (>= (setq cnt (1- cnt)) 0)
7405 (if (< level org-last-level)
7407 (setq cnt (- org-last-level level))
7408 (while (>= (setq cnt (1- cnt)) 0)
7414 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
7415 "<li><a href=\"#sec-%d\">%s</a></li>\n")
7417 (setq org-last-level level))
7420 (while (> org-last-level 0)
7421 (setq org-last-level (1- org-last-level))
7425 (org-init-section-numbers)
7427 (while (setq line (pop lines) origline line)
7428 ;; replace "<" and ">" by "<" and ">"
7429 ;; handle @<..> HTML tags (replace "@>..<" by "<..>")
7430 (setq line (org-html-expand line))
7433 (if (and org-export-with-fixed-width
7434 (string-match "^[ \t]*:\\(.*\\)" line))
7436 (let ((l (match-string 1 line)))
7437 (while (string-match " " l)
7438 (setq l (replace-match " " t t l)))
7439 (insert "\n<span style='font-family:Courier'>"
7442 (not (string-match "^[ \t]+\\(:.*\\)"
7446 (when (string-match org-link-regexp line)
7447 (setq type (match-string 1 line))
7449 ((member type '("http" "https" "ftp" "mailto" "news"))
7451 (setq line (replace-match
7452 "<a href=\"\\1:\\2\"><\\1:\\2></a>"
7454 ((string= type "file")
7457 (let* ((filename (match-string 2 line))
7460 (string-match (org-image-file-name-regexp) filename))))
7461 (setq line (replace-match
7462 (if (and org-export-html-inline-images
7464 "<img src=\"\\2\"/>"
7465 "<a href=\"\\2\">\\1:\\2</a>")
7468 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
7469 (setq line (replace-match
7470 "<i><\\1:\\2></i>" nil nil line)))))
7473 (if (and (string-match org-todo-line-regexp line)
7474 (match-beginning 2))
7475 (if (equal (match-string 2 line) org-done-string)
7476 (setq line (replace-match
7477 "<span style='color:green'>\\2</span>"
7479 (setq line (replace-match "<span style='color:red'>\\2</span>"
7483 (if (string-match org-deadline-line-regexp line)
7485 (if (save-match-data
7486 (string-match "<a href"
7487 (substring line 0 (match-beginning 0))))
7488 nil ; Don't do the replacement - it is inside a link
7489 (setq line (replace-match "<span style='color:red'>\\&</span>"
7493 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
7494 ;; This is a headline
7495 (setq level (- (match-end 1) (match-beginning 1))
7496 txt (match-string 2 line))
7497 (if (<= level umax) (setq head-count (+ head-count 1)))
7498 (org-html-level-start level txt umax
7499 (and org-export-with-toc (<= level umax))
7502 ((and org-export-with-tables
7503 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
7504 (if (not table-open)
7506 (setq table-open t table-buffer nil table-orig-buffer nil))
7508 (setq table-buffer (cons line table-buffer)
7509 table-orig-buffer (cons origline table-orig-buffer))
7510 (when (or (not lines)
7511 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
7513 (setq table-open nil
7514 table-buffer (nreverse table-buffer)
7515 table-orig-buffer (nreverse table-orig-buffer))
7516 (insert (org-format-table-html table-buffer table-orig-buffer))))
7519 ;; Lines starting with "-", and empty lines make new paragraph.
7520 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
7521 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
7523 (if org-export-html-with-timestamp
7524 (insert org-export-html-html-helper-timestamp))
7525 (insert "</body>\n</html>\n")
7528 (goto-char (point-min)))))
7530 (defun org-format-table-html (lines olines)
7531 "Find out which HTML converter to use and return the HTML code."
7532 (if (string-match "^[ \t]*|" (car lines))
7533 ;; A normal org table
7534 (org-format-org-table-html lines)
7535 ;; Table made by table.el - test for spanning
7536 (let* ((hlines (delq nil (mapcar
7538 (if (string-match "^[ \t]*\\+-" x) x
7541 (first (car hlines))
7542 (ll (and (string-match "\\S-+" first)
7543 (match-string 0 first)))
7544 (re (concat "^[ \t]*" (regexp-quote ll)))
7545 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
7547 (if (and (not spanning)
7548 (not org-export-prefer-native-exporter-for-tables))
7549 ;; We can use my own converter with HTML conversions
7550 (org-format-table-table-html lines)
7551 ;; Need to use the code generator in table.el, with the original text.
7552 (org-format-table-table-html-using-table-generate-source olines)))))
7554 (defun org-format-org-table-html (lines)
7555 "Format a table into html."
7556 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
7557 (setq lines (nreverse lines))
7558 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
7559 (setq lines (nreverse lines))
7560 (let ((head (and org-export-highlight-first-table-line
7562 (lambda (x) (string-match "^[ \t]*|-" x))
7564 lastline line fields html empty)
7565 (setq html (concat org-export-html-table-tag "\n"))
7566 (while (setq lastline line
7568 (setq empty " ")
7570 (if (string-match "^[ \t]*|-" line)
7572 ;; A hline: simulate an empty table row instead.
7573 (setq line (org-fake-empty-table-line lastline)
7577 (throw 'next-line t)))
7578 ;; Break the line into fields
7579 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
7583 (mapconcat (lambda (x)
7584 (if (equal x "") (setq x empty))
7586 (concat "<th>" x "</th>")
7587 (concat "<td valign=\"top\">" x "</td>")))
7590 (setq html (concat html "</table>\n"))
7593 (defun org-fake-empty-table-line (line)
7594 "Replace everything except \"|\" with spaces."
7595 (let ((i (length line))
7596 (newstr (copy-sequence line)))
7599 (if (not (eq (aref newstr i) ?|))
7600 (aset newstr i ?\ )))
7603 (defun org-format-table-table-html (lines)
7604 "Format a table generated by table.el into html.
7605 This conversion does *not* use `table-generate-source' from table.el.
7606 This has the advantage that Org-mode's HTML conversions can be used.
7607 But it has the disadvantage, that no cell- or row-spanning is allowed."
7608 (let (line field-buffer
7609 (head org-export-highlight-first-table-line)
7611 (setq html (concat org-export-html-table-tag "\n"))
7612 (while (setq line (pop lines))
7613 (setq empty " ")
7615 (if (string-match "^[ \t]*\\+-" line)
7624 (if (equal x "") (setq x empty))
7626 (concat "<th valign=\"top\">" x
7628 (concat "<td valign=\"top\">" x
7633 (setq field-buffer nil)))
7635 (throw 'next-line t)))
7636 ;; Break the line into fields and store the fields
7637 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
7639 (setq field-buffer (mapcar
7641 (concat x "<br>" (pop fields)))
7643 (setq field-buffer fields))))
7644 (setq html (concat html "</table>\n"))
7647 (defun org-format-table-table-html-using-table-generate-source (lines)
7648 "Format a table into html, using `table-generate-source' from table.el.
7649 This has the advantage that cell- or row-spanning is allowed.
7650 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
7652 (with-current-buffer (get-buffer-create " org-tmp1 ")
7654 (insert (mapconcat 'identity lines "\n"))
7655 (goto-char (point-min))
7656 (if (not (re-search-forward "|[^+]" nil t))
7657 (error "Error processing table."))
7658 (table-recognize-table)
7659 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
7660 (table-generate-source 'html " org-tmp2 ")
7661 (set-buffer " org-tmp2 ")
7662 (buffer-substring (point-min) (point-max))))
7664 (defun org-html-expand (string)
7665 "Prepare STRING for HTML export. Applies all active conversions."
7666 ;; First check if there is a link in the line - if yes, apply conversions
7667 ;; only before the start of the link.
7668 (let* ((m (string-match org-link-regexp string))
7669 (s (if m (substring string 0 m) string))
7670 (r (if m (substring string m) "")))
7671 ;; convert < to < and > to >
7672 (while (string-match "<" s)
7673 (setq s (replace-match "<" nil nil s)))
7674 (while (string-match ">" s)
7675 (setq s (replace-match ">" nil nil s)))
7676 (if org-export-html-expand
7677 (while (string-match "@<\\([^&]*\\)>" s)
7678 (setq s (replace-match "<\\1>" nil nil s))))
7679 (if org-export-with-emphasize
7680 (setq s (org-export-html-convert-emphasize s)))
7681 (if org-export-with-sub-superscripts
7682 (setq s (org-export-html-convert-sub-super s)))
7683 (if org-export-with-TeX-macros
7684 (let ((start 0) wd ass)
7685 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
7686 (setq wd (match-string 1 s))
7687 (if (setq ass (assoc wd org-html-entities))
7688 (setq s (replace-match (or (cdr ass)
7689 (concat "&" (car ass) ";"))
7691 (setq start (+ start (length wd)))))))
7694 (defun org-create-multibrace-regexp (left right n)
7695 "Create a regular expression which will match a balanced sexp.
7696 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
7697 as single character strings.
7698 The regexp returned will match the entire expression including the
7699 delimiters. It will also define a single group which contains the
7700 match except for the outermost delimiters. The maximum depth of
7701 stacked delimiters is N. Escaping delimiters is not possible."
7702 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
7705 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
7708 re (concat re or next)
7709 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
7710 (concat left "\\(" re "\\)" right)))
7712 (defvar org-match-substring-regexp
7714 "\\([^\\]\\)\\([_^]\\)\\("
7715 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
7717 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
7719 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
7720 "The regular expression matching a sub- or superscript.")
7722 (defun org-export-html-convert-sub-super (string)
7723 "Convert sub- and superscripts in STRING to HTML."
7725 (while (string-match org-match-substring-regexp string)
7726 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
7727 (setq c (or (match-string 8 string)
7728 (match-string 6 string)
7729 (match-string 5 string)))
7730 (setq string (replace-match
7731 (concat (match-string 1 string)
7732 "<" key ">" c "</" key ">")
7734 (while (string-match "\\\\\\([_^]\\)" string)
7735 (setq string (replace-match (match-string 1 string) t t string))))
7738 (defun org-export-html-convert-emphasize (string)
7739 (while (string-match
7740 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
7742 (setq string (replace-match
7743 (concat "<b>" (match-string 3 string) "</b>")
7745 (while (string-match
7746 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
7748 (setq string (replace-match
7749 (concat "<i>" (match-string 3 string) "</i>")
7751 (while (string-match
7752 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
7754 (setq string (replace-match
7755 (concat "<u>" (match-string 3 string) "</u>")
7759 (defun org-parse-key-lines ()
7760 "Find the special key lines with the information for exporters."
7763 (let ((re (org-make-options-regexp
7764 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
7766 (while (re-search-forward re nil t)
7767 (setq key (match-string 1))
7768 (cond ((string-equal key "TITLE")
7769 (setq title (match-string 2)))
7770 ((string-equal key "AUTHOR")
7771 (setq author (match-string 2)))
7772 ((string-equal key "EMAIL")
7773 (setq email (match-string 2)))
7774 ((string-equal key "LANGUAGE")
7775 (setq language (match-string 2)))
7776 ((string-equal key "TEXT")
7777 (setq text (concat text "\n" (match-string 2))))
7778 ((string-equal key "OPTIONS")
7779 (setq options (match-string 2))))))))
7781 (defun org-parse-export-options (s)
7782 "Parse the export options line."
7783 (let ((op '(("H" . org-export-headline-levels)
7784 ("num" . org-export-with-section-numbers)
7785 ("toc" . org-export-with-toc)
7786 ("\\n" . org-export-preserve-breaks)
7787 ("@" . org-export-html-expand)
7788 (":" . org-export-with-fixed-width)
7789 ("|" . org-export-with-tables)
7790 ("^" . org-export-with-sub-superscripts)
7791 ("*" . org-export-with-emphasize)
7792 ("TeX" . org-export-with-TeX-macros)))
7794 (while (setq o (pop op))
7795 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
7797 (set (make-local-variable (cdr o))
7798 (car (read-from-string (match-string 1 s))))))))
7800 (defun org-html-level-start (level title umax with-toc head-count)
7801 "Insert a new level in HTML export."
7802 (let ((l (1+ (max level umax))))
7803 (while (<= l org-level-max)
7804 (if (aref levels-open (1- l))
7806 (org-html-level-close l)
7807 (aset levels-open (1- l) nil)))
7811 (if (aref levels-open (1- level))
7812 (insert "<li>" title "<p>\n")
7813 (aset levels-open (1- level) t)
7814 (insert "<ul><li>" title "<p>\n")))
7815 (if org-export-with-section-numbers
7816 (setq title (concat (org-section-number level) " " title)))
7817 (setq level (+ level 1))
7819 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
7820 level head-count title level))
7821 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
7823 (defun org-html-level-close (&rest args)
7824 "Terminate one level in HTML export."
7828 ;; Variable holding the vector with section numbers
7829 (defvar org-section-numbers (make-vector org-level-max 0))
7831 (defun org-init-section-numbers ()
7832 "Initialize the vector for the section numbers."
7834 (numbers (nreverse (org-split-string "" "\\.")))
7835 (depth (1- (length org-section-numbers)))
7836 (i depth) number-string)
7839 (aset org-section-numbers i 0)
7840 (setq number-string (or (car numbers) "0"))
7841 (if (string-match "\\`[A-Z]\\'" number-string)
7842 (aset org-section-numbers i
7843 (- (string-to-char number-string) ?A -1))
7844 (aset org-section-numbers i (string-to-int number-string)))
7848 (defun org-section-number (&optional level)
7849 "Return a string with the current section number.
7850 When LEVEL is non-nil, increase section numbers on that level."
7851 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
7854 (aset org-section-numbers
7855 level (1+ (aref org-section-numbers level))))
7856 (setq idx (1+ level))
7857 (while (<= idx depth)
7859 (aset org-section-numbers idx 0))
7860 (setq idx (1+ idx))))
7862 (while (<= idx depth)
7863 (setq n (aref org-section-numbers idx))
7864 (setq string (concat string (if (not (string= string "")) "." "")
7866 (setq idx (1+ idx)))
7868 (if (string-match "\\`\\([@0]\\.\\)+" string)
7869 (setq string (replace-match "" nil nil string)))
7870 (if (string-match "\\(\\.0\\)+\\'" string)
7871 (setq string (replace-match "" nil nil string))))
7877 ;; - Bindings in Org-mode map are currently
7878 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
7879 ;; abcd fgh j lmnopqrstuvwxyz ? # -+ /= [] ; |,.<> \t necessary bindings
7880 ;; e (?) useful from outline-mode
7881 ;; i k @ expendable from outline-mode
7882 ;; 0123456789 ! $%^& * ()_{} " ~`' free
7884 (define-key org-mode-map [(tab)] 'org-cycle)
7885 (define-key org-mode-map "\C-i" 'org-cycle)
7886 (define-key org-mode-map [(meta tab)] 'org-complete)
7887 (define-key org-mode-map "\M-\C-i" 'org-complete)
7888 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
7889 (define-key org-mode-map [(meta left)] 'org-metaleft)
7890 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
7891 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
7892 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
7893 (define-key org-mode-map [(meta right)] 'org-metaright)
7894 (define-key org-mode-map [(meta up)] 'org-metaup)
7895 (define-key org-mode-map [(meta down)] 'org-metadown)
7896 ;(define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-subtree)
7897 ;(define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-subtree)
7898 ;(define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-subtree)
7899 (define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-special)
7900 (define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-special)
7901 (define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-special)
7902 (define-key org-mode-map "\C-c\C-j" 'org-goto)
7903 (define-key org-mode-map "\C-c\C-t" 'org-todo)
7904 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
7905 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
7906 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
7907 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
7908 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
7909 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
7910 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
7911 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
7912 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
7913 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
7914 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
7915 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
7916 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
7917 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
7918 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
7919 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
7920 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
7921 (define-key org-mode-map "\C-c[" 'org-add-file)
7922 (define-key org-mode-map "\C-c]" 'org-remove-file)
7923 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
7924 (define-key org-mode-map [(shift up)] 'org-shiftup)
7925 (define-key org-mode-map [(shift down)] 'org-shiftdown)
7926 (define-key org-mode-map [(shift left)] 'org-timestamp-down-day)
7927 (define-key org-mode-map [(shift right)] 'org-timestamp-up-day)
7928 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
7929 ;; The following line is e.g. necessary for German keyboards under Suse Linux
7930 (unless org-xemacs-p
7931 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
7932 (define-key org-mode-map [(shift tab)] 'org-shifttab)
7933 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
7934 (define-key org-mode-map [(return)] 'org-return)
7935 (define-key org-mode-map [(shift return)] 'org-table-copy-down)
7936 (define-key org-mode-map [(meta return)] 'org-meta-return)
7937 (define-key org-mode-map [(control up)] 'org-move-line-up)
7938 (define-key org-mode-map [(control down)] 'org-move-line-down)
7939 (define-key org-mode-map "\C-c?" 'org-table-current-column)
7940 (define-key org-mode-map "\C-c " 'org-table-blank-field)
7941 (define-key org-mode-map "\C-c+" 'org-table-sum)
7942 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
7943 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
7944 (define-key org-mode-map "\C-c#" 'org-table-create-with-table.el)
7945 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
7946 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
7947 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
7948 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
7949 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
7950 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
7951 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
7952 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
7953 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
7954 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
7955 (define-key org-mode-map "\C-c\C-x\C-h" 'org-export-as-html-and-open)
7958 ;; FIXME: Do we really need to save match data in these commands?
7959 ;; I would like to remove it in order to minimize impact.
7960 ;; Self-insert already does not preserve it. How much resources used by this???
7962 (defsubst org-table-p ()
7963 (if (and (eq major-mode 'org-mode) font-lock-mode)
7964 (eq (get-text-property (point) 'face) 'org-table-face)
7965 (save-match-data (org-at-table-p))))
7967 (defun org-self-insert-command (N)
7968 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
7969 If the cursor is in a table looking at whitespace, the whitespace is
7970 overwritten, and the table is not marked as requiring realignment."
7972 (if (and (org-table-p)
7974 (looking-at "[^|\n]* +|"))
7975 (let (org-table-may-need-update)
7976 (goto-char (1- (match-end 0)))
7977 (delete-backward-char 1)
7978 (goto-char (match-beginning 0))
7979 (self-insert-command N))
7980 (setq org-table-may-need-update t)
7981 (self-insert-command N)))
7984 ;; The following two functions might still be optimized to trigger
7985 ;; re-alignment less frequently.
7987 (defun org-delete-backward-char (N)
7988 "Like `delete-backward-char', insert whitespace at field end in tables.
7989 When deleting backwards, in tables this function will insert whitespace in
7990 front of the next \"|\" separator, to keep the table aligned. The table will
7991 still be marked for re-alignment, because a narrow field may lead to a
7992 reduced column width."
7994 (if (and (org-table-p)
7996 (looking-at ".*?|"))
7997 (let ((pos (point)))
7998 (backward-delete-char N)
7999 (skip-chars-forward "^|")
8001 (goto-char (1- pos)))
8002 (backward-delete-char N)))
8004 (defun org-delete-char (N)
8005 "Like `delete-char', but insert whitespace at field end in tables.
8006 When deleting characters, in tables this function will insert whitespace in
8007 front of the next \"|\" separator, to keep the table aligned. The table
8008 will still be marked for re-alignment, because a narrow field may lead to
8009 a reduced column width."
8011 (if (and (org-table-p)
8013 (if (looking-at ".*?|")
8014 (let ((pos (point)))
8015 (replace-match (concat
8016 (substring (match-string 0) 1 -1)
8021 ;; How to do this: Measure non-white length of current string
8022 ;; If equal to column width, we should realign.
8024 (when (eq org-enable-table-editor 'optimized)
8025 ;; If the user wants maximum table support, we need to hijack
8026 ;; some standard editing functions
8027 (substitute-key-definition 'self-insert-command 'org-self-insert-command
8028 org-mode-map global-map)
8029 (substitute-key-definition 'delete-char 'org-delete-char
8030 org-mode-map global-map)
8031 (substitute-key-definition 'delete-backward-char 'org-delete-backward-char
8032 org-mode-map global-map)
8033 (define-key org-mode-map "|" 'self-insert-command))
8035 (defun org-shiftcursor-error ()
8036 "Throw an error because Shift-Cursor command was applied in wrong context."
8037 (error "This command is only active in tables and on headlines."))
8039 (defun org-shifttab ()
8040 "Call `(org-cycle t)' or `org-table-previous-field'."
8043 ((org-at-table-p) (org-table-previous-field))
8044 (t (org-cycle '(4)))))
8046 (defun org-shiftmetaleft ()
8047 "Call `org-promote-subtree' or `org-table-delete-column'."
8050 ((org-at-table-p) (org-table-delete-column))
8051 ((org-on-heading-p) (org-promote-subtree))
8052 (t (org-shiftcursor-error))))
8054 (defun org-shiftmetaright ()
8055 "Call `org-demote-subtree' or `org-table-insert-column'."
8058 ((org-at-table-p) (org-table-insert-column))
8059 ((org-on-heading-p) (org-demote-subtree))
8060 (t (org-shiftcursor-error))))
8062 (defun org-shiftmetaup (&optional arg)
8063 "Call `org-move-subtree-up' or `org-table-kill-row'."
8066 ((org-at-table-p) (org-table-kill-row))
8067 ((org-on-heading-p) (org-move-subtree-up arg))
8068 (t (org-shiftcursor-error))))
8069 (defun org-shiftmetadown (&optional arg)
8070 "Call `org-move-subtree-down' or `org-table-insert-row'."
8073 ((org-at-table-p) (org-table-insert-row arg))
8074 ((org-on-heading-p) (org-move-subtree-down arg))
8075 (t (org-shiftcursor-error))))
8077 (defun org-metaleft (&optional arg)
8078 "Call `org-do-promote' or `org-table-move-column' to left."
8081 ((org-at-table-p) (org-table-move-column 'left))
8082 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
8083 (t (backward-word (prefix-numeric-value arg)))))
8085 (defun org-metaright (&optional arg)
8086 "Call `org-do-demote' or `org-table-move-column' to right."
8089 ((org-at-table-p) (org-table-move-column nil))
8090 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
8091 (t (forward-word (prefix-numeric-value arg)))))
8093 (defun org-metaup (&optional arg)
8094 "Call `org-move-subtree-up' or `org-table-move-row' up."
8097 ((org-at-table-p) (org-table-move-row 'up))
8098 ((org-on-heading-p) (org-move-subtree-up arg))
8099 (t (org-shiftcursor-error))))
8101 (defun org-metadown (&optional arg)
8102 "Call `org-move-subtree-down' or `org-table-move-row' down."
8105 ((org-at-table-p) (org-table-move-row nil))
8106 ((org-on-heading-p) (org-move-subtree-down arg))
8107 (t (org-shiftcursor-error))))
8109 (defun org-shiftup (&optional arg)
8110 "Call `org-timestamp-up' or `org-priority-up'."
8113 ((org-at-timestamp-p) (org-timestamp-up arg))
8114 (t (org-priority-up))))
8116 (defun org-shiftdown (&optional arg)
8117 "Call `org-timestamp-down' or `org-priority-down'."
8120 ((org-at-timestamp-p) (org-timestamp-down arg))
8121 (t (org-priority-down))))
8123 (defun org-copy-special ()
8124 "Call either `org-table-copy' or `org-copy-subtree'."
8126 (if (org-at-table-p)
8127 (org-table-copy-region)
8128 (org-copy-subtree)))
8130 (defun org-cut-special ()
8131 "Call either `org-table-copy' or `org-cut-subtree'."
8133 (if (org-at-table-p)
8134 (org-table-cut-region)
8137 (defun org-paste-special (arg)
8138 "Call either `org-table-paste-rectangle' or `org-paste-subtree'."
8140 (if (org-at-table-p)
8141 (org-table-paste-rectangle)
8142 (org-paste-subtree arg)))
8144 (defun org-ctrl-c-ctrl-c (&optional arg)
8145 "Call realign table, or recognize a table.el table.
8146 When the cursor is inside a table created by the table.el package,
8147 activate that table. Otherwise, if the cursor is at a normal table
8148 created with org.el, re-align that table. This command works even if
8149 the automatic table editor has been turned off."
8151 (let ((org-enable-table-editor t))
8153 ((org-at-table.el-p)
8155 (beginning-of-line 1)
8156 (re-search-forward "|" (save-excursion (end-of-line 2) (point))) ;FIXME: line-end-position?
8157 (table-recognize-table))
8160 ((save-excursion (beginning-of-line 1) (looking-at "#\\+[A-Z]+"))
8161 (let ((org-inhibit-startup t)) (org-mode)))
8162 ((org-region-active-p)
8163 (org-table-convert-region (region-beginning) (region-end) arg))
8164 ((and (region-beginning) (region-end))
8165 (if (y-or-n-p "Convert inactive region to table? ")
8166 (org-table-convert-region (region-beginning) (region-end) arg)
8168 (t (error "No table at point, and no region to make one.")))))
8170 (defun org-return ()
8171 "Call `org-table-next-row' or `newline'."
8175 (org-table-justify-field-maybe)
8176 (org-table-next-row))
8179 (defun org-meta-return (&optional arg)
8180 "Call `org-insert-heading' or `org-table-wrap-region'."
8184 (org-table-wrap-region arg))
8185 (t (org-insert-heading))))
8189 ;; First, remove the outline menus.
8191 (add-hook 'org-mode-hook
8193 (delete-menu-item '("Headings"))
8194 (delete-menu-item '("Show"))
8195 (delete-menu-item '("Hide"))
8196 (set-menubar-dirty-flag)))
8197 (setq org-mode-map (delq (assoc 'menu-bar (cdr org-mode-map))
8200 ;; Define the Org-mode menus
8201 (easy-menu-define org-org-menu org-mode-map "Org menu"
8203 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
8204 ["Sparse Tree" org-occur t]
8205 ["Show All" show-all t]
8207 ["New Heading" org-insert-heading t]
8208 ("Navigate Headings"
8209 ["Up" outline-up-heading t]
8210 ["Next" outline-next-visible-heading t]
8211 ["Previous" outline-previous-visible-heading t]
8212 ["Next Same Level" outline-forward-same-level t]
8213 ["Previous Same Level" outline-backward-same-level t]
8215 ["Jump" org-goto t])
8217 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
8218 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
8220 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
8221 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
8222 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
8224 ["Promote Heading" org-metaleft (not (org-at-table-p))]
8225 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
8226 ["Demote Heading" org-metaright (not (org-at-table-p))]
8227 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))])
8230 ["TODO/DONE/-" org-todo t]
8231 ["Show TODO Tree" org-show-todo-tree t]
8233 ["Set Priority" org-priority t]
8234 ["Priority Up" org-shiftup t]
8235 ["Priority Down" org-shiftdown t])
8236 ("Dates and Scheduling"
8237 ["Timestamp" org-time-stamp t]
8239 ["1 Day Later" org-timestamp-up-day t]
8240 ["1 Day Earlier" org-timestamp-down-day t]
8241 ["1 ... Later" org-shiftup t]
8242 ["1 ... Earlier" org-shiftdown t])
8243 ["Compute Time Range" org-evaluate-time-range t]
8244 ["Schedule Item" org-schedule t]
8245 ["Deadline" org-deadline t]
8247 ["Goto Calendar" org-goto-calendar t]
8248 ["Date from Calendar" org-date-from-calendar t])
8251 ["Show TODO Tree this File" org-show-todo-tree t]
8252 ["Check Deadlines this File" org-check-deadlines t]
8253 ["Timeline Current File" org-timeline t]
8255 ["Agenda" org-agenda t])
8256 ("File List for Agenda")
8259 ["Store Link (Global)" org-store-link t]
8260 ["Insert Link" org-insert-link t]
8261 ["Follow Link" org-open-at-point t])
8264 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
8265 ["Next Field" org-cycle (org-at-table-p)]
8266 ["Previous Field" org-shifttab (org-at-table-p)]
8267 ["Next Row" org-return (org-at-table-p)]
8269 ["Blank Field" org-table-blank-field (org-at-table-p)]
8270 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
8273 ["Move Column Left" org-metaleft (org-at-table-p)]
8274 ["Move Column Right" org-metaright (org-at-table-p)]
8275 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
8276 ["Insert Column" org-shiftmetaright (org-at-table-p)])
8278 ["Move Row Up" org-metaup (org-at-table-p)]
8279 ["Move Row Down" org-metadown (org-at-table-p)]
8280 ["Delete Row" org-shiftmetaup (org-at-table-p)]
8281 ["Insert Row" org-shiftmetadown (org-at-table-p)]
8283 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
8285 ["Copy Rectangle" org-copy-special (org-at-table-p)]
8286 ["Cut Rectangle" org-cut-special (org-at-table-p)]
8287 ["Paste Rectangle" org-paste-special (org-at-table-p)]
8288 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
8290 ["Which Column?" org-table-current-column (org-at-table-p)]
8291 ["Sum Column/Rectangle" org-table-sum
8292 (or (org-at-table-p) (org-region-active-p))]
8293 ["Eval Formula" org-table-eval-formula (org-at-table-p)]
8295 ["Invisible Vlines" org-table-toggle-vline-visibility
8296 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
8298 ["Create" org-table-create (and (not (org-at-table-p))
8299 org-enable-table-editor)]
8300 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
8301 ["Import from File" org-table-import (not (org-at-table-p))]
8302 ["Export to File" org-table-export (org-at-table-p)]
8304 ["Create/Convert from/to table.el" org-table-create-with-table.el t])
8307 ["ASCII" org-export-as-ascii t]
8308 ["Extract Visible Text" org-export-copy-visible t]
8309 ["HTML" org-export-as-html t]
8310 ["HTML and Open" org-export-as-html-and-open t]
8311 ; ["OPML" org-export-as-opml nil]
8313 ["Option Template" org-insert-export-options-template t]
8314 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
8317 ["Show Version" org-version t]
8318 ["Info Documentation" org-info t])
8320 ["Browse Org Group" org-customize t]
8322 ["Build Full Customize Menu" org-create-customize-menu
8323 (fboundp 'customize-menu-create)])
8326 (defun org-info (&optional node)
8327 "Read documentation for Org-mode in the info system.
8328 With optional NODE, go directly to that node."
8331 (Info-goto-node (format "(org)%s" (or node ""))))
8333 (defun org-install-agenda-files-menu ()
8335 '("Org") "File List for Agenda"
8338 ["Edit File List" (customize-variable 'org-agenda-files) t]
8339 ["Add Current File to List" org-add-file t]
8340 ["Remove Current File from List" org-remove-file t]
8342 (mapcar 'org-file-menu-entry org-agenda-files))))
8346 (defun org-customize ()
8347 "Call the customize function with org as argument."
8349 (customize-browse 'org))
8351 (defun org-create-customize-menu ()
8352 "Create a full customization menu for Org-mode, insert it into the menu."
8354 (if (fboundp 'customize-menu-create)
8357 '("Org") "Customize"
8358 `(["Browse Org group" org-customize t]
8360 ,(customize-menu-create 'org)
8361 ["Set" Custom-set t]
8362 ["Save" Custom-save t]
8363 ["Reset to Current" Custom-reset-current t]
8364 ["Reset to Saved" Custom-reset-saved t]
8365 ["Reset to Standard Settings" Custom-reset-standard t]))
8366 (message "\"Org\"-menu now contains full customization menu"))
8367 (error "Cannot expand menu (outdated version of cus-edit.el)")))
8369 ;;; Miscellaneous stuff
8371 (defun org-move-line-down (arg)
8372 "Move the current line down. With prefix argument, move it past ARG lines."
8374 (let ((col (current-column))
8376 (beginning-of-line 1) (setq beg (point))
8377 (beginning-of-line 2) (setq end (point))
8378 (beginning-of-line (+ 1 arg))
8379 (setq pos (move-marker (make-marker) (point)))
8380 (insert (delete-and-extract-region beg end))
8382 (move-to-column col)))
8384 (defun org-move-line-up (arg)
8385 "Move the current line up. With prefix argument, move it past ARG lines."
8387 (let ((col (current-column))
8389 (beginning-of-line 1) (setq beg (point))
8390 (beginning-of-line 2) (setq end (point))
8391 (beginning-of-line (- arg))
8392 (setq pos (move-marker (make-marker) (point)))
8393 (insert (delete-and-extract-region beg end))
8395 (move-to-column col)))
8397 ;; Functions needed for Emacs/XEmacs region compatibility
8399 (defun org-region-active-p ()
8400 "Is `transient-mark-mode' on and the region active?
8401 Works on both Emacs and XEmacs."
8402 (if org-ignore-region
8405 (and zmacs-regions (region-active-p))
8406 (and transient-mark-mode mark-active))))
8408 (defun org-add-to-invisibility-spec (arg)
8409 "Add elements to `buffer-invisibility-spec'.
8410 See documentation for `buffer-invisibility-spec' for the kind of elements
8413 ((fboundp 'add-to-invisibility-spec)
8414 (add-to-invisibility-spec arg))
8415 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
8416 (setq buffer-invisibility-spec (list arg)))
8418 (setq buffer-invisibility-spec
8419 (cons arg buffer-invisibility-spec)))))
8421 (defun org-remove-from-invisibility-spec (arg)
8422 "Remove elements from `buffer-invisibility-spec'."
8423 (if (fboundp 'remove-from-invisibility-spec)
8424 (remove-from-invisibility-spec arg)
8425 (if (consp buffer-invisibility-spec)
8426 (setq buffer-invisibility-spec
8427 (delete arg buffer-invisibility-spec)))))
8429 (defun org-in-invisibility-spec-p (arg)
8430 "Is ARG a member of `buffer-invisibility-spec'?."
8431 (if (consp buffer-invisibility-spec)
8432 (member arg buffer-invisibility-spec)
8435 (defun org-image-file-name-regexp ()
8436 "Return regexp matching the file names of images."
8437 (if (fboundp 'image-file-name-regexp)
8438 (image-file-name-regexp)
8439 (let ((image-file-name-extensions
8440 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
8441 "xbm" "xpm" "pbm" "pgm" "ppm")))
8443 (regexp-opt (nconc (mapcar 'upcase
8444 image-file-name-extensions)
8445 image-file-name-extensions)
8449 ;; Functions needed for compatibility with old outline.el
8451 ;; The following functions capture almost the entire compatibility code
8452 ;; between the different versions of outline-mode. The only other place
8453 ;; where this is important are the font-lock-keywords. Search for
8454 ;; `org-noutline-p' to find it.
8456 ;; C-a should go to the beginning of a *visible* line, also in the
8457 ;; new outline.el. I guess this should be patched into Emacs?
8458 (defun org-beginning-of-line ()
8459 "Go to the beginning of the current line. If that is invisible, continue
8460 to a visible line beginning. This makes the function of C-a more intuitive."
8462 (beginning-of-line 1)
8466 (if (org-invisible-p)
8467 (while (and (not (bobp)) (org-invisible-p))
8469 (beginning-of-line 1))
8471 (when org-noutline-p
8472 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
8474 (defun org-invisible-p ()
8475 "Check if point is at a character currently not visible."
8477 ;; Early versions of noutline don't have `outline-invisible-p'.
8478 (if (fboundp 'outline-invisible-p)
8479 (outline-invisible-p)
8480 (get-char-property (point) 'invisible))
8482 (skip-chars-backward "^\r\n")
8485 (equal (char-before) ?\r)))))
8487 (defun org-back-to-heading (&optional invisible-ok)
8488 "Move to previous heading line, or beg of this line if it's a heading.
8489 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
8491 (outline-back-to-heading invisible-ok)
8492 (if (looking-at outline-regexp)
8494 (if (re-search-backward (concat (if invisible-ok "[\r\n]" "^")
8498 (progn (forward-char 1)
8499 (looking-at outline-regexp)))
8500 (error "Before first heading")))))
8502 (defun org-on-heading-p (&optional invisible-ok)
8503 "Return t if point is on a (visible) heading line.
8504 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
8506 (outline-on-heading-p 'invisible-ok)
8508 (skip-chars-backward "^\n\r")
8509 (and (looking-at outline-regexp)
8512 (equal (char-before) ?\n))))))
8514 (defun org-up-heading-all (arg)
8515 "Move to the heading line of which the present line is a subheading.
8516 This function considers both visible and invisible heading lines.
8517 With argument, move up ARG levels."
8519 (if (fboundp 'outline-up-heading-all)
8520 (outline-up-heading-all arg) ; emacs 21 version of outline.el
8521 (outline-up-heading arg t)) ; emacs 22 version of outline.el
8522 (org-back-to-heading t)
8523 (looking-at outline-regexp)
8524 (if (<= (- (match-end 0) (match-beginning 0)) arg)
8525 (error "Cannot move up %d levels" arg)
8527 (concat "[\n\r]" (regexp-quote
8528 (make-string (- (match-end 0) (match-beginning 0) arg)
8533 (defun org-show-hidden-entry ()
8534 "Show an entry where even the heading is hidden."
8536 (if (not org-noutline-p)
8538 (org-back-to-heading t)
8539 (org-flag-heading nil)))
8542 (defun org-check-occur-regexp (regexp)
8543 "If REGEXP starts with \"^\", modify it to check for \\r as well.
8544 Of course, only for the old outline mode."
8547 (if (string-match "^\\^" regexp)
8548 (concat "[\n\r]" (substring regexp 1))
8551 (defun org-flag-heading (flag &optional entry)
8552 "Flag the current heading. FLAG non-nil means make invisible.
8553 When ENTRY is non-nil, show the entire entry."
8555 (org-back-to-heading t)
8556 (if (not org-noutline-p)
8557 ;; Make the current headline visible
8558 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
8559 ;; Check if we should show the entire entry
8563 (save-excursion ;; FIXME: Is this the fix for points in the -|
8564 ;; middle of text? |
8565 (and (outline-next-heading) ;; |
8566 (org-flag-heading nil)))) ; show the next heading _|
8567 (outline-flag-region (max 1 (1- (point)))
8568 (save-excursion (outline-end-of-heading) (point))
8571 (if flag ?\r ?\n))))))
8573 (defun org-show-subtree ()
8574 "Show everything after this heading at deeper levels."
8575 (outline-flag-region
8578 (outline-end-of-subtree) (outline-next-heading) (point))
8579 (if org-noutline-p nil ?\n)))
8581 (defun org-show-entry ()
8582 "Show the body directly following this heading.
8583 Show the heading too, if it is currently invisible."
8586 (org-back-to-heading t)
8587 (outline-flag-region
8590 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
8591 (or (match-beginning 1) (point-max)))
8592 (if org-noutline-p nil ?\n))))
8595 (defun org-make-options-regexp (kwds)
8596 "Make a regular expression for keyword lines."
8598 (if org-noutline-p "^" "[\n\r]")
8600 (mapconcat 'regexp-quote kwds "\\|")
8602 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
8604 ;; Advise the bookmark-jump function to make jump position visible
8605 ;; Wrapped into eval-after-load to avoid loading advice unnecessarily
8606 (eval-after-load "bookmark"
8607 '(defadvice bookmark-jump (after org-make-visible activate)
8608 "Make the position visible."
8609 (and (eq major-mode 'org-mode)
8611 (org-show-hierarchy-above))))
8617 (run-hooks 'org-load-hook)
8619 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
8621 ;;; org.el ends here